@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
@@ -15,6 +15,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
15
15
  Object.defineProperty(exports, "__esModule", { value: true });
16
16
  exports.chrisConnection = exports.ChRISConnection = exports.Client = void 0;
17
17
  exports.chrisConnection_init = chrisConnection_init;
18
+ const identityEpoch_js_1 = require("./identityEpoch.js");
18
19
  const folderMemo_1 = require("../filebrowser/folderMemo");
19
20
  const requestLedger_1 = require("../net/requestLedger");
20
21
  const adapter_js_1 = require("../chrisapi/adapter.js");
@@ -25,7 +26,19 @@ const chrisContext_js_1 = require("../context/chrisContext.js");
25
26
  const chrisIO_js_1 = require("../io/chrisIO.js");
26
27
  const errorStack_js_1 = require("../error/errorStack.js");
27
28
  const chalk_1 = __importDefault(require("chalk"));
28
- const node_async_hooks_1 = require("node:async_hooks");
29
+ /**
30
+ * Says whether a context string names a user or a CUBE, as
31
+ * `chrisContextURL_parse` will find: known at once, with nothing awaited.
32
+ *
33
+ * @param context - The context string.
34
+ * @returns True when it names who or where.
35
+ */
36
+ function contextIdentity_names(context) {
37
+ const parts = context.split("@");
38
+ if (parts.length > 1 && parts[0] !== "")
39
+ return true;
40
+ return /https?:\/\/[^?]+/.test(parts.length > 1 ? parts[1] ?? "" : context);
41
+ }
29
42
  /**
30
43
  * Helper function to validate and format a context string.
31
44
  * @param context - The context string to check.
@@ -61,10 +74,23 @@ class ChRISConnection {
61
74
  */
62
75
  constructor(config, storageProvider) {
63
76
  this.authToken = null;
77
+ /** The saved login the connection was initialised with, and the file its token is read from; null when none was saved. */
78
+ this.savedLogin = null;
64
79
  this.user = null;
65
80
  this.chrisURL = null;
66
81
  this.client = null;
67
- this.elevatedClientContext = new node_async_hooks_1.AsyncLocalStorage();
82
+ /** Counts every change of who is connected: a read of a saved token notes it, and is not taken if it has moved. */
83
+ this.credentials = 0;
84
+ /** Counts every login, logout and move of context as it is asked for: an answer that comes back after a later one was asked is not acted on. */
85
+ this.asked = 0;
86
+ /** Whether the saved token file is known to be the named identity's: false after a transition that failed part way, until someone signs in. */
87
+ this.saved = true;
88
+ /** A move of context failed part way and has not been asked again: asked again and written, its file is the named identity's. */
89
+ this.moveFailed = false;
90
+ /** Token files whose removal at a logout failed: not read back until a login writes over them. */
91
+ this.refused = new Set();
92
+ /** The awaited part of a change of identity that is under way, or null. */
93
+ this.transition = null;
68
94
  /**
69
95
  * Initializes the connection with configuration and storage provider.
70
96
  * @param config - The connection configuration object.
@@ -93,51 +119,92 @@ class ChRISConnection {
93
119
  this._config = config;
94
120
  this.storageProvider = storageProvider;
95
121
  this.tokenFile = this._config.tokenFilepath;
122
+ const saved = config.loginSaved ?? null;
123
+ this.savedLogin = saved === null ? null : { user: saved.user, url: saved.url, tokenFile: this.tokenFile };
124
+ }
125
+ /**
126
+ * Who the session is authenticated as before any change of identity: the
127
+ * saved login read at initialisation, while a usable token from its own
128
+ * file is held. A context moved since does not move it.
129
+ *
130
+ * @returns `user@url`, or null when no saved login holds a usable token.
131
+ *
132
+ * @example
133
+ * const owner: string | null = await chrisConnection.savedLogin_name();
134
+ */
135
+ async savedLogin_name() {
136
+ const saved = this.savedLogin;
137
+ if (saved === null)
138
+ return null;
139
+ const token = await this.authToken_get();
140
+ if (!token || this.tokenFile !== saved.tokenFile)
141
+ return null;
142
+ return (0, identityEpoch_js_1.identityName_spell)(saved.user, saved.url);
96
143
  }
97
144
  /**
98
145
  * Establishes a connection to the ChRIS CUBE and authenticates the user.
99
- * @param options - Connection options including user, password, debug flag, and URL.
100
- * @returns A Promise resolving to the authentication token on success, or null on failure.
146
+ * @param options - Connection options: user, password and URL.
147
+ * @returns A Promise resolving to the authentication token on success, or
148
+ * null when no token was issued or a later login or logout replaced this one.
149
+ * @throws {Error} When the login failed, with what failed in words (a refusal
150
+ * of the credentials, an untrusted certificate, an unreachable host): the
151
+ * caller says it, and the process goes on.
101
152
  */
102
153
  async connection_connect(options) {
103
- const { user, password, debug, url } = options;
154
+ const { user, password, url } = options;
155
+ // Its place in the order is taken now, as it is asked for and before anything is awaited. Whoever is
156
+ // connected stays readable while CUBE is asked; if a later login or logout is asked before this one's
157
+ // turn comes, this one's answer (a token or a refusal) is dropped.
158
+ const mine = this.asked_take();
104
159
  // Ensure configuration is initialized before use
105
160
  if (this.storageProvider) {
106
161
  await (0, config_js_1.config_init)(this.storageProvider);
107
162
  this._config = config_js_1.connectionConfig;
108
163
  }
109
- const authUrl = url + "auth-token/";
110
- this.user = user;
111
- this.chrisURL = url;
164
+ // Resolved below the root, never joined as text: a root given without its slash could otherwise name another host.
165
+ const root = (0, adapter_js_1.apiRoot_parse)(url);
166
+ const authUrl = new URL('auth-token/', root).href;
112
167
  console.log(`Connecting to ${url} with user ${user}`);
113
- await this._config.context_set(user, url);
114
- this.tokenFile = this._config.tokenFilepath;
168
+ const answer = { superseded: false };
115
169
  try {
116
- this.authToken = await (0, adapter_js_1.authToken_get)(authUrl, user, password);
117
- if (this.authToken) {
118
- // console.log("Auth token: " + this.authToken);
119
- await this.token_saveToFile(this.tokenFile, this.authToken);
120
- console.log("Auth token saved successfully");
121
- console.log("ChRIS URL saved successfully");
122
- return this.authToken;
123
- }
124
- else {
170
+ // Nothing of the connection is changed until CUBE has answered: while the password is being
171
+ // exchanged, and if it is refused, whoever was connected is still wholly connected (their user, their
172
+ // CUBE, their token and their client together).
173
+ const token = await (0, adapter_js_1.authToken_get)(authUrl, user, password, root);
174
+ if (!token) {
125
175
  console.log("Failed to receive auth token");
126
176
  return null;
127
177
  }
178
+ // The new identity is published in one step, with nothing awaited inside it: there is no moment at
179
+ // which the user is the new one and the client the old. It is published in its turn among the
180
+ // changes of identity under way (a logout asked for meanwhile comes after it, and ends it), and what
181
+ // it writes to disk is written before the next change begins.
182
+ await this.transition_run(async () => {
183
+ if (mine !== this.asked) {
184
+ answer.superseded = true;
185
+ return;
186
+ }
187
+ this.identity_publish(user, url, token);
188
+ // Said only when it is so: a token that could not be saved privately is held for this session and not on disk.
189
+ const saved = await this.login_persist(user, url, token);
190
+ console.log(saved ? "Auth token saved successfully" : "Auth token held for this session; it was not saved");
191
+ if (this.saved)
192
+ console.log("ChRIS URL saved successfully");
193
+ });
194
+ if (answer.superseded) {
195
+ console.log(`The login of ${user} was answered after a later login or logout was asked for; it was not acted on`);
196
+ return null;
197
+ }
198
+ return token;
128
199
  }
129
200
  catch (error) {
130
201
  // The real cause, said as what it is: only CUBE's refusal blames the
131
202
  // credentials; an untrusted certificate or an unreachable host says so (#965).
132
203
  const failure = await (0, loginFailure_js_1.loginFailure_diagnose)(error, authUrl, this.loginProbe);
133
- console.error('');
134
- for (const line of (0, loginFailure_js_1.loginFailure_lines)(failure, url))
135
- console.error(line);
136
- console.error("\nExiting to system with code 1...");
137
- if (debug) {
138
- throw error;
139
- }
140
- process.exit(1);
204
+ // A refusal of a login that a later one has since replaced is nobody's news: it ends nothing.
205
+ if (mine !== this.asked)
206
+ return null;
207
+ throw new Error((0, loginFailure_js_1.loginFailure_lines)(failure, url).join('\n'));
141
208
  }
142
209
  }
143
210
  /**
@@ -147,8 +214,8 @@ class ChRISConnection {
147
214
  *
148
215
  * @param url - Base URL of the CUBE API, ending in `/`.
149
216
  * @param token - The token to prove.
150
- * @throws {Error} chrisapi's error: carrying CUBE's response when it
151
- * refused, "No server response!" when nothing came back.
217
+ * @throws {Error} Carrying CUBE's response when it refused or
218
+ * redirected, "No server response!" when nothing came back.
152
219
  */
153
220
  async token_check(url, token) {
154
221
  await (0, adapter_js_1.token_verify)(url, token);
@@ -170,11 +237,13 @@ class ChRISConnection {
170
237
  */
171
238
  async connection_connectWithToken(options) {
172
239
  const { user, url, token } = options;
240
+ const mine = this.asked_take();
173
241
  if (this.storageProvider) {
174
242
  await (0, config_js_1.config_init)(this.storageProvider);
175
243
  this._config = config_js_1.connectionConfig;
176
244
  }
177
245
  const client = (0, adapter_js_1.client_create)(url, token);
246
+ const answer = { superseded: false };
178
247
  try {
179
248
  await (0, adapter_js_1.token_verify)(url, token);
180
249
  }
@@ -191,14 +260,18 @@ class ChRISConnection {
191
260
  const reason = error instanceof Error ? error.message : String(error);
192
261
  return { connected: false, reason: `${url} refused the token for ${user}: ${reason}` };
193
262
  }
194
- this.user = user;
195
- this.chrisURL = url;
196
- await this._config.context_set(user, url);
197
- this.tokenFile = this._config.tokenFilepath;
198
- this.authToken = token;
199
- // One folder lookup per path per session, as client_get makes it.
200
- this.client = (0, folderMemo_1.folderLookup_memoize)(client);
201
- await this.token_saveToFile(this.tokenFile, token);
263
+ // Published in one step, with the client the token was proved for (its folder lookups remembered, as
264
+ // client_get makes them).
265
+ await this.transition_run(async () => {
266
+ if (mine !== this.asked) {
267
+ answer.superseded = true;
268
+ return;
269
+ }
270
+ this.identity_publish(user, url, token, (0, folderMemo_1.folderLookup_memoize)(client));
271
+ await this.login_persist(user, url, token);
272
+ });
273
+ if (answer.superseded)
274
+ return { connected: false, reason: `the login of ${user} was answered after a later login or logout was asked for; it was not acted on` };
202
275
  return { connected: true };
203
276
  }
204
277
  /**
@@ -208,6 +281,9 @@ class ChRISConnection {
208
281
  */
209
282
  async context_set(context) {
210
283
  context = contextString_check(context);
284
+ // A context that names a user or a CUBE takes its place in the order now, as it is asked for and
285
+ // before anything is awaited: of two asked together the later is the one made, whichever is read first.
286
+ const mine = contextIdentity_names(context) ? this.asked_take() : null;
211
287
  const parsedContext = await (0, chrisContext_js_1.chrisContextURL_parse)(context);
212
288
  if (errorStack_js_1.errorStack.messagesOfType_has('error')) {
213
289
  const error = errorStack_js_1.errorStack.stack_pop();
@@ -217,21 +293,68 @@ class ChRISConnection {
217
293
  return false;
218
294
  }
219
295
  let status = true;
220
- let needsRefresh = false;
221
- if (parsedContext.user) {
222
- status =
223
- status &&
224
- (await chrisContext_js_1.chrisContext.current_set(chrisContext_js_1.Context.ChRISuser, parsedContext.user)); // Await this call
225
- this.user = parsedContext.user;
226
- needsRefresh = true;
227
- await this._config.context_set(parsedContext.user, parsedContext.URL || '');
228
- }
229
- if (parsedContext.URL) {
230
- status =
231
- status && (await chrisContext_js_1.chrisContext.current_set(chrisContext_js_1.Context.ChRISURL, parsedContext.URL)); // Await this call
232
- this.chrisURL = parsedContext.URL;
233
- needsRefresh = true;
234
- await this._config.context_set(this.user || "", parsedContext.URL);
296
+ if (parsedContext.user || parsedContext.URL) {
297
+ const answer = { superseded: false };
298
+ await this.transition_run(async () => {
299
+ if (mine !== this.asked) {
300
+ answer.superseded = true;
301
+ return;
302
+ }
303
+ // Who the context names is compared with who is connected when this change's turn comes, not when
304
+ // it was asked for: a login that finished in between is what it is compared with.
305
+ const user = parsedContext.user || this.user;
306
+ const url = parsedContext.URL || this.chrisURL;
307
+ // The same user on the same CUBE named again is no change of identity, and empties nothing.
308
+ const changed = this.identity_differs(user, url);
309
+ // Another user or another CUBE: from this moment nobody is connected as the one before, and until
310
+ // the new one's token has been read nobody is connected at all. (Nothing is awaited before this.)
311
+ // The change is made known once, below, when it is known who is connected after it.
312
+ const known = this.saved;
313
+ const retried = this.moveFailed;
314
+ if (changed)
315
+ this.identity_publish(user, url, null, null, false);
316
+ try {
317
+ status = await this.contextIdentity_write(parsedContext, status);
318
+ // The client for who the context now names, from their own saved token; and, now that it is known
319
+ // whether they have one, who is connected is said by name.
320
+ // The context is written: the token file it names is this identity's, and is read. (A move that
321
+ // failed and is asked again comes here with the name already moved: its file is confirmed now.)
322
+ // Only a login held for this session keeps its token in memory in place of whatever the file holds.
323
+ // A logout from such a login is not such a move: naming its context again reads nothing back.
324
+ const signedOut = this.authToken === null;
325
+ // A move to another identity, once written, confirms that identity's file whatever came before.
326
+ this.saved = changed || known || retried;
327
+ this.moveFailed = false;
328
+ await this.client_rebuild();
329
+ // Nobody was connected under this name and its saved token has now been read: that is a change
330
+ // of who is connected, and is said.
331
+ if (!changed && signedOut && this.authToken !== null)
332
+ (0, identityEpoch_js_1.identityEpoch_raise)(this.identityName_get());
333
+ }
334
+ catch (error) {
335
+ // The fields have moved and the write of it failed part way: nobody's client or token is kept
336
+ // from before, so what is held is one coherent thing (the named context, not signed in).
337
+ // And the saved token is not read until someone signs in: the file still named may be the one
338
+ // before's.
339
+ if (changed) {
340
+ this.client = null;
341
+ this.authToken = null;
342
+ this.saved = false;
343
+ this.moveFailed = true;
344
+ }
345
+ throw error;
346
+ }
347
+ finally {
348
+ // The change is said whether or not the write of it went through: the caches were the one
349
+ // before's either way.
350
+ if (changed)
351
+ (0, identityEpoch_js_1.identityEpoch_raise)(this.authToken !== null ? this.identityName_get() : null);
352
+ }
353
+ });
354
+ // A later login, logout or move was asked for: none of this one is made, its folder, feed and
355
+ // plugin included, and its caller is told so.
356
+ if (answer.superseded)
357
+ return false;
235
358
  }
236
359
  if (parsedContext.folder) {
237
360
  status =
@@ -248,18 +371,53 @@ class ChRISConnection {
248
371
  status &&
249
372
  (await chrisContext_js_1.chrisContext.current_set(chrisContext_js_1.Context.ChRISplugin, parsedContext.plugin)); // Await this call
250
373
  }
251
- // Refresh the client with the new context
252
- if (needsRefresh) {
253
- await this.client_refresh();
374
+ return status;
375
+ }
376
+ /**
377
+ * Writes the user and the URL a context names into the session's context
378
+ * and the saved configuration, the user first. Once one is refused by the
379
+ * context, the next is not asked of it (the configuration is still written).
380
+ *
381
+ * @param parsedContext - The context asked for.
382
+ * @param status - Whether every write so far was taken.
383
+ * @returns Whether every write so far, these included, was taken.
384
+ */
385
+ async contextIdentity_write(parsedContext, status) {
386
+ if (parsedContext.user) {
387
+ status = status && (await chrisContext_js_1.chrisContext.current_set(chrisContext_js_1.Context.ChRISuser, parsedContext.user));
388
+ await this._config.context_set(parsedContext.user, parsedContext.URL || '');
389
+ }
390
+ if (parsedContext.URL) {
391
+ status = status && (await chrisContext_js_1.chrisContext.current_set(chrisContext_js_1.Context.ChRISURL, parsedContext.URL));
392
+ await this._config.context_set(this.user || "", parsedContext.URL);
254
393
  }
255
394
  return status;
256
395
  }
396
+ /**
397
+ * Whether a user and a CUBE name another identity than the one held now.
398
+ *
399
+ * @param user - The user named, or null.
400
+ * @param url - The CUBE named, or null.
401
+ * @returns True when either differs from the held user and CUBE (null reads as empty).
402
+ */
403
+ identity_differs(user, url) {
404
+ return `${user ?? ''}\n${url ?? ''}` !== `${this.user ?? ''}\n${this.chrisURL ?? ''}`;
405
+ }
406
+ /**
407
+ * The name of the identity held now, as a change of identity says it.
408
+ *
409
+ * @returns `user@url`, an absent user or CUBE spelt empty.
410
+ */
411
+ identityName_get() {
412
+ return (0, identityEpoch_js_1.identityName_spell)(this.user ?? '', this.chrisURL ?? '');
413
+ }
257
414
  /**
258
415
  * Retrieves the authentication token.
259
416
  * @param forceLoad - If true, forces loading the token from storage.
260
417
  * @returns A Promise resolving to the authentication token or null.
261
418
  */
262
419
  async authToken_get(forceLoad) {
420
+ await this.transition_wait();
263
421
  if (!this.authToken || forceLoad) {
264
422
  await this.token_load();
265
423
  }
@@ -288,21 +446,61 @@ class ChRISConnection {
288
446
  if (!this._config) {
289
447
  return null; // config not initialized
290
448
  }
291
- this.chrisURL = await this._config.chrisURL_load();
449
+ // Read for who is connected now: if that changes before the read comes back, what was read is of the
450
+ // context as it was, and is not put in place of the new one's.
451
+ const began = this.credentials;
452
+ const loaded = await this.url_load();
453
+ if (began === this.credentials && !this.chrisURL)
454
+ this.chrisURL = loaded;
292
455
  }
293
456
  return this.chrisURL;
294
457
  }
458
+ /**
459
+ * The CUBE for a connection that names none yet: while the token file in
460
+ * use is the saved login's, the address read with it at startup, so the
461
+ * first client and whatever is keyed by that login name one CUBE.
462
+ *
463
+ * @returns The address, or null when none is saved.
464
+ */
465
+ async url_load() {
466
+ const saved = this.savedLogin;
467
+ if (saved !== null && this.tokenFile === saved.tokenFile)
468
+ return saved.url;
469
+ return this._config ? await this._config.chrisURL_load() : null;
470
+ }
295
471
  /**
296
472
  * Refreshes the ChRIS API client with current token and URL.
297
473
  * @returns A Promise resolving to the refreshed Client instance or null.
298
474
  */
299
475
  async client_refresh() {
300
- this.tokenFile = this._config.tokenFilepath;
301
- this.chrisURL = await this.chrisURL_get();
302
- this.authToken = await this.authToken_get(true); // Pass true directly
303
- if (this.chrisURL && this.authToken) {
304
- this.client = (0, folderMemo_1.folderLookup_memoize)((0, adapter_js_1.client_create)(this.chrisURL, this.authToken));
476
+ await this.transition_wait();
477
+ return this.client_rebuild();
478
+ }
479
+ /**
480
+ * Makes the client again from the token saved for who the context names.
481
+ * The work of {@link client_refresh}, without waiting for a change of
482
+ * identity to finish: it is what such a change itself calls.
483
+ *
484
+ * @returns The client, or null when no token is saved for them.
485
+ */
486
+ async client_rebuild() {
487
+ const began = this.credentials;
488
+ // The token file follows the configuration only while it is known to be the named identity's.
489
+ if (this.saved)
490
+ this.tokenFile = this._config.tokenFilepath;
491
+ if (!this.chrisURL) {
492
+ const loaded = await this.url_load();
493
+ if (began !== this.credentials)
494
+ return this.client;
495
+ if (!this.chrisURL)
496
+ this.chrisURL = loaded;
305
497
  }
498
+ await this.token_load();
499
+ // Someone logged in or out while the token was being read: the client is theirs to make.
500
+ if (began !== this.credentials)
501
+ return this.client;
502
+ // A client for who the context now names, or none: one made for whoever was named before is never kept.
503
+ this.client = this.chrisURL && this.authToken ? (0, folderMemo_1.folderLookup_memoize)((0, adapter_js_1.client_create)(this.chrisURL, this.authToken)) : null;
306
504
  return this.client;
307
505
  }
308
506
  /**
@@ -310,9 +508,13 @@ class ChRISConnection {
310
508
  * @returns A Promise resolving to the Client instance or null.
311
509
  */
312
510
  async client_get() {
313
- const elevatedClient = this.elevatedClientContext.getStore();
314
- if (elevatedClient)
511
+ // Work being done as another user (a `sudo`) has that user's client for its own length.
512
+ const elevatedClient = (0, identityEpoch_js_1.identityElevatedClient_get)();
513
+ if (elevatedClient !== null)
315
514
  return elevatedClient;
515
+ // A login, a logout or a change of context that is under way is waited for: nobody is handed a client
516
+ // from the middle of one.
517
+ await this.transition_wait();
316
518
  if ((await this.authToken_get()) &&
317
519
  (await this.chrisURL_get()) &&
318
520
  this.chrisURL &&
@@ -341,20 +543,24 @@ class ChRISConnection {
341
543
  const url = await this.chrisURL_get();
342
544
  if (!url)
343
545
  throw new Error('Not connected to ChRIS. Run connect first.');
546
+ const root = (0, adapter_js_1.apiRoot_parse)(url);
547
+ const authUrl = new URL('auth-token/', root).href;
344
548
  let token;
345
549
  try {
346
- token = await (0, adapter_js_1.authToken_get)(`${url}auth-token/`, credentials.username, credentials.password);
550
+ token = await (0, adapter_js_1.authToken_get)(authUrl, credentials.username, credentials.password, root);
347
551
  }
348
552
  catch (error) {
349
553
  // A refusal is the credentials' to answer for; a certificate or a
350
554
  // network failure says what it is instead (#965).
351
- const failure = await (0, loginFailure_js_1.loginFailure_diagnose)(error, `${url}auth-token/`, this.loginProbe);
555
+ const failure = await (0, loginFailure_js_1.loginFailure_diagnose)(error, authUrl, this.loginProbe);
352
556
  if (failure.kind === 'tls' || failure.kind === 'network')
353
557
  throw new Error((0, loginFailure_js_1.loginFailure_lines)(failure, url).join(' '));
354
558
  throw error;
355
559
  }
356
560
  const elevatedClient = (0, adapter_js_1.client_create)(url, token);
357
- return await this.elevatedClientContext.run(elevatedClient, operation);
561
+ // Run as that user for the length of the operation: given their client, and marked so that the
562
+ // session's caches are neither read nor filled by it.
563
+ return await (0, identityEpoch_js_1.identityElevated_run)(elevatedClient, operation);
358
564
  }
359
565
  /**
360
566
  * Checks if the client is currently connected.
@@ -367,27 +573,144 @@ class ChRISConnection {
367
573
  * Logs out the user by clearing the authentication token from storage.
368
574
  */
369
575
  async connection_logout() {
370
- this.authToken = null;
576
+ this.asked_take();
577
+ // Nobody is connected from this moment: the token and the client that carries it go together, a read
578
+ // of the saved token that is under way is not taken when it comes back, and what is cached of who was
579
+ // connected is emptied.
580
+ await this.transition_run(async () => {
581
+ // In its turn: a login still writing its token finishes first, and this then ends it. The file
582
+ // removed is the one that is current when this turn comes.
583
+ this.identity_publish(this.user, this.chrisURL, null, null, true, true);
584
+ // The file removed is the one known to be theirs. After a login held for the session only, or a
585
+ // move of context that failed part way, the file named may be the one before's: it is left alone.
586
+ if (!this.saved) {
587
+ console.log("Logged out successfully");
588
+ return;
589
+ }
590
+ const file = this.tokenFile;
591
+ try {
592
+ await this.storageProvider.remove(file);
593
+ console.log("Logged out successfully");
594
+ }
595
+ catch (error) {
596
+ // The token could not be removed: it is still on disk, and that file is not read back, whoever
597
+ // names its context again, until a login writes a token over it.
598
+ this.refused.add(file);
599
+ console.error("Error during logout:", error);
600
+ }
601
+ });
602
+ }
603
+ /**
604
+ * Writes a login's context and saves its token, in that order: the token
605
+ * file is the login's own only once its context has been written.
606
+ *
607
+ * @param user - Who logged in.
608
+ * @param url - Their CUBE.
609
+ * @param token - Their token.
610
+ * @returns Whether the token is on disk; false when it is held for this session only.
611
+ */
612
+ async login_persist(user, url, token) {
371
613
  try {
372
- await this.storageProvider.remove(this.tokenFile);
373
- console.log("Logged out successfully");
614
+ await this._config.context_set(user, url);
374
615
  }
375
616
  catch (error) {
376
- console.error("Error during logout:", error);
617
+ // The context could not be written: the login stands for this session, with no file known to be
618
+ // its own. Nothing is read from, written to or removed at the path the one before had.
619
+ const reason = error instanceof Error ? error.message : String(error);
620
+ console.error(`The login is held for this session; its context could not be saved: ${reason}`);
621
+ return false;
377
622
  }
623
+ this.tokenFile = this._config.tokenFilepath;
624
+ this.saved = true;
625
+ const written = await this.token_saveToFile(this.tokenFile, token);
626
+ // A token written over one whose removal had failed is the new login's: the file is read again.
627
+ if (written)
628
+ this.refused.delete(this.tokenFile);
629
+ return written;
630
+ }
631
+ /**
632
+ * Takes the next place in the order of logins, logouts and moves of
633
+ * context, as one is asked for.
634
+ *
635
+ * @returns The place taken: an answer that comes back when it is no longer the latest is not acted on.
636
+ */
637
+ asked_take() {
638
+ this.asked += 1;
639
+ return this.asked;
640
+ }
641
+ /**
642
+ * Publishes who is connected, in one step with nothing awaited inside
643
+ * it: the user, the CUBE, the token and the client change together, a
644
+ * read of a saved token begun before this moment is not taken when it
645
+ * comes back, and the change of identity is made known.
646
+ *
647
+ * @param user - The user now connected, or whoever the context names.
648
+ * @param url - Their CUBE.
649
+ * @param token - Their token, or null when nobody is connected.
650
+ * @param client - A client already made for that token, when there is one.
651
+ * @param announce - False when the caller makes the change known itself, once it knows who is connected after it.
652
+ * @param keepFile - True when the saved token file is still whose it was (a logout, which then removes it).
653
+ */
654
+ identity_publish(user, url, token, client = null, announce = true, keepFile = false) {
655
+ // Whose the saved token file is has to be established again for whoever is published, except by a
656
+ // logout, which removes the file it knows.
657
+ if (!keepFile)
658
+ this.saved = false;
659
+ this.moveFailed = false;
660
+ this.user = user;
661
+ this.chrisURL = url;
662
+ this.authToken = token;
663
+ this.client = client;
664
+ this.credentials += 1;
665
+ // Named when someone is connected (`user@url`, the name their checkpoints are kept under); null when nobody is.
666
+ if (announce)
667
+ (0, identityEpoch_js_1.identityEpoch_raise)(token !== null && user !== null && url !== null ? (0, identityEpoch_js_1.identityName_spell)(user, url) : null);
668
+ }
669
+ /**
670
+ * Runs a change of identity: its publication and what it writes to and
671
+ * reads from disk. Changes run one at a time, in the order they were
672
+ * asked for, and {@link client_get} and {@link authToken_get} wait for
673
+ * all of them.
674
+ *
675
+ * @param work - The change.
676
+ */
677
+ async transition_run(work) {
678
+ // One at a time, in the order asked: a change begins when the one before it has finished everything
679
+ // it does, what it writes to disk included.
680
+ const before = this.transition ?? Promise.resolve();
681
+ const run = before.then(work);
682
+ const held = run.then(() => undefined, () => undefined).then(() => {
683
+ if (this.transition === held)
684
+ this.transition = null;
685
+ });
686
+ this.transition = held;
687
+ await run;
688
+ }
689
+ /** Waits for a change of identity that is under way to finish. */
690
+ async transition_wait() {
691
+ while (this.transition !== null)
692
+ await this.transition;
378
693
  }
379
694
  /**
380
695
  * Saves data to a specified file using the storage provider.
381
696
  * @param file - The path to the file.
382
697
  * @param info - The string data to save.
698
+ * @returns Whether it was saved; false when it could not be, or could not be saved privately.
383
699
  */
384
700
  async token_saveToFile(file, info) {
701
+ const store = this.storageProvider;
385
702
  try {
386
- await this.storageProvider.write(file, info || "");
703
+ // A token is a credential: its owner's alone on disk, where the store has such a notion.
704
+ if (store.writePrivate !== undefined)
705
+ await store.writePrivate(file, info || "");
706
+ else
707
+ await store.write(file, info || "");
708
+ return true;
387
709
  }
388
710
  catch (error) {
389
- console.error("For info: ", info);
711
+ // What failed to be saved is never said: it is the token.
390
712
  console.error("Error saving to file ", file, ": ", error);
713
+ return false;
391
714
  }
392
715
  }
393
716
  /**
@@ -395,8 +718,18 @@ class ChRISConnection {
395
718
  * @returns A Promise that resolves when the token is loaded.
396
719
  */
397
720
  async token_load() {
721
+ // Whose token is being read: if someone logs in or out before the read comes back, what was read is
722
+ // not theirs, and is not taken.
723
+ const began = this.credentials;
724
+ // After a move of context or a logout that failed part way, the file named may hold a token that is
725
+ // not the named identity's, or one that was to have been removed: it is not read.
726
+ if (!this.saved || this.refused.has(this.tokenFile))
727
+ return;
728
+ let read = null;
398
729
  try {
399
- this.authToken = await this.storageProvider.read(this.tokenFile);
730
+ // A token saved before files were made private is made so when it is next read.
731
+ await this.storageProvider.private_tighten?.(this.tokenFile);
732
+ read = await this.storageProvider.read(this.tokenFile);
400
733
  }
401
734
  catch (error) {
402
735
  // A missing token file is the normal logged-out state; any other read
@@ -406,7 +739,18 @@ class ChRISConnection {
406
739
  const msg = error instanceof Error ? error.message : String(error);
407
740
  errorStack_js_1.errorStack.stack_push("warning", `Could not read auth token file ${this.tokenFile}: ${msg}`);
408
741
  }
409
- this.authToken = null;
742
+ read = null;
743
+ }
744
+ if (began !== this.credentials)
745
+ return;
746
+ const lost = this.authToken !== null && read === null;
747
+ this.authToken = read;
748
+ // The token that was held is gone from disk: whoever it was is no longer connected, though the user
749
+ // and the CUBE named are the same. Their client goes, and what is cached of them is emptied.
750
+ if (lost) {
751
+ this.client = null;
752
+ this.credentials += 1;
753
+ (0, identityEpoch_js_1.identityEpoch_raise)(null);
410
754
  }
411
755
  }
412
756
  }