@jacebenson/jsn 5.2.0 → 5.3.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.
@@ -10,10 +10,11 @@ import { AppError, CodeConfirmationRequired, errAPI, errUsage, errConfirmationRe
10
10
  import { declareCapabilities } from '../capabilities.js';
11
11
  import { resolveScope } from './scopes.js';
12
12
  import { unwrapSysId } from '../resolve-record.js';
13
+ import { assertNoUnresolvedProblems, DEFAULT_OPERATION_TIMEOUT_MS } from '../update-set-apply.js';
13
14
 
14
15
  declareCapabilities('updatesets', {
15
- mutationSubcommands: ['create', 'set', 'complete', 'ignore', 'parent', 'import', 'reopen'],
16
- mutationContextExemptSubcommands: ['create', 'set', 'import', 'reopen'],
16
+ mutationSubcommands: ['create', 'set', 'complete', 'ignore', 'parent', 'import', 'reopen', 'preview', 'commit'],
17
+ mutationContextExemptSubcommands: ['create', 'set', 'import', 'reopen', 'preview', 'commit'],
17
18
  localPreviewSubcommands: ['import'],
18
19
  });
19
20
 
@@ -97,6 +98,121 @@ export async function resolveUpdateSetByName(app, name) {
97
98
  throw errUsage(`Multiple update sets named "${name}" (${records.length}): ${scopes}.${scopeNote}\nRun bare "jsn updatesets set" and pick by scope.`);
98
99
  }
99
100
 
101
+ const RETRIEVED_FIELDS = 'sys_id,name,state,remote_sys_id,update_set,sys_created_on,sys_updated_on';
102
+
103
+ function remoteState(record) {
104
+ const raw = record?.state;
105
+ return String(raw?.value ?? raw ?? '').toLowerCase();
106
+ }
107
+
108
+ /**
109
+ * Resolve a *retrieved* update set (sys_remote_update_set) by exact name or
110
+ * sys_id. Imported XML lives here; local capture sets live in sys_update_set.
111
+ * @returns {Promise<object>} raw record
112
+ */
113
+ export async function resolveRetrievedUpdateSet(app, identifier) {
114
+ assertSafeExactMatch(identifier);
115
+ const isSysID = /^[0-9a-f]{32}$/i.test(identifier);
116
+ const params = new URLSearchParams();
117
+ params.set('sysparm_query', isSysID ? `sys_id=${identifier}` : `name=${identifier}`);
118
+ params.set('sysparm_limit', isSysID ? '1' : '20');
119
+ params.set('sysparm_display_value', 'all');
120
+ params.set('sysparm_fields', RETRIEVED_FIELDS);
121
+ const records = await app.sdk.list('sys_remote_update_set', params);
122
+ if (!records.length) {
123
+ throw errUsage(
124
+ `Retrieved update set not found: ${identifier}`,
125
+ `Load the XML first (jsn updatesets import <file>), or pass the sys_id of the retrieved set.`,
126
+ );
127
+ }
128
+ if (records.length > 1) {
129
+ throw errUsage(`Multiple retrieved update sets named "${identifier}". Pass the sys_id instead:\n${records.map((r) => ` ${getStringField(r, 'sys_id')} ${remoteState(r)}`).join('\n')}`);
130
+ }
131
+ return records[0];
132
+ }
133
+
134
+ async function fetchRetrievedUpdateSet(app, sysID) {
135
+ const params = new URLSearchParams();
136
+ params.set('sysparm_query', `sys_id=${sysID}`);
137
+ params.set('sysparm_limit', '1');
138
+ params.set('sysparm_display_value', 'all');
139
+ params.set('sysparm_fields', RETRIEVED_FIELDS);
140
+ const [record] = await app.sdk.list('sys_remote_update_set', params);
141
+ return record || null;
142
+ }
143
+
144
+ /**
145
+ * Confirmation gate shared by updatesets mutations. Automation gets a
146
+ * confirmation-required error with a rerun command instead of a prompt.
147
+ * @returns {Promise<boolean>} false when the human declined
148
+ */
149
+ async function confirmUpdateSetMutation(argv, app, question, rerun) {
150
+ if (argv.yes) return true;
151
+ if (!canPrompt() || argv.json || argv.get || (argv.format && argv.format !== FormatAuto)) {
152
+ throw new AppError(CodeConfirmationRequired, `${question} — confirmation required. Pass --yes after approving this target.`,
153
+ `Rerun: ${buildRerunCommand(argv, { rerun })}`);
154
+ }
155
+ return confirm({ message: question, default: false });
156
+ }
157
+
158
+ function timeoutFrom(argv) {
159
+ const seconds = Number(argv.timeout ?? DEFAULT_OPERATION_TIMEOUT_MS / 1000);
160
+ if (!Number.isFinite(seconds) || seconds <= 0) throw errUsage('--timeout must be a positive number of seconds');
161
+ return Math.round(seconds * 1000);
162
+ }
163
+
164
+ /**
165
+ * The platform records the local update set a commit produced on the retrieved
166
+ * record itself (`sys_remote_update_set.update_set`). Prefer that exact
167
+ * reference; only fall back to a name lookup when it is absent.
168
+ */
169
+ function localReferenceID(reference) {
170
+ if (!reference) return '';
171
+ if (typeof reference === 'object') {
172
+ const value = String(reference.value ?? '').trim();
173
+ if (/^[0-9a-f]{32}$/i.test(value)) return value;
174
+ const link = String(reference.link ?? '');
175
+ const match = link.match(/\/([0-9a-f]{32})(?:\/)?$/i);
176
+ return match ? match[1] : '';
177
+ }
178
+ return /^[0-9a-f]{32}$/i.test(String(reference).trim()) ? String(reference).trim() : '';
179
+ }
180
+
181
+ /**
182
+ * Find the local update set a commit created. Ambiguity is reported, not
183
+ * guessed: duplicate names are legitimate on ServiceNow.
184
+ */
185
+ async function findLocalUpdateSet(app, name, reference) {
186
+ const referenceID = localReferenceID(reference);
187
+ if (referenceID) {
188
+ try {
189
+ const record = await app.sdk.get('sys_update_set', referenceID);
190
+ if (record) {
191
+ return {
192
+ sys_id: getStringField(record, 'sys_id') || referenceID,
193
+ name: getStringField(record, 'name') || name,
194
+ state: String(record.state?.value ?? record.state ?? ''),
195
+ ambiguous: false,
196
+ };
197
+ }
198
+ } catch { /* fall back to the name lookup */ }
199
+ }
200
+ const params = new URLSearchParams();
201
+ params.set('sysparm_query', `name=${name}^ORDERBYDESCsys_created_on`);
202
+ params.set('sysparm_display_value', 'all');
203
+ params.set('sysparm_limit', '2');
204
+ params.set('sysparm_fields', 'sys_id,name,state,sys_created_on');
205
+ try {
206
+ const records = await app.sdk.list('sys_update_set', params);
207
+ if (records.length === 1) {
208
+ return { sys_id: getStringField(records[0], 'sys_id'), name: getStringField(records[0], 'name'), state: String(records[0].state?.value ?? records[0].state ?? ''), ambiguous: false };
209
+ }
210
+ return { ambiguous: true, count: records.length, note: records.length ? 'Multiple local update sets share this name' : 'No local update set with this name was found' };
211
+ } catch (error) {
212
+ return { ambiguous: false, unverified: true, note: `Could not read local update sets: ${error.message}` };
213
+ }
214
+ }
215
+
100
216
 
101
217
  function rawReferenceId(value) {
102
218
  if (!value) return '';
@@ -546,8 +662,23 @@ export function updateSetsCmd(wrap) {
546
662
  builder: y => y
547
663
  .positional('file', { type: 'string', describe: 'Update set XML export' })
548
664
  .option('dry-run', { type: 'boolean', describe: 'Inspect locally without any instance requests' })
549
- .option('yes', { type: 'boolean', describe: 'Confirm loading the displayed XML into the selected target' }),
665
+ .option('yes', { type: 'boolean', describe: 'Confirm loading the displayed XML into the selected target' })
666
+ .option('name', { type: 'string', describe: 'Unsupported: the set keeps the name in its XML envelope' })
667
+ .option('local', { type: 'boolean', describe: 'Unsupported: import always loads a retrieved update set' })
668
+ .option('state', { type: 'string', describe: 'Unsupported: import never changes state' }),
550
669
  handler: wrap(async (argv, app) => {
670
+ // The proposed import modifiers are refused explicitly so none of
671
+ // them can silently rewrite identity, convert the target table, or
672
+ // flip state. Preview/commit/reopen are the supported transitions.
673
+ if (argv.name !== undefined) {
674
+ throw errUsage('Import cannot rename a retrieved update set: its name, sys_id, and remote_sys_id come from the exported envelope, so rewriting them would change the set\'s identity.\nLoad it unchanged, then rename the retrieved set in ServiceNow if you need a different name.');
675
+ }
676
+ if (argv.local) {
677
+ throw errUsage('Import always creates a retrieved update set (sys_remote_update_set); it does not convert XML into a local capture set.\nPreview and commit it to apply the changes (jsn updatesets preview / commit).');
678
+ }
679
+ if (argv.state !== undefined) {
680
+ throw errUsage('Import never sets state. A loaded retrieved set is previewed and committed explicitly; a local set is reopened with "jsn updatesets reopen".');
681
+ }
551
682
  const stat = await fs.promises.stat(argv.file);
552
683
  if (!stat.isFile() || stat.size > MAX_UPDATE_SET_BYTES) throw errUsage('Expected an XML file no larger than 50 MiB');
553
684
  const xml = await fs.promises.readFile(argv.file, 'utf8');
@@ -556,15 +687,123 @@ export function updateSetsCmd(wrap) {
556
687
  if (argv.dryRun) return app.ok({ ...summary, members, dry_run: true }, { summary: `XML: ${inspection.name}; ${inspection.count} updates (local inspection only)` });
557
688
  app.requireInstance();
558
689
  const question = `Load "${inspection.name}" (${inspection.count} updates) into ${app.getEffectiveInstance()} as a retrieved update set? This does not commit its changes.`;
559
- if (!argv.yes) {
560
- if (!canPrompt() || argv.json || argv.get || (argv.format && argv.format !== FormatAuto)) {
561
- throw new AppError(CodeConfirmationRequired, `${question} — confirmation required. Pass --yes after approving this target.`,
562
- `Rerun: ${buildRerunCommand(argv, { rerun: ['updatesets', 'import', argv.file, '--yes'] })}`);
563
- }
564
- if (!await confirm({ message: question, default: false })) return;
565
- }
690
+ if (!await confirmUpdateSetMutation(argv, app, question, ['updatesets', 'import', argv.file, '--yes'])) return;
566
691
  const result = await app.sdk.importUpdateSet(xml, inspection, path.basename(argv.file));
567
- app.ok({ ...summary, ...result, committed: false }, { summary: `Loaded retrieved update set "${inspection.name}" (${result.count} updates); not committed` });
692
+ app.ok({ ...summary, ...result, committed: false }, {
693
+ summary: `Loaded retrieved update set "${inspection.name}" (${result.count} updates); not committed`,
694
+ breadcrumbs: [
695
+ { action: 'preview', cmd: `jsn updatesets preview ${quoteShellArg(result.sys_id)}`, description: 'Preview against this instance before committing' },
696
+ { action: 'problems', cmd: `jsn updatesets problems ${quoteShellArg(result.sys_id)}`, description: 'Review preview problems' },
697
+ ],
698
+ });
699
+ }),
700
+ })
701
+ .command({
702
+ command: 'preview <name>',
703
+ describe: 'Run the platform preview for a loaded retrieved update set and report its problems',
704
+ builder: y => y
705
+ .positional('name', { type: 'string', describe: 'Retrieved update set name or sys_id' })
706
+ .option('yes', { type: 'boolean', describe: 'Confirm starting the preview on the selected target' })
707
+ .option('timeout', { type: 'number', describe: 'Seconds to wait for the preview tracker (default 600)' }),
708
+ handler: wrap(async (argv, app) => {
709
+ app.requireInstance();
710
+ const target = await resolveRetrievedUpdateSet(app, argv.name);
711
+ const sysID = getStringField(target, 'sys_id');
712
+ const state = remoteState(target);
713
+ if (!['loaded', 'previewed'].includes(state)) {
714
+ throw errUsage(`Cannot preview a retrieved update set in state "${state}"; expected loaded or previewed.\nInspect it first: jsn records get sys_remote_update_set ${sysID}`);
715
+ }
716
+ const question = `Preview retrieved update set "${getStringField(target, 'name')}" (state: ${state}) on ${app.getEffectiveInstance()}? Preview does not commit changes.`;
717
+ if (!await confirmUpdateSetMutation(argv, app, question, ['updatesets', 'preview', sysID, '--yes'])) return;
718
+ const progress = await app.sdk.previewUpdateSet(sysID, { timeoutMs: timeoutFrom(argv) });
719
+ const verified = await fetchRetrievedUpdateSet(app, sysID);
720
+ if (!verified || remoteState(verified) !== 'previewed') {
721
+ throw errAPI(200, `Preview reported "${progress.label}" but the retrieved update set is in state "${verified ? remoteState(verified) || 'unknown' : 'unreadable'}".\nInspect it in ServiceNow before committing; jsn will not commit a set the platform has not previewed.`);
722
+ }
723
+ const { problems, count, unresolved, truncated } = await app.sdk.listUpdateSetPreviewProblems(sysID);
724
+ app.ok({
725
+ update_set: getStringField(target, 'name'),
726
+ sys_id: sysID,
727
+ state: 'previewed',
728
+ preview: { status: progress.label, percent_complete: progress.percent_complete, message: progress.message, tracked: progress.tracked !== false },
729
+ problems: count,
730
+ unresolved: unresolved.length,
731
+ truncated,
732
+ problems_detail: problems,
733
+ }, {
734
+ summary: `Previewed retrieved update set "${getStringField(target, 'name')}": ${unresolved.length} unresolved problem(s) of ${count}`,
735
+ breadcrumbs: unresolved.length
736
+ ? [{ action: 'problems', cmd: `jsn updatesets problems ${quoteShellArg(sysID)}`, description: 'Review the problems a human must resolve' }]
737
+ : [{ action: 'commit', cmd: `jsn updatesets commit ${quoteShellArg(sysID)} --yes`, description: 'Commit after reviewing the preview' }],
738
+ });
739
+ }),
740
+ })
741
+ .command({
742
+ command: 'problems <name>',
743
+ aliases: ['preview-problems'],
744
+ describe: 'List preview problems for a retrieved update set (read-only; never resolves them)',
745
+ builder: y => y
746
+ .positional('name', { type: 'string', describe: 'Retrieved update set name or sys_id' })
747
+ .option('include-resolved', { type: 'boolean', describe: 'Include problems a human already accepted or skipped' }),
748
+ handler: wrap(async (argv, app) => {
749
+ app.requireInstance();
750
+ const target = await resolveRetrievedUpdateSet(app, argv.name);
751
+ const sysID = getStringField(target, 'sys_id');
752
+ const { problems, count, unresolved, truncated } = await app.sdk.listUpdateSetPreviewProblems(sysID);
753
+ const shown = argv.includeResolved ? problems : unresolved;
754
+ app.ok({
755
+ update_set: getStringField(target, 'name'),
756
+ sys_id: sysID,
757
+ state: remoteState(target),
758
+ count,
759
+ unresolved: unresolved.length,
760
+ truncated,
761
+ problems: shown,
762
+ }, {
763
+ summary: `${unresolved.length} unresolved preview problem(s) for "${getStringField(target, 'name')}" (${count} total)`,
764
+ breadcrumbs: [{ action: 'show', cmd: `jsn records get sys_remote_update_set ${quoteShellArg(sysID)}`, description: 'Open the retrieved update set record' }],
765
+ });
766
+ }),
767
+ })
768
+ .command({
769
+ command: 'commit <name>',
770
+ describe: 'Commit a previewed retrieved update set once its preview problems are resolved',
771
+ builder: y => y
772
+ .positional('name', { type: 'string', describe: 'Retrieved update set name or sys_id' })
773
+ .option('yes', { type: 'boolean', describe: 'Confirm applying the update set to the selected target' })
774
+ .option('timeout', { type: 'number', describe: 'Seconds to wait for the commit tracker (default 600)' }),
775
+ handler: wrap(async (argv, app) => {
776
+ app.requireInstance();
777
+ const target = await resolveRetrievedUpdateSet(app, argv.name);
778
+ const sysID = getStringField(target, 'sys_id');
779
+ const name = getStringField(target, 'name');
780
+ const state = remoteState(target);
781
+ if (state === 'loaded') {
782
+ throw errUsage(`Retrieved update set "${name}" has not been previewed yet.\nRun: jsn updatesets preview ${quoteShellArg(sysID)}`);
783
+ }
784
+ if (state !== 'previewed') {
785
+ throw errUsage(`Cannot commit a retrieved update set in state "${state}"; expected previewed.`);
786
+ }
787
+ const previewProblems = await app.sdk.listUpdateSetPreviewProblems(sysID);
788
+ assertNoUnresolvedProblems(previewProblems);
789
+ const question = `Commit retrieved update set "${name}" (${previewProblems.count} preview problem(s), none unresolved) to ${app.getEffectiveInstance()}? This applies its changes to the instance.`;
790
+ if (!await confirmUpdateSetMutation(argv, app, question, ['updatesets', 'commit', sysID, '--yes'])) return;
791
+ const progress = await app.sdk.commitUpdateSet(sysID, { timeoutMs: timeoutFrom(argv) });
792
+ const verified = await fetchRetrievedUpdateSet(app, sysID);
793
+ if (!verified || remoteState(verified) !== 'committed') {
794
+ throw errAPI(200, `Commit reported "${progress.label}" but the retrieved update set is in state "${verified ? remoteState(verified) || 'unknown' : 'unreadable'}".\nThe commit may still be running; inspect Retrieved Update Sets on the target before retrying. jsn does not retry it.`);
795
+ }
796
+ const local = await findLocalUpdateSet(app, name, verified.update_set);
797
+ app.ok({
798
+ update_set: name,
799
+ sys_id: sysID,
800
+ state: 'committed',
801
+ commit: { status: progress.label, percent_complete: progress.percent_complete, message: progress.message, tracked: progress.tracked !== false },
802
+ preview_problems: previewProblems.count,
803
+ local_update_set: local,
804
+ }, {
805
+ summary: `Committed retrieved update set "${name}"${local.sys_id ? ` as local update set ${local.sys_id}` : ` (${local.note || 'local update set not confirmed'})`}`,
806
+ });
568
807
  }),
569
808
  })
570
809
  .command({
@@ -789,6 +1028,9 @@ export function updateSetsCmd(wrap) {
789
1028
  console.log(' show <name> Show an update set (type counts + risky items)');
790
1029
  console.log(' export <name> Export an update set to XML (stdout or --out)');
791
1030
  console.log(' import <file> Load retrieved XML (--dry-run inspects locally; --yes confirms)');
1031
+ console.log(' preview <set> Platform preview of a loaded retrieved set; reports problems');
1032
+ console.log(' problems <set> List preview problems (read-only; never resolves them)');
1033
+ console.log(' commit <set> Commit a previewed retrieved set after problems are resolved');
792
1034
  console.log(' reopen <name> Explicitly return a closed set to in progress');
793
1035
  console.log(' set [name] Set the current update set (picker when run bare)');
794
1036
  console.log(' create Create a new update set (auto-sets as current)');
package/src/errors.js CHANGED
@@ -54,6 +54,11 @@ export function errAuth(msg) {
54
54
  return new AppError(CodeAuth, msg, 'Run: jsn auth login');
55
55
  }
56
56
 
57
+ /** Authentication failure with domain-specific recovery guidance. */
58
+ export function errAuthHint(msg, hint) {
59
+ return new AppError(CodeAuth, msg, hint);
60
+ }
61
+
57
62
  export function errForbidden(msg) {
58
63
  return new AppError(CodeForbidden, msg, '', 403);
59
64
  }
@@ -265,9 +270,11 @@ export function renderAppError(err, { app = null, argv = null, identifier = '' }
265
270
 
266
271
  if (code === CodeNotFound) {
267
272
  let text = `Error (${code}): ${err.message}\n`;
268
- if (identifier) {
269
- text += `\nHint: The identifier "${identifier}" was not found. Check the name or sys_id.\n`;
270
- }
273
+ // A command that knows why the identifier missed says so; the generic line
274
+ // is only the fallback (it used to replace every command-specific hint, and
275
+ // interpolated the subcommand name as if it were the identifier).
276
+ if (err.hint) text += `\nHint: ${err.hint}\n`;
277
+ else if (identifier) text += `\nHint: The identifier "${identifier}" was not found. Check the name or sys_id.\n`;
271
278
  return { stream: 'stderr', text, exitCode: 1 };
272
279
  }
273
280
 
package/src/output.js CHANGED
@@ -186,6 +186,33 @@ export class OutputWriter {
186
186
  }
187
187
  }
188
188
 
189
+ /**
190
+ * Write one item of an event stream (e.g. `records watch`).
191
+ *
192
+ * A stream cannot use the single-envelope `ok()`, so this method emits one
193
+ * compact JSON object per line — newline-delimited JSON, the shape agents
194
+ * and scripts can consume incrementally without buffering the whole run.
195
+ * Human formats print `opts.line` (domain-formatted by the command) and
196
+ * fall back to the JSON line when the command supplied none.
197
+ *
198
+ * `--get` stays meaningful: the path is resolved against each event, and
199
+ * a path that does not resolve emits `null` rather than aborting the
200
+ * stream mid-observation.
201
+ */
202
+ writeEvent(data, opts = {}) {
203
+ const format = this.effectiveFormat();
204
+ if (format === FormatStyled || format === FormatMarkdown) {
205
+ this.writer.write(`${opts.line ?? JSON.stringify(data)}\n`);
206
+ return;
207
+ }
208
+ if (this.jqFilter) {
209
+ const value = resolvePath(data, this.jqFilter);
210
+ this.writer.write(`${JSON.stringify(value === undefined ? null : value)}\n`);
211
+ return;
212
+ }
213
+ this.writer.write(`${JSON.stringify(data)}\n`);
214
+ }
215
+
189
216
  writeJSON(data, opts) {
190
217
  const resp = { ok: true, data, summary: opts.summary || '', breadcrumbs: opts.breadcrumbs || [] };
191
218
  if (opts.notice) resp.notice = opts.notice;
@@ -385,7 +412,7 @@ export class OutputWriter {
385
412
  let val = getDisplayValue(row[col]);
386
413
  const width = colWidths[col] || 20;
387
414
 
388
- if (j === 0 && instanceURL && table && row.sys_id) {
415
+ if (j === 0 && instanceURL && table && row.sys_id && isTTY(this.writer)) {
389
416
  const url = getTableURL(instanceURL, table, row.sys_id);
390
417
  val = hyperlink(val, url);
391
418
  }
@@ -61,7 +61,7 @@ export default {
61
61
  options: { singular: 'table', scopeValidation: true, showFields: ['name', 'label', 'super_class', 'create_access_controls', 'sys_scope', 'sys_created_on', 'sys_updated_on', 'sys_created_by', 'sys_updated_by', 'is_extendable'] } },
62
62
  incidents: { table: 'incident', aliases: ['incident', 'inc'], columns: ['number', 'short_description', 'priority', 'state', 'assigned_to'], kind: 'ticket' },
63
63
  changes: { table: 'change_request', aliases: ['change_request', 'chg'], columns: ['number', 'short_description', 'risk', 'state', 'assigned_to'], kind: 'ticket' },
64
- requests: { table: 'sc_req_item', aliases: ['sc_req_item', 'req'], columns: ['number', 'short_description', 'stage', 'assigned_to'], kind: 'ticket' },
64
+ requests: { table: 'sc_req_item', aliases: ['sc_req_item', 'req'], columns: ['number', 'cat_item', 'short_description', 'stage', 'assigned_to'], kind: 'ticket' },
65
65
  tasks: { table: 'sc_task', aliases: ['sc_task', 'task'], columns: ['number', 'short_description', 'state', 'assigned_to'], kind: 'ticket' },
66
66
  uipolicies: { table: 'sys_ui_policy', aliases: ['uipolicy', 'up'], columns: ['short_description', 'table', 'sys_class_name', 'active'],
67
67
  identifierField: 'short_description', options: { singular: 'UI policy', scopeValidation: true },
@@ -0,0 +1,206 @@
1
+ // Record watching: bounded observation of one ServiceNow record over AMB.
2
+ //
3
+ // The AMB client (src/amb.js) owns the wire protocol. This module owns the
4
+ // observation session: what counts as an event, when to fetch the record to
5
+ // fill in detail the notification omitted, bounded duration, cancellation,
6
+ // reconnect backoff and — most importantly — honest gap reporting.
7
+ //
8
+ // A record-watcher subscription is best-effort delivery, not a durable
9
+ // stream. After a disconnect the platform does not replay what was missed,
10
+ // so this module reports a gap instead of pretending the event list is
11
+ // complete.
12
+
13
+ import { AppError, CodeUsage } from './errors.js';
14
+ import { normalizeRecordWatcherEvent, recordWatcherChannel } from './amb.js';
15
+
16
+ export const DEFAULT_RECONNECT_DELAYS = [1000, 2000, 4000, 8000, 16000, 30000];
17
+
18
+ function defaultSleep(ms, signal) {
19
+ return new Promise((resolve) => {
20
+ if (signal?.aborted) return resolve();
21
+ const timer = setTimeout(done, ms);
22
+ function done() {
23
+ clearTimeout(timer);
24
+ signal?.removeEventListener('abort', done);
25
+ resolve();
26
+ }
27
+ if (signal) signal.addEventListener('abort', done, { once: true });
28
+ });
29
+ }
30
+
31
+ /** Does the notification carry enough detail that a follow-up read is redundant? */
32
+ export function notificationHasDetail(event) {
33
+ return Boolean(event?.record) || (Array.isArray(event?.changes) && event.changes.length > 0);
34
+ }
35
+
36
+ /**
37
+ * Watch one record until a bound is reached, the caller cancels, or a fatal
38
+ * error occurs.
39
+ *
40
+ * @param {object} opts
41
+ * @param {{ start: Function, next: Function, stop: Function }} opts.client
42
+ * @param {string} opts.table
43
+ * @param {string} opts.sysID
44
+ * @param {string} [opts.query] — encoded query; defaults to `sys_id=<sysID>`
45
+ * @param {number} [opts.timeoutMs] — 0 means "until cancelled"
46
+ * @param {number} [opts.maxEvents] — 0 means unlimited
47
+ * @param {AbortSignal} [opts.signal]
48
+ * @param {'auto'|'always'|'never'} [opts.statePolicy]
49
+ * @param {() => Promise<object|null>} [opts.fetchState]
50
+ * @param {(event: object) => any} [opts.onEvent]
51
+ * @param {(status: object) => any} [opts.onStatus]
52
+ * @param {boolean} [opts.reconnect]
53
+ * @param {number[]} [opts.reconnectDelays]
54
+ * @param {() => number} [opts.now]
55
+ * @param {Function} [opts.sleep]
56
+ */
57
+ export async function watchRecord({
58
+ client,
59
+ table,
60
+ sysID,
61
+ query,
62
+ timeoutMs = 0,
63
+ maxEvents = 0,
64
+ signal,
65
+ statePolicy = 'auto',
66
+ fetchState,
67
+ onEvent = () => {},
68
+ onStatus = () => {},
69
+ reconnect = true,
70
+ reconnectDelays = DEFAULT_RECONNECT_DELAYS,
71
+ now = () => Date.now(),
72
+ sleep = defaultSleep,
73
+ }) {
74
+ if (!client) throw new AppError(CodeUsage, 'Record watch needs an AMB client.');
75
+ if (!table) throw new AppError(CodeUsage, 'Record watch needs a table.');
76
+ if (!sysID) throw new AppError(CodeUsage, 'Record watch needs a record sys_id.');
77
+ if (!['auto', 'always', 'never'].includes(statePolicy)) {
78
+ throw new AppError(CodeUsage, `Unknown state policy: ${statePolicy}`);
79
+ }
80
+ if (timeoutMs < 0 || maxEvents < 0) throw new AppError(CodeUsage, 'Watch bounds cannot be negative.');
81
+ if (statePolicy !== 'never' && typeof fetchState !== 'function') {
82
+ throw new AppError(CodeUsage, 'State fetching is enabled but no record reader was supplied.');
83
+ }
84
+
85
+ const channel = recordWatcherChannel(table, query || `sys_id=${sysID}`);
86
+ const startedAt = now();
87
+ const startedISO = new Date(startedAt).toISOString();
88
+ const deadline = timeoutMs > 0 ? startedAt + timeoutMs : Infinity;
89
+
90
+ let events = 0;
91
+ let gaps = 0;
92
+ let attempts = 0;
93
+ let lastEventAt = null;
94
+ let connected = false;
95
+ let reason = 'timeout';
96
+
97
+ const finish = async (why) => {
98
+ reason = why;
99
+ try { await client.stop([channel]); } catch { /* unsubscription is best effort */ }
100
+ onStatus({ type: 'unsubscribed', reason: why });
101
+ const endedAt = now();
102
+ return {
103
+ type: 'watch_summary',
104
+ table,
105
+ sys_id: sysID,
106
+ channel,
107
+ reason: why,
108
+ events,
109
+ gaps,
110
+ reconnects: Math.max(0, gaps),
111
+ complete: gaps === 0 && reason !== 'error',
112
+ started_at: startedISO,
113
+ ended_at: new Date(endedAt).toISOString(),
114
+ duration_ms: Math.max(0, endedAt - startedAt),
115
+ last_event_at: lastEventAt,
116
+ };
117
+ };
118
+
119
+ onStatus({ type: 'connecting', table, sys_id: sysID, channel });
120
+
121
+ try {
122
+ while (true) {
123
+ const remaining = deadline - now();
124
+ if (remaining <= 0) return await finish('timeout');
125
+ if (signal?.aborted) return await finish('cancelled');
126
+
127
+ if (!connected) {
128
+ const session = await client.start([channel]);
129
+ connected = true;
130
+ attempts = 0;
131
+ const resumed = gaps > 0;
132
+ onStatus({
133
+ type: resumed ? 'reconnected' : 'subscribed',
134
+ channel,
135
+ ...(session?.sessionStatus ? { session_status: session.sessionStatus } : {}),
136
+ // State the limitation, do not imply the stream was continuous.
137
+ ...(resumed ? { may_have_missed_events: true, gaps } : {}),
138
+ });
139
+ }
140
+
141
+ let messages;
142
+ try {
143
+ messages = await client.next({ timeoutMs: Math.min(remaining, 60000), signal });
144
+ } catch (error) {
145
+ if (signal?.aborted) return await finish('cancelled');
146
+ if (deadline - now() <= 0) return await finish('timeout');
147
+ if (error?.fatal === true || !reconnect) throw error;
148
+
149
+ // A dropped connection is a real gap in observation, not a retry note.
150
+ gaps += 1;
151
+ const gapStart = lastEventAt || startedISO;
152
+ const gapAt = new Date(now()).toISOString();
153
+ onStatus({
154
+ type: 'gap',
155
+ at: gapAt,
156
+ since: gapStart,
157
+ reason: error?.message || String(error),
158
+ code: error?.code || null,
159
+ });
160
+ connected = false;
161
+ const wait = reconnectDelays[Math.min(attempts, reconnectDelays.length - 1)];
162
+ attempts += 1;
163
+ const waitedUntil = now() + wait;
164
+ while (now() < waitedUntil && !signal?.aborted && now() < deadline) {
165
+ await sleep(Math.min(wait, Math.max(1, waitedUntil - now())), signal);
166
+ }
167
+ continue;
168
+ }
169
+
170
+ for (const message of messages) {
171
+ if (signal?.aborted) return await finish('cancelled');
172
+ const event = normalizeRecordWatcherEvent(message, { table, sysID }, new Date(now()).toISOString());
173
+ // The channel query scopes delivery to this record. The live payload
174
+ // does not carry a sys_id (jsn fills it from the subscription), so this
175
+ // guard only bites on an instance that does send one — for example a
176
+ // table-level channel returning a different record.
177
+ if (event.sys_id && sysID && event.sys_id !== sysID) continue;
178
+
179
+ const shouldFetch = statePolicy === 'always'
180
+ || (statePolicy === 'auto' && !notificationHasDetail(event));
181
+ if (shouldFetch) {
182
+ try {
183
+ const record = await fetchState();
184
+ event.state = { source: 'fetched', fetched_at: new Date(now()).toISOString(), record };
185
+ } catch (error) {
186
+ // Never let a failed follow-up read masquerade as a failed or
187
+ // complete event; keep the notification and record the problem.
188
+ event.state = null;
189
+ event.state_error = {
190
+ code: error?.code || null,
191
+ message: error?.message || String(error),
192
+ };
193
+ }
194
+ }
195
+
196
+ events += 1;
197
+ lastEventAt = event.received_at;
198
+ await onEvent(event);
199
+ if (maxEvents > 0 && events >= maxEvents) return await finish('max_events');
200
+ }
201
+ }
202
+ } catch (error) {
203
+ await finish('error');
204
+ throw error;
205
+ }
206
+ }