@remix_labs/machine-starter 2.12988.0-dev → 2.12990.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/common.js CHANGED
@@ -12,8 +12,26 @@ let children = {};
12
12
  let ffiLoops = {};
13
13
  let blobs = {};
14
14
  let blobsLoops = {};
15
+ let coordination = {};
15
16
 
16
- function terminateAll() {
17
+ class TaskQueue {
18
+ constructor() {
19
+ this.tail = Promise.resolve();
20
+ this.length = 0;
21
+ }
22
+ run(fn) { // fn shall return a promise. run also returns a promise
23
+ length++;
24
+ const result = this.tail.then(() => fn());
25
+ this.tail = result.catch(() => {});
26
+ length--;
27
+ return result;
28
+ }
29
+ }
30
+
31
+ function terminateAllOnExit() {
32
+ // this is a simplified termination function that kills all VMs, but
33
+ // doesn't clean everything properly up. Use this only for the "on-exit"
34
+ // callback of node.
17
35
  console.log("[machine-starter] terminate all VMs");
18
36
  for (let [vmID, worker] of Object.entries(workers)) {
19
37
  worker.terminate();
@@ -31,59 +49,75 @@ function terminateAll() {
31
49
  blobsLoop.terminate();
32
50
  }
33
51
  workers = {};
52
+ worker_topics = {};
34
53
  children = {};
35
54
  ffiLoops = {};
36
55
  blobs = {};
37
56
  blobsLoops = {};
57
+ coordination = {};
38
58
  }
39
59
 
40
- function terminateVM(vmID) {
41
- console.log("[machine-starter] terminate VM", vmID);
42
- let worker = workers[vmID];
43
- if (worker) {
44
- let vmChildren = children[vmID];
60
+ function getCoord(vmID) {
61
+ let coord = coordination[vmID];
62
+ if (!coord) {
63
+ coord = { queue: new TaskQueue() };
64
+ coordination[vmID] = coord;
65
+ }
66
+ return coord;
67
+ }
68
+
69
+ async function terminateVM(vmID) {
70
+ let coord = getCoord(vmID);
71
+ await coord.queue.run(async () => {
72
+ console.log("[machine-starter] terminate VM:", vmID);
73
+ // make the VM first unknown to the outside and disconnect it,
74
+ // then clean up resources (including stopping the VM)
75
+ let channel = await last_hub.newChannel();
76
+ let topic = worker_topics[vmID];
77
+ let payload = { _rmx_type:"msg_vm_register", id: vmID, alive: false };
78
+ let msg = channel.newJSONMessage("msg_vm_register", "vm", payload);
79
+ await channel.publish(topic + "/announce", msg, true);
80
+ // NB. This msg is a leak - it will never be removed.
81
+ await channel.disconnect("vm_" + vmID);
82
+ // now the VM is isolated and cannot communicate with the
83
+ // hub anymore
84
+ let worker = workers[vmID];
85
+ let vmChildren = children[vmID] || [];
45
86
  let blobList = blobs[vmID] || [];
46
87
  let ffiLoop = ffiLoops[vmID];
47
88
  let blobsLoop = blobsLoops[vmID];
48
89
  delete children[vmID];
49
90
  delete ffiLoops[vmID];
50
91
  delete blobsLoops[vmID];
51
- killVM(vmID);
52
- ffiLoop.terminate();
92
+ delete worker_topics[vmID];
93
+ delete workers[vmID];
94
+ // terminate our endpoints of communication
95
+ if (ffiLoop) {
96
+ ffiLoop.terminate();
97
+ }
53
98
  if (blobsLoop) {
54
99
  blobsLoop.terminate();
55
100
  }
56
101
  for (let blob_url of blobList) {
57
102
  console.log("[machine-starter] revoke ", blob_url);
58
103
  URL.revokeObjectURL(blob_url);
59
- };
60
- if (vmChildren) {
61
- for (let subID of vmChildren) {
62
- terminateVM(subID)
63
- }
64
104
  }
65
- }
66
- }
67
-
68
- function killVM(vmID) {
69
- let worker = workers[vmID];
70
- let topic = worker_topics[vmID];
71
- delete workers[vmID];
72
- delete worker_topics[vmID];
73
- if (topic && last_hub) {
74
- let payload = { _rmx_type:"msg_vm_register", id: vmID, alive: false };
75
- last_hub.newChannel().then(channel => {
76
- let msg = channel.newJSONMessage("msg_vm_register", "vm", payload);
77
- channel.publish(topic + "/announce", msg, true)
78
- }).then(_ => worker.terminate())
79
- } else {
80
- worker.terminate()
105
+ // kill the worker:
106
+ console.log("[machine-starter] terminate web worker for VM:", vmID);
107
+ worker.terminate();
108
+ // go on with sub VMs
109
+ for (let subID of vmChildren) {
110
+ terminateVM(subID) // do not wait
111
+ }
112
+ });
113
+ if (coord.queue.length == 0) {
114
+ delete coordination[vmID];
81
115
  }
82
116
  }
83
117
 
84
118
  if (globalThis.Process) {
85
119
  Process.on("exit", () => {
86
- terminateAll()
120
+ terminateAllOnExit()
87
121
  })
88
122
  };
89
123
 
@@ -133,84 +167,86 @@ async function StartWASM2(hub, config, getWorker) {
133
167
  console.log("[machine-starter] Call MixExplain() for explaining debug levels, and MixSetMask(m) for changing these")
134
168
  };
135
169
  last_hub = hub;
136
- let channel = await hub.newChannel();
137
- // injected by either index.js or node.js
138
- let worker = await getWorker();
139
- if (workers[config.vmID] || ffiLoops[config.vmID])
140
- throw new Error("Cannot start VM, the ID is used: " + config.vmID);
141
- workers[config.vmID] = worker;
142
- if (config.topicPrefix != undefined && config.topicPrefix != "") {
143
- worker_topics[config.vmID] = config.topicPrefix + "/vm/" + config.vmID;
144
- } else {
145
- worker_topics[config.vmID] = "/org/" + config.org + "/ws/" + config.workspace + "/vm/" + config.vmID;
146
- }
147
- let starterFFIs = config.localFFIs || {};
148
- // from now on, the "local" FFIs are called "starter" FFIs, because this
149
- // distinguishes these from other locally defined FFIs
150
- let mixcore = await createStarterMixcore(config.mixcore);
151
- if (mixcore) {
152
- // merge the ffis and store them back into the config so sub vms also get them
153
- config.localFFIs = Object.assign(starterFFIs, await mixcoreStarterFFIs(mixcore));
154
- // delete the mixcore config to avoid being handled further by the worker
155
- delete config.mixcore;
156
- }
157
- let starterFFIkind = {};
158
- let starterFFIfuns = {};
159
- for (const [k, v] of Object.entries(starterFFIs)) {
160
- starterFFIfuns[k] = {...v};
161
- if (v.isRaw && (v.canFail || v.useJsonDecoder)) {
162
- console.error("A raw, starter FFI must neither be failing nor use the JSON decoder: " + k);
170
+ // get thr coord object - perhaps the ID was already used for a VM
171
+ let coord = getCoord(vmID);
172
+ await coord.queue.run(async () => {
173
+ let channel = await hub.newChannel("vm_" + config.vmID);
174
+ // injected by either index.js or node.js
175
+ let worker = await getWorker();
176
+ workers[config.vmID] = worker;
177
+ if (config.topicPrefix != undefined && config.topicPrefix != "") {
178
+ worker_topics[config.vmID] = config.topicPrefix + "/vm/" + config.vmID;
163
179
  } else {
164
- starterFFIkind[k] = {...v};
165
- delete starterFFIkind[k].run;
180
+ worker_topics[config.vmID] = "/org/" + config.org + "/ws/" + config.workspace + "/vm/" + config.vmID;
166
181
  }
167
- };
168
- let vm_kind = { isRaw:false, canFail:false, useJsonDecoder:false};
169
- starterFFIkind["$vm_start"] = vm_kind;
170
- starterFFIfuns["$vm_start"] = (conn, args) => ffi_vm_start(conn, args, getWorker);
171
- starterFFIkind["$vm_stop"] = vm_kind;
172
- starterFFIfuns["$vm_stop"] = ffi_vm_stop;
173
- let mixrtCode = config.mixrtCode;
174
- if (typeof(mixrtCode) == "string" && mixrtCode.startsWith("remix://")) {
175
- // for the desktop only: precompile the mixrt module to get faster
176
- // startup times
177
- if (globalThis.mixrtCodeModule && globalThis.mixrtCodeURL == mixrtCode) {
178
- console.log("[machine-starter] reusing mixrt");
179
- mixrtCode = globalThis.mixrtCodeModule;
180
- } else {
181
- let url = mixrtCode;
182
- console.log("[machine-starter] pre-compiling mixrt");
183
- mixrtCode = await WebAssembly.compileStreaming(fetch(url));
184
- globalThis.mixrtCodeURL = url;
185
- globalThis.mixrtCodeModule = mixrtCode;
182
+ let starterFFIs = config.localFFIs || {};
183
+ // from now on, the "local" FFIs are called "starter" FFIs, because this
184
+ // distinguishes these from other locally defined FFIs
185
+ let mixcore = await createStarterMixcore(config.mixcore);
186
+ if (mixcore) {
187
+ // merge the ffis and store them back into the config so sub vms also get them
188
+ config.localFFIs = Object.assign(starterFFIs, await mixcoreStarterFFIs(mixcore));
189
+ // delete the mixcore config to avoid being handled further by the worker
190
+ delete config.mixcore;
186
191
  }
187
- };
188
- ffiLoops[config.vmID] = setupStarterFFIs(hub, config, starterFFIfuns);
189
- blobsLoops[config.vmID] = setupBlobs(hub, config);
190
- let config_msg =
191
- { "_rmx_type": "msg_vm_configure",
192
- "baseURL": config.baseURL,
193
- "org": config.org,
194
- "workspace": config.workspace,
195
- "topicPrefix": config.topicPrefix,
196
- "vmID": config.vmID,
197
- "user": config.user,
198
- "token": config.token,
199
- "hub": channel.port,
200
- "outputViaMQTT": !(config.noOutputViaMQTT),
201
- "machType": config.machType,
202
- "debugMask": initialMask,
203
- "starterFFIs": starterFFIkind,
204
- "allowInsecureHttp": globalThis.GROOVEBOX_ALLOW_INSECURE_HTTP,
205
- "interceptFFI": config.interceptFFI,
206
- "interceptDynloadFFI": config.interceptDynloadFFI,
207
- "mixcore": config.mixcore,
208
- "mixrtCode": mixrtCode
209
- // can be: base64-encoded string, Uint8Array, or a URL as string
210
- // (http, https, data)
192
+ let starterFFIkind = {};
193
+ let starterFFIfuns = {};
194
+ for (const [k, v] of Object.entries(starterFFIs)) {
195
+ starterFFIfuns[k] = {...v};
196
+ if (v.isRaw && (v.canFail || v.useJsonDecoder)) {
197
+ console.error("A raw, starter FFI must neither be failing nor use the JSON decoder: " + k);
198
+ } else {
199
+ starterFFIkind[k] = {...v};
200
+ delete starterFFIkind[k].run;
201
+ }
211
202
  };
212
- worker.postMessage(config_msg, [ channel.port ]);
213
- return worker;
203
+ let vm_kind = { isRaw:false, canFail:false, useJsonDecoder:false};
204
+ starterFFIkind["$vm_start"] = vm_kind;
205
+ starterFFIfuns["$vm_start"] = (conn, args) => ffi_vm_start(conn, args, getWorker);
206
+ starterFFIkind["$vm_stop"] = vm_kind;
207
+ starterFFIfuns["$vm_stop"] = ffi_vm_stop;
208
+ let mixrtCode = config.mixrtCode;
209
+ if (typeof(mixrtCode) == "string" && mixrtCode.startsWith("remix://")) {
210
+ // for the desktop only: precompile the mixrt module to get faster
211
+ // startup times
212
+ if (globalThis.mixrtCodeModule && globalThis.mixrtCodeURL == mixrtCode) {
213
+ console.log("[machine-starter] reusing mixrt");
214
+ mixrtCode = globalThis.mixrtCodeModule;
215
+ } else {
216
+ let url = mixrtCode;
217
+ console.log("[machine-starter] pre-compiling mixrt");
218
+ mixrtCode = await WebAssembly.compileStreaming(fetch(url));
219
+ globalThis.mixrtCodeURL = url;
220
+ globalThis.mixrtCodeModule = mixrtCode;
221
+ }
222
+ };
223
+ ffiLoops[config.vmID] = setupStarterFFIs(hub, config, starterFFIfuns);
224
+ blobsLoops[config.vmID] = setupBlobs(hub, config);
225
+ let config_msg =
226
+ { "_rmx_type": "msg_vm_configure",
227
+ "baseURL": config.baseURL,
228
+ "org": config.org,
229
+ "workspace": config.workspace,
230
+ "topicPrefix": config.topicPrefix,
231
+ "vmID": config.vmID,
232
+ "user": config.user,
233
+ "token": config.token,
234
+ "hub": channel.port,
235
+ "outputViaMQTT": !(config.noOutputViaMQTT),
236
+ "machType": config.machType,
237
+ "debugMask": initialMask,
238
+ "starterFFIs": starterFFIkind,
239
+ "allowInsecureHttp": globalThis.GROOVEBOX_ALLOW_INSECURE_HTTP,
240
+ "interceptFFI": config.interceptFFI,
241
+ "interceptDynloadFFI": config.interceptDynloadFFI,
242
+ "mixcore": config.mixcore,
243
+ "mixrtCode": mixrtCode
244
+ // can be: base64-encoded string, Uint8Array, or a URL as string
245
+ // (http, https, data)
246
+ };
247
+ worker.postMessage(config_msg, [ channel.port ]);
248
+ return worker;
249
+ });
214
250
  }
215
251
 
216
252
  async function mixcoreStarterFFIs(mixcore) {
@@ -387,7 +423,7 @@ async function starterFFIsMessageLoop(hub, config, starterFFIs, terminate) {
387
423
  sub.next().then((msg) => ({msg})),
388
424
  terminate.then(() => ({terminated: true})),
389
425
  ]);
390
- if (terminated) {
426
+ if (terminated || msg.eof) {
391
427
  // console.log("[machine-starter] terminate FFI loop", vmID);
392
428
  return;
393
429
  }
@@ -396,7 +432,7 @@ async function starterFFIsMessageLoop(hub, config, starterFFIs, terminate) {
396
432
  let args = decode(msg.payload.args);
397
433
  let fun = starterFFIs[name];
398
434
  if (initialMask & DEBUG_STATE)
399
- console.debug("[groovebox-starter] starter FFI call", vmID, call_id, name);
435
+ console.debug("[machine-starter] starter FFI call", vmID, call_id, name);
400
436
  try {
401
437
  if (!fun) throw new Error("No such starter FFI in groovebox starter: " + name);
402
438
  let connector =
@@ -410,21 +446,21 @@ async function starterFFIsMessageLoop(hub, config, starterFFIs, terminate) {
410
446
  if (r instanceof Promise) {
411
447
  // r.catch(_ => null); // prevent "unhandled rejection"
412
448
  if (initialMask & DEBUG_STATE)
413
- console.debug("[groovebox-starter] running FFI call asynchronously", vmID, call_id, name);
449
+ console.debug("[machine-starter] running FFI call asynchronously", vmID, call_id, name);
414
450
  await comm.later(call_id);
415
451
  let value = await r;
416
452
  if (initialMask & DEBUG_STATE)
417
- console.debug("[groovebox-starter] async FFI call returned", vmID, call_id, name);
453
+ console.debug("[machine-starter] async FFI call returned", vmID, call_id, name);
418
454
  await comm.returnOrFail(fun, call_id, value);
419
455
  } else {
420
456
  if (initialMask & DEBUG_STATE)
421
- console.debug("[groovebox-starter] sync FFI call returned", vmID, call_id, name);
457
+ console.debug("[machine-starter] sync FFI call returned", vmID, call_id, name);
422
458
  await comm.returnOrFail(fun, call_id, r);
423
459
  }
424
460
  } catch (reason) {
425
461
  if (initialMask & DEBUG_STATE) {
426
- console.debug("[groovebox-starter] FFI call exception", vmID, call_id, name);
427
- console.debug("[groovebox-starter] exception", reason);
462
+ console.debug("[machine-starter] FFI call exception", vmID, call_id, name);
463
+ console.debug("[machine-starter] exception", reason);
428
464
  };
429
465
  await comm.error(call_id, reason.message, reason.stack);
430
466
  }
@@ -447,7 +483,7 @@ async function blobsMessageLoop(hub, config, terminate) {
447
483
  sub.next().then((msg) => ({msg})),
448
484
  terminate.then(() => ({terminated: true})),
449
485
  ]);
450
- if (terminated) {
486
+ if (terminated || msg.eof) {
451
487
  // console.log("[machine-starter] terminate blobs loop", vmID);
452
488
  return;
453
489
  }
@@ -517,6 +553,6 @@ class FFIComm {
517
553
  }
518
554
 
519
555
  // use terminateVM to shut a worker down!
520
- export { StartWASM, StartWASM2, terminateAll, terminateVM,
556
+ export { StartWASM, StartWASM2, terminateVM,
521
557
  Token, Case, Opaque
522
558
  }
@@ -1,2 +1,2 @@
1
- var GROOVEBOX_BUILD = "12988";
1
+ var GROOVEBOX_BUILD = "12990";
2
2
  export { GROOVEBOX_BUILD }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@remix_labs/machine-starter",
3
- "version": "2.12988.0-dev",
3
+ "version": "2.12990.0",
4
4
  "description": "start the groove",
5
5
  "main": "node.js",
6
6
  "browser": "index.js",
@@ -11,7 +11,7 @@
11
11
  "author": "Remixlabs staff",
12
12
  "license": "ISC",
13
13
  "dependencies": {
14
- "@remix_labs/hub-client": "2.12988.0-dev",
14
+ "@remix_labs/hub-client": "2.12990.0",
15
15
  "nanoid": "^5.0.2",
16
16
  "web-worker": "^1.2.0"
17
17
  },