File size: 2,693 Bytes
9e18664
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""Local-only control channel for the independent LoomG2 viewer."""
import json
from pathlib import Path
import queue
import subprocess
import threading
import time

import rerun_cli


class ViewerControl:
    def __init__(self, port):
        helper = Path(rerun_cli.__file__).parent / 'rerun.exe'
        self.process = subprocess.Popen(
            [str(helper), 'viewer-mcp'], stdin=subprocess.PIPE,
            stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
            text=True, encoding='utf-8', creationflags=subprocess.CREATE_NO_WINDOW)
        self.messages = queue.Queue()
        self.sequence = 0
        threading.Thread(target=self._read, daemon=True).start()
        self.rpc('initialize', dict(protocolVersion='2024-11-05', capabilities={},
                                   clientInfo=dict(name='LoomG2 data loader', version='1')))
        deadline = time.monotonic() + 45
        while True:
            try:
                self.call('rerun_connect', dict(endpoint=f'http://127.0.0.1:{port}'))
                break
            except (RuntimeError, queue.Empty):
                if time.monotonic() > deadline:
                    self.close()
                    raise
                time.sleep(.5)

    def _read(self):
        for line in self.process.stdout:
            try:
                self.messages.put(json.loads(line))
            except ValueError:
                continue
        self.messages.put(None)

    def rpc(self, method, params):
        self.sequence += 1
        self.process.stdin.write(json.dumps(dict(jsonrpc='2.0', id=self.sequence,
                                                method=method, params=params)) + '\n')
        self.process.stdin.flush()
        deadline = time.monotonic() + 15
        while True:
            message = self.messages.get(timeout=max(.01, deadline - time.monotonic()))
            if message is None:
                raise RuntimeError('Viewer control helper exited')
            if message.get('id') == self.sequence:
                if 'error' in message:
                    raise RuntimeError(str(message['error']))
                return message['result']

    def call(self, name, arguments=None):
        result = self.rpc('tools/call', dict(name=name, arguments=arguments or {}))
        if result.get('isError'):
            raise RuntimeError(str(result.get('content')))
        if 'structuredContent' in result:
            return result['structuredContent']
        return json.loads(next(c['text'] for c in result['content'] if c['type'] == 'text'))

    def close(self):
        if self.process.poll() is None:
            self.process.terminate()
        self.process.wait(timeout=5)