@velaro/cli 1.4.96 → 1.4.98

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/lib/log-search.js CHANGED
@@ -1,93 +1,200 @@
1
1
  // Complete Velaro Logger reads (2026-10-14).
2
2
  //
3
- // WHY: velaro-messaging's /superadmin/logs/search and /internal/logs/search silently under-report text queries.
3
+ // WHY: velaro-messaging's /superadmin/logs/search and /internal/logs/search silently under-reported text queries.
4
4
  // Proven live that day: q=[HttpFallback] over 3.9 h returned 0-2 rows while 136 existed, and q=AsrsNegotiateFailed
5
- // (no level) returned 0 while 4 existed. The AI-search path only sees the newest 1,000 candidates and its answer was
6
- // final; the exact path only sees the newest 5,000 rows of the window before filtering. Neither said so.
5
+ // (no level) returned 0 while 4 existed. The AI-search path only saw the newest 1,000 candidates and its answer was
6
+ // final; the exact path only saw the newest 5,000 rows of the window before filtering. Neither said so.
7
7
  //
8
- // HOW (no q= ever sent): level/siteId/source/integration/platform/environment/correlationId are pushed to the
9
- // server (Table Storage OData, cheap and exact); includeTotal=true makes the server report totalCountCapped when a
10
- // slice hit its scan cap; a capped slice is bisected until none is capped; text (contains/regex/logger) is
11
- // filtered client side. The result says whether it is COMPLETE, so a 0 is never ambiguous.
8
+ // TWO MODES, picked automatically from the first response:
9
+ // * CURSOR mode (server with velaro-messaging PR #2510, response carries `truncated`/`scannedRows`): the server scans the
10
+ // window newest-first applying level/site AND text (as an escaped regex, which also forces the exact path) while it
11
+ // scans, reports `truncated`, and returns `nextCursor` whenever more rows may exist. We follow the cursor until it is
12
+ // null, so a 2 h window is a handful of requests instead of hundreds.
13
+ // * BISECT mode (older server): never send q=; push level/site/etc server side; includeTotal=true reports
14
+ // totalCountCapped for a slice; a capped slice is bisected until none is capped; text is filtered client side.
15
+ // Either way the result says COMPLETE or INCOMPLETE, so a 0 is never ambiguous. Hard caps: maxRequests and maxSeconds.
12
16
  //
13
17
  // KEEP IN SYNC: this file is duplicated byte for byte in mcp/log-search.js (the npm packages ship separately);
14
18
  // cli/lib/log-search.test.js fails if the two copies drift.
15
19
 
16
20
  const MIN_SLICE_MS = 2000;
17
21
 
22
+ export const escapeRegex = (s) => String(s).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&');
23
+
24
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
25
+ const tsOf = (e) => { const t = Date.parse(e.timestamp ?? e.LogTimestamp ?? ''); return Number.isNaN(t) ? 0 : t; };
26
+
27
+ /**
28
+ * fetch that retries ONLY 429 (honouring Retry-After, seconds, capped at 30 s) for up to `retries` attempts and returns the final Response.
29
+ * `init` may be a function so each attempt gets a fresh AbortSignal.
30
+ */
31
+ export async function fetchRetry429(url, init = {}, { retries = 3, fetchImpl = fetch, sleepImpl = sleep } = {}) {
32
+ for (let attempt = 0; ; attempt++) {
33
+ const res = await fetchImpl(url, typeof init === 'function' ? init() : init);
34
+ if (res.status === 429 && attempt < retries) {
35
+ // Number(null) is 0, which would turn a 429 without Retry-After into an immediate retry: a missing header means the 5 s default.
36
+ const raw = res.headers?.get?.('retry-after');
37
+ const ra = raw == null || raw === '' ? NaN : Number(raw);
38
+ await sleepImpl(Math.min(Number.isFinite(ra) && ra >= 0 ? ra : 5, 30) * 1000);
39
+ continue;
40
+ }
41
+ return res;
42
+ }
43
+ }
44
+
45
+ /** fetchRetry429 + JSON. Any non-2xx throws an Error carrying `.status` and the response text. */
46
+ export async function fetchJsonRetry(url, init = {}, opts = {}) {
47
+ const res = await fetchRetry429(url, init, opts);
48
+ if (!res.ok) {
49
+ const err = new Error(`HTTP ${res.status}: ${(await res.text().catch(() => '')).slice(0, 400)}`);
50
+ err.status = res.status;
51
+ throw err;
52
+ }
53
+ return res.json();
54
+ }
55
+
18
56
  /**
19
57
  * @param {object} o
20
- * @param {(query: string) => Promise<any>} o.fetchJson GET `...search?<query>` and return parsed JSON (caller adds auth)
58
+ * @param {(query: string) => Promise<any>} o.fetchJson GET `...search?<query>` and return parsed JSON (caller adds auth/timeout)
21
59
  * @param {Date} o.from
22
60
  * @param {Date} o.to
23
61
  * @param {object} [o.params] server-side filters: level, siteId, source, integration, platform, environment, correlationId
24
- * @param {string} [o.contains] case-insensitive substring of the message (client side)
25
- * @param {string} [o.regex] regex on the message (client side)
26
- * @param {string} [o.logger] substring of the logger name (client side)
62
+ * @param {string} [o.contains] case-insensitive substring of the message
63
+ * @param {string} [o.regex] regex on the message
64
+ * @param {string} [o.logger] substring of the logger name
27
65
  * @param {number} [o.maxRequests=200]
66
+ * @param {number} [o.maxSeconds=120] wall-clock budget for the whole read
67
+ * @param {number} [o.wanted=Infinity] CURSOR mode: stop once this many matches were collected (newest first); the result is then `satisfied`
28
68
  */
29
- export async function completeLogSearch({ fetchJson, from, to, params = {}, contains, regex, logger, maxRequests = 200 }) {
69
+ export async function completeLogSearch({ fetchJson, from, to, params = {}, contains, regex, logger, maxRequests = 200, maxSeconds = 120, wanted = Infinity }) {
30
70
  const server = {};
31
71
  for (const k of ['level', 'siteId', 'source', 'integration', 'platform', 'environment', 'correlationId']) {
32
72
  if (params[k] !== undefined && params[k] !== null && params[k] !== '') server[k] = String(k === 'level' ? String(params[k]).toUpperCase() : params[k]);
33
73
  }
34
74
  const byId = new Map();
35
75
  const unresolved = [];
76
+ const started = Date.now();
36
77
  let requests = 0;
37
78
  let slices = 0;
38
79
  let scanned = 0;
39
80
  let budgetExhausted = false;
81
+ let timeExhausted = false;
40
82
 
41
- const call = async (a, b, cursor, total) => {
42
- if (requests >= maxRequests) { budgetExhausted = true; return null; }
43
- requests++;
44
- const q = new URLSearchParams({ from: a.toISOString(), to: b.toISOString(), take: '500', ...server });
45
- if (total) q.set('includeTotal', 'true');
83
+ const canRequest = () => {
84
+ if (requests >= maxRequests) { budgetExhausted = true; return false; }
85
+ if ((Date.now() - started) / 1000 >= maxSeconds && requests > 0) { timeExhausted = true; return false; }
86
+ return true;
87
+ };
88
+ const norm = (r) => (Array.isArray(r) ? { entries: r } : (r || {}));
89
+ const add = (e) => byId.set(e.id ?? `${e.timestamp}|${e.message}`, e);
90
+
91
+ // ---- text handling shared by both modes ----
92
+ const textQ = regex ?? (contains ? escapeRegex(contains) : undefined);
93
+ const textLogger = logger ? escapeRegex(logger) : undefined;
94
+
95
+ // ---- probe: first CURSOR-mode page, doubles as the new-server detector ----
96
+ const cursorQuery = (cursor) => {
97
+ const q = new URLSearchParams({ from: from.toISOString(), to: to.toISOString(), take: '500', ...server });
98
+ if (textQ) q.set('q', textQ);
99
+ if (textLogger) q.set('logger', textLogger);
100
+ if (textQ || textLogger) q.set('regex', 'true'); // regex also forces the exact path (the AI-search path is never consulted)
101
+ q.set('fallthrough', 'false');
46
102
  if (cursor) q.set('cursor', cursor);
47
- const r = await fetchJson(q.toString());
48
- return Array.isArray(r) ? { entries: r } : (r || {});
103
+ return q.toString();
49
104
  };
50
105
 
51
- const walk = async (a, b) => {
52
- const r = await call(a, b, null, true);
53
- if (!r) { unresolved.push(`${a.toISOString()}..${b.toISOString()} (request budget)`); return; }
54
- if (r.totalCountCapped === true && (b - a) > MIN_SLICE_MS) {
55
- const mid = new Date(a.getTime() + Math.floor((b - a) / 2));
56
- await walk(a, mid);
57
- await walk(mid, b);
58
- return;
59
- }
60
- if (r.totalCountCapped === true) unresolved.push(`${a.toISOString()}..${b.toISOString()} (still capped at <=2s)`);
61
- slices++;
62
- scanned += Number(r.totalCount ?? (r.entries?.length ?? 0));
63
- for (const e of r.entries ?? []) byId.set(e.id ?? `${e.timestamp}|${e.message}`, e);
64
- let cursor = r.nextCursor;
65
- while (cursor) {
66
- const r2 = await call(a, b, cursor, false);
67
- if (!r2) { unresolved.push(`${a.toISOString()}..${b.toISOString()} (request budget while paging)`); break; }
68
- for (const e of r2.entries ?? []) byId.set(e.id ?? `${e.timestamp}|${e.message}`, e);
69
- cursor = r2.nextCursor;
106
+ let mode = 'bisect';
107
+ let satisfied = false;
108
+ let cursorDone = false;
109
+
110
+ if (canRequest()) {
111
+ requests++;
112
+ const probe = norm(await fetchJson(cursorQuery(null)));
113
+ if (typeof probe.truncated === 'boolean') {
114
+ mode = 'cursor';
115
+ scanned += Number(probe.scannedRows ?? 0);
116
+ for (const e of probe.entries ?? []) add(e);
117
+ let page = probe;
118
+ let cursor = probe.nextCursor || null;
119
+ for (;;) {
120
+ // The ONLY way a cursor read is COMPLETE: the last page said truncated === false and carried no cursor. `truncated: true` with no
121
+ // cursor means the server stopped scanning (deadline/cap) and could not say where to continue: INCOMPLETE, never COMPLETE.
122
+ if (!cursor) {
123
+ if (page.truncated === false) cursorDone = true;
124
+ else unresolved.push('the server stopped scanning (truncated) without a cursor to continue from');
125
+ break;
126
+ }
127
+ if (byId.size >= wanted) { satisfied = true; break; }
128
+ if (!canRequest()) { unresolved.push(`cursor ${cursor} (${timeExhausted ? 'time budget' : 'request budget'})`); break; }
129
+ requests++;
130
+ const next = norm(await fetchJson(cursorQuery(cursor)));
131
+ scanned += Number(next.scannedRows ?? 0);
132
+ for (const e of next.entries ?? []) add(e);
133
+ if (next.nextCursor && next.nextCursor === cursor) {
134
+ unresolved.push('no progress: the server returned the cursor it was given (its scan budget ended before reaching any row)');
135
+ break;
136
+ }
137
+ page = next;
138
+ cursor = next.nextCursor || null;
139
+ }
140
+ slices = 1;
70
141
  }
71
- };
142
+ }
72
143
 
73
- await walk(from, to);
144
+ // ---- BISECT mode (older server) ----
145
+ if (mode === 'bisect' && !budgetExhausted) {
146
+ const call = async (a, b, cursor, total) => {
147
+ if (!canRequest()) return null;
148
+ requests++;
149
+ const q = new URLSearchParams({ from: a.toISOString(), to: b.toISOString(), take: '500', ...server });
150
+ if (total) q.set('includeTotal', 'true');
151
+ if (cursor) q.set('cursor', cursor);
152
+ return norm(await fetchJson(q.toString()));
153
+ };
154
+ const walk = async (a, b) => {
155
+ const r = await call(a, b, null, true);
156
+ if (!r) { unresolved.push(`${a.toISOString()}..${b.toISOString()} (${timeExhausted ? 'time' : 'request'} budget)`); return; }
157
+ if (r.totalCountCapped === true && (b - a) > MIN_SLICE_MS) {
158
+ const mid = new Date(a.getTime() + Math.floor((b - a) / 2));
159
+ await walk(a, mid);
160
+ await walk(mid, b);
161
+ return;
162
+ }
163
+ if (r.totalCountCapped === true) unresolved.push(`${a.toISOString()}..${b.toISOString()} (still capped at <=2s: a log storm; add level/site)`);
164
+ slices++;
165
+ scanned += Number(r.totalCount ?? (r.entries?.length ?? 0));
166
+ for (const e of r.entries ?? []) add(e);
167
+ let cursor = r.nextCursor;
168
+ while (cursor) {
169
+ const r2 = await call(a, b, cursor, false);
170
+ if (!r2) { unresolved.push(`${a.toISOString()}..${b.toISOString()} (budget while paging)`); break; }
171
+ for (const e of r2.entries ?? []) add(e);
172
+ cursor = r2.nextCursor;
173
+ }
174
+ };
175
+ await walk(from, to);
176
+ }
74
177
 
75
178
  let rows = [...byId.values()];
76
179
  const msg = (e) => String(e.message ?? e.Message ?? '');
77
- if (contains) { const c = contains.toLowerCase(); rows = rows.filter((e) => msg(e).toLowerCase().includes(c)); }
78
- if (regex) { const re = new RegExp(regex, 'i'); rows = rows.filter((e) => re.test(msg(e))); }
79
- if (logger) { const l = logger.toLowerCase(); rows = rows.filter((e) => String(e.logger ?? e.Logger ?? '').toLowerCase().includes(l)); }
80
- rows.sort((x, y) => String(y.timestamp ?? '').localeCompare(String(x.timestamp ?? '')));
180
+ if (mode === 'bisect') {
181
+ if (contains) { const c = contains.toLowerCase(); rows = rows.filter((e) => msg(e).toLowerCase().includes(c)); }
182
+ if (regex) { const re = new RegExp(regex, 'i'); rows = rows.filter((e) => re.test(msg(e))); }
183
+ if (logger) { const l = logger.toLowerCase(); rows = rows.filter((e) => String(e.logger ?? e.Logger ?? '').toLowerCase().includes(l)); }
184
+ }
185
+ rows.sort((x, y) => tsOf(y) - tsOf(x)); // compare as instants: fractional-second digit counts differ between rows
81
186
 
82
- return { entries: rows, fetched: byId.size, scanned, requests, slices, complete: unresolved.length === 0 && !budgetExhausted, unresolved, budgetExhausted };
187
+ const complete = mode === 'cursor' ? (cursorDone && unresolved.length === 0) : (unresolved.length === 0 && !budgetExhausted && !timeExhausted);
188
+ return { entries: rows, fetched: byId.size, scanned, requests, slices, mode, complete, satisfied, unresolved, budgetExhausted, timeExhausted };
83
189
  }
84
190
 
85
- /** One line a human or an LLM can trust: says COMPLETE or INCOMPLETE and how much was examined. */
191
+ /** One line a human or an LLM can trust: says COMPLETE or INCOMPLETE and how much the SERVER actually scanned. */
86
192
  export function describeCompleteness(r) {
87
- const base = `${r.entries.length} matched of ${r.fetched} fetched (server scanned ${r.scanned}) in ${r.requests} request(s)/${r.slices} slice(s)`;
193
+ const base = `${r.entries.length} matched (${r.fetched} fetched; server scanned ${r.scanned} rows) in ${r.requests} request(s), ${r.mode} mode`;
194
+ if (r.satisfied) return `${base}; showing the newest matches, more may exist beyond what was asked for (stopped early on purpose).`;
88
195
  return r.complete
89
- ? `${base}; COMPLETE (no slice hit the server scan cap), so 0 matches means nothing was logged.`
90
- : `${base}; INCOMPLETE (${r.unresolved.length} slice(s) unresolved${r.budgetExhausted ? ', request budget exhausted' : ''}): narrow the window or add level/site; a short or empty result is NOT proof of absence.`;
196
+ ? `${base}; COMPLETE (the whole window was covered), so 0 matches means nothing was logged.`
197
+ : `${base}; INCOMPLETE (${r.unresolved.length} part(s) not covered${r.budgetExhausted ? ', request budget exhausted' : ''}${r.timeExhausted ? ', time budget exhausted' : ''}): narrow the window or add level/site; a short or empty result is NOT proof of absence.`;
91
198
  }
92
199
 
93
200
  /** For raw (server-side q=) responses: surfaces searchPath/scannedRows/truncated so a 0 is never ambiguous. */
@@ -96,5 +203,7 @@ export function describeRawMeta(resp) {
96
203
  return 'server did not report scan metadata (older deploy): treat an empty or short result as unverified, use the complete mode.';
97
204
  }
98
205
  const t = resp.truncated === true;
99
- return `searchPath=${resp.searchPath} scannedRows=${resp.scannedRows} truncated=${t}${t ? ' (NOT proof of absence; continue with nextCursor or narrow the window)' : ''}${resp.nextCursor ? ' nextCursor=present' : ''}`;
206
+ // exact=false: the answer involves the AI-search index, which is best-effort (written behind, can lag, misses text that starts mid-word).
207
+ const bestEffort = resp.exact === false ? ' exact=false (answered from the best-effort search index: it can lag and misses text that starts mid-word, so treat counts as a floor, not exact)' : '';
208
+ return `searchPath=${resp.searchPath} scannedRows=${resp.scannedRows} truncated=${t}${t ? ' (NOT proof of absence; continue with nextCursor or narrow the window)' : ''}${bestEffort}${resp.nextCursor ? ' nextCursor=present' : ''}`;
100
209
  }