@fnndsc/cumin 3.30.6 → 3.31.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 (161) hide show
  1. package/dist/cache/checkpointWatch.d.ts +36 -0
  2. package/dist/cache/checkpointWatch.js +83 -0
  3. package/dist/cache/checkpointWatch.js.map +1 -0
  4. package/dist/cache/index.d.ts +1 -1
  5. package/dist/cache/index.js +4 -1
  6. package/dist/cache/index.js.map +1 -1
  7. package/dist/cache/listCache.d.ts +54 -2
  8. package/dist/cache/listCache.js +120 -24
  9. package/dist/cache/listCache.js.map +1 -1
  10. package/dist/cache/listCheckpoint.d.ts +5 -8
  11. package/dist/cache/listCheckpoint.js +17 -28
  12. package/dist/cache/listCheckpoint.js.map +1 -1
  13. package/dist/cache/listingInvalidation.js +11 -6
  14. package/dist/cache/listingInvalidation.js.map +1 -1
  15. package/dist/cache/procCache.d.ts +11 -0
  16. package/dist/cache/procCache.js +26 -1
  17. package/dist/cache/procCache.js.map +1 -1
  18. package/dist/cache/procCheckpoint.d.ts +11 -6
  19. package/dist/cache/procCheckpoint.js +280 -86
  20. package/dist/cache/procCheckpoint.js.map +1 -1
  21. package/dist/cache/queryIndex.d.ts +11 -0
  22. package/dist/cache/queryIndex.js +38 -2
  23. package/dist/cache/queryIndex.js.map +1 -1
  24. package/dist/cache/queryIndexCheckpoint.d.ts +32 -0
  25. package/dist/cache/queryIndexCheckpoint.js +180 -30
  26. package/dist/cache/queryIndexCheckpoint.js.map +1 -1
  27. package/dist/chrisapi/adapter.d.ts +266 -37
  28. package/dist/chrisapi/adapter.js +577 -116
  29. package/dist/chrisapi/adapter.js.map +1 -1
  30. package/dist/chrisapi/contract.d.ts +20 -20
  31. package/dist/chrisapi/contract.js +213 -60
  32. package/dist/chrisapi/contract.js.map +1 -1
  33. package/dist/chrisapi/cubeRequest.d.ts +198 -0
  34. package/dist/chrisapi/cubeRequest.js +345 -0
  35. package/dist/chrisapi/cubeRequest.js.map +1 -0
  36. package/dist/chrisapi/shape.d.ts +186 -0
  37. package/dist/chrisapi/shape.js +274 -0
  38. package/dist/chrisapi/shape.js.map +1 -0
  39. package/dist/cli.js +2 -1
  40. package/dist/cli.js.map +1 -1
  41. package/dist/compute/computeResources.d.ts +3 -0
  42. package/dist/compute/computeResources.js +5 -3
  43. package/dist/compute/computeResources.js.map +1 -1
  44. package/dist/config/config.d.ts +14 -0
  45. package/dist/config/config.js +6 -3
  46. package/dist/config/config.js.map +1 -1
  47. package/dist/connect/chrisConnection.d.ts +116 -6
  48. package/dist/connect/chrisConnection.js +418 -74
  49. package/dist/connect/chrisConnection.js.map +1 -1
  50. package/dist/connect/identityEpoch.d.ts +263 -0
  51. package/dist/connect/identityEpoch.js +414 -0
  52. package/dist/connect/identityEpoch.js.map +1 -0
  53. package/dist/connect/loginFailure.js +39 -22
  54. package/dist/connect/loginFailure.js.map +1 -1
  55. package/dist/context/chrisContext.js +36 -30
  56. package/dist/context/chrisContext.js.map +1 -1
  57. package/dist/error/errorStack.d.ts +1 -1
  58. package/dist/error/errorStack.js +1 -2
  59. package/dist/error/errorStack.js.map +1 -1
  60. package/dist/feeds/chrisAccess.d.ts +7 -2
  61. package/dist/feeds/chrisAccess.js +20 -7
  62. package/dist/feeds/chrisAccess.js.map +1 -1
  63. package/dist/feeds/chrisFeed.d.ts +8 -10
  64. package/dist/feeds/chrisFeed.js +27 -57
  65. package/dist/feeds/chrisFeed.js.map +1 -1
  66. package/dist/feeds/chrisTags.d.ts +1 -1
  67. package/dist/feeds/chrisTags.js +66 -24
  68. package/dist/feeds/chrisTags.js.map +1 -1
  69. package/dist/filebrowser/chrisFileBrowser.d.ts +0 -1
  70. package/dist/filebrowser/chrisFileBrowser.js +3 -5
  71. package/dist/filebrowser/chrisFileBrowser.js.map +1 -1
  72. package/dist/filebrowser/chrisFiles.d.ts +0 -1
  73. package/dist/filebrowser/chrisFiles.js +3 -4
  74. package/dist/filebrowser/chrisFiles.js.map +1 -1
  75. package/dist/filebrowser/chrisPACS.d.ts +4 -4
  76. package/dist/filebrowser/chrisPACS.js +10 -33
  77. package/dist/filebrowser/chrisPACS.js.map +1 -1
  78. package/dist/filebrowser/chrisPipeline.js +10 -45
  79. package/dist/filebrowser/chrisPipeline.js.map +1 -1
  80. package/dist/groups/chrisGroups.d.ts +3 -0
  81. package/dist/groups/chrisGroups.js +20 -8
  82. package/dist/groups/chrisGroups.js.map +1 -1
  83. package/dist/index.d.ts +6 -8
  84. package/dist/index.js +17 -28
  85. package/dist/index.js.map +1 -1
  86. package/dist/io/chrisIO.d.ts +81 -42
  87. package/dist/io/chrisIO.js +176 -325
  88. package/dist/io/chrisIO.js.map +1 -1
  89. package/dist/io/holderClient.d.ts +248 -0
  90. package/dist/io/holderClient.js +289 -0
  91. package/dist/io/holderClient.js.map +1 -0
  92. package/dist/io/holderFolder.d.ts +151 -0
  93. package/dist/io/holderFolder.js +311 -0
  94. package/dist/io/holderFolder.js.map +1 -0
  95. package/dist/io/holderIO.d.ts +258 -0
  96. package/dist/io/holderIO.js +557 -0
  97. package/dist/io/holderIO.js.map +1 -0
  98. package/dist/io/holderRequest.d.ts +299 -0
  99. package/dist/io/holderRequest.js +447 -0
  100. package/dist/io/holderRequest.js.map +1 -0
  101. package/dist/io/holderUpload.d.ts +62 -0
  102. package/dist/io/holderUpload.js +81 -0
  103. package/dist/io/holderUpload.js.map +1 -0
  104. package/dist/io/io.d.ts +12 -0
  105. package/dist/io/io.js.map +1 -1
  106. package/dist/io/localUpload.d.ts +59 -0
  107. package/dist/io/localUpload.js +150 -0
  108. package/dist/io/localUpload.js.map +1 -0
  109. package/dist/io/node_io.d.ts +16 -0
  110. package/dist/io/node_io.js +72 -0
  111. package/dist/io/node_io.js.map +1 -1
  112. package/dist/io/streamWatch.js +2 -2
  113. package/dist/io/streamWatch.js.map +1 -1
  114. package/dist/io/transferPool.d.ts +18 -2
  115. package/dist/io/transferPool.js +32 -7
  116. package/dist/io/transferPool.js.map +1 -1
  117. package/dist/pacs/chrisPACS.d.ts +3 -9
  118. package/dist/pacs/chrisPACS.js +102 -61
  119. package/dist/pacs/chrisPACS.js.map +1 -1
  120. package/dist/pacs/queryIndexSweep.d.ts +0 -9
  121. package/dist/pacs/queryIndexSweep.js +45 -41
  122. package/dist/pacs/queryIndexSweep.js.map +1 -1
  123. package/dist/path/chrisPath.d.ts +8 -3
  124. package/dist/path/chrisPath.js +10 -9
  125. package/dist/path/chrisPath.js.map +1 -1
  126. package/dist/pipelines/chrisPipeline.d.ts +28 -5
  127. package/dist/pipelines/chrisPipeline.js +270 -94
  128. package/dist/pipelines/chrisPipeline.js.map +1 -1
  129. package/dist/pipelines/pipelineMemo.d.ts +0 -16
  130. package/dist/pipelines/pipelineMemo.js +0 -27
  131. package/dist/pipelines/pipelineMemo.js.map +1 -1
  132. package/dist/plugins/chrisPlugins.d.ts +9 -5
  133. package/dist/plugins/chrisPlugins.js +97 -58
  134. package/dist/plugins/chrisPlugins.js.map +1 -1
  135. package/dist/resources/chrisObjContext.d.ts +7 -11
  136. package/dist/resources/chrisObjContext.js +7 -42
  137. package/dist/resources/chrisObjContext.js.map +1 -1
  138. package/dist/resources/chrisResources.d.ts +186 -74
  139. package/dist/resources/chrisResources.js +421 -117
  140. package/dist/resources/chrisResources.js.map +1 -1
  141. package/dist/resources/resourceShapes.d.ts +109 -0
  142. package/dist/resources/resourceShapes.js +22 -0
  143. package/dist/resources/resourceShapes.js.map +1 -0
  144. package/dist/users/chrisUsers.d.ts +4 -1
  145. package/dist/users/chrisUsers.js +6 -2
  146. package/dist/users/chrisUsers.js.map +1 -1
  147. package/dist/utils/keypair.js +21 -10
  148. package/dist/utils/keypair.js.map +1 -1
  149. package/package.json +10 -3
  150. package/dist/activities/chrisActivity.d.ts +0 -19
  151. package/dist/activities/chrisActivity.js +0 -29
  152. package/dist/activities/chrisActivity.js.map +0 -1
  153. package/dist/jobs/chrisJob.d.ts +0 -43
  154. package/dist/jobs/chrisJob.js +0 -174
  155. package/dist/jobs/chrisJob.js.map +0 -1
  156. package/dist/jobs/index.d.ts +0 -7
  157. package/dist/jobs/index.js +0 -24
  158. package/dist/jobs/index.js.map +0 -1
  159. package/dist/jobs/jobMonitor.d.ts +0 -46
  160. package/dist/jobs/jobMonitor.js +0 -102
  161. package/dist/jobs/jobMonitor.js.map +0 -1
@@ -42,9 +42,10 @@ exports.procLayoutHome_set = procLayoutHome_set;
42
42
  */
43
43
  const crypto_1 = require("crypto");
44
44
  const fs_1 = require("fs");
45
- const os_1 = require("os");
46
45
  const path_1 = require("path");
46
+ const fond_1 = require("@fnndsc/fond");
47
47
  const procCache_1 = require("./procCache");
48
+ const identityEpoch_1 = require("../connect/identityEpoch");
48
49
  const errorStack_1 = require("../error/errorStack");
49
50
  // v3: per-feed shards. v2 (one file, instances with metrics) is still read
50
51
  // for migration; v1 never carried metrics and is not read.
@@ -75,8 +76,7 @@ function dataFacts_check(value) {
75
76
  }
76
77
  /** Returns the default directory for persistent process-cache files. */
77
78
  function procCheckpointRoot_get() {
78
- const cacheHome = process.env.XDG_CACHE_HOME ?? (0, path_1.join)((0, os_1.homedir)(), '.cache');
79
- return (0, path_1.join)(cacheHome, 'chell', 'proc');
79
+ return (0, path_1.join)((0, fond_1.xdgDir_resolve)('cache'), 'chell', 'proc');
80
80
  }
81
81
  /** Hashes an identity into a short, non-revealing directory key. */
82
82
  function identityKey_get(identity) {
@@ -127,6 +127,32 @@ function procFeed_check(value) {
127
127
  integer_check(feed.cancelledJobs) &&
128
128
  integer_check(feed.createdJobs);
129
129
  }
130
+ /**
131
+ * Whether a persisted status is one an instance may be saved in: none yet,
132
+ * or a terminal one.
133
+ *
134
+ * @param status - The persisted status.
135
+ * @returns True when it is null or a terminal status.
136
+ */
137
+ function procInstanceStatus_check(status) {
138
+ return status === null ||
139
+ (typeof status === 'string' && (0, procCache_1.status_isTerminal)(status));
140
+ }
141
+ /**
142
+ * Whether a persisted instance's run record is well formed: its start, end,
143
+ * output size, pipeline and workflow each absent or of its kind (the last
144
+ * two may be null).
145
+ *
146
+ * @param instance - The persisted instance.
147
+ * @returns True when every run field is absent or well formed.
148
+ */
149
+ function procInstanceMetrics_check(instance) {
150
+ return (instance.startedAt === undefined || typeof instance.startedAt === 'string') &&
151
+ (instance.finishedAt === undefined || typeof instance.finishedAt === 'string') &&
152
+ (instance.outputBytes === undefined || typeof instance.outputBytes === 'number') &&
153
+ (instance.pipelineName === undefined || instance.pipelineName === null || typeof instance.pipelineName === 'string') &&
154
+ (instance.workflowID === undefined || instance.workflowID === null || typeof instance.workflowID === 'number');
155
+ }
130
156
  /** Reports whether a value is a structurally valid persisted instance. */
131
157
  function procInstance_check(value) {
132
158
  if (!value || typeof value !== 'object')
@@ -134,15 +160,10 @@ function procInstance_check(value) {
134
160
  const instance = value;
135
161
  const parentValid = instance.parentID === null || integer_check(instance.parentID);
136
162
  const pluginTypeValid = instance.pluginType === undefined || typeof instance.pluginType === 'string';
137
- const statusValid = instance.status === null ||
138
- (typeof instance.status === 'string' && (0, procCache_1.status_isTerminal)(instance.status));
163
+ const statusValid = procInstanceStatus_check(instance.status);
139
164
  const joinsValid = instance.joinParentIDs === undefined ||
140
165
  (Array.isArray(instance.joinParentIDs) && instance.joinParentIDs.every(integer_check));
141
- const metricsValid = (instance.startedAt === undefined || typeof instance.startedAt === 'string') &&
142
- (instance.finishedAt === undefined || typeof instance.finishedAt === 'string') &&
143
- (instance.outputBytes === undefined || typeof instance.outputBytes === 'number') &&
144
- (instance.pipelineName === undefined || instance.pipelineName === null || typeof instance.pipelineName === 'string') &&
145
- (instance.workflowID === undefined || instance.workflowID === null || typeof instance.workflowID === 'number');
166
+ const metricsValid = procInstanceMetrics_check(instance);
146
167
  return metricsValid &&
147
168
  integer_check(instance.id) &&
148
169
  integer_check(instance.feedID) &&
@@ -176,24 +197,53 @@ function shardGraph_fault(feedID, instances) {
176
197
  byID.set(instance.id, instance);
177
198
  }
178
199
  for (const instance of byID.values()) {
179
- if (instance.parentID !== null && !byID.has(instance.parentID)) {
180
- return `instance ${instance.id} names parent ${instance.parentID}, which the shard does not hold`;
181
- }
182
- for (const id of instance.joinParentIDs ?? []) {
183
- if (id === instance.id || !byID.has(id))
184
- return `instance ${instance.id} names join parent ${id}, which the shard does not hold`;
185
- }
186
- const ancestors = new Set([instance.id]);
187
- let ancestor = instance.parentID === null ? undefined : byID.get(instance.parentID);
188
- while (ancestor) {
189
- if (ancestors.has(ancestor.id))
190
- return `instance ${instance.id} sits on a cycle`;
191
- ancestors.add(ancestor.id);
192
- ancestor = ancestor.parentID === null ? undefined : byID.get(ancestor.parentID);
193
- }
200
+ const fault = shardInstanceParents_fault(instance, byID);
201
+ if (fault !== null)
202
+ return fault;
194
203
  }
195
204
  return null;
196
205
  }
206
+ /**
207
+ * Why one instance of a shard does not stand on the shard's own instances,
208
+ * or null when it does: its parent and each join parent held (a join
209
+ * parent never the instance itself), and no cycle above it.
210
+ *
211
+ * @param instance - The instance.
212
+ * @param byID - The shard's instances, by id.
213
+ * @returns The first fault found, in words, or null.
214
+ */
215
+ function shardInstanceParents_fault(instance, byID) {
216
+ if (instance.parentID !== null && !byID.has(instance.parentID)) {
217
+ return `instance ${instance.id} names parent ${instance.parentID}, which the shard does not hold`;
218
+ }
219
+ for (const id of instance.joinParentIDs ?? []) {
220
+ if (id === instance.id || !byID.has(id))
221
+ return `instance ${instance.id} names join parent ${id}, which the shard does not hold`;
222
+ }
223
+ const parent = instance.parentID === null ? undefined : byID.get(instance.parentID);
224
+ if (ancestry_isCyclic(instance.id, parent, byID))
225
+ return `instance ${instance.id} sits on a cycle`;
226
+ return null;
227
+ }
228
+ /**
229
+ * Whether the chain of parents above an instance comes back on itself.
230
+ *
231
+ * @param id - The instance's id.
232
+ * @param parent - Its parent, or undefined for a root.
233
+ * @param byID - The instances the chain is read through, by id.
234
+ * @returns True when an ancestor repeats (the instance's own id included).
235
+ */
236
+ function ancestry_isCyclic(id, parent, byID) {
237
+ const ancestors = new Set([id]);
238
+ let ancestor = parent;
239
+ while (ancestor) {
240
+ if (ancestors.has(ancestor.id))
241
+ return true;
242
+ ancestors.add(ancestor.id);
243
+ ancestor = ancestor.parentID === null ? undefined : byID.get(ancestor.parentID);
244
+ }
245
+ return false;
246
+ }
197
247
  /**
198
248
  * Validates all snapshot fields and graph relationships before restoration.
199
249
  *
@@ -204,46 +254,75 @@ function procCacheSnapshot_check(value) {
204
254
  if (!value || typeof value !== 'object')
205
255
  return false;
206
256
  const snapshot = value;
207
- if (!Array.isArray(snapshot.feeds) ||
208
- !Array.isArray(snapshot.instances) ||
209
- !Array.isArray(snapshot.topologyLoaded) ||
210
- !snapshot.feeds.every(procFeed_check) ||
211
- !snapshot.instances.every(procInstance_check) ||
212
- !snapshot.topologyLoaded.every(integer_check)) {
257
+ if (!snapshotRows_check(snapshot)) {
213
258
  return false;
214
259
  }
215
260
  const feedIDs = new Set(snapshot.feeds.map((feed) => feed.id));
216
261
  const instanceByID = new Map(snapshot.instances.map((instance) => [instance.id, instance]));
217
- if (feedIDs.size !== snapshot.feeds.length ||
218
- instanceByID.size !== snapshot.instances.length ||
219
- new Set(snapshot.topologyLoaded).size !== snapshot.topologyLoaded.length ||
220
- snapshot.topologyLoaded.some((feedID) => !feedIDs.has(feedID))) {
262
+ if (!snapshotIDs_check(snapshot, feedIDs, instanceByID)) {
221
263
  return false;
222
264
  }
223
265
  for (const instance of snapshot.instances) {
224
- if (!feedIDs.has(instance.feedID))
225
- return false;
226
- const parent = instance.parentID === null
227
- ? undefined
228
- : instanceByID.get(instance.parentID);
229
- if (instance.parentID !== null && (!parent || parent.feedID !== instance.feedID))
230
- return false;
231
- if (instance.joinParentIDs?.some((id) => {
232
- const joinParent = instanceByID.get(id);
233
- return !joinParent || joinParent.feedID !== instance.feedID || id === instance.id;
234
- }))
266
+ if (!snapshotInstance_stands(instance, feedIDs, instanceByID))
235
267
  return false;
236
- const ancestors = new Set([instance.id]);
237
- let ancestor = parent;
238
- while (ancestor) {
239
- if (ancestors.has(ancestor.id))
240
- return false;
241
- ancestors.add(ancestor.id);
242
- ancestor = ancestor.parentID === null ? undefined : instanceByID.get(ancestor.parentID);
243
- }
244
268
  }
245
269
  return true;
246
270
  }
271
+ /**
272
+ * Whether a snapshot's feeds, instances and loaded marks are lists of
273
+ * well-formed entries.
274
+ *
275
+ * @param snapshot - The snapshot candidate.
276
+ * @returns True when all three are lists and every entry is well formed.
277
+ */
278
+ function snapshotRows_check(snapshot) {
279
+ return Array.isArray(snapshot.feeds) &&
280
+ Array.isArray(snapshot.instances) &&
281
+ Array.isArray(snapshot.topologyLoaded) &&
282
+ snapshot.feeds.every(procFeed_check) &&
283
+ snapshot.instances.every(procInstance_check) &&
284
+ snapshot.topologyLoaded.every(integer_check);
285
+ }
286
+ /**
287
+ * Whether a snapshot's ids are unique (feeds, instances and loaded marks)
288
+ * and every loaded mark names a feed it holds.
289
+ *
290
+ * @param snapshot - The snapshot, its lists well formed.
291
+ * @param feedIDs - Its feeds' ids.
292
+ * @param instanceByID - Its instances, by id.
293
+ * @returns True when no id repeats and no loaded mark is a stranger.
294
+ */
295
+ function snapshotIDs_check(snapshot, feedIDs, instanceByID) {
296
+ return !(feedIDs.size !== snapshot.feeds.length ||
297
+ instanceByID.size !== snapshot.instances.length ||
298
+ new Set(snapshot.topologyLoaded).size !== snapshot.topologyLoaded.length ||
299
+ snapshot.topologyLoaded.some((feedID) => !feedIDs.has(feedID)));
300
+ }
301
+ /**
302
+ * Whether one instance of a snapshot stands: its feed held, its parent and
303
+ * each join parent held in its own feed (a join parent never itself), and
304
+ * no cycle above it.
305
+ *
306
+ * @param instance - The instance.
307
+ * @param feedIDs - The snapshot's feeds' ids.
308
+ * @param instanceByID - The snapshot's instances, by id.
309
+ * @returns True when the instance stands.
310
+ */
311
+ function snapshotInstance_stands(instance, feedIDs, instanceByID) {
312
+ if (!feedIDs.has(instance.feedID))
313
+ return false;
314
+ const parent = instance.parentID === null
315
+ ? undefined
316
+ : instanceByID.get(instance.parentID);
317
+ if (instance.parentID !== null && (!parent || parent.feedID !== instance.feedID))
318
+ return false;
319
+ if (instance.joinParentIDs?.some((id) => {
320
+ const joinParent = instanceByID.get(id);
321
+ return !joinParent || joinParent.feedID !== instance.feedID || id === instance.id;
322
+ }))
323
+ return false;
324
+ return !ancestry_isCyclic(instance.id, parent, instanceByID);
325
+ }
247
326
  /** Shared header checks for any checkpoint file of the current schema. */
248
327
  function header_check(value, identity) {
249
328
  if (!value || typeof value !== 'object')
@@ -302,12 +381,15 @@ function shardReadFault_name(error) {
302
381
  return code;
303
382
  return error instanceof Error ? error.message : String(error);
304
383
  }
305
- /** Writes one mode-0600 JSON file through a same-directory atomic rename. */
384
+ /**
385
+ * Writes one mode-0600 JSON file through a same-directory atomic rename.
386
+ *
387
+ * @param path - The file.
388
+ * @param value - What it holds.
389
+ * @returns Whether the commit is confirmed on disk.
390
+ */
306
391
  async function json_write(path, value) {
307
- const temporaryPath = `${path}.${process.pid}-${(0, crypto_1.randomUUID)()}.tmp`;
308
- await fs_1.promises.writeFile(temporaryPath, `${JSON.stringify(value)}\n`, { encoding: 'utf8', mode: 0o600 });
309
- await fs_1.promises.rename(temporaryPath, path);
310
- await fs_1.promises.chmod(path, 0o600);
392
+ return (0, fond_1.recordFile_writeAsync)(path, `${JSON.stringify(value)}\n`, { mode: 0o600 });
311
393
  }
312
394
  /** Ensures the checkpoint directory exists, private to the user. */
313
395
  async function dir_ensure(dir) {
@@ -315,6 +397,55 @@ async function dir_ensure(dir) {
315
397
  await fs_1.promises.chmod((0, path_1.dirname)(dir), 0o700);
316
398
  await fs_1.promises.chmod(dir, 0o700);
317
399
  }
400
+ /**
401
+ * The feeds a roster marks unseen, whole ids only; none from a roster
402
+ * written before the mark existed.
403
+ *
404
+ * @param roster - The roster.
405
+ * @returns The unseen feeds' ids.
406
+ */
407
+ function rosterUnseen_read(roster) {
408
+ return Array.isArray(roster.unseen) ? roster.unseen.filter((id) => Number.isInteger(id)) : [];
409
+ }
410
+ /**
411
+ * Whether parsed JSON is a compatible roster file for an identity whose
412
+ * every feed is well formed.
413
+ *
414
+ * @param value - The parsed roster.
415
+ * @param identity - Canonical ChRIS identity string.
416
+ * @returns True when the roster may be read.
417
+ */
418
+ function rosterFile_fits(value, identity) {
419
+ return rosterFile_check(value, identity) && value.feeds.every(procFeed_check);
420
+ }
421
+ /**
422
+ * Whether parsed JSON is a compatible shard file for an identity that
423
+ * holds the feed its file name says.
424
+ *
425
+ * @param value - The parsed shard.
426
+ * @param identity - Canonical ChRIS identity string.
427
+ * @param feedID - The feed its file name says.
428
+ * @returns True when the shard may be read as that feed's.
429
+ */
430
+ function shardFile_fits(value, identity, feedID) {
431
+ return shardFile_check(value, identity) && value.feedID === feedID;
432
+ }
433
+ /**
434
+ * Takes a shard that stands into a snapshot: its instances, its feed's
435
+ * loaded mark when the shard was loaded, and its data facts when they are
436
+ * well formed.
437
+ *
438
+ * @param snapshot - The snapshot being assembled; added to in place.
439
+ * @param feedID - The shard's feed.
440
+ * @param shard - The shard.
441
+ */
442
+ function shard_take(snapshot, feedID, shard) {
443
+ snapshot.instances.push(...shard.instances);
444
+ if (shard.loaded)
445
+ snapshot.topologyLoaded.push(feedID);
446
+ if (shard.dataFacts !== undefined && dataFacts_check(shard.dataFacts) && snapshot.dataFacts !== undefined)
447
+ snapshot.dataFacts[feedID] = shard.dataFacts;
448
+ }
318
449
  /**
319
450
  * Assembles the sharded checkpoint into one snapshot. Shards whose feed is
320
451
  * absent from the roster are orphans (a feed removed after its shard was
@@ -336,12 +467,10 @@ async function shards_assemble(dir, identity) {
336
467
  const roster = await json_read((0, path_1.join)(dir, ROSTER_FILE));
337
468
  if (roster === null)
338
469
  return null;
339
- if (!rosterFile_check(roster, identity))
340
- throw new Error('incompatible checkpoint');
341
- if (!roster.feeds.every(procFeed_check))
470
+ if (!rosterFile_fits(roster, identity))
342
471
  throw new Error('incompatible checkpoint');
343
472
  const feedIDs = new Set(roster.feeds.map((feed) => feed.id));
344
- const unseen = Array.isArray(roster.unseen) ? roster.unseen.filter((id) => Number.isInteger(id)) : [];
473
+ const unseen = rosterUnseen_read(roster);
345
474
  const snapshot = { feeds: roster.feeds, instances: [], topologyLoaded: [], dataFacts: {}, unseen };
346
475
  let skipped = 0;
347
476
  const torn = [];
@@ -362,7 +491,7 @@ async function shards_assemble(dir, identity) {
362
491
  torn.push(`feed ${feedID}: unreadable (${shardReadFault_name(error)})`);
363
492
  continue;
364
493
  }
365
- if (!shardFile_check(shard, identity) || shard.feedID !== feedID) {
494
+ if (!shardFile_fits(shard, identity, feedID)) {
366
495
  skipped++;
367
496
  continue;
368
497
  }
@@ -371,11 +500,7 @@ async function shards_assemble(dir, identity) {
371
500
  torn.push(`feed ${feedID}: ${fault}`);
372
501
  continue;
373
502
  }
374
- snapshot.instances.push(...shard.instances);
375
- if (shard.loaded)
376
- snapshot.topologyLoaded.push(feedID);
377
- if (shard.dataFacts !== undefined && dataFacts_check(shard.dataFacts) && snapshot.dataFacts !== undefined)
378
- snapshot.dataFacts[feedID] = shard.dataFacts;
503
+ shard_take(snapshot, feedID, shard);
379
504
  }
380
505
  if (skipped > 0) {
381
506
  errorStack_1.errorStack.stack_push('warning', `proc checkpoint: ${skipped} feed shard(s) skipped (orphaned or unreadable)`);
@@ -396,8 +521,13 @@ async function shards_assemble(dir, identity) {
396
521
  */
397
522
  async function procCheckpoint_restore(identity, root = procCheckpointRoot_get()) {
398
523
  const dir = procCheckpointDir_get(identity, root);
524
+ const began = (0, identityEpoch_1.identityEpoch_get)();
399
525
  try {
400
526
  const assembled = await shards_assemble(dir, identity);
527
+ // The identity changed while the checkpoint was being read: it is the one before's, and is not put into
528
+ // the cache of whoever is connected now.
529
+ if (began !== (0, identityEpoch_1.identityEpoch_get)() || !(0, identityEpoch_1.identityCache_usable)())
530
+ return { restored: false, count: 0, reason: 'the identity changed' };
401
531
  if (assembled) {
402
532
  if (!procCacheSnapshot_check(assembled.snapshot)) {
403
533
  return { restored: false, count: 0, reason: 'incompatible checkpoint' };
@@ -411,6 +541,8 @@ async function procCheckpoint_restore(identity, root = procCheckpointRoot_get())
411
541
  };
412
542
  }
413
543
  const legacy = await json_read(procCheckpointPath_get(identity, root));
544
+ if (began !== (0, identityEpoch_1.identityEpoch_get)() || !(0, identityEpoch_1.identityCache_usable)())
545
+ return { restored: false, count: 0, reason: 'the identity changed' };
414
546
  if (legacy === null)
415
547
  return { restored: false, count: 0, reason: 'no checkpoint' };
416
548
  if (!legacyFile_check(legacy, identity)) {
@@ -453,15 +585,23 @@ function roster_isConsistent() {
453
585
  *
454
586
  * @param identity - Canonical ChRIS identity string.
455
587
  * @param root - Checkpoint directory override.
456
- * @returns Promise resolved after the file is durable in place; resolves
457
- * without writing when the roster is inconsistent.
588
+ * @returns True once the roster is written and its commit confirmed on disk;
589
+ * false when nothing was written (the roster inconsistent, another
590
+ * identity's) or the commit is unconfirmed, and then the cache is not
591
+ * marked checkpointed.
458
592
  */
459
593
  async function procCheckpointRoster_save(identity, root = procCheckpointRoot_get()) {
594
+ // Written only by the session's own identity's work: what other work sees of the tree is not its to save
595
+ // under this name.
596
+ if (!(0, identityEpoch_1.identityCache_usable)())
597
+ return false;
460
598
  if (!roster_isConsistent())
461
- return;
599
+ return false;
462
600
  const dir = procCheckpointDir_get(identity, root);
463
- await dir_ensure(dir);
464
601
  const cache = (0, procCache_1.procCache_get)();
602
+ // What is written is the roster as it stands now, taken before anything is waited for: a change of
603
+ // identity while the folder is being made cannot put the next identity's roster in this one's file.
604
+ const began = (0, identityEpoch_1.identityEpoch_get)();
465
605
  const file = {
466
606
  schemaVersion: PROC_CHECKPOINT_SCHEMA,
467
607
  identity,
@@ -469,12 +609,20 @@ async function procCheckpointRoster_save(identity, root = procCheckpointRoot_get
469
609
  feeds: cache.feedIDs_get().map((id) => ({ ...cache.feed_get(id) })),
470
610
  unseen: cache.unseen_get(),
471
611
  };
472
- await json_write((0, path_1.join)(dir, ROSTER_FILE), file);
473
- cache.checkpoint_mark(file.writtenAt);
612
+ await dir_ensure(dir);
613
+ const written = await json_write((0, path_1.join)(dir, ROSTER_FILE), file);
614
+ // A roster in place but not confirmed on disk may come back as the one before after a crash: the cache is
615
+ // not called checkpointed on it.
616
+ if (!written.durable)
617
+ return false;
618
+ if (began === (0, identityEpoch_1.identityEpoch_get)())
619
+ cache.checkpoint_mark(file.writtenAt);
620
+ return true;
474
621
  }
475
622
  /**
476
- * Atomically writes one feed's shard, or removes it when the feed no longer
477
- * holds topology (removed from the roster, or emptied).
623
+ * Atomically writes one feed's shard, or removes it when the feed, still in
624
+ * the cache, no longer holds topology. A feed gone from the cache is left
625
+ * alone: its shard goes only in the sweep after a confirmed roster.
478
626
  *
479
627
  * @param identity - Canonical ChRIS identity string.
480
628
  * @param feedID - The feed whose shard to write.
@@ -482,11 +630,18 @@ async function procCheckpointRoster_save(identity, root = procCheckpointRoot_get
482
630
  * @returns Promise resolved after the shard is durable in place.
483
631
  */
484
632
  async function procCheckpointFeed_save(identity, feedID, root = procCheckpointRoot_get()) {
633
+ if (!(0, identityEpoch_1.identityCache_usable)())
634
+ return;
485
635
  const dir = procCheckpointDir_get(identity, root);
486
636
  const cache = (0, procCache_1.procCache_get)();
487
637
  const snapshot = cache.feedSnapshot_create(feedID);
488
638
  const path = shardPath_get(dir, feedID);
489
- if (!cache.feed_get(feedID) || (snapshot.instances.length === 0 && !snapshot.loaded && snapshot.dataFacts === undefined)) {
639
+ // A feed gone from the cache keeps its shard: the roster on disk may still name it (its rewrite may fail or be
640
+ // unconfirmed), and only the sweep after a confirmed roster (procCheckpoint_save) removes what no roster names.
641
+ if (!cache.feed_get(feedID))
642
+ return;
643
+ // A feed still here whose topology was let go has nothing to keep.
644
+ if (snapshot.instances.length === 0 && !snapshot.loaded && snapshot.dataFacts === undefined) {
490
645
  await fs_1.promises.rm(path, { force: true });
491
646
  return;
492
647
  }
@@ -504,7 +659,9 @@ async function procCheckpointFeed_save(identity, feedID, root = procCheckpointRo
504
659
  }
505
660
  /**
506
661
  * Saves the whole process cache: the roster and every feed shard, removing
507
- * shards for feeds no longer in the roster.
662
+ * shards for feeds no longer in the roster once that roster is confirmed on
663
+ * disk (an unconfirmed one may come back as the one before, which still
664
+ * names them).
508
665
  *
509
666
  * @param identity - Canonical ChRIS identity string.
510
667
  * @param root - Checkpoint directory override.
@@ -512,14 +669,23 @@ async function procCheckpointFeed_save(identity, feedID, root = procCheckpointRo
512
669
  * without writing when the roster is inconsistent.
513
670
  */
514
671
  async function procCheckpoint_save(identity, root = procCheckpointRoot_get()) {
672
+ if (!(0, identityEpoch_1.identityCache_usable)())
673
+ return;
515
674
  if (!roster_isConsistent())
516
675
  return;
517
676
  const dir = procCheckpointDir_get(identity, root);
518
677
  const cache = (0, procCache_1.procCache_get)();
519
- await procCheckpointRoster_save(identity, root);
678
+ const began = (0, identityEpoch_1.identityEpoch_get)();
520
679
  const wanted = new Set(cache.shardedFeedIDs_get());
521
- for (const feedID of wanted)
680
+ const confirmed = await procCheckpointRoster_save(identity, root);
681
+ for (const feedID of wanted) {
682
+ // The identity changed part-way: the rest of the tree is the next identity's, and none of it is written here.
683
+ if (began !== (0, identityEpoch_1.identityEpoch_get)())
684
+ return;
522
685
  await procCheckpointFeed_save(identity, feedID, root);
686
+ }
687
+ if (began !== (0, identityEpoch_1.identityEpoch_get)() || !confirmed)
688
+ return;
523
689
  for (const name of await fs_1.promises.readdir(dir)) {
524
690
  const match = SHARD_PATTERN.exec(name);
525
691
  if (match && !wanted.has(Number(match[1])))
@@ -540,11 +706,20 @@ async function procCheckpoint_save(identity, root = procCheckpointRoot_get()) {
540
706
  * @returns Function that stops watching and cancels pending saves.
541
707
  */
542
708
  function procCheckpoint_watch(identity, root = procCheckpointRoot_get(), delayMs = 1000, floorMs = exports.PROC_CHECKPOINT_FLOOR_MS) {
709
+ // Installed only by the session's own identity's work: a warm-up that outlived a change of identity (its
710
+ // restore came back after someone else connected) watches nothing, and writes nothing under its name.
711
+ if (!(0, identityEpoch_1.identityCache_usable)())
712
+ return () => undefined;
543
713
  const timers = new Map();
544
714
  const lastWrite = new Map();
545
715
  // Layouts are kept beside the index this watcher keeps.
546
716
  procLayoutHome_set({ identity, root });
717
+ // The identity this watcher writes for is the one connected when it was started. Once another has
718
+ // connected, the tree is the other's: nothing more is written under this name.
719
+ const began = (0, identityEpoch_1.identityEpoch_get)();
547
720
  const shard_write = async (key) => {
721
+ if ((0, identityEpoch_1.identityEpoch_get)() !== began)
722
+ return;
548
723
  if (key === 'roster')
549
724
  await procCheckpointRoster_save(identity, root);
550
725
  else if (key === 'all')
@@ -553,7 +728,7 @@ function procCheckpoint_watch(identity, root = procCheckpointRoot_get(), delayMs
553
728
  await procCheckpointFeed_save(identity, key, root);
554
729
  };
555
730
  const shard_schedule = (key) => {
556
- if (timers.has(key))
731
+ if (timers.has(key) || (0, identityEpoch_1.identityEpoch_get)() !== began)
557
732
  return;
558
733
  const earliest = (lastWrite.get(key) ?? 0) + floorMs;
559
734
  const wait = Math.max(delayMs, earliest - Date.now());
@@ -601,12 +776,16 @@ function procCheckpoint_watch(identity, root = procCheckpointRoot_get(), delayMs
601
776
  return;
602
777
  shard_schedule(change.scope === 'roster' ? 'roster' : change.feedID);
603
778
  });
604
- return () => {
779
+ const watch_stop = () => {
605
780
  listener_remove();
606
781
  for (const timer of timers.values())
607
782
  clearTimeout(timer);
608
783
  timers.clear();
784
+ retire_remove();
609
785
  };
786
+ // Retired at a change of identity: the tree it watched is no longer the one it writes for.
787
+ const retire_remove = (0, identityEpoch_1.identityChange_listen)(watch_stop);
788
+ return watch_stop;
610
789
  }
611
790
  /**
612
791
  * The longest node id a kept layout takes. A shape's hub is named by its
@@ -658,6 +837,10 @@ function layoutPath_get(name) {
658
837
  async function procLayout_get(name) {
659
838
  if (!procLayoutName_check(name))
660
839
  return null;
840
+ // Layouts are kept for the session's identity, by its own work: other work has none.
841
+ if (!(0, identityEpoch_1.identityCache_usable)())
842
+ return null;
843
+ const home = layoutHome;
661
844
  const held = layoutsHeld.get(name);
662
845
  if (held !== undefined)
663
846
  return held;
@@ -674,10 +857,13 @@ async function procLayout_get(name) {
674
857
  if (!file || typeof file !== 'object')
675
858
  return null;
676
859
  const record = file;
677
- if (record.schemaVersion !== PROC_CHECKPOINT_SCHEMA || record.identity !== layoutHome?.identity || record.name !== name
860
+ if (record.schemaVersion !== PROC_CHECKPOINT_SCHEMA || record.identity !== home?.identity || record.name !== name
678
861
  || typeof record.writtenAt !== 'string' || !procLayoutPositions_check(record.positions))
679
862
  return null;
680
863
  const kept = { name, positions: record.positions, writtenAt: record.writtenAt };
864
+ // Read for the identity that was connected when it was asked for: if another is now, it is not theirs to hold.
865
+ if (layoutHome !== home)
866
+ return null;
681
867
  layoutsHeld.set(name, kept);
682
868
  return kept;
683
869
  }
@@ -696,11 +882,16 @@ async function procLayout_set(name, positions) {
696
882
  if (!procLayoutPositions_check(positions))
697
883
  throw new Error('not a set of places');
698
884
  const record = { name, positions, writtenAt: new Date().toISOString() };
885
+ // Kept and written for the session's identity, by its own work; other work is handed the record and no more.
886
+ if (!(0, identityEpoch_1.identityCache_usable)())
887
+ return record;
699
888
  layoutsHeld.set(name, record);
700
889
  const path = layoutPath_get(name);
701
- if (path !== null && layoutHome !== null) {
890
+ // Whose folder it is written in is settled now, before anything is waited for.
891
+ const home = layoutHome;
892
+ if (path !== null && home !== null) {
702
893
  await dir_ensure((0, path_1.dirname)(path));
703
- await json_write(path, { schemaVersion: PROC_CHECKPOINT_SCHEMA, identity: layoutHome.identity, ...record });
894
+ await json_write(path, { schemaVersion: PROC_CHECKPOINT_SCHEMA, identity: home.identity, ...record });
704
895
  }
705
896
  return record;
706
897
  }
@@ -713,4 +904,7 @@ function procLayoutHome_set(home) {
713
904
  layoutHome = home;
714
905
  layoutsHeld.clear();
715
906
  }
907
+ // Layouts are one identity's: at a change of identity there is no home for them, and none held, until the
908
+ // next identity's watcher names its own.
909
+ (0, identityEpoch_1.identityChange_listen)(() => { procLayoutHome_set(null); });
716
910
  //# sourceMappingURL=procCheckpoint.js.map