@larc-iu/plaid-client 0.2.0-alpha.2 → 0.2.0-alpha.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/services.js CHANGED
@@ -10,12 +10,130 @@
10
10
  */
11
11
  import { transformRequest, transformResponse } from './transforms.js';
12
12
 
13
+ // An absolute URL anywhere in an error message, with the phrase that introduces
14
+ // it (`... at http://host/api/v1/spans`). Client and transport errors name the
15
+ // endpoint they called, which is the service operator's business and not the
16
+ // requester's.
17
+ const URL_IN_TEXT = /(?:\s+(?:at|for url:?))?\s*\b[a-zA-Z][\w+.-]*:\/\/\S+/g;
18
+
19
+ /**
20
+ * What a requester is told when an error carries no message of its own.
21
+ * Naming the JS class instead would say nothing they can act on.
22
+ */
23
+ export const UNKNOWN_FAILURE = 'The service could not finish this request.';
24
+
25
+ const redact = (text, secrets) => {
26
+ let out = text;
27
+ for (const secret of secrets || []) {
28
+ if (secret && String(secret).length >= 8) out = out.split(String(secret)).join('[redacted]');
29
+ }
30
+ return out.trim();
31
+ };
32
+
33
+ /** A write sent to the server whose answer never came back. */
34
+ export const UNKNOWN_OUTCOME =
35
+ 'The Plaid server did not answer. This change may or may not have been saved.';
36
+
37
+ /** The server was never reached, so nothing was sent. */
38
+ export const UNREACHABLE = 'The Plaid server could not be reached.';
39
+
40
+ // A few reads travel as a POST, and saved nothing either way (the Python twin
41
+ // and plaid-ui's errors.js keep the same list).
42
+ const READ_POSTS = /\/api\/v1\/(?:query|login|invites\/lookup)(?:[?#]|$)/;
43
+
44
+ // Node's fetch (undici) names a connection that never opened by its code: a
45
+ // refused port, a name that did not resolve, a connect timeout. Nothing was
46
+ // sent then. A browser's fetch says only "Failed to fetch", which cannot be
47
+ // told apart from a reset, so it counts as sent.
48
+ const NEVER_CONNECTED = new Set([
49
+ 'ECONNREFUSED',
50
+ 'ENOTFOUND',
51
+ 'EAI_AGAIN',
52
+ 'EHOSTUNREACH',
53
+ 'ENETUNREACH',
54
+ 'UND_ERR_CONNECT_TIMEOUT',
55
+ ]);
56
+
57
+ const neverConnected = (error) => {
58
+ const seen = new Set();
59
+ let cause = error && error.originalError;
60
+ while (cause && typeof cause === 'object' && !seen.has(cause)) {
61
+ seen.add(cause);
62
+ if (NEVER_CONNECTED.has(cause.code)) return true;
63
+ cause = cause.cause;
64
+ }
65
+ return false;
66
+ };
67
+
68
+ const networkFailure = (error) => {
69
+ const method = String(error.method || '').toUpperCase();
70
+ if (neverConnected(error)) return UNREACHABLE;
71
+ if (method && method !== 'GET' && method !== 'HEAD' && !READ_POSTS.test(String(error.url || ''))) {
72
+ return UNKNOWN_OUTCOME;
73
+ }
74
+ return 'The Plaid server did not answer.';
75
+ };
76
+
77
+ /**
78
+ * One line about a failure that is safe to show the person who asked.
79
+ *
80
+ * Strips absolute URLs (so an internal host never reaches a requester's screen)
81
+ * and any `secrets` given (a model provider's API key can come back inside its
82
+ * own error text). The whole error still goes to the operator's console: this
83
+ * is the requester's half only. The Python twin is `requester_message`.
84
+ *
85
+ * Only a connection that never opened is "could not be reached". A write whose
86
+ * answer never came (a reset, a timeout) may have been saved, and says so
87
+ * (`UNKNOWN_OUTCOME`).
88
+ *
89
+ * @param {any} error
90
+ * @param {string[]} [secrets]
91
+ * @returns {string}
92
+ */
93
+ export function requesterMessage(error, secrets = []) {
94
+ if (error && typeof error.status === 'number') {
95
+ if (!error.status) return networkFailure(error);
96
+ let text = String(error.message || '');
97
+ if (error.url) text = text.split(` at ${error.url}`).join('').split(error.url).join('');
98
+ text = text.trim().replace(/[\s,:;]+$/, '');
99
+ return redact(text, secrets) || `HTTP ${error.status}`;
100
+ }
101
+ // An Error is read by its message and nothing else: `String(new TypeError(''))`
102
+ // is 'TypeError', which names the class to the requester and tells them
103
+ // nothing they can act on.
104
+ const raw =
105
+ error && typeof error === 'object' && 'message' in error
106
+ ? String(error.message ?? '')
107
+ : String(error ?? '');
108
+ const text = raw.replace(URL_IN_TEXT, '').trim().replace(/[\s,:;]+$/, '');
109
+ return redact(text, secrets) || UNKNOWN_FAILURE;
110
+ }
111
+
112
+ /**
113
+ * What the requester is told when a request fails, named by the service.
114
+ *
115
+ * Every path that reports a failed request goes through here, so a raw message
116
+ * cannot reach a requester from one of them. (Python's twin additionally lets a
117
+ * `ValueError` through unprefixed, as an authored refusal; JS has no
118
+ * distinguished refusal type, so every failure is named by the service.)
119
+ *
120
+ * @param {any} error
121
+ * @param {string} [serviceName]
122
+ * @param {string[]} [secrets]
123
+ * @returns {string}
124
+ */
125
+ export function serviceErrorMessage(error, serviceName = '', secrets = []) {
126
+ const text = requesterMessage(error, secrets);
127
+ return serviceName ? `${serviceName}: ${text}` : text;
128
+ }
129
+
13
130
  /**
14
131
  * Discover the services seen on a project — a synchronous GET. Returns every
15
132
  * service ever registered on the project: currently connected ones carry
16
133
  * `online: true`; previously-seen offline ones carry `online: false` plus a
17
134
  * `lastSeenAt` stamp. Callers that need a service they can actually submit
18
- * work to should filter on `online`.
135
+ * work to should filter on `online`. Goes over the wire even while a batch is
136
+ * open on the client.
19
137
  *
20
138
  * @param {Object} client - PlaidClient instance
21
139
  * @param {string} projectId - Project UUID
@@ -36,9 +154,45 @@ export function discoverServices(client, projectId) {
36
154
  * @returns {Promise<void>}
37
155
  */
38
156
  export function discardService(client, projectId, serviceId) {
39
- return client._request('DELETE', `/api/v1/projects/${projectId}/services/${encodeURIComponent(serviceId)}`);
157
+ // outOfBand: the registry is not project data (see the note at the top of
158
+ // http.js).
159
+ return client._request('DELETE', `/api/v1/projects/${projectId}/services/${encodeURIComponent(serviceId)}`, {
160
+ outOfBand: true,
161
+ });
162
+ }
163
+
164
+ /**
165
+ * POST a progress, result or error event for an in-flight request; the server
166
+ * relays it to the waiting requester. The Python twin is `_report_event`.
167
+ *
168
+ * outOfBand: these are signals to whoever is waiting, not writes to the
169
+ * project (see the note at the top of http.js). A service may report them on
170
+ * the batch it is filling, where queueing them would hold every one back until
171
+ * submit, deliver none at all if the batch aborts, and take slots in the
172
+ * batch's results. The requester would hear nothing and wait out its idle
173
+ * timeout on work that had already finished.
174
+ *
175
+ * @param {Object} client - PlaidClient instance
176
+ * @param {string} projectId - Project UUID
177
+ * @param {string} requestId - The request id
178
+ * @param {Object} body - The event payload
179
+ * @returns {Promise<any>}
180
+ */
181
+ export function reportRequestEvent(client, projectId, requestId, body) {
182
+ return client._request(
183
+ 'POST',
184
+ `/api/v1/projects/${projectId}/service-requests/${encodeURIComponent(requestId)}/events`,
185
+ { body, outOfBand: true },
186
+ );
40
187
  }
41
188
 
189
+ /**
190
+ * HTTP statuses a refused service channel answers with that retrying cannot
191
+ * fix: a bad or revoked token, no write access to the project, a project that
192
+ * does not exist. The same set as the Python client's.
193
+ */
194
+ const PERMANENT_STATUSES = new Set([400, 401, 403, 404, 405, 422]);
195
+
42
196
  /**
43
197
  * Register a service and handle incoming work requests.
44
198
  *
@@ -52,21 +206,46 @@ export function discardService(client, projectId, serviceId) {
52
206
  * @param {Object} serviceInfo - {serviceId, serviceName, description}
53
207
  * @param {function} onServiceRequest - Handler callback (data, responseHelper)
54
208
  * @param {Object} extras - Optional additional metadata
55
- * @returns {Object} ServiceRegistration with .stop(), .isRunning(), .serviceInfo
209
+ * @param {function} [onStatus] - Optional callback (event, projectId, detail) for
210
+ * connection-state transitions: 'registered', 'reconnected', 'disconnected',
211
+ * and 'stopped' when the server refuses the channel for a reason retrying
212
+ * cannot fix (see PERMANENT_STATUSES), which ends the registration.
213
+ * Called once per transition, not once per retry.
214
+ * @returns {Object} ServiceRegistration with .stop(), .isRunning(), .isConnected(),
215
+ * .serviceInfo
56
216
  */
57
- export function serve(client, projectId, serviceInfo, onServiceRequest, extras = {}) {
217
+ export function serve(client, projectId, serviceInfo, onServiceRequest, extras = {}, onStatus = null) {
58
218
  const { serviceId, serviceName, description = '' } = serviceInfo;
59
219
  let connection = null;
60
220
  let isRunning = true;
61
221
  let reconnectTimer = null;
222
+ // Last state REPORTED, so an outage produces one "lost" line and one "back"
223
+ // line however many retries it took.
224
+ let isConnected = false;
225
+ let everConnected = false;
226
+
227
+ const report = (event, detail) => {
228
+ if (!onStatus) return;
229
+ try { onStatus(event, projectId, detail); } catch (_) { /* never disturb the loop */ }
230
+ };
231
+ const noteConnected = () => {
232
+ if (isConnected) return;
233
+ const first = !everConnected;
234
+ isConnected = true;
235
+ everConnected = true;
236
+ report(first ? 'registered' : 'reconnected');
237
+ };
238
+ const noteDisconnected = () => {
239
+ if (!isConnected) return;
240
+ isConnected = false;
241
+ report('disconnected');
242
+ };
62
243
 
63
244
  const reportEvent = (requestId, body) =>
64
- client
65
- ._request('POST', `/api/v1/projects/${projectId}/service-requests/${encodeURIComponent(requestId)}/events`, { body })
66
- .catch((error) => {
67
- // 404 just means the requester already went away; nothing to do.
68
- console.warn('Failed to report request event:', error.message || error);
69
- });
245
+ reportRequestEvent(client, projectId, requestId, body).catch((error) => {
246
+ // 404 just means the requester already went away; nothing to do.
247
+ console.warn('Failed to report request event:', error.message || error);
248
+ });
70
249
 
71
250
  const serviceRegistration = {
72
251
  stop: () => {
@@ -76,6 +255,10 @@ export function serve(client, projectId, serviceInfo, onServiceRequest, extras =
76
255
  if (connection) connection.close();
77
256
  },
78
257
  isRunning: () => isRunning,
258
+ // Whether the request channel is open RIGHT NOW, i.e. whether the server
259
+ // currently sees this service as online. A registration that is retrying
260
+ // through a server restart is still running but not connected.
261
+ isConnected: () => isRunning && !!connection && connection.readyState === 1,
79
262
  serviceInfo: { serviceId, serviceName, description, extras },
80
263
  };
81
264
 
@@ -89,26 +272,113 @@ export function serve(client, projectId, serviceInfo, onServiceRequest, extras =
89
272
  const qs = params.toString();
90
273
  const channelPath = `/api/v1/projects/${projectId}/services/${encodeURIComponent(serviceId)}/requests${qs ? `?${qs}` : ''}`;
91
274
 
92
- // The channel only carries `connected` (ignored) and `service_request` events.
275
+ // The requests this channel is serving, by id, each flagged once a
276
+ // `service_cancel` arrives. The handler reads it as `responseHelper.cancelled`;
277
+ // whether to stop is the handler's decision (a write under way should
278
+ // finish), and the request still ends with whatever it reports.
279
+ const cancelled = new Map();
280
+
281
+ // Beyond `connected` (ignored), the channel carries `service_request` and
282
+ // `service_cancel` events.
93
283
  const onChannelEvent = (eventType, payload) => {
94
284
  if (!isRunning) return true;
95
- if (eventType !== 'service_request' || !payload) return;
285
+ if (!payload) return;
286
+ if (eventType === 'service_cancel') {
287
+ if (cancelled.has(payload.requestId)) cancelled.set(payload.requestId, true);
288
+ return;
289
+ }
290
+ if (eventType !== 'service_request') return;
96
291
  const requestId = payload.requestId;
97
292
  if (!requestId) return;
293
+ cancelled.set(requestId, false);
294
+ const finished = () => cancelled.delete(requestId);
295
+
296
+ // Every service is told who asked (`requesterId`), beside the payload
297
+ // when that is a plain object, and on the helper regardless. A delegating
298
+ // service (extras `delegation: true`) also gets a short-lived token for the
299
+ // requesting user (`delegatedToken`) and the projects that token reaches
300
+ // (`delegatedProjects`, the request's own first), as the Python client
301
+ // hands them over.
302
+ const requesterId = payload.requesterId || null;
303
+ const extra = {
304
+ ...(requesterId ? { requesterId } : {}),
305
+ ...(payload.delegatedToken ? { delegatedToken: payload.delegatedToken } : {}),
306
+ ...(payload.delegatedProjects ? { delegatedProjects: payload.delegatedProjects } : {}),
307
+ };
308
+ const data =
309
+ Object.keys(extra).length && payload.data && typeof payload.data === 'object' && !Array.isArray(payload.data)
310
+ ? { ...payload.data, ...extra }
311
+ : payload.data;
98
312
 
313
+ const scope = createCancelScope(() => cancelled.get(requestId) === true);
99
314
  const responseHelper = {
100
- progress: (percent, msg) =>
101
- reportEvent(requestId, { status: 'progress', progress: { percent, message: msg } }),
102
- complete: (data) =>
103
- reportEvent(requestId, { status: 'completed', data }),
104
- error: (error) =>
105
- reportEvent(requestId, { status: 'error', data: { error: error?.message || error } }),
315
+ requestId,
316
+ requesterId,
317
+ // True once the requester asked for the request to stop.
318
+ get cancelled() {
319
+ return scope.cancelled;
320
+ },
321
+ raiseIfCancelled: () => scope.raiseIfCancelled(),
322
+ critical: (fn) => scope.critical(fn),
323
+ // Extra fields ride in the progress payload (a chat service sends the
324
+ // reply text so far as `text`).
325
+ //
326
+ // This is a CANCELLATION CHECKPOINT: it throws ServiceCancelled if the
327
+ // requester has stopped the request, so a service that reports progress
328
+ // through its work is cancellable without doing anything else. Use
329
+ // `critical()` around writes to hold it off.
330
+ progress: (percent, msg, extra) => {
331
+ scope.raiseIfCancelled();
332
+ return reportEvent(requestId, {
333
+ status: 'progress',
334
+ progress: { percent, message: msg, ...extra },
335
+ });
336
+ },
337
+ complete: (data) => {
338
+ finished();
339
+ return reportEvent(requestId, { status: 'completed', data });
340
+ },
341
+ // Asked to stop, and it did. Reported as a result carrying
342
+ // `stopped: true`, so a client can tell "you stopped it" from "it broke".
343
+ stopped: (data) => {
344
+ finished();
345
+ return reportEvent(requestId, {
346
+ status: 'completed',
347
+ data: { ...(data || {}), stopped: true },
348
+ });
349
+ },
350
+ // Every failure a requester is shown goes out through here, whoever
351
+ // reports it, so the scrub lives here rather than only in `settle`: a
352
+ // service that catches its own error and calls `helper.error(err)`
353
+ // would otherwise put the endpoint the client called on the requester's
354
+ // screen. Already-sanitized text passes through unchanged.
355
+ error: (error) => {
356
+ finished();
357
+ return reportEvent(requestId, {
358
+ status: 'error',
359
+ data: { error: requesterMessage(error) },
360
+ });
361
+ },
106
362
  };
107
363
 
364
+ // A handler may be async, so a rejected promise has to be caught too, or a
365
+ // cancelled async service would report a failure instead of a stop.
366
+ const settle = (error) => {
367
+ if (error instanceof ServiceCancelled || error?.name === 'ServiceCancelled') {
368
+ responseHelper.stopped();
369
+ } else {
370
+ // What reaches the requester is the sanitized half: the raw message
371
+ // names the endpoint the client called, which is the operator's
372
+ // business. The console keeps the whole error.
373
+ console.error(`Service ${serviceId} failed request ${requestId}:`, error);
374
+ responseHelper.error(serviceErrorMessage(error, serviceName));
375
+ }
376
+ };
108
377
  try {
109
- onServiceRequest(payload.data, responseHelper);
378
+ const maybe = onServiceRequest(data, responseHelper);
379
+ if (maybe && typeof maybe.catch === 'function') maybe.catch(settle);
110
380
  } catch (error) {
111
- responseHelper.error(error?.message || error);
381
+ settle(error);
112
382
  }
113
383
  };
114
384
  const openChannel = () => client.messages.listen(projectId, onChannelEvent, channelPath);
@@ -118,12 +388,30 @@ export function serve(client, projectId, serviceInfo, onServiceRequest, extras =
118
388
  throw new Error(`Failed to start service: ${error.message}`);
119
389
  }
120
390
 
121
- // Reopen the channel if it drops (e.g. the server restarted). Reopening
122
- // re-registers the service server-side, so presence and reachability come
123
- // back together.
391
+ // Reopen the channel whenever it drops (e.g. the server restarted), for as
392
+ // long as the service runs. Reopening re-registers the service server-side,
393
+ // so presence and reachability come back together, and a server restart never
394
+ // means a service restart. A reopened channel counts as connected only once
395
+ // the server has actually answered it (readyState OPEN), not merely because
396
+ // the attempt was made.
397
+ //
398
+ // A channel the server REFUSED for a reason retrying cannot fix (the token
399
+ // was revoked, the user lost write access, the project is gone) ends the
400
+ // registration instead: the server closes a channel whose opener lost the
401
+ // right to it, and reopening it every few seconds forever would only hide
402
+ // that from the operator.
124
403
  reconnectTimer = setInterval(() => {
125
- if (!isRunning) return;
126
- if (connection && connection.readyState === 2) { // CLOSED (dropped)
404
+ if (!isRunning || !connection) return;
405
+ if (connection.readyState === 1) { noteConnected(); return; }
406
+ if (connection.readyState === 2) { // CLOSED (dropped or failed)
407
+ const status = connection.error?.status;
408
+ if (PERMANENT_STATUSES.has(status)) {
409
+ noteDisconnected();
410
+ serviceRegistration.stop();
411
+ report('stopped', `HTTP ${status}`);
412
+ return;
413
+ }
414
+ noteDisconnected();
127
415
  try { connection = openChannel(); } catch (_) { /* retry next tick */ }
128
416
  }
129
417
  }, 3000);
@@ -136,27 +424,200 @@ export function serve(client, projectId, serviceInfo, onServiceRequest, extras =
136
424
  *
137
425
  * Streams the service's progress + result back over a single server-mediated
138
426
  * response (no broadcast). Rejects if no service is connected (503), if the
139
- * service reports an error, or on timeout.
427
+ * service reports an error, or after `timeout` of SILENCE.
428
+ *
429
+ * The request outlives this call: after a timeout, an abort, or a dropped
430
+ * connection the service goes on, and `attachServiceRequest` collects the
431
+ * result given the request id, which `opts.onAccepted` receives as soon as
432
+ * the server has taken the request. Pass `opts.requestId` (a UUID you mint)
433
+ * to know the id before submitting; submitting an id that names a request
434
+ * you already made rejoins it instead of starting another.
435
+ *
436
+ * Errors that leave the request alive carry `pending: true`: a timeout, a
437
+ * stop, a dropped connection. An error without it is the end of the request.
140
438
  *
141
439
  * @param {Object} client - PlaidClient instance
142
440
  * @param {string} projectId - Project UUID
143
441
  * @param {string} serviceId - Service ID to request
144
442
  * @param {any} data - Request payload
145
- * @param {number} [timeout=10000] - Timeout in ms
443
+ * @param {number} [timeout=10000] - How long the service may say NOTHING, in ms.
444
+ * Every event it sends starts the clock again, so this does not cap a long run
146
445
  * @param {function} [onProgress] - Called with each progress payload {percent, message}
446
+ * @param {AbortSignal} [signal] - Abort to stop waiting; rejects with an AbortError
447
+ * @param {Object} [opts]
448
+ * @param {string} [opts.requestId] - A client-minted request id (UUID)
449
+ * @param {function} [opts.onAccepted] - Called with the request id once the server has it
450
+ * @param {string[]} [opts.projectIds] - Other projects the request is about, beside
451
+ * `projectId`. A delegating service's token is scoped to `projectId` and to those of
452
+ * these the requester can read, and reaches nothing else
453
+ * @param {boolean} [opts.noOperation] - Carry no open operation: the service's writes
454
+ * are a group of their own, not part of whatever operation this client has open
147
455
  * @returns {Promise<any>} The service's result
148
456
  */
149
- export function requestService(client, projectId, serviceId, data, timeout = 10000, onProgress) {
457
+ export function requestService(client, projectId, serviceId, data, timeout = 10000, onProgress, signal, opts = {}) {
150
458
  // Propagate an open logical operation (client.beginOperation) to the
151
459
  // service: its writes then fold under the requester's audit-log entry
152
460
  // (the Python BaseService adopts the id around process_request). Only for a
153
461
  // plain-object payload — that's the only shape the service param schema
154
462
  // delivers anyway.
155
- const group = client.operationGroup;
463
+ // Its kind and reference go too, so a service that writes before the
464
+ // requester does still records them.
465
+ //
466
+ // `opts.noOperation` sends none: the service starts a group of its own. For
467
+ // a request that is its own action whatever else is on the wire, such as
468
+ // approving an assistant's plan or starting a service run. The client holds
469
+ // one open operation, so without it an edit still saving at that moment
470
+ // would take in every write the request makes, under the edit's kind.
471
+ const group = opts.noOperation ? null : client.operationGroup;
156
472
  const payload =
157
473
  group && data && typeof data === 'object' && !Array.isArray(data)
158
- ? { ...data, operationGroup: { id: group.id, message: group.message } }
474
+ ? {
475
+ ...data,
476
+ operationGroup: {
477
+ id: group.id,
478
+ message: group.message,
479
+ ...(group.kind ? { kind: group.kind } : {}),
480
+ ...(group.ref ? { ref: group.ref } : {}),
481
+ },
482
+ }
159
483
  : data;
484
+ const query = new URLSearchParams();
485
+ if (opts.requestId) query.set('request-id', opts.requestId);
486
+ if (opts.projectIds?.length) query.set('project-ids', opts.projectIds.join(','));
487
+ const qs = String(query) ? `?${query}` : '';
488
+ return streamServiceRequest(
489
+ client,
490
+ {
491
+ url: `${client.baseUrl}/api/v1/projects/${projectId}/services/${encodeURIComponent(serviceId)}/requests${qs}`,
492
+ method: 'POST',
493
+ body: JSON.stringify(payload === undefined ? null : transformRequest(payload)),
494
+ onStatus: (response) =>
495
+ response.status === 503 ? new Error(`No live service '${serviceId}' on this project`) : null,
496
+ what: 'Service request',
497
+ },
498
+ timeout,
499
+ onProgress,
500
+ signal,
501
+ opts.onAccepted,
502
+ );
503
+ }
504
+
505
+ /**
506
+ * Rejoin a service request made earlier (by this user) and await its result:
507
+ * the latest progress is replayed, then the result comes, or at once if the
508
+ * request already finished. Rejects with an error whose `status` is 404 when
509
+ * the request is unknown or expired (the server keeps a finished request's
510
+ * result for a while, not forever). As with `requestService`, `timeout` is
511
+ * how long the service may be silent, and an error carrying `pending: true`
512
+ * means the request is still there to rejoin again.
513
+ *
514
+ * @param {Object} client - PlaidClient instance
515
+ * @param {string} projectId - Project UUID
516
+ * @param {string} requestId - The request id (from `onAccepted` or your own)
517
+ * @param {number} [timeout=10000] - How long the service may say NOTHING, in ms
518
+ * @param {function} [onProgress] - Called with each progress payload {percent, message}
519
+ * @param {AbortSignal} [signal] - Abort to stop waiting; rejects with an AbortError
520
+ * @returns {Promise<any>} The service's result
521
+ */
522
+ export function attachServiceRequest(client, projectId, requestId, timeout = 10000, onProgress, signal) {
523
+ return streamServiceRequest(
524
+ client,
525
+ {
526
+ url: `${client.baseUrl}/api/v1/projects/${projectId}/service-requests/${encodeURIComponent(requestId)}`,
527
+ method: 'GET',
528
+ what: 'Attach to service request',
529
+ },
530
+ timeout,
531
+ onProgress,
532
+ signal,
533
+ );
534
+ }
535
+
536
+ /**
537
+ * Thrown inside a handler when the requester has asked it to stop.
538
+ *
539
+ * Cooperative cancellation: nothing interrupts a handler, so the request ends
540
+ * at the next point the handler looks. `responseHelper.progress` is that
541
+ * point, which is why a long service that already reports progress needs no
542
+ * changes at all. `serve` catches this and ends the request as STOPPED rather
543
+ * than failed.
544
+ */
545
+ export class ServiceCancelled extends Error {
546
+ constructor(message = 'The requester stopped this request') {
547
+ super(message);
548
+ this.name = 'ServiceCancelled';
549
+ }
550
+ }
551
+
552
+ /**
553
+ * The cancellation half of a responseHelper: a flag, a depth counter, and one
554
+ * rule about when a checkpoint may raise. Split from the transport so it can
555
+ * be reasoned about on its own. Mirrors `CancelScope` in the Python client.
556
+ */
557
+ export function createCancelScope(isCancelled) {
558
+ // Depth of nested `critical()` blocks; while non-zero, a checkpoint will
559
+ // not throw.
560
+ let criticalDepth = 0;
561
+ return {
562
+ get cancelled() {
563
+ return !!isCancelled();
564
+ },
565
+ /** Stop here if the requester has asked the request to stop. */
566
+ raiseIfCancelled() {
567
+ if (isCancelled() && criticalDepth === 0) throw new ServiceCancelled();
568
+ },
569
+ /**
570
+ * Run `fn` as a stretch that must finish once begun, usually the writes.
571
+ * Checkpoints inside do not throw, so a half-written document is never
572
+ * left behind; cancellation takes effect at the first checkpoint after.
573
+ */
574
+ async critical(fn) {
575
+ criticalDepth++;
576
+ try {
577
+ return await fn();
578
+ } finally {
579
+ criticalDepth--;
580
+ }
581
+ },
582
+ };
583
+ }
584
+
585
+ /**
586
+ * Ask the service to stop a request made earlier (by this user). The request
587
+ * still ends with whatever the service then reports, on the stream of whoever
588
+ * is awaiting it. Rejects with 404 if unknown or expired, 409 once finished.
589
+ *
590
+ * outOfBand: a DELETE, but not a write. It signals a running service and
591
+ * changes no project data (see the note at the top of http.js).
592
+ *
593
+ * @param {Object} client - PlaidClient instance
594
+ * @param {string} projectId - Project UUID
595
+ * @param {string} requestId - The request id
596
+ * @returns {Promise<void>}
597
+ */
598
+ export function cancelServiceRequest(client, projectId, requestId) {
599
+ return client._request(
600
+ 'DELETE',
601
+ `/api/v1/projects/${projectId}/service-requests/${encodeURIComponent(requestId)}`,
602
+ { outOfBand: true },
603
+ );
604
+ }
605
+
606
+ /**
607
+ * Mark an error as one that leaves the request ALIVE on the server: a timeout,
608
+ * a stop, a dropped connection. The service goes on working and its result
609
+ * still waits under the request id, so a caller holding that id can rejoin it
610
+ * with `attachServiceRequest`, and must not forget the id the way it forgets
611
+ * a request that really ended. An error without `pending` is terminal.
612
+ */
613
+ const stillRunning = (err) => Object.assign(err, { pending: true });
614
+
615
+ /**
616
+ * Open a request stream (submit or attach) and read it to its terminal
617
+ * event: `accepted` names the request, `progress` events go to `onProgress`,
618
+ * and `result` / `error` settle the promise.
619
+ */
620
+ function streamServiceRequest(client, { url, method, body, onStatus, what }, timeout, onProgress, signal, onAccepted) {
160
621
  return new Promise((resolve, reject) => {
161
622
  const abortController = new AbortController();
162
623
  let settled = false;
@@ -167,38 +628,70 @@ export function requestService(client, projectId, serviceId, data, timeout = 100
167
628
  abortController.abort();
168
629
  fn(arg);
169
630
  };
170
- const timer = setTimeout(
171
- () => finish(reject, new Error(`Service request timed out after ${timeout}ms`)),
172
- timeout,
173
- );
631
+
632
+ // `timeout` is IDLE time, meaning how long the service may say nothing. It
633
+ // is not a deadline on the run: every event from the server restarts it,
634
+ // because a service that is reporting its progress is not hung. As a
635
+ // deadline on the whole run it killed working transcriptions at the
636
+ // five-minute default and left their writes to land on a document the page
637
+ // had already handed back to the user as editable.
638
+ let timer;
639
+ const waitAgain = () => {
640
+ clearTimeout(timer);
641
+ timer = setTimeout(
642
+ () =>
643
+ finish(reject, stillRunning(new Error(`${what} timed out after ${timeout}ms of silence`))),
644
+ timeout,
645
+ );
646
+ };
647
+ waitAgain();
648
+
649
+ // An external signal stops waiting on a long request (a UI's Stop button).
650
+ // Reject with an AbortError so a caller can tell a deliberate stop from a
651
+ // failure. The service is not told here: it goes on, and its result can
652
+ // still be collected by request id (see cancelServiceRequest to stop it).
653
+ const stop = () => {
654
+ const err = new Error('The service request was stopped');
655
+ err.name = 'AbortError';
656
+ finish(reject, stillRunning(err));
657
+ };
658
+ if (signal) {
659
+ if (signal.aborted) {
660
+ stop();
661
+ return;
662
+ }
663
+ signal.addEventListener('abort', stop, { once: true });
664
+ }
174
665
 
175
666
  (async () => {
176
667
  let response;
177
668
  try {
178
- response = await fetch(
179
- `${client.baseUrl}/api/v1/projects/${projectId}/services/${encodeURIComponent(serviceId)}/requests`,
180
- {
181
- method: 'POST',
182
- headers: {
183
- 'Authorization': `Bearer ${client.token}`,
184
- 'Content-Type': 'application/json',
185
- 'Accept': 'text/event-stream',
186
- },
187
- body: JSON.stringify(payload === undefined ? null : transformRequest(payload)),
188
- signal: abortController.signal,
669
+ response = await fetch(url, {
670
+ method,
671
+ headers: {
672
+ 'Authorization': `Bearer ${client.token}`,
673
+ 'Content-Type': 'application/json',
674
+ 'Accept': 'text/event-stream',
189
675
  },
190
- );
676
+ ...(body === undefined ? {} : { body }),
677
+ signal: abortController.signal,
678
+ });
191
679
  } catch (error) {
192
- if (error.name !== 'AbortError') finish(reject, new Error(`Failed to submit service request: ${error.message}`));
680
+ // The POST may or may not have reached the server. Treat it as alive:
681
+ // rejoining a request that was never made simply 404s.
682
+ if (error.name !== 'AbortError') finish(reject, stillRunning(new Error(`${what} could not be sent: ${error.message}`)));
193
683
  return;
194
684
  }
195
685
 
196
- if (response.status === 503) {
197
- finish(reject, new Error(`No live service '${serviceId}' on this project`));
686
+ const special = onStatus ? onStatus(response) : null;
687
+ if (special) {
688
+ finish(reject, special);
198
689
  return;
199
690
  }
200
691
  if (!response.ok) {
201
- finish(reject, new Error(`Service request failed: HTTP ${response.status} ${response.statusText}`));
692
+ const err = new Error(`${what} failed: HTTP ${response.status} ${response.statusText}`);
693
+ err.status = response.status;
694
+ finish(reject, err);
202
695
  return;
203
696
  }
204
697
 
@@ -223,13 +716,16 @@ export function requestService(client, projectId, serviceId, data, timeout = 100
223
716
  dataLine = line.slice(6);
224
717
  } else if (line === '' && eventType && dataLine) {
225
718
  const payload = transformResponse(JSON.parse(dataLine));
226
- if (eventType === 'progress') {
719
+ waitAgain(); // it spoke, so it is not hung
720
+ if (eventType === 'accepted') {
721
+ if (onAccepted) { try { onAccepted(payload.requestId); } catch (_) { /* ignore */ } }
722
+ } else if (eventType === 'progress') {
227
723
  if (onProgress) { try { onProgress(payload.progress); } catch (_) { /* ignore */ } }
228
724
  } else if (eventType === 'result') {
229
725
  finish(resolve, payload.data);
230
726
  return;
231
727
  } else if (eventType === 'error') {
232
- finish(reject, new Error(payload?.error || 'Service request failed'));
728
+ finish(reject, new Error(payload?.error || `${what} failed`));
233
729
  return;
234
730
  }
235
731
  eventType = '';
@@ -237,9 +733,9 @@ export function requestService(client, projectId, serviceId, data, timeout = 100
237
733
  }
238
734
  }
239
735
  }
240
- finish(reject, new Error('Service closed the connection without a result'));
736
+ finish(reject, stillRunning(new Error('Service closed the connection without a result')));
241
737
  } catch (error) {
242
- if (error.name !== 'AbortError') finish(reject, new Error(`Service request stream error: ${error.message}`));
738
+ if (error.name !== 'AbortError') finish(reject, stillRunning(new Error(`${what} stream error: ${error.message}`)));
243
739
  }
244
740
  })();
245
741
  });