-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Expand file tree
/
Copy pathinspectableBridgeService.ts
More file actions
193 lines (176 loc) · 7.48 KB
/
inspectableBridgeService.ts
File metadata and controls
193 lines (176 loc) · 7.48 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import { type IDisposable } from "core/index";
import { Observable } from "core/Misc/observable";
import { type BrowserRequest, type BrowserResponse, type CommandInfo } from "../../cli/protocol";
import { type ServiceDefinition } from "../../modularity/serviceDefinition";
import { type ICliConnectionStatus, CliConnectionStatusIdentity } from "./cliConnectionStatus";
import { type IInspectableCommandRegistry, type InspectableCommandDescriptor, InspectableCommandRegistryIdentity } from "./inspectableCommandRegistry";
import { Logger } from "core/Misc/logger";
/**
* Options for the inspectable bridge service.
*/
export interface IInspectableBridgeServiceOptions {
/**
* The WebSocket port for the bridge's browser port.
*/
port: number;
/**
* The session display name sent to the bridge.
* Can be a getter to provide a dynamic value that is re-read
* each time the bridge queries session information.
*/
name: string;
}
/**
* Creates the service definition for the InspectableBridgeService.
* @param options The options for connecting to the bridge.
* @returns A service definition that produces an IInspectableCommandRegistry.
*/
export function MakeInspectableBridgeServiceDefinition(options: IInspectableBridgeServiceOptions): ServiceDefinition<[IInspectableCommandRegistry, ICliConnectionStatus], []> {
return {
friendlyName: "Inspectable Bridge Service",
produces: [InspectableCommandRegistryIdentity, CliConnectionStatusIdentity],
factory: () => {
const commands = new Map<string, InspectableCommandDescriptor>();
let ws: WebSocket | null = null;
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
let disposed = false;
let connected = false;
const onConnectionStatusChanged = new Observable<boolean>();
function setConnected(value: boolean) {
if (connected !== value) {
connected = value;
onConnectionStatusChanged.notifyObservers(value);
}
}
function sendToBridge(message: BrowserRequest) {
ws?.send(JSON.stringify(message));
}
function connect() {
if (disposed) {
return;
}
try {
ws = new WebSocket(`ws://127.0.0.1:${options.port}`);
} catch {
scheduleReconnect();
return;
}
ws.onopen = () => {
setConnected(true);
sendToBridge({ type: "register", name: options.name });
};
ws.onmessage = (event) => {
try {
const message = JSON.parse(event.data as string);
void handleMessage(message);
} catch {
Logger.Warn("InspectableBridgeService: Failed to parse message from bridge.");
}
};
ws.onclose = () => {
ws = null;
setConnected(false);
scheduleReconnect();
};
ws.onerror = () => {
// onclose will fire after onerror, which handles reconnection.
};
}
function scheduleReconnect() {
if (disposed || reconnectTimer !== null) {
return;
}
reconnectTimer = setTimeout(() => {
reconnectTimer = null;
connect();
}, 3000);
}
async function handleMessage(message: BrowserResponse) {
switch (message.type) {
case "listCommands": {
const commandList: CommandInfo[] = Array.from(commands.values()).map((cmd) => ({
id: cmd.id,
description: cmd.description,
args: cmd.args,
}));
sendToBridge({
type: "commandListResponse",
requestId: message.requestId,
commands: commandList,
});
break;
}
case "getInfo": {
sendToBridge({
type: "infoResponse",
requestId: message.requestId,
name: options.name,
});
break;
}
case "execCommand": {
const command = commands.get(message.commandId);
if (!command) {
sendToBridge({
type: "commandResponse",
requestId: message.requestId,
error: `Unknown command: ${message.commandId}`,
});
break;
}
try {
const result = await command.executeAsync(message.args);
sendToBridge({
type: "commandResponse",
requestId: message.requestId,
result,
});
} catch (error: unknown) {
sendToBridge({
type: "commandResponse",
requestId: message.requestId,
error: String(error),
});
}
break;
}
}
}
// Initiate connection.
connect();
const registry: IInspectableCommandRegistry & ICliConnectionStatus & IDisposable = {
addCommand(descriptor: InspectableCommandDescriptor): IDisposable {
if (commands.has(descriptor.id)) {
throw new Error(`Command '${descriptor.id}' is already registered.`);
}
commands.set(descriptor.id, descriptor);
return {
dispose: () => {
commands.delete(descriptor.id);
},
};
},
get isConnected() {
return connected;
},
onConnectionStatusChanged,
dispose: () => {
disposed = true;
if (reconnectTimer !== null) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
commands.clear();
setConnected(false);
onConnectionStatusChanged.clear();
if (ws) {
ws.onclose = null;
ws.close();
ws = null;
}
},
};
return registry;
},
};
}