@fnndsc/salsa 4.5.7 → 4.6.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.
Files changed (158) hide show
  1. package/README.md +0 -2
  2. package/dist/compute/index.d.ts +0 -9
  3. package/dist/compute/index.js +0 -16
  4. package/dist/compute/index.js.map +1 -1
  5. package/dist/dag/feedData.js +166 -73
  6. package/dist/dag/feedData.js.map +1 -1
  7. package/dist/dag/feedLoad.d.ts +1 -1
  8. package/dist/dag/feedLoad.js +6 -4
  9. package/dist/dag/feedLoad.js.map +1 -1
  10. package/dist/dicom/pixels.js +95 -36
  11. package/dist/dicom/pixels.js.map +1 -1
  12. package/dist/dicom/series.d.ts +4 -1
  13. package/dist/dicom/series.js +80 -31
  14. package/dist/dicom/series.js.map +1 -1
  15. package/dist/dicom/tags.d.ts +28 -0
  16. package/dist/dicom/tags.js +30 -0
  17. package/dist/dicom/tags.js.map +1 -1
  18. package/dist/files/copy.d.ts +197 -0
  19. package/dist/files/copy.js +636 -0
  20. package/dist/files/copy.js.map +1 -0
  21. package/dist/files/copyFolder.d.ts +103 -0
  22. package/dist/files/copyFolder.js +199 -0
  23. package/dist/files/copyFolder.js.map +1 -0
  24. package/dist/files/create.d.ts +178 -0
  25. package/dist/files/create.js +444 -0
  26. package/dist/files/create.js.map +1 -0
  27. package/dist/files/download.d.ts +188 -0
  28. package/dist/files/download.js +541 -0
  29. package/dist/files/download.js.map +1 -0
  30. package/dist/files/index.d.ts +69 -141
  31. package/dist/files/index.js +184 -535
  32. package/dist/files/index.js.map +1 -1
  33. package/dist/files/listing.d.ts +132 -0
  34. package/dist/files/listing.js +179 -0
  35. package/dist/files/listing.js.map +1 -0
  36. package/dist/files/move.d.ts +125 -0
  37. package/dist/files/move.js +334 -0
  38. package/dist/files/move.js.map +1 -0
  39. package/dist/files/pathMapper.d.ts +24 -1
  40. package/dist/files/pathMapper.js +108 -47
  41. package/dist/files/pathMapper.js.map +1 -1
  42. package/dist/files/proof.d.ts +315 -0
  43. package/dist/files/proof.js +574 -0
  44. package/dist/files/proof.js.map +1 -0
  45. package/dist/files/removal.d.ts +223 -0
  46. package/dist/files/removal.js +318 -0
  47. package/dist/files/removal.js.map +1 -0
  48. package/dist/files/replace.d.ts +175 -0
  49. package/dist/files/replace.js +582 -0
  50. package/dist/files/replace.js.map +1 -0
  51. package/dist/files/upload.d.ts +205 -0
  52. package/dist/files/upload.js +478 -0
  53. package/dist/files/upload.js.map +1 -0
  54. package/dist/index.d.ts +14 -2
  55. package/dist/index.js +45 -32
  56. package/dist/index.js.map +1 -1
  57. package/dist/jobs/index.d.ts +1 -1
  58. package/dist/jobs/index.js +1 -2
  59. package/dist/jobs/index.js.map +1 -1
  60. package/dist/jobs/jobOps.d.ts +0 -13
  61. package/dist/jobs/jobOps.js +0 -37
  62. package/dist/jobs/jobOps.js.map +1 -1
  63. package/dist/pacs/anonymise.d.ts +17 -36
  64. package/dist/pacs/anonymise.js +29 -67
  65. package/dist/pacs/anonymise.js.map +1 -1
  66. package/dist/pipelines/index.d.ts +1 -13
  67. package/dist/pipelines/index.js +0 -38
  68. package/dist/pipelines/index.js.map +1 -1
  69. package/dist/pipelines/invocation.js +321 -167
  70. package/dist/pipelines/invocation.js.map +1 -1
  71. package/dist/pipelines/manifest.js.map +1 -1
  72. package/dist/pipelines/packages.d.ts +11 -8
  73. package/dist/pipelines/packages.js +253 -77
  74. package/dist/pipelines/packages.js.map +1 -1
  75. package/dist/plugins/adminToken.d.ts +67 -0
  76. package/dist/plugins/adminToken.js +77 -0
  77. package/dist/plugins/adminToken.js.map +1 -0
  78. package/dist/plugins/index.d.ts +0 -7
  79. package/dist/plugins/index.js +0 -16
  80. package/dist/plugins/index.js.map +1 -1
  81. package/dist/plugins/peer_search.d.ts +0 -15
  82. package/dist/plugins/peer_search.js +0 -25
  83. package/dist/plugins/peer_search.js.map +1 -1
  84. package/dist/plugins/plugin_add.d.ts +14 -2
  85. package/dist/plugins/plugin_add.js +42 -13
  86. package/dist/plugins/plugin_add.js.map +1 -1
  87. package/dist/plugins/plugin_docker.d.ts +25 -0
  88. package/dist/plugins/plugin_docker.js +33 -0
  89. package/dist/plugins/plugin_docker.js.map +1 -1
  90. package/dist/plugins/plugin_register.d.ts +0 -10
  91. package/dist/plugins/plugin_register.js +3 -54
  92. package/dist/plugins/plugin_register.js.map +1 -1
  93. package/dist/plugins/plugin_sync.js +45 -22
  94. package/dist/plugins/plugin_sync.js.map +1 -1
  95. package/dist/plugins/plugin_validate.js +47 -13
  96. package/dist/plugins/plugin_validate.js.map +1 -1
  97. package/dist/plugins/store_import.d.ts +0 -9
  98. package/dist/plugins/store_import.js +3 -29
  99. package/dist/plugins/store_import.js.map +1 -1
  100. package/dist/retrieve/task.d.ts +137 -0
  101. package/dist/retrieve/task.js +41 -0
  102. package/dist/retrieve/task.js.map +1 -0
  103. package/dist/retrieve/watch.d.ts +2 -118
  104. package/dist/retrieve/watch.js +452 -321
  105. package/dist/retrieve/watch.js.map +1 -1
  106. package/dist/vfs/providers/etc.d.ts +6 -4
  107. package/dist/vfs/providers/etc.js +12 -4
  108. package/dist/vfs/providers/etc.js.map +1 -1
  109. package/dist/vfs/providers/native.d.ts +116 -39
  110. package/dist/vfs/providers/native.js +291 -347
  111. package/dist/vfs/providers/native.js.map +1 -1
  112. package/dist/vfs/providers/pacs.d.ts +29 -3
  113. package/dist/vfs/providers/pacs.js +303 -73
  114. package/dist/vfs/providers/pacs.js.map +1 -1
  115. package/dist/vfs/providers/pacs_content.js +22 -6
  116. package/dist/vfs/providers/pacs_content.js.map +1 -1
  117. package/dist/vfs/providers/proc/backfill.d.ts +46 -0
  118. package/dist/vfs/providers/proc/backfill.js +147 -0
  119. package/dist/vfs/providers/proc/backfill.js.map +1 -0
  120. package/dist/vfs/providers/proc/book.d.ts +176 -0
  121. package/dist/vfs/providers/proc/book.js +73 -0
  122. package/dist/vfs/providers/proc/book.js.map +1 -0
  123. package/dist/vfs/providers/proc/catchup.d.ts +69 -0
  124. package/dist/vfs/providers/proc/catchup.js +125 -0
  125. package/dist/vfs/providers/proc/catchup.js.map +1 -0
  126. package/dist/vfs/providers/proc/feedIndex.d.ts +146 -0
  127. package/dist/vfs/providers/proc/feedIndex.js +354 -0
  128. package/dist/vfs/providers/proc/feedIndex.js.map +1 -0
  129. package/dist/vfs/providers/proc/feedTopology.d.ts +85 -0
  130. package/dist/vfs/providers/proc/feedTopology.js +192 -0
  131. package/dist/vfs/providers/proc/feedTopology.js.map +1 -0
  132. package/dist/vfs/providers/proc/locate.d.ts +60 -0
  133. package/dist/vfs/providers/proc/locate.js +103 -0
  134. package/dist/vfs/providers/proc/locate.js.map +1 -0
  135. package/dist/vfs/providers/proc/path.d.ts +50 -0
  136. package/dist/vfs/providers/proc/path.js +106 -0
  137. package/dist/vfs/providers/proc/path.js.map +1 -0
  138. package/dist/vfs/providers/proc/roster.d.ts +95 -0
  139. package/dist/vfs/providers/proc/roster.js +425 -0
  140. package/dist/vfs/providers/proc/roster.js.map +1 -0
  141. package/dist/vfs/providers/proc/rows.d.ts +120 -0
  142. package/dist/vfs/providers/proc/rows.js +181 -0
  143. package/dist/vfs/providers/proc/rows.js.map +1 -0
  144. package/dist/vfs/providers/proc/subtree.d.ts +73 -0
  145. package/dist/vfs/providers/proc/subtree.js +125 -0
  146. package/dist/vfs/providers/proc/subtree.js.map +1 -0
  147. package/dist/vfs/providers/proc/sweep.d.ts +89 -0
  148. package/dist/vfs/providers/proc/sweep.js +297 -0
  149. package/dist/vfs/providers/proc/sweep.js.map +1 -0
  150. package/dist/vfs/providers/proc.d.ts +47 -346
  151. package/dist/vfs/providers/proc.js +349 -1806
  152. package/dist/vfs/providers/proc.js.map +1 -1
  153. package/dist/vfs/providers/share.js +4 -1
  154. package/dist/vfs/providers/share.js.map +1 -1
  155. package/package.json +3 -3
  156. package/dist/pacs/resultDecode.d.ts +0 -13
  157. package/dist/pacs/resultDecode.js +0 -19
  158. package/dist/pacs/resultDecode.js.map +0 -1
@@ -1,10 +1,22 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
2
16
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
18
  };
5
19
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.retrieveTask_make = retrieveTask_make;
7
- exports.retrieveProgress_classify = retrieveProgress_classify;
8
20
  exports.retrieveTasks_skipComplete = retrieveTasks_skipComplete;
9
21
  exports.retrieveTasks_fire = retrieveTasks_fire;
10
22
  exports.retrieve_fireAndWatch = retrieve_fireAndWatch;
@@ -30,6 +42,8 @@ exports.retrieve_confirmLoop = retrieve_confirmLoop;
30
42
  */
31
43
  const ws_1 = __importDefault(require("ws"));
32
44
  const cumin_1 = require("@fnndsc/cumin");
45
+ const task_js_1 = require("./task.js");
46
+ __exportStar(require("./task.js"), exports);
33
47
  /** Concurrent retrieve creations; more overloads CUBE and loses retrieves. */
34
48
  const FIRE_CONCURRENCY = 4;
35
49
  /** Retry attempts for one retrieve creation, with backoff between them. */
@@ -53,42 +67,6 @@ const NO_ACTIVITY_TIMEOUT_MS = 60_000;
53
67
  const ASK_AFTER_MS = 20_000;
54
68
  const SERIES_TIMEOUT_MS = 5 * 60 * 1_000;
55
69
  const CHECKER_INTERVAL_MS = 2_000;
56
- /**
57
- * Builds a fresh retrieve task from series identity facts.
58
- *
59
- * @param info - Label, UIDs, PACS name, and expected file count.
60
- * @returns A pending task ready for {@link retrieve_fireAndWatch}.
61
- */
62
- function retrieveTask_make(info) {
63
- return {
64
- ...info,
65
- syntheticQueryId: null,
66
- retrieveId: null,
67
- status: 'pending',
68
- actualFiles: 0,
69
- lastProgressFiles: 0,
70
- lastProgressTime: Date.now(),
71
- firstFileTime: 0,
72
- startTime: 0,
73
- lonkConfirmed: false,
74
- cubePathDir: null,
75
- };
76
- }
77
- /**
78
- * Classifies a task's state for progress reporting.
79
- *
80
- * @param task - The task to classify.
81
- * @returns The progress status consumers render.
82
- */
83
- function retrieveProgress_classify(task) {
84
- if (task.status === 'pulled')
85
- return task.lonkConfirmed ? 'done' : 'unconfirmed';
86
- if (task.status === 'pending' || task.status === 'pulling')
87
- return 'running';
88
- if (task.status === 'unfired')
89
- return 'error';
90
- return task.status;
91
- }
92
70
  /**
93
71
  * Marks tasks whose series are already fully registered in CUBE as pulled,
94
72
  * so firing skips them. This is what makes a retrieve idempotent: re-running
@@ -193,6 +171,349 @@ function lonkWsUrl_build(tokenUrl, token) {
193
171
  .replace(/^http(s?):\/\//, (_m, s) => `ws${s}://`)
194
172
  .replace(/v1\/downloadtokens\/\d+\//, `v1/pacs/ws/?token=${token}`);
195
173
  }
174
+ /**
175
+ * Opens a LONK socket and subscribes it to the series given.
176
+ *
177
+ * A reconnect subscribes only what is still in flight: the retrieves are
178
+ * already running on the server, so re-firing them would duplicate work that
179
+ * was never lost.
180
+ *
181
+ * @param lonkUrl - The LONK WebSocket URL.
182
+ * @param subscribe - The series to subscribe.
183
+ * @returns The open socket.
184
+ */
185
+ async function lonkSocket_open(lonkUrl, subscribe) {
186
+ const socket = new ws_1.default(lonkUrl);
187
+ await new Promise((openResolve, openReject) => {
188
+ socket.once('open', openResolve);
189
+ socket.once('error', (err) => openReject(err));
190
+ });
191
+ for (const t of subscribe) {
192
+ socket.send(JSON.stringify({ SeriesInstanceUID: t.seriesUID, pacs_name: t.pacsName, action: 'subscribe' }));
193
+ }
194
+ return socket;
195
+ }
196
+ /**
197
+ * Whether a task's retrieve is over, one way or another.
198
+ *
199
+ * @param t - The task.
200
+ * @returns True when it reached a terminal state.
201
+ */
202
+ function task_isSettled(t) {
203
+ return t.status === 'pulled' || t.status === 'error' || t.status === 'unfired' || t.status === 'stalled' || t.status === 'timeout' || t.status === 'unconfirmed';
204
+ }
205
+ /**
206
+ * One watch over a set of fired series: its LONK socket (replaced when it
207
+ * dies, up to a budget), when it last saw life from the PACS, whether the
208
+ * operator is being asked, and the checker that judges the series. It
209
+ * settles once every fired series is terminal, or once it stops looking.
210
+ */
211
+ class LonkWatch {
212
+ fired;
213
+ lonkUrl;
214
+ events;
215
+ emit;
216
+ /** The socket the watch listens on now. */
217
+ ws;
218
+ /** Whether the watch has ended. */
219
+ resolved = false;
220
+ /** How many more times a dead socket is replaced. */
221
+ reconnectsLeft = WATCH_RECONNECT_ATTEMPTS;
222
+ /**
223
+ * When this watch last saw life from the PACS, on ANY of its series.
224
+ * Quiet is a property of the watch, not of each series: a PACS busy
225
+ * sending the first series has not gone silent on the ten queued behind
226
+ * it, and they cannot report files they have not been sent yet.
227
+ */
228
+ lastActivityAt = 0;
229
+ /**
230
+ * When the PACS last sent anything. A yes to "keep waiting?" restarts the
231
+ * clock above, which times the next question; it does not make the PACS
232
+ * any less silent, and this is the silence the question says.
233
+ */
234
+ quietSince = 0;
235
+ /** While the operator is being asked, the silence rule holds its tongue. */
236
+ asking = false;
237
+ /** The checker's timer, while the watch runs. */
238
+ checker = null;
239
+ /** Settles the watch's promise. */
240
+ watch_settle = () => undefined;
241
+ /** Every task, by series. */
242
+ taskByUID;
243
+ /**
244
+ * @param socket - The socket already open and subscribed.
245
+ * @param tasks - Every task, fired or not.
246
+ * @param fired - The tasks whose retrieve was fired.
247
+ * @param lonkUrl - The LONK URL, for a replacement socket.
248
+ * @param events - Progress callbacks.
249
+ * @param emit - Tells a surface how a task stands.
250
+ */
251
+ constructor(socket, tasks, fired, lonkUrl, events, emit) {
252
+ this.fired = fired;
253
+ this.lonkUrl = lonkUrl;
254
+ this.events = events;
255
+ this.emit = emit;
256
+ this.ws = socket;
257
+ this.taskByUID = new Map(tasks.map((t) => [t.seriesUID, t]));
258
+ }
259
+ /**
260
+ * Watches until every fired series is terminal, or the watch stops looking.
261
+ *
262
+ * @returns Once the watch has ended.
263
+ */
264
+ watch_run() {
265
+ return new Promise((resolve) => {
266
+ this.watch_settle = resolve;
267
+ this.lastActivityAt = Date.now();
268
+ this.quietSince = this.lastActivityAt;
269
+ this.checker = setInterval(() => { this.checker_tick(); }, CHECKER_INTERVAL_MS);
270
+ this.socket_listen();
271
+ });
272
+ }
273
+ /** Ends the watch: the checker stops, the socket closes, the promise settles. */
274
+ watch_end() {
275
+ if (this.resolved)
276
+ return;
277
+ this.resolved = true;
278
+ if (this.checker !== null)
279
+ clearInterval(this.checker);
280
+ try {
281
+ this.ws.close();
282
+ }
283
+ catch { /* best-effort socket cleanup */ }
284
+ this.watch_settle();
285
+ }
286
+ /**
287
+ * The series this watch is still waiting on.
288
+ *
289
+ * @returns The fired tasks pending or pulling.
290
+ */
291
+ inFlight_list() {
292
+ return this.fired.filter((t) => t.status === 'pending' || t.status === 'pulling');
293
+ }
294
+ /**
295
+ * Replaces a dead socket, or gives up and records what is unknown.
296
+ *
297
+ * A LONK socket carries no state a client cannot rebuild: the retrieves run
298
+ * on the server regardless, and a fresh subscription resumes reporting on
299
+ * them. Only when reconnection is exhausted does the watch admit it stopped
300
+ * looking — and even then it says so rather than calling the retrieves
301
+ * failed.
302
+ */
303
+ socket_replace() {
304
+ if (this.resolved)
305
+ return;
306
+ const remaining = this.inFlight_list();
307
+ if (remaining.length === 0) {
308
+ this.watch_end();
309
+ return;
310
+ }
311
+ if (this.reconnectsLeft <= 0) {
312
+ for (const t of remaining) {
313
+ t.status = 'unconfirmed';
314
+ t.endCause = 'watchLost';
315
+ this.emit(t, 'unconfirmed');
316
+ }
317
+ this.watch_end();
318
+ return;
319
+ }
320
+ this.reconnectsLeft -= 1;
321
+ this.events.reconnect?.(WATCH_RECONNECT_ATTEMPTS - this.reconnectsLeft, WATCH_RECONNECT_ATTEMPTS, remaining.length);
322
+ void lonkSocket_open(this.lonkUrl, remaining)
323
+ .then((replacement) => {
324
+ if (this.resolved) {
325
+ try {
326
+ replacement.close();
327
+ }
328
+ catch { /* the watch already ended */ }
329
+ return;
330
+ }
331
+ this.ws = replacement;
332
+ // A reconnection is a new view, not new silence: charging the
333
+ // gap to the PACS would declare the study dead on reconnect.
334
+ this.lastActivityAt = Date.now();
335
+ this.quietSince = this.lastActivityAt;
336
+ this.socket_listen();
337
+ })
338
+ .catch(() => { this.socket_replace(); });
339
+ }
340
+ /** One pass of the checker: judges every series still open, ends the watch when none is, else may ask. */
341
+ checker_tick() {
342
+ const now = Date.now();
343
+ let allTerminal = true;
344
+ for (const t of this.fired) {
345
+ if (task_isSettled(t))
346
+ continue;
347
+ allTerminal = false;
348
+ this.task_judge(t, now);
349
+ }
350
+ if (allTerminal) {
351
+ this.watch_end();
352
+ return;
353
+ }
354
+ this.silence_ask(now);
355
+ }
356
+ /**
357
+ * Judges one open series by its own evidence and the watch's silence.
358
+ *
359
+ * @param t - The series.
360
+ * @param now - The checker's clock.
361
+ */
362
+ task_judge(t, now) {
363
+ // A series that began and then stopped is stalled on its own
364
+ // evidence: it was being sent, and it no longer is.
365
+ if (t.actualFiles > 0 && now - t.lastProgressTime > STALL_TIMEOUT_MS) {
366
+ t.status = 'stalled';
367
+ this.emit(t, 'stalled');
368
+ return;
369
+ }
370
+ // The long stop: a series that trickles and never ends. Counted
371
+ // from its first file, never from the fire, so waiting a turn in a
372
+ // large study costs a series nothing.
373
+ if (t.firstFileTime > 0 && now - t.firstFileTime > SERIES_TIMEOUT_MS) {
374
+ t.status = 'timeout';
375
+ this.emit(t, 'timeout');
376
+ return;
377
+ }
378
+ // Nothing has arrived for this series. That is evidence of a lost
379
+ // retrieve only when nothing has arrived for ANY of them. Charged
380
+ // per series from its own fire time, this declared every series
381
+ // after the first few dead fifteen seconds into any study large
382
+ // enough that the PACS served them in turn.
383
+ if (this.events.stillWaiting === undefined && t.startTime > 0 && t.actualFiles === 0 && now - this.lastActivityAt > NO_ACTIVITY_TIMEOUT_MS) {
384
+ t.status = 'pulled';
385
+ t.lonkConfirmed = false;
386
+ t.endCause = 'pacsSilent';
387
+ this.emit(t, 'unconfirmed');
388
+ }
389
+ }
390
+ /**
391
+ * With someone to ask: after a short silence, CUBE first (a series may
392
+ * have landed unseen), then the operator decides whether to keep waiting
393
+ * for the rest.
394
+ *
395
+ * @param now - The checker's clock.
396
+ */
397
+ silence_ask(now) {
398
+ const question_ask = this.events.stillWaiting;
399
+ if (question_ask === undefined || this.asking || now - this.lastActivityAt <= ASK_AFTER_MS)
400
+ return;
401
+ const silent = this.fired.filter((t) => t.status === 'pending' && t.startTime > 0 && t.actualFiles === 0);
402
+ if (silent.length === 0)
403
+ return;
404
+ this.asking = true;
405
+ void this.silence_question(silent, question_ask);
406
+ }
407
+ /**
408
+ * Asks CUBE whether the silent series landed, then the operator whether
409
+ * to keep waiting for those that did not; a no ends them unconfirmed.
410
+ *
411
+ * @param silent - The series the PACS has sent nothing of.
412
+ * @param ask - The operator's question.
413
+ */
414
+ async silence_question(silent, ask) {
415
+ const silenceStart = this.lastActivityAt;
416
+ await Promise.all(silent.map(async (t) => {
417
+ const stateResult = await (0, cumin_1.seriesStorage_resolve)(t.seriesUID);
418
+ if (stateResult.ok && stateResult.value.folderPath !== null && t.status === 'pending') {
419
+ t.status = 'pulled';
420
+ t.lonkConfirmed = true;
421
+ t.cubePathDir = stateResult.value.folderPath;
422
+ t.actualFiles = stateResult.value.fileCount;
423
+ this.emit(t, 'done');
424
+ }
425
+ }));
426
+ const waiting = silent.filter((t) => t.status === 'pending');
427
+ // Files arrived while CUBE was asked: the question is moot.
428
+ if (waiting.length === 0 || this.lastActivityAt !== silenceStart || this.resolved) {
429
+ this.asking = false;
430
+ return;
431
+ }
432
+ const keep = await ask(waiting, Math.round((Date.now() - this.quietSince) / 1000)).catch(() => false);
433
+ if (this.resolved)
434
+ return;
435
+ if (keep || this.lastActivityAt !== silenceStart) {
436
+ this.lastActivityAt = Date.now();
437
+ }
438
+ else {
439
+ for (const t of waiting) {
440
+ if (t.status !== 'pending')
441
+ continue;
442
+ t.status = 'unconfirmed';
443
+ t.reason = 'stopped waiting: the PACS had sent nothing and CUBE had none of it';
444
+ t.endCause = 'pacsSilent';
445
+ this.emit(t, 'unconfirmed');
446
+ }
447
+ }
448
+ this.asking = false;
449
+ }
450
+ /**
451
+ * Applies one LONK frame to its series: a file count, the end, or the
452
+ * receiver's error. Any frame from the PACS is life on the watch.
453
+ *
454
+ * @param data - The frame.
455
+ */
456
+ frame_apply(data) {
457
+ try {
458
+ const outer = JSON.parse(data.toString());
459
+ const seriesUID = outer.SeriesInstanceUID;
460
+ const message = outer.message;
461
+ if (!seriesUID || !message)
462
+ return;
463
+ const t = this.taskByUID.get(seriesUID);
464
+ if (!t)
465
+ return;
466
+ this.lastActivityAt = Date.now();
467
+ this.quietSince = this.lastActivityAt;
468
+ this.taskMessage_apply(t, message);
469
+ }
470
+ catch {
471
+ // Deliberate absorption: a malformed LONK frame carries no correlation
472
+ // to fail; the checker's stall/timeout guards still bound the watch.
473
+ }
474
+ }
475
+ /**
476
+ * Applies one LONK message to its series: a file count, the end, or the
477
+ * receiver's error; a message that says none of these changes nothing.
478
+ *
479
+ * @param t - The series the frame named.
480
+ * @param message - The frame's message.
481
+ */
482
+ taskMessage_apply(t, message) {
483
+ if ('ndicom' in message && typeof message.ndicom === 'number') {
484
+ const n = message.ndicom;
485
+ t.actualFiles = n;
486
+ t.lastProgressFiles = n;
487
+ t.lastProgressTime = Date.now();
488
+ if (t.firstFileTime === 0 && n > 0)
489
+ t.firstFileTime = t.lastProgressTime;
490
+ if (t.status === 'pending')
491
+ t.status = 'pulling';
492
+ this.emit(t, 'running');
493
+ }
494
+ else if ('done' in message && message.done === true) {
495
+ t.status = 'pulled';
496
+ t.lonkConfirmed = true;
497
+ if (t.actualFiles < t.expectedFiles)
498
+ t.actualFiles = t.expectedFiles;
499
+ this.emit(t, 'done');
500
+ }
501
+ else if ('error' in message && typeof message.error === 'string') {
502
+ t.status = 'error';
503
+ t.reason = `the receiver could not store a file: ${message.error}`;
504
+ this.emit(t, 'error');
505
+ }
506
+ }
507
+ /** Attaches this watch's handlers to whichever socket is current. */
508
+ socket_listen() {
509
+ this.ws.on('message', (data) => { this.frame_apply(data); });
510
+ // A dead socket is a lost view, not a lost retrieve: reconnect and keep
511
+ // watching. Only when that fails repeatedly does the watch stop, and even
512
+ // then it records what it no longer knows rather than declaring failure.
513
+ this.ws.on('error', () => { this.socket_replace(); });
514
+ this.ws.on('close', () => { this.socket_replace(); });
515
+ }
516
+ }
196
517
  /**
197
518
  * Opens a LONK WebSocket, fires retrieves for the tasks, and blocks until
198
519
  * every task reaches a terminal state. Mutates each task's status,
@@ -206,258 +527,109 @@ function lonkWsUrl_build(tokenUrl, token) {
206
527
  * @returns Number of tasks whose retrieve could not be fired.
207
528
  */
208
529
  async function retrieve_fireAndWatch(tasks, pacsserver, client, events = {}, phase = 'watching') {
209
- const emit = (task, status) => {
210
- events.task?.(task, status ?? retrieveProgress_classify(task), phase);
530
+ const task_emit = (task, status) => {
531
+ events.task?.(task, status ?? (0, task_js_1.retrieveProgress_classify)(task), phase);
211
532
  };
212
533
  const downloadToken = await (0, cumin_1.downloadToken_create)(client);
213
534
  const lonkUrl = lonkWsUrl_build(downloadToken.url, downloadToken.token);
214
- /**
215
- * Opens a LONK socket and subscribes it to the series given.
216
- *
217
- * A reconnect subscribes only what is still in flight: the retrieves are
218
- * already running on the server, so re-firing them would duplicate work that
219
- * was never lost.
220
- */
221
- const socket_open = async (subscribe) => {
222
- const socket = new ws_1.default(lonkUrl);
223
- await new Promise((openResolve, openReject) => {
224
- socket.once('open', openResolve);
225
- socket.once('error', (err) => openReject(err));
226
- });
227
- for (const t of subscribe) {
228
- socket.send(JSON.stringify({ SeriesInstanceUID: t.seriesUID, pacs_name: t.pacsName, action: 'subscribe' }));
229
- }
230
- return socket;
231
- };
232
- let ws = await socket_open(tasks);
535
+ const ws = await lonkSocket_open(lonkUrl, tasks);
233
536
  await tasks_fireBounded(tasks, pacsserver);
234
537
  const fired = tasks.filter((t) => t.status !== 'unfired');
235
538
  const firingErrors = tasks.length - fired.length;
236
539
  if (fired.length === 0) {
237
540
  for (const t of tasks) {
238
541
  if (t.status === 'unfired')
239
- emit(t, 'error');
542
+ task_emit(t, 'error');
240
543
  }
241
544
  ws.close();
242
545
  return firingErrors;
243
546
  }
244
547
  for (const t of tasks) {
245
- emit(t, t.status === 'unfired' ? 'error' : 'running');
548
+ task_emit(t, t.status === 'unfired' ? 'error' : 'running');
246
549
  }
247
- const taskByUID = new Map(tasks.map((t) => [t.seriesUID, t]));
248
- await new Promise((resolve) => {
249
- let resolved = false;
250
- let reconnectsLeft = WATCH_RECONNECT_ATTEMPTS;
251
- // When this watch last saw life from the PACS, on ANY of its series.
252
- // Quiet is a property of the watch, not of each series: a PACS busy
253
- // sending the first series has not gone silent on the ten queued
254
- // behind it, and they cannot report files they have not been sent yet.
255
- let lastActivityAt = Date.now();
256
- // When the PACS last sent anything. A yes to "keep waiting?" restarts
257
- // the clock above, which times the next question; it does not make
258
- // the PACS any less silent, and this is the silence the question says.
259
- let quietSince = lastActivityAt;
260
- // While the operator is being asked, the silence rule holds its tongue.
261
- let asking = false;
262
- const done = () => {
263
- if (resolved)
264
- return;
265
- resolved = true;
266
- clearInterval(checker);
267
- try {
268
- ws.close();
269
- }
270
- catch { /* best-effort socket cleanup */ }
271
- resolve();
272
- };
273
- /** The series this watch is still waiting on. */
274
- const inFlight = () => fired.filter((t) => t.status === 'pending' || t.status === 'pulling');
275
- /**
276
- * Replaces a dead socket, or gives up and records what is unknown.
277
- *
278
- * A LONK socket carries no state a client cannot rebuild: the retrieves run
279
- * on the server regardless, and a fresh subscription resumes reporting on
280
- * them. Only when reconnection is exhausted does the watch admit it stopped
281
- * looking — and even then it says so rather than calling the retrieves
282
- * failed.
283
- */
284
- const socket_replace = () => {
285
- if (resolved)
286
- return;
287
- const remaining = inFlight();
288
- if (remaining.length === 0) {
289
- done();
290
- return;
291
- }
292
- if (reconnectsLeft <= 0) {
293
- for (const t of remaining) {
294
- t.status = 'unconfirmed';
295
- t.endCause = 'watchLost';
296
- emit(t, 'unconfirmed');
297
- }
298
- done();
299
- return;
300
- }
301
- reconnectsLeft -= 1;
302
- events.reconnect?.(WATCH_RECONNECT_ATTEMPTS - reconnectsLeft, WATCH_RECONNECT_ATTEMPTS, remaining.length);
303
- void socket_open(remaining)
304
- .then((replacement) => {
305
- if (resolved) {
306
- try {
307
- replacement.close();
308
- }
309
- catch { /* the watch already ended */ }
310
- return;
311
- }
312
- ws = replacement;
313
- // A reconnection is a new view, not new silence: charging the
314
- // gap to the PACS would declare the study dead on reconnect.
315
- lastActivityAt = Date.now();
316
- quietSince = lastActivityAt;
317
- socket_listen();
318
- })
319
- .catch(() => socket_replace());
320
- };
321
- const checker = setInterval(() => {
322
- const now = Date.now();
323
- let allTerminal = true;
324
- for (const t of fired) {
325
- if (t.status === 'pulled' || t.status === 'error' || t.status === 'unfired' || t.status === 'stalled' || t.status === 'timeout' || t.status === 'unconfirmed') {
326
- continue;
327
- }
328
- allTerminal = false;
329
- // A series that began and then stopped is stalled on its own
330
- // evidence: it was being sent, and it no longer is.
331
- if (t.actualFiles > 0 && now - t.lastProgressTime > STALL_TIMEOUT_MS) {
332
- t.status = 'stalled';
333
- emit(t, 'stalled');
334
- continue;
335
- }
336
- // The long stop: a series that trickles and never ends. Counted
337
- // from its first file, never from the fire, so waiting a turn in a
338
- // large study costs a series nothing.
339
- if (t.firstFileTime > 0 && now - t.firstFileTime > SERIES_TIMEOUT_MS) {
340
- t.status = 'timeout';
341
- emit(t, 'timeout');
342
- continue;
343
- }
344
- // Nothing has arrived for this series. That is evidence of a lost
345
- // retrieve only when nothing has arrived for ANY of them. Charged
346
- // per series from its own fire time, this declared every series
347
- // after the first few dead fifteen seconds into any study large
348
- // enough that the PACS served them in turn.
349
- if (events.stillWaiting === undefined && t.startTime > 0 && t.actualFiles === 0 && now - lastActivityAt > NO_ACTIVITY_TIMEOUT_MS) {
350
- t.status = 'pulled';
351
- t.lonkConfirmed = false;
352
- t.endCause = 'pacsSilent';
353
- emit(t, 'unconfirmed');
354
- continue;
355
- }
356
- }
357
- if (allTerminal) {
358
- done();
359
- return;
360
- }
361
- // With someone to ask: after a short silence, CUBE first (a series
362
- // may have landed unseen), then the operator decides whether to keep
363
- // waiting for the rest.
364
- const ask = events.stillWaiting;
365
- if (ask !== undefined && !asking && now - lastActivityAt > ASK_AFTER_MS) {
366
- const silent = fired.filter((t) => t.status === 'pending' && t.startTime > 0 && t.actualFiles === 0);
367
- if (silent.length === 0)
368
- return;
369
- asking = true;
370
- const silenceStart = lastActivityAt;
371
- void (async () => {
372
- await Promise.all(silent.map(async (t) => {
373
- const stateResult = await (0, cumin_1.seriesStorage_resolve)(t.seriesUID);
374
- if (stateResult.ok && stateResult.value.folderPath !== null && t.status === 'pending') {
375
- t.status = 'pulled';
376
- t.lonkConfirmed = true;
377
- t.cubePathDir = stateResult.value.folderPath;
378
- t.actualFiles = stateResult.value.fileCount;
379
- emit(t, 'done');
380
- }
381
- }));
382
- const waiting = silent.filter((t) => t.status === 'pending');
383
- // Files arrived while CUBE was asked: the question is moot.
384
- if (waiting.length === 0 || lastActivityAt !== silenceStart || resolved) {
385
- asking = false;
386
- return;
387
- }
388
- const keep = await ask(waiting, Math.round((Date.now() - quietSince) / 1000)).catch(() => false);
389
- if (resolved)
390
- return;
391
- if (keep || lastActivityAt !== silenceStart) {
392
- lastActivityAt = Date.now();
393
- }
394
- else {
395
- for (const t of waiting) {
396
- if (t.status !== 'pending')
397
- continue;
398
- t.status = 'unconfirmed';
399
- t.reason = 'stopped waiting: the PACS had sent nothing and CUBE had none of it';
400
- t.endCause = 'pacsSilent';
401
- emit(t, 'unconfirmed');
402
- }
403
- }
404
- asking = false;
405
- })();
406
- }
407
- }, CHECKER_INTERVAL_MS);
408
- /** Attaches this watch's handlers to whichever socket is current. */
409
- const socket_listen = () => {
410
- ws.on('message', (data) => {
411
- try {
412
- const outer = JSON.parse(data.toString());
413
- const seriesUID = outer.SeriesInstanceUID;
414
- const message = outer.message;
415
- if (!seriesUID || !message)
416
- return;
417
- const t = taskByUID.get(seriesUID);
418
- if (!t)
419
- return;
420
- lastActivityAt = Date.now();
421
- quietSince = lastActivityAt;
422
- if ('ndicom' in message && typeof message.ndicom === 'number') {
423
- const n = message.ndicom;
424
- t.actualFiles = n;
425
- t.lastProgressFiles = n;
426
- t.lastProgressTime = Date.now();
427
- if (t.firstFileTime === 0 && n > 0)
428
- t.firstFileTime = t.lastProgressTime;
429
- if (t.status === 'pending')
430
- t.status = 'pulling';
431
- emit(t, 'running');
432
- }
433
- else if ('done' in message && message.done === true) {
434
- t.status = 'pulled';
435
- t.lonkConfirmed = true;
436
- if (t.actualFiles < t.expectedFiles)
437
- t.actualFiles = t.expectedFiles;
438
- emit(t, 'done');
439
- }
440
- else if ('error' in message && typeof message.error === 'string') {
441
- t.status = 'error';
442
- t.reason = `the receiver could not store a file: ${message.error}`;
443
- emit(t, 'error');
444
- }
445
- }
446
- catch {
447
- // Deliberate absorption: a malformed LONK frame carries no correlation
448
- // to fail; the checker's stall/timeout guards still bound the watch.
449
- }
450
- });
451
- // A dead socket is a lost view, not a lost retrieve: reconnect and keep
452
- // watching. Only when that fails repeatedly does the watch stop, and even
453
- // then it records what it no longer knows rather than declaring failure.
454
- ws.on('error', () => { socket_replace(); });
455
- ws.on('close', () => { socket_replace(); });
456
- };
457
- socket_listen();
458
- });
550
+ await new LonkWatch(ws, tasks, fired, lonkUrl, events, task_emit).watch_run();
459
551
  return firingErrors;
460
552
  }
553
+ /**
554
+ * Whether the watch did not see a series end: it ended pulled without a
555
+ * confirmation, or unconfirmed. Both are "we did not see the end", and CUBE
556
+ * is the only thing that knows.
557
+ *
558
+ * @param t - The series.
559
+ * @returns True when CUBE must be asked about it.
560
+ */
561
+ function task_isUnseen(t) {
562
+ return (t.status === 'pulled' && !t.lonkConfirmed) || t.status === 'unconfirmed';
563
+ }
564
+ /**
565
+ * Asks CUBE about each candidate; a series found there arrived, whatever
566
+ * the watch managed to see.
567
+ *
568
+ * @param tasks - The series to ask about (mutated when found).
569
+ * @param events - Progress callbacks.
570
+ */
571
+ async function retrieveStorage_ask(tasks, events) {
572
+ await Promise.all(tasks.map(async (t) => {
573
+ const stateResult = await (0, cumin_1.seriesStorage_resolve)(t.seriesUID);
574
+ if (stateResult.ok && stateResult.value.folderPath !== null) {
575
+ t.lonkConfirmed = true;
576
+ t.cubePathDir = stateResult.value.folderPath;
577
+ // A series found in CUBE arrived, whatever the watch managed to see.
578
+ t.status = 'pulled';
579
+ t.actualFiles = stateResult.value.fileCount;
580
+ events.task?.(t, 'done', 'retrying');
581
+ }
582
+ }));
583
+ }
584
+ /**
585
+ * Sets a series back to pending for a refire, with nothing of its last
586
+ * watch left on it, and says so.
587
+ *
588
+ * @param t - The series (mutated).
589
+ * @param events - Progress callbacks.
590
+ */
591
+ function retryTask_reset(t, events) {
592
+ t.status = 'pending';
593
+ t.actualFiles = 0;
594
+ t.lastProgressFiles = 0;
595
+ t.lastProgressTime = Date.now();
596
+ t.firstFileTime = 0;
597
+ t.startTime = 0;
598
+ t.lonkConfirmed = false;
599
+ t.syntheticQueryId = null;
600
+ t.retrieveId = null;
601
+ delete t.endCause;
602
+ events.task?.(t, 'running', 'retrying');
603
+ }
604
+ /**
605
+ * Ends a series CUBE still does not have after the confirm loop: an error
606
+ * when it was fired again, else unconfirmed with its cause and reason.
607
+ *
608
+ * @param t - The series (mutated).
609
+ * @param refired - Whether any refire round ran.
610
+ * @param retryMax - The refire rounds allowed, for the words.
611
+ * @param silent - The series the PACS sent nothing of.
612
+ * @param events - Progress callbacks.
613
+ */
614
+ function retryTask_end(t, refired, retryMax, silent, events) {
615
+ if (refired) {
616
+ // Fired again and still nowhere in CUBE: that is a failure observed.
617
+ t.status = 'error';
618
+ delete t.endCause;
619
+ t.reason = `nothing reached CUBE after ${retryMax} more ${retryMax === 1 ? 'try' : 'tries'}`;
620
+ events.task?.(t, 'error', 'retrying');
621
+ }
622
+ else {
623
+ // Not seen to finish and not in CUBE yet: unknown, not failed. A
624
+ // PACS slow to begin keeps sending after the watch ends.
625
+ t.status = 'unconfirmed';
626
+ t.endCause ??= silent.has(t) ? 'pacsSilent' : 'watchLost';
627
+ t.reason ??= silent.has(t)
628
+ ? `the PACS sent nothing for ${NO_ACTIVITY_TIMEOUT_MS / 1_000} s and CUBE has none of it`
629
+ : 'the watch ended before any file arrived; the PACS may still be sending (check with pacs status)';
630
+ events.task?.(t, 'unconfirmed', 'retrying');
631
+ }
632
+ }
461
633
  /**
462
634
  * Confirms unconfirmed series against CUBE storage and refires the rest, up
463
635
  * to `retryMax` rounds; series still unconfirmed afterwards are marked
@@ -474,72 +646,31 @@ async function retrieve_fireAndWatch(tasks, pacsserver, client, events = {}, pha
474
646
  async function retrieve_confirmLoop(allTasks, retryMax, pacsserver, client, events = {}) {
475
647
  let extraFiringErrors = 0;
476
648
  // A series the watch lost sight of is a candidate for exactly the same
477
- // treatment as one whose confirmation went missing: ask CUBE. Both are
478
- // "we did not see the end", and CUBE is the only thing that knows.
479
- let retryCandidates = allTasks.filter((t) => (t.status === 'pulled' && !t.lonkConfirmed) || t.status === 'unconfirmed');
649
+ // treatment as one whose confirmation went missing: ask CUBE.
650
+ let retryCandidates = allTasks.filter(task_isUnseen);
480
651
  // The series the watch gave up on because the PACS sent nothing at all,
481
652
  // as distinct from the ones it lost sight of: each ends differently in
482
653
  // words.
483
654
  const silent = new Set(retryCandidates.filter((t) => t.status === 'pulled' && t.actualFiles === 0));
484
- /** Asks CUBE about each candidate; a series found there arrived. */
485
- const storage_ask = async (tasks) => {
486
- await Promise.all(tasks.map(async (t) => {
487
- const stateResult = await (0, cumin_1.seriesStorage_resolve)(t.seriesUID);
488
- if (stateResult.ok && stateResult.value.folderPath !== null) {
489
- t.lonkConfirmed = true;
490
- t.cubePathDir = stateResult.value.folderPath;
491
- // A series found in CUBE arrived, whatever the watch managed to see.
492
- t.status = 'pulled';
493
- t.actualFiles = stateResult.value.fileCount;
494
- events.task?.(t, 'done', 'retrying');
495
- }
496
- }));
497
- };
498
655
  // CUBE is asked at least once, whatever the retry count: with no retries
499
656
  // the loop below never ran, and every series the watch had not seen
500
657
  // finish was declared an error unasked, while its files were landing.
501
- await storage_ask(retryCandidates);
658
+ await retrieveStorage_ask(retryCandidates, events);
502
659
  retryCandidates = retryCandidates.filter((t) => !t.lonkConfirmed);
503
660
  let refired = false;
504
661
  for (let attempt = 1; attempt <= retryMax && retryCandidates.length > 0; attempt++) {
505
662
  events.retryRound?.(attempt, retryMax, retryCandidates.length);
506
663
  refired = true;
507
664
  for (const t of retryCandidates) {
508
- t.status = 'pending';
509
- t.actualFiles = 0;
510
- t.lastProgressFiles = 0;
511
- t.lastProgressTime = Date.now();
512
- t.firstFileTime = 0;
513
- t.startTime = 0;
514
- t.lonkConfirmed = false;
515
- t.syntheticQueryId = null;
516
- t.retrieveId = null;
517
- delete t.endCause;
518
- events.task?.(t, 'running', 'retrying');
665
+ retryTask_reset(t, events);
519
666
  }
520
667
  extraFiringErrors += await retrieve_fireAndWatch(retryCandidates, pacsserver, client, events, 'retrying');
521
- retryCandidates = retryCandidates.filter((t) => (t.status === 'pulled' && !t.lonkConfirmed) || t.status === 'unconfirmed');
522
- await storage_ask(retryCandidates);
668
+ retryCandidates = retryCandidates.filter(task_isUnseen);
669
+ await retrieveStorage_ask(retryCandidates, events);
523
670
  retryCandidates = retryCandidates.filter((t) => !t.lonkConfirmed);
524
671
  }
525
672
  for (const t of retryCandidates) {
526
- if (refired) {
527
- // Fired again and still nowhere in CUBE: that is a failure observed.
528
- t.status = 'error';
529
- delete t.endCause;
530
- t.reason = `nothing reached CUBE after ${retryMax} more ${retryMax === 1 ? 'try' : 'tries'}`;
531
- events.task?.(t, 'error', 'retrying');
532
- }
533
- else {
534
- // Not seen to finish and not in CUBE yet: unknown, not failed. A
535
- // PACS slow to begin keeps sending after the watch ends.
536
- t.status = 'unconfirmed';
537
- t.endCause ??= silent.has(t) ? 'pacsSilent' : 'watchLost';
538
- t.reason ??= silent.has(t)
539
- ? `the PACS sent nothing for ${NO_ACTIVITY_TIMEOUT_MS / 1_000} s and CUBE has none of it`
540
- : 'the watch ended before any file arrived; the PACS may still be sending (check with pacs status)';
541
- events.task?.(t, 'unconfirmed', 'retrying');
542
- }
673
+ retryTask_end(t, refired, retryMax, silent, events);
543
674
  }
544
675
  return extraFiringErrors;
545
676
  }