-
Notifications
You must be signed in to change notification settings - Fork 415
/
index.js
330 lines (296 loc) · 12.4 KB
/
index.js
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
// @flow
//
// Copyright (c) 2018-present, GM Cruise LLC
//
// This source code is licensed under the Apache License, Version 2.0,
// found in the LICENSE file in the root directory of this source tree.
// You may not use this file except in compliance with the License.
import microMemoize from "micro-memoize";
import { TimeUtil, type Time } from "rosbag";
// $FlowFixMe - flow does not like workers.
import UserNodePlayerWorker from "worker-loader!webviz-core/src/players/UserNodePlayer/nodeRuntimeWorker"; // eslint-disable-line
// $FlowFixMe - flow does not like workers.
import NodeDataWorker from "worker-loader!webviz-core/src/players/UserNodePlayer/nodeTransformerWorker"; // eslint-disable-line
import type { SetUserNodeDiagnostics, AddUserNodeLogs, SetUserNodeTrust } from "webviz-core/src/actions/userNodes";
import type {
AdvertisePayload,
Message,
Player,
PlayerState,
PublishPayload,
SubscribePayload,
PlayerStateActiveData,
Topic,
} from "webviz-core/src/players/types";
import { isUserNodeTrusted } from "webviz-core/src/players/UserNodePlayer/nodeSecurity";
import {
DiagnosticSeverity,
type NodeData,
type NodeRegistration,
type Diagnostic,
type ProcessMessageOutput,
type RegistrationOutput,
Sources,
ErrorCodes,
} from "webviz-core/src/players/UserNodePlayer/types";
import type { UserNodeLog } from "webviz-core/src/players/UserNodePlayer/types";
import type { UserNodes } from "webviz-core/src/types/panels";
import type { RosDatatypes } from "webviz-core/src/types/RosDatatypes";
import Rpc from "webviz-core/src/util/Rpc";
import signal from "webviz-core/src/util/signal";
type UserNodeActions = {
setUserNodeDiagnostics: SetUserNodeDiagnostics,
addUserNodeLogs: AddUserNodeLogs,
setUserNodeTrust: SetUserNodeTrust,
};
// TODO: FUTURE - Performance tests
// TODO: FUTURE - Consider how to incorporate with existing hardcoded nodes (esp re: stories/testing)
// 1 - Do we convert them all over to the new node format / Typescript? What about imported libraries?
// 2 - Do we keep them in the old format for a while and support both formats?
export default class UserNodePlayer implements Player {
_player: Player;
_nodeRegistrations: NodeRegistration[] = [];
_subscriptions: SubscribePayload[] = [];
_userNodes: UserNodes = {};
// TODO: FUTURE - Terminate unused workers (some sort of timeout, for whole array or per rpc)
// Not sure if there is perf issue with unused workers (may just go idle) - requires more research
_unusedNodeRuntimeWorkers: Rpc[] = [];
_lastPlayerStateActiveData: ?PlayerStateActiveData;
_setUserNodeDiagnostics: (nodeId: string, diagnostics: Diagnostic[]) => void;
_addUserNodeLogs: (nodeId: string, logs: UserNodeLog[]) => void;
_setNodeTrust: (nodeId: string, trusted: boolean) => void;
_nodeTransformWorker: Rpc = new Rpc(new NodeDataWorker());
_userDatatypes: RosDatatypes = {};
constructor(player: Player, userNodeActions: UserNodeActions) {
this._player = player;
const { setUserNodeDiagnostics, addUserNodeLogs, setUserNodeTrust } = userNodeActions;
// TODO(troy): can we make the below action flow better? Might be better to
// just add an id, and the thing you want to update? Instead of passing in
// objects?
this._setUserNodeDiagnostics = (nodeId: string, diagnostics: Diagnostic[]) => {
setUserNodeDiagnostics({ [nodeId]: { diagnostics } });
};
this._addUserNodeLogs = (nodeId: string, logs: UserNodeLog[]) => {
addUserNodeLogs({ [nodeId]: { logs } });
};
this._setNodeTrust = (id: string, trusted: boolean) => {
setUserNodeTrust({ id, trusted });
};
}
_getTopics = microMemoize((topics: Topic[], nodeRegistrations: NodeRegistration[]) => {
return [...topics, ...nodeRegistrations.map((nodeRegistration) => nodeRegistration.output)];
});
// When updating Webviz nodes while paused, we seek to the current time
// (i.e. invoke _getMessages with an empty array) to refresh messages
_getMessages = microMemoize(
async (messages: Message[]): Promise<Message[]> => {
const promises = [];
for (const message of messages) {
for (const nodeRegistration of this._nodeRegistrations) {
if (
this._subscriptions.find(({ topic }) => topic === nodeRegistration.output.name) &&
nodeRegistration.inputs.includes(message.topic)
) {
promises.push(nodeRegistration.processMessage(message));
}
}
}
const nodeMessages: Message[] = (await Promise.all(promises)).filter(Boolean);
return [...messages, ...nodeMessages].sort((a, b) => TimeUtil.compare(a.receiveTime, b.receiveTime));
}
);
_getDatatypes = microMemoize((datatypes, userDatatypes) => ({ ...userDatatypes, ...datatypes }));
// Called when userNode state is updated.
async setUserNodes(userNodes: UserNodes): Promise<void> {
this._userNodes = userNodes;
// TODO: Currently the below causes us to reset workers twice, since we are
// forcing a 'seek' here.
return this._resetWorkers().then(() => {
const currentTime = this._lastPlayerStateActiveData && this._lastPlayerStateActiveData.currentTime;
const isPlaying = this._lastPlayerStateActiveData && this._lastPlayerStateActiveData.isPlaying;
if (!currentTime || isPlaying) {
return;
}
this._player.seekPlayback(currentTime);
});
}
// Defines the inputs/outputs and worker interface of a user node.
_getNodeRegistration(nodeId: string, nodeData: NodeData): NodeRegistration {
const { inputTopics, outputTopic, transpiledCode: nodeCode, outputDatatype, datatypes } = nodeData;
// Update datatypes for the player state to consume.
this._userDatatypes = { ...this._userDatatypes, ...datatypes };
let rpc;
const terminateSignal = signal<void>();
return {
inputs: inputTopics,
output: { name: outputTopic, datatype: outputDatatype },
processMessage: async (message: Message) => {
// Register the node within a web worker to be executed.
if (!rpc) {
rpc = this._unusedNodeRuntimeWorkers.pop() || new Rpc(new UserNodePlayerWorker());
const { error, userNodeDiagnostics, userNodeLogs } = await rpc.send<RegistrationOutput>("registerNode", {
nodeCode,
});
if (error) {
this._setUserNodeDiagnostics(nodeId, [
...userNodeDiagnostics,
{
source: Sources.Runtime,
severity: DiagnosticSeverity.Error,
message: error,
code: ErrorCodes.RUNTIME,
},
]);
return;
}
this._addUserNodeLogs(nodeId, userNodeLogs);
}
const result = await Promise.race([
rpc.send<ProcessMessageOutput>("processMessage", { message }),
terminateSignal,
]);
if (result && result.error) {
this._setUserNodeDiagnostics(nodeId, [
{
source: Sources.Runtime,
severity: DiagnosticSeverity.Error,
message: result.error,
code: ErrorCodes.RUNTIME,
},
]);
return;
}
if (result) {
this._addUserNodeLogs(nodeId, result.userNodeLogs);
}
// TODO: FUTURE - surface runtime errors / infinite loop errors
if (!result || !result.message) {
return;
}
return {
topic: outputTopic,
datatype: nodeData.outputDatatype,
op: "message",
message: result.message,
receiveTime: message.receiveTime,
};
},
terminate: () => {
terminateSignal.resolve();
if (rpc) {
this._unusedNodeRuntimeWorkers.push(rpc);
}
},
};
}
// We need to reset workers in a variety of circumstances:
// - When a user node is updated, added or deleted
// - When we seek (in order to reset state)
// - When a new child player is added
//
// For the time being, resetWorkers is a catchall for these circumstances. As
// performance bottlenecks are identified, it will be subject to change.
async _resetWorkers() {
// This early return is an optimization measure so that the
// `nodeRegistrations` array is not re-defined, which will invalidate
// downstream caches. (i.e. `this._getTopics`)
if (!this._nodeRegistrations.length && !Object.entries(this._userNodes).length) {
return;
}
for (const nodeRegistration of this._nodeRegistrations) {
nodeRegistration.terminate();
}
const nodeRegistrations: NodeRegistration[] = [];
for (const [nodeId, nodeObj] of Object.entries(this._userNodes)) {
const node = ((nodeObj: any): { name: string, sourceCode: string });
if (!isUserNodeTrusted({ id: nodeId, sourceCode: node.sourceCode })) {
this._setNodeTrust(nodeId, false);
continue;
} else {
this._setNodeTrust(nodeId, true);
}
const { topics = [], datatypes: playerDatatypes = {} } = this._lastPlayerStateActiveData || {};
const nodeData = await this._nodeTransformWorker.send("transform", {
name: node.name,
sourceCode: node.sourceCode,
playerInfo: { topics, playerDatatypes },
priorRegisteredTopics: nodeRegistrations.map(({ output }) => output),
});
const { diagnostics } = nodeData;
this._setUserNodeDiagnostics(nodeId, diagnostics);
if (diagnostics.some(({ severity }) => severity === DiagnosticSeverity.Error)) {
continue;
}
nodeRegistrations.push(this._getNodeRegistration(nodeId, nodeData));
}
this._nodeRegistrations = nodeRegistrations;
}
setListener(listener: (PlayerState) => Promise<void>) {
this._player.setListener(async (playerState: PlayerState) => {
const { activeData } = playerState;
if (activeData) {
const { messages, topics, datatypes } = activeData;
// For resetting node state after seeking.
// TODO: Make resetWorkers more efficient in this case since we don't
// need to recompile/validate anything.
if (
this._lastPlayerStateActiveData &&
activeData.lastSeekTime !== this._lastPlayerStateActiveData.lastSeekTime
) {
await this._resetWorkers();
}
// If we do not have active player data from a previous call, then our
// player just spun up, meaning we should re-run our user nodes in case
// they have inputs that now exist in the current player context.
if (!this._lastPlayerStateActiveData) {
this._lastPlayerStateActiveData = activeData;
await this._resetWorkers().then(() => {
this.setSubscriptions(this._subscriptions);
});
}
const newPlayerState = {
...playerState,
activeData: {
...activeData,
messages: await this._getMessages(messages),
topics: this._getTopics(topics, this._nodeRegistrations),
datatypes: this._getDatatypes(datatypes, this._userDatatypes),
},
};
this._lastPlayerStateActiveData = playerState.activeData;
return listener(newPlayerState);
}
return listener(playerState);
});
}
setSubscriptions(subscriptions: SubscribePayload[]) {
this._subscriptions = subscriptions;
const realTopicSubscriptions: SubscribePayload[] = [];
for (const subscription of subscriptions) {
const nodeRegistration = this._nodeRegistrations.find((info) => info.output.name === subscription.topic);
if (nodeRegistration) {
for (const inputTopic of nodeRegistration.inputs) {
realTopicSubscriptions.push({
topic: inputTopic,
requester: { type: "node", name: nodeRegistration.output.name },
});
}
} else {
realTopicSubscriptions.push(subscription);
}
}
this._player.setSubscriptions(realTopicSubscriptions);
}
close = () => {
for (const nodeRegistration of this._nodeRegistrations) {
nodeRegistration.terminate();
}
this._player.close();
};
setPublishers = (publishers: AdvertisePayload[]) => this._player.setPublishers(publishers);
publish = (request: PublishPayload) => this._player.publish(request);
startPlayback = () => this._player.startPlayback();
pausePlayback = () => this._player.pausePlayback();
setPlaybackSpeed = (speed: number) => this._player.setPlaybackSpeed(speed);
seekPlayback = (time: Time) => this._player.seekPlayback(time);
}