@steve31415/baselib 3.62.3 → 3.64.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.
- package/dist/db.d.ts +4 -3
- package/dist/db.js +9 -3
- package/dist/log-browser.d.ts +3 -0
- package/dist/log-browser.js +108 -13
- package/dist/log-core.d.ts +24 -0
- package/dist/log-core.js +61 -10
- package/dist/ops/format.d.ts +1 -1
- package/dist/ops/format.js +1 -1
- package/dist/ops/logs.d.ts +31 -34
- package/dist/ops/logs.js +54 -29
- package/dist/sync-browser/client.d.ts +11 -0
- package/dist/sync-browser/client.js +23 -2
- package/package.json +1 -1
package/dist/db.d.ts
CHANGED
|
@@ -143,9 +143,10 @@ export declare const IDLE_PROBE_TIMEOUT_MS = 3000;
|
|
|
143
143
|
* any transaction or advisory lock it held is gone.
|
|
144
144
|
* Each event carries `elapsedMs` (time in that phase: the connect
|
|
145
145
|
* attempt, the wait, the idle spell, the checkout), the pg `code`, the
|
|
146
|
-
* pool's counts (`total`, `idle`, `waiting`, `connecting`, `max`)
|
|
147
|
-
*
|
|
148
|
-
* `credentialRemainingMs`; the logger adds
|
|
146
|
+
* pool's counts (`total`, `idle`, `waiting`, `connecting`, `max`), the
|
|
147
|
+
* process's uptime (`processUptimeMs`, since 3.63.0) and, given a Cloud
|
|
148
|
+
* SQL credential reader, `credentialRemainingMs`; the logger adds
|
|
149
|
+
* request activity, as on every
|
|
149
150
|
* server event (`activity.ts`: was Cloud Run CPU allocated?). Query:
|
|
150
151
|
* `['apps'] | where kind == 'db-connection-loss' | summarize count() by app, tostring(meta.phase)`.
|
|
151
152
|
*
|
package/dist/db.js
CHANGED
|
@@ -156,6 +156,11 @@ function connectionLossWarner(pool, logger, credentialExpiry) {
|
|
|
156
156
|
phase,
|
|
157
157
|
...extra,
|
|
158
158
|
...(since === undefined ? {} : { elapsedMs: Date.now() - since }),
|
|
159
|
+
// Since 2026-11-14 some Cloud Run instances lose every connection at
|
|
160
|
+
// 12-hour multiples of their start (KNOWN_LOG_PATTERNS fleet entry):
|
|
161
|
+
// processUptimeMs % 43_200_000 near 0 recognizes that without a join
|
|
162
|
+
// against the platform dataset's "Starting new instance" lines.
|
|
163
|
+
processUptimeMs: Math.round(process.uptime() * 1000),
|
|
159
164
|
code: err.code,
|
|
160
165
|
pool: { total: pool.totalCount, idle: pool.idleCount, waiting: pool.waitingCount, connecting: connectingCount(pool), max: pool.options.max },
|
|
161
166
|
...(credentialExpiry
|
|
@@ -198,9 +203,10 @@ function connectionLossWarner(pool, logger, credentialExpiry) {
|
|
|
198
203
|
* any transaction or advisory lock it held is gone.
|
|
199
204
|
* Each event carries `elapsedMs` (time in that phase: the connect
|
|
200
205
|
* attempt, the wait, the idle spell, the checkout), the pg `code`, the
|
|
201
|
-
* pool's counts (`total`, `idle`, `waiting`, `connecting`, `max`)
|
|
202
|
-
*
|
|
203
|
-
* `credentialRemainingMs`; the logger adds
|
|
206
|
+
* pool's counts (`total`, `idle`, `waiting`, `connecting`, `max`), the
|
|
207
|
+
* process's uptime (`processUptimeMs`, since 3.63.0) and, given a Cloud
|
|
208
|
+
* SQL credential reader, `credentialRemainingMs`; the logger adds
|
|
209
|
+
* request activity, as on every
|
|
204
210
|
* server event (`activity.ts`: was Cloud Run CPU allocated?). Query:
|
|
205
211
|
* `['apps'] | where kind == 'db-connection-loss' | summarize count() by app, tostring(meta.phase)`.
|
|
206
212
|
*
|
package/dist/log-browser.d.ts
CHANGED
|
@@ -23,6 +23,9 @@ export declare const pageId: string;
|
|
|
23
23
|
* (`navigator.maxTouchPoints`) to tell it apart.
|
|
24
24
|
*/
|
|
25
25
|
export declare function deviceLabel(userAgent: string, touchPoints?: number): string;
|
|
26
|
+
/** The drop marker's message and `kind`. The kind matches the server's
|
|
27
|
+
* stdout drop markers, so one query finds both. */
|
|
28
|
+
export declare const DROP_MARKER_MESSAGE = "log ship dropped events";
|
|
26
29
|
export declare function createBrowserLogger(opts?: BrowserLoggerOptions): Logger;
|
|
27
30
|
/**
|
|
28
31
|
* Make the shared `logger` forward to `instance`. Call once at boot, right
|
package/dist/log-browser.js
CHANGED
|
@@ -65,6 +65,81 @@ export function deviceLabel(userAgent, touchPoints = 0) {
|
|
|
65
65
|
: 'other';
|
|
66
66
|
return `${os}-${browser}`;
|
|
67
67
|
}
|
|
68
|
+
/** The drop marker's message and `kind`. The kind matches the server's
|
|
69
|
+
* stdout drop markers, so one query finds both. */
|
|
70
|
+
export const DROP_MARKER_MESSAGE = 'log ship dropped events';
|
|
71
|
+
const DROP_MARKER_KIND = 'log-ship-drop';
|
|
72
|
+
function emptyTally() {
|
|
73
|
+
return { events: 0, batches: 0, levels: { error: 0, warn: 0, info: 0, debug: 0 }, firstTime: null, lastTime: null, reasons: new Set() };
|
|
74
|
+
}
|
|
75
|
+
function widen(t, first, last) {
|
|
76
|
+
if (t.firstTime === null || first < t.firstTime)
|
|
77
|
+
t.firstTime = first;
|
|
78
|
+
if (t.lastTime === null || last > t.lastTime)
|
|
79
|
+
t.lastTime = last;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Counts what the page's shipper gave up on, and reports it as one WARN
|
|
83
|
+
* (`kind: 'log-ship-drop'`) after the next delivery, when it can arrive:
|
|
84
|
+
* browser logs have no stdout mirror, so without it a drop left no trace
|
|
85
|
+
* outside the devtools console (2026-11-16, notes task a0f43dda). A marker
|
|
86
|
+
* that is itself dropped folds back into the tally for the next one.
|
|
87
|
+
*/
|
|
88
|
+
class DropReporter {
|
|
89
|
+
tally = emptyTally();
|
|
90
|
+
record(batch, reason) {
|
|
91
|
+
for (const event of batch.events) {
|
|
92
|
+
if (event.kind === DROP_MARKER_KIND && event.message === DROP_MARKER_MESSAGE)
|
|
93
|
+
this.refold(event);
|
|
94
|
+
else
|
|
95
|
+
this.count(event);
|
|
96
|
+
}
|
|
97
|
+
if (batch.events.some((e) => e.kind !== DROP_MARKER_KIND)) {
|
|
98
|
+
this.tally.batches++;
|
|
99
|
+
this.tally.reasons.add(reason);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/** Axiom kept a batch but refused `failed` of its events (levels unknown). */
|
|
103
|
+
recordPartial(batch, failed) {
|
|
104
|
+
this.tally.events += failed;
|
|
105
|
+
this.tally.batches++;
|
|
106
|
+
this.tally.reasons.add('partial');
|
|
107
|
+
widen(this.tally, batch.firstTime, batch.lastTime);
|
|
108
|
+
}
|
|
109
|
+
/** The marker's meta for what was dropped since the last one, or null. */
|
|
110
|
+
take() {
|
|
111
|
+
const t = this.tally;
|
|
112
|
+
if (t.events === 0)
|
|
113
|
+
return null;
|
|
114
|
+
this.tally = emptyTally();
|
|
115
|
+
return {
|
|
116
|
+
events: t.events,
|
|
117
|
+
batches: t.batches,
|
|
118
|
+
levels: t.levels,
|
|
119
|
+
firstTime: t.firstTime,
|
|
120
|
+
lastTime: t.lastTime,
|
|
121
|
+
reasons: [...t.reasons].sort(),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
count(event) {
|
|
125
|
+
this.tally.events++;
|
|
126
|
+
this.tally.levels[event.level] = (this.tally.levels[event.level] ?? 0) + 1;
|
|
127
|
+
widen(this.tally, event._time, event._time);
|
|
128
|
+
}
|
|
129
|
+
refold(marker) {
|
|
130
|
+
const m = marker.meta;
|
|
131
|
+
if (!m)
|
|
132
|
+
return;
|
|
133
|
+
this.tally.events += m.events ?? 0;
|
|
134
|
+
this.tally.batches += m.batches ?? 0;
|
|
135
|
+
for (const level of ['error', 'warn', 'info', 'debug'])
|
|
136
|
+
this.tally.levels[level] += m.levels?.[level] ?? 0;
|
|
137
|
+
if (m.firstTime && m.lastTime)
|
|
138
|
+
widen(this.tally, m.firstTime, m.lastTime);
|
|
139
|
+
for (const r of m.reasons ?? [])
|
|
140
|
+
this.tally.reasons.add(r);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
68
143
|
function metaContent(name) {
|
|
69
144
|
return document.querySelector(`meta[name="${name}"]`)?.content || undefined;
|
|
70
145
|
}
|
|
@@ -74,30 +149,44 @@ export function createBrowserLogger(opts = {}) {
|
|
|
74
149
|
const token = opts.token ?? metaContent('pw-log-token');
|
|
75
150
|
const baseUrl = opts.baseUrl ?? 'https://api.axiom.co';
|
|
76
151
|
const buildId = metaContent('pw-build-id');
|
|
152
|
+
const drops = new DropReporter();
|
|
153
|
+
// Assigned below; the shipper's callbacks only run after construction.
|
|
154
|
+
let reportDrops = () => { };
|
|
77
155
|
const shipper = token
|
|
78
156
|
? new LogShipper({
|
|
79
157
|
url: `${baseUrl}/v1/datasets/${dataset}/ingest`,
|
|
80
158
|
token,
|
|
81
159
|
// Chromium rejects keepalive request bodies over 64 KiB outright, so
|
|
82
160
|
// keep batches small; keepalive lets a flush started during page
|
|
83
|
-
// unload complete. Retries run while the page lives; page
|
|
84
|
-
//
|
|
161
|
+
// unload complete. Retries run while the page lives; what a page
|
|
162
|
+
// still holds when it dies is lost unrecorded (best-effort). A
|
|
163
|
+
// give-up while it lives is reported by the drop marker below.
|
|
85
164
|
batchSize: 20,
|
|
86
165
|
fetchInit: { keepalive: true },
|
|
87
166
|
// Browser logs have no stdout backstop, and the ERRORs most worth
|
|
88
167
|
// keeping are often the ones an offline stretch causes: while the
|
|
89
|
-
// browser reports itself offline,
|
|
90
|
-
//
|
|
91
|
-
//
|
|
168
|
+
// browser reports itself offline, or attempts get no HTTP answer at
|
|
169
|
+
// all (a laptop on a hotspot with no upstream says it is online),
|
|
170
|
+
// failed attempts don't count, so a batch waits out the outage (until
|
|
171
|
+
// the page dies or the buffer cap evicts it) instead of being dropped
|
|
172
|
+
// after its 6 attempts (~5 min).
|
|
92
173
|
isOffline: () => navigator.onLine === false,
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
}
|
|
174
|
+
holdWhileUnreachable: true,
|
|
175
|
+
onGiveUp: (batch, error, reason) => {
|
|
176
|
+
drops.record(batch, reason);
|
|
177
|
+
console.warn(`log ship dropped a batch (${reason}): ${String(error)}`, {
|
|
178
|
+
batch_id: batch.id,
|
|
179
|
+
events: batch.events.length,
|
|
180
|
+
});
|
|
181
|
+
},
|
|
182
|
+
onPartialFailure: (batch, failed, failures) => {
|
|
183
|
+
drops.recordPartial(batch, failed);
|
|
184
|
+
console.warn(`log ship: Axiom rejected ${failed} of ${batch.events.length} events`, {
|
|
185
|
+
batch_id: batch.id,
|
|
186
|
+
failures,
|
|
187
|
+
});
|
|
188
|
+
},
|
|
189
|
+
onDelivered: () => reportDrops(),
|
|
101
190
|
})
|
|
102
191
|
: undefined;
|
|
103
192
|
function build(context) {
|
|
@@ -127,6 +216,12 @@ export function createBrowserLogger(opts = {}) {
|
|
|
127
216
|
device: deviceLabel(navigator.userAgent, navigator.maxTouchPoints ?? 0),
|
|
128
217
|
...opts.context,
|
|
129
218
|
});
|
|
219
|
+
const markerLogger = logger.with({ kind: DROP_MARKER_KIND });
|
|
220
|
+
reportDrops = () => {
|
|
221
|
+
const meta = drops.take();
|
|
222
|
+
if (meta)
|
|
223
|
+
markerLogger.warn(DROP_MARKER_MESSAGE, meta);
|
|
224
|
+
};
|
|
130
225
|
// Ship what's pending whenever the page may be going away.
|
|
131
226
|
const flushNow = () => void logger.flush();
|
|
132
227
|
addEventListener('pagehide', flushNow);
|
package/dist/log-core.d.ts
CHANGED
|
@@ -87,6 +87,24 @@ export interface ShipperOptions {
|
|
|
87
87
|
* offlineRetryMs, or at once on resume(). The signal only decides
|
|
88
88
|
* what a failure means — attempts still run while "offline". */
|
|
89
89
|
isOffline?: () => boolean;
|
|
90
|
+
/** Also treat the network as down while attempts get no HTTP answer at
|
|
91
|
+
* all (a fetch rejection or the attempt timeout), whatever isOffline()
|
|
92
|
+
* says: once two attempts in a row — of any batches — got no answer,
|
|
93
|
+
* further no-answer failures are uncounted waits of offlineRetryMs, as
|
|
94
|
+
* if offline, until some attempt gets an HTTP answer again. An HTTP
|
|
95
|
+
* error (5xx, 408, 429) still counts, so an ingest outage still gives
|
|
96
|
+
* up; a batch that alone fails while others are delivered still counts.
|
|
97
|
+
*
|
|
98
|
+
* The browser sets it (2026-11-16, notes task a0f43dda): a Mac on a
|
|
99
|
+
* phone hotspot with no working upstream reported navigator.onLine ===
|
|
100
|
+
* true for hours while every request failed, so batches spent their 6
|
|
101
|
+
* attempts in ~5 minutes and 2 h 48 min of logs, ERRORs included, were
|
|
102
|
+
* dropped. The server leaves it off: its drops are stdout-mirrored and
|
|
103
|
+
* counted, and an instance must not hold batches indefinitely. */
|
|
104
|
+
holdWhileUnreachable?: boolean;
|
|
105
|
+
/** Axiom accepted a batch (2xx). The browser uses it to report earlier
|
|
106
|
+
* drops once delivery works again. */
|
|
107
|
+
onDelivered?: (batch: ShippedBatch) => void;
|
|
90
108
|
/** A delivery attempt failed; the batch will be retried. */
|
|
91
109
|
onAttemptFailure?: (batch: ShippedBatch, error: unknown) => void;
|
|
92
110
|
/** The batch is abandoned — its events will never reach Axiom. */
|
|
@@ -120,6 +138,12 @@ export declare class LogShipper {
|
|
|
120
138
|
private pumpTimer;
|
|
121
139
|
private pumping;
|
|
122
140
|
private closed;
|
|
141
|
+
/** Consecutive attempts (any batches) that got no HTTP answer. */
|
|
142
|
+
private unansweredStreak;
|
|
143
|
+
/** An uncounted (offline or unreachable) wait is in force: every waiting
|
|
144
|
+
* batch is deferred with it, so one request probes per offlineRetryMs
|
|
145
|
+
* (2026-11-16: 50 held batches made 4 500 failing requests an hour). */
|
|
146
|
+
private holding;
|
|
123
147
|
private finalPromise;
|
|
124
148
|
private readonly inflight;
|
|
125
149
|
private readonly batchSize;
|
package/dist/log-core.js
CHANGED
|
@@ -136,6 +136,15 @@ export function truncate(s, max) {
|
|
|
136
136
|
* next CPU window either way) and only matter while ingest is failing. */
|
|
137
137
|
export const DEFAULT_MAX_ATTEMPTS = 6;
|
|
138
138
|
export const DEFAULT_RETRY_DELAYS_MS = [5_000, 15_000, 40_000, 90_000, 150_000];
|
|
139
|
+
/** Chromium refuses a keepalive request (TypeError, "Failed to fetch") once
|
|
140
|
+
* the keepalive bodies in flight exceed 64 KiB; a body that large ships
|
|
141
|
+
* without keepalive (it only matters during page unload). */
|
|
142
|
+
const KEEPALIVE_BODY_MAX = 60 * 1024;
|
|
143
|
+
const LEVEL_RANK = { debug: 0, info: 1, warn: 2, error: 3 };
|
|
144
|
+
/** The most severe level among a batch's events (eviction order). */
|
|
145
|
+
function batchRank(batch) {
|
|
146
|
+
return batch.events.reduce((m, e) => Math.max(m, LEVEL_RANK[e.level] ?? 1), 0);
|
|
147
|
+
}
|
|
139
148
|
const RESPONSE_BODY_MAX = 300;
|
|
140
149
|
/** A 4xx is a verdict on the bytes, not the moment: retrying the identical
|
|
141
150
|
* body cannot succeed. 408 (timeout) and 429 (rate limit) are the exceptions. */
|
|
@@ -173,6 +182,12 @@ export class LogShipper {
|
|
|
173
182
|
pumpTimer;
|
|
174
183
|
pumping = false;
|
|
175
184
|
closed = false;
|
|
185
|
+
/** Consecutive attempts (any batches) that got no HTTP answer. */
|
|
186
|
+
unansweredStreak = 0;
|
|
187
|
+
/** An uncounted (offline or unreachable) wait is in force: every waiting
|
|
188
|
+
* batch is deferred with it, so one request probes per offlineRetryMs
|
|
189
|
+
* (2026-11-16: 50 held batches made 4 500 failing requests an hour). */
|
|
190
|
+
holding = false;
|
|
176
191
|
finalPromise;
|
|
177
192
|
inflight = new Set();
|
|
178
193
|
batchSize;
|
|
@@ -226,6 +241,7 @@ export class LogShipper {
|
|
|
226
241
|
/** Retry every waiting batch now, ahead of its backoff — the browser
|
|
227
242
|
* calls this when it comes back online. */
|
|
228
243
|
resume() {
|
|
244
|
+
this.holding = false;
|
|
229
245
|
for (const b of this.pending)
|
|
230
246
|
b.nextAttemptAt = 0;
|
|
231
247
|
void this.pump();
|
|
@@ -270,11 +286,19 @@ export class LogShipper {
|
|
|
270
286
|
firstAttempt,
|
|
271
287
|
settleFirst,
|
|
272
288
|
};
|
|
273
|
-
// Enforce the caps over everything undelivered: evict
|
|
274
|
-
//
|
|
289
|
+
// Enforce the caps over everything undelivered: evict the least severe
|
|
290
|
+
// batch (by its most severe event), oldest first among equals, so
|
|
291
|
+
// ERRORs outlast WARNs and INFOs; if nothing evictable remains, the new
|
|
292
|
+
// batch itself is the casualty.
|
|
275
293
|
while (this.totalEvents + events.length > this.maxBufferedEvents ||
|
|
276
294
|
this.totalBytes + batch.bytes > this.maxBufferedBytes) {
|
|
277
|
-
|
|
295
|
+
let victim;
|
|
296
|
+
for (const b of this.pending) {
|
|
297
|
+
if (b.attempting || b.terminal)
|
|
298
|
+
continue;
|
|
299
|
+
if (!victim || batchRank(b) < batchRank(victim))
|
|
300
|
+
victim = b;
|
|
301
|
+
}
|
|
278
302
|
if (!victim) {
|
|
279
303
|
batch.terminal = true;
|
|
280
304
|
settleFirst();
|
|
@@ -344,23 +368,41 @@ export class LogShipper {
|
|
|
344
368
|
attempt(batch, timeoutMs) {
|
|
345
369
|
batch.attempting = true;
|
|
346
370
|
const p = (async () => {
|
|
347
|
-
const outcome = await this.ship(batch.body, timeoutMs);
|
|
371
|
+
const outcome = await this.ship(batch.body, batch.bytes, timeoutMs);
|
|
348
372
|
batch.attempting = false;
|
|
349
373
|
if (batch.terminal)
|
|
350
374
|
return;
|
|
351
375
|
batch.settleFirst();
|
|
352
|
-
if (
|
|
376
|
+
if (outcome.ok || outcome.answered)
|
|
377
|
+
this.unansweredStreak = 0;
|
|
378
|
+
else
|
|
379
|
+
this.unansweredStreak++;
|
|
380
|
+
const unreachable = this.opts.holdWhileUnreachable === true && this.unansweredStreak >= 2;
|
|
381
|
+
if (!outcome.ok && !outcome.terminal && (unreachable || this.opts.isOffline?.())) {
|
|
353
382
|
// Uncounted: the budget is for failures that could be the batch's
|
|
354
|
-
// or the service's, and an offline failure is neither.
|
|
355
|
-
|
|
383
|
+
// or the service's, and an offline failure is neither. The others
|
|
384
|
+
// wait with it: one probe per wait, not one per batch.
|
|
385
|
+
const next = Date.now() + this.offlineRetryMs;
|
|
386
|
+
for (const b of this.pending) {
|
|
387
|
+
if (!b.attempting && !b.terminal)
|
|
388
|
+
b.nextAttemptAt = Math.max(b.nextAttemptAt, next);
|
|
389
|
+
}
|
|
390
|
+
this.holding = true;
|
|
356
391
|
this.schedulePump();
|
|
357
392
|
return;
|
|
358
393
|
}
|
|
394
|
+
if (this.holding && (outcome.ok || outcome.answered)) {
|
|
395
|
+
// The probe got through: release everything that waited behind it.
|
|
396
|
+
this.holding = false;
|
|
397
|
+
for (const b of this.pending)
|
|
398
|
+
b.nextAttemptAt = 0;
|
|
399
|
+
}
|
|
359
400
|
batch.attempt++;
|
|
360
401
|
if (outcome.ok) {
|
|
361
402
|
this.remove(batch);
|
|
362
403
|
if (outcome.failed > 0)
|
|
363
404
|
this.opts.onPartialFailure?.(batch, outcome.failed, outcome.failures);
|
|
405
|
+
this.opts.onDelivered?.(batch);
|
|
364
406
|
}
|
|
365
407
|
else if (outcome.terminal) {
|
|
366
408
|
this.giveUp(batch, outcome.error, 'rejected');
|
|
@@ -380,11 +422,17 @@ export class LogShipper {
|
|
|
380
422
|
return p;
|
|
381
423
|
}
|
|
382
424
|
/** One POST. Never throws. */
|
|
383
|
-
async ship(body, timeoutMs) {
|
|
425
|
+
async ship(body, bytes, timeoutMs) {
|
|
384
426
|
const fetchFn = this.opts.fetchFn ?? fetch;
|
|
427
|
+
let init = this.opts.fetchInit;
|
|
428
|
+
if (init?.keepalive && bytes > KEEPALIVE_BODY_MAX) {
|
|
429
|
+
const { keepalive: _keepalive, ...rest } = init;
|
|
430
|
+
init = rest;
|
|
431
|
+
}
|
|
432
|
+
let answered = false;
|
|
385
433
|
try {
|
|
386
434
|
const res = await fetchFn(this.opts.url, {
|
|
387
|
-
...
|
|
435
|
+
...init,
|
|
388
436
|
method: 'POST',
|
|
389
437
|
headers: {
|
|
390
438
|
authorization: `Bearer ${this.opts.token}`,
|
|
@@ -393,6 +441,7 @@ export class LogShipper {
|
|
|
393
441
|
body,
|
|
394
442
|
signal: AbortSignal.timeout(timeoutMs),
|
|
395
443
|
});
|
|
444
|
+
answered = true;
|
|
396
445
|
if (res.ok) {
|
|
397
446
|
const parsed = (await res.json().catch(() => undefined));
|
|
398
447
|
return {
|
|
@@ -409,10 +458,12 @@ export class LogShipper {
|
|
|
409
458
|
ok: false,
|
|
410
459
|
error: new Error(`ingest returned ${res.status}${detail}`),
|
|
411
460
|
terminal: isTerminalStatus(res.status),
|
|
461
|
+
answered: true,
|
|
412
462
|
};
|
|
413
463
|
}
|
|
414
464
|
catch (err) {
|
|
415
|
-
|
|
465
|
+
// A failure reading an answered response's body still had an answer.
|
|
466
|
+
return { ok: false, error: err ?? new Error('ship failed'), terminal: false, answered };
|
|
416
467
|
}
|
|
417
468
|
}
|
|
418
469
|
async runFinal(deadlineMs) {
|
package/dist/ops/format.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export declare const isRecord: (v: unknown) => v is Record<string, unknown>;
|
|
2
2
|
/** Recursively drop null/undefined values and the objects left empty by
|
|
3
|
-
* that. Axiom's
|
|
3
|
+
* that. Axiom's query formats return every field of the dataset's
|
|
4
4
|
* union schema, almost all null; this turns a row back into what was
|
|
5
5
|
* actually logged. Arrays are kept whole (elements pruned in place). */
|
|
6
6
|
export declare function pruneNulls(value: unknown): unknown;
|
package/dist/ops/format.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// null pruning, key flattening, aligned tables, and the time-flag grammar.
|
|
3
3
|
export const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v) && !(v instanceof Date);
|
|
4
4
|
/** Recursively drop null/undefined values and the objects left empty by
|
|
5
|
-
* that. Axiom's
|
|
5
|
+
* that. Axiom's query formats return every field of the dataset's
|
|
6
6
|
* union schema, almost all null; this turns a row back into what was
|
|
7
7
|
* actually logged. Arrays are kept whole (elements pruned in place). */
|
|
8
8
|
export function pruneNulls(value) {
|
package/dist/ops/logs.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Runner } from '../deploy/types.js';
|
|
2
2
|
import { type CliIo } from './cli.js';
|
|
3
|
-
export declare const AXIOM_QUERY_URL = "https://api.axiom.co/v1/datasets/_apl?format=
|
|
3
|
+
export declare const AXIOM_QUERY_URL = "https://api.axiom.co/v1/datasets/_apl?format=tabular";
|
|
4
4
|
export declare const QUERY_TOKEN_SECRET = "shared--axiom-query-token";
|
|
5
5
|
export declare const USAGE = "usage: pw-logs [options] [APL tail]\nQuery the fleet's Axiom logs (query-only token from Secret Manager).\n\n -d, --dataset <name> apps (default) | platform | rum\n -a, --app <name> app filter; default: the enclosing repo's deploy.config.json for\n apps/rum (\"all\" for none); platform has no default \u2014 it is keyed\n by GCP service name, not app, and a Cloud Run Job's service (e.g.\n radar-cf-probe, corpus-build) rarely equals its owning app's repo\n name, so pass -a explicitly there or you get every service\n -l, --level <level> debug | info | warn | error; add \"+\" for that level and above (warn+)\n -s, --since <when> window start: duration back from now (30m, 6h, 3d) or timestamp (default 1h)\n -u, --until <when> window end, same forms (default now)\n -n, --limit <n> rows to return (default 200); events are the newest, printed oldest first\n --json print events (or aggregation rows) as a JSON array\n --all text mode: show every field (batch ids, full build_id)\n --apl print the query that would run and exit\n -h, --help\n\nThe tail is appended to the generated pipeline. The newest-first ordering\nis added only when the tail just filters or reshapes events (where, extend,\nproject-away/keep/rename, mv-expand, parse); a summarize, project, order or\ntake stage of your own decides the order. The limit always applies.\nExamples:\n pw-logs -l error -s 6h\n pw-logs -a chime \"where meta.user == 'x' | where message has 'sync'\"\n pw-logs -a all -l warn+ -s 24h \"summarize n=count() by app, message\"\n pw-logs -d platform -s 3d \"where severity != 'INFO'\"\nFields: apps = app, level, message, source, build_id, meta.* (a map: query\nsub-keys with dot notation, cast for summarize by \u2014 tostring(meta.user));\nplatform = service, severity, text, revision; rum = app, metric, value,\nrating, path, build_id.";
|
|
6
6
|
type Fields = Record<string, unknown>;
|
|
@@ -34,48 +34,45 @@ export declare function buildApl(q: LogsQuery): {
|
|
|
34
34
|
apl: string;
|
|
35
35
|
autoOrdered: boolean;
|
|
36
36
|
};
|
|
37
|
-
interface
|
|
38
|
-
|
|
39
|
-
|
|
37
|
+
interface TabularField {
|
|
38
|
+
name: string;
|
|
39
|
+
type?: string;
|
|
40
|
+
/** Present on a summarize's aggregation columns: `{ name: 'max', fields: ['_time'] }`. */
|
|
41
|
+
agg?: {
|
|
42
|
+
name: string;
|
|
43
|
+
fields?: string[];
|
|
44
|
+
} | null;
|
|
40
45
|
}
|
|
41
|
-
interface
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
46
|
+
interface TabularTable {
|
|
47
|
+
fields: TabularField[];
|
|
48
|
+
columns: unknown[][];
|
|
49
|
+
/** A summarize's group-by columns; dropped by any stage after it. */
|
|
50
|
+
groups?: {
|
|
51
|
+
name: string;
|
|
52
|
+
}[] | null;
|
|
47
53
|
}
|
|
48
|
-
interface
|
|
54
|
+
export interface TabularResponse {
|
|
49
55
|
status?: {
|
|
50
56
|
isPartial?: boolean;
|
|
51
57
|
rowsMatched?: number;
|
|
52
58
|
elapsedTime?: number;
|
|
53
59
|
};
|
|
54
|
-
|
|
55
|
-
buckets?: {
|
|
56
|
-
series?: {
|
|
57
|
-
startTime: string;
|
|
58
|
-
endTime: string;
|
|
59
|
-
groups: LegacyGroup[] | null;
|
|
60
|
-
}[];
|
|
61
|
-
totals?: LegacyGroup[];
|
|
62
|
-
};
|
|
63
|
-
request?: {
|
|
64
|
-
aggregations?: {
|
|
65
|
-
op: string;
|
|
66
|
-
field: string;
|
|
67
|
-
alias: string;
|
|
68
|
-
}[] | null;
|
|
69
|
-
};
|
|
60
|
+
tables?: TabularTable[];
|
|
70
61
|
}
|
|
71
|
-
/**
|
|
72
|
-
|
|
62
|
+
/** The first table's rows as records, `_time` first and as ISO. min/max of
|
|
63
|
+
* _time come back as epoch nanoseconds and are shown as timestamps. */
|
|
64
|
+
export declare function tableRows(response: TabularResponse): Fields[];
|
|
65
|
+
/** Whether the table is events (one row per logged event) rather than an
|
|
66
|
+
* aggregation or a reshaped table: no summarize columns, an event time,
|
|
67
|
+
* and the dataset's marker field (present on every event) filled in. A
|
|
68
|
+
* summarize followed by more stages loses its aggregation markers, so the
|
|
69
|
+
* `_time`/marker checks are what keep those rows a table. */
|
|
70
|
+
export declare function isEventTable(response: TabularResponse, rows: Fields[], marker: string | undefined): boolean;
|
|
71
|
+
/** Events as flat records: `_time` first, nulls (the dataset union's every
|
|
72
|
+
* other column) gone, Axiom's ingest time (`_sysTime`) dropped. */
|
|
73
|
+
export declare function eventRecords(rows: Fields[]): Fields[];
|
|
73
74
|
/** One greppable line per event: the dataset's headline, then the rest as k=v. */
|
|
74
75
|
export declare function renderEvents(dataset: string, records: Fields[], all: boolean): string;
|
|
75
|
-
/** Aggregation rows: group keys then aggregation aliases; a bucket time
|
|
76
|
-
* column when the query binned by time. min/max of _time come back as
|
|
77
|
-
* epoch nanoseconds and are shown as timestamps. */
|
|
78
|
-
export declare function aggregationRecords(response: LegacyResponse): Fields[];
|
|
79
76
|
export declare function renderTable(records: Fields[]): string;
|
|
80
77
|
export interface LogsOptions extends Partial<CliIo> {
|
|
81
78
|
argv: string[];
|
|
@@ -90,6 +87,6 @@ export declare function queryAxiom(fetchFn: typeof fetch, token: string, body: {
|
|
|
90
87
|
apl: string;
|
|
91
88
|
startTime: string;
|
|
92
89
|
endTime: string;
|
|
93
|
-
}): Promise<
|
|
90
|
+
}): Promise<TabularResponse>;
|
|
94
91
|
export declare function runLogs(options: LogsOptions): Promise<number>;
|
|
95
92
|
export {};
|
package/dist/ops/logs.js
CHANGED
|
@@ -13,7 +13,7 @@ import { LOG_LEVELS } from '../log-core.js';
|
|
|
13
13
|
import { findAppConfig } from './app.js';
|
|
14
14
|
import { cliIo, parseCli } from './cli.js';
|
|
15
15
|
import { flatten, formatRecords, pairs, parseTimeFlag, pruneNulls, scalarText } from './format.js';
|
|
16
|
-
export const AXIOM_QUERY_URL = 'https://api.axiom.co/v1/datasets/_apl?format=
|
|
16
|
+
export const AXIOM_QUERY_URL = 'https://api.axiom.co/v1/datasets/_apl?format=tabular';
|
|
17
17
|
export const QUERY_TOKEN_SECRET = 'shared--axiom-query-token';
|
|
18
18
|
const DEFAULT_LIMIT = 200;
|
|
19
19
|
const DEFAULT_SINCE = '1h';
|
|
@@ -135,9 +135,53 @@ const isoTime = (t) => {
|
|
|
135
135
|
const d = new Date(t);
|
|
136
136
|
return isNaN(d.getTime()) ? t : d.toISOString();
|
|
137
137
|
};
|
|
138
|
-
/**
|
|
139
|
-
|
|
140
|
-
|
|
138
|
+
/** The first table's rows as records, `_time` first and as ISO. min/max of
|
|
139
|
+
* _time come back as epoch nanoseconds and are shown as timestamps. */
|
|
140
|
+
export function tableRows(response) {
|
|
141
|
+
const table = response.tables?.[0];
|
|
142
|
+
if (!table)
|
|
143
|
+
return [];
|
|
144
|
+
const timeAggs = new Set(table.fields
|
|
145
|
+
.filter((f) => (f.agg?.name === 'min' || f.agg?.name === 'max') && f.agg.fields?.length === 1 && f.agg.fields[0] === '_time')
|
|
146
|
+
.map((f) => f.name));
|
|
147
|
+
const count = Math.max(0, ...table.columns.map((c) => c.length));
|
|
148
|
+
const rows = [];
|
|
149
|
+
for (let i = 0; i < count; i++) {
|
|
150
|
+
const row = {};
|
|
151
|
+
if (table.fields.some((f) => f.name === '_time'))
|
|
152
|
+
row._time = undefined;
|
|
153
|
+
table.fields.forEach((f, c) => {
|
|
154
|
+
const v = table.columns[c]?.[i] ?? null;
|
|
155
|
+
if (f.name === '_time' && typeof v === 'string')
|
|
156
|
+
row._time = isoTime(v);
|
|
157
|
+
else if (timeAggs.has(f.name) && typeof v === 'number')
|
|
158
|
+
row[f.name] = new Date(Math.round(v / 1e6)).toISOString();
|
|
159
|
+
else
|
|
160
|
+
row[f.name] = v;
|
|
161
|
+
});
|
|
162
|
+
rows.push(row);
|
|
163
|
+
}
|
|
164
|
+
return rows;
|
|
165
|
+
}
|
|
166
|
+
/** Whether the table is events (one row per logged event) rather than an
|
|
167
|
+
* aggregation or a reshaped table: no summarize columns, an event time,
|
|
168
|
+
* and the dataset's marker field (present on every event) filled in. A
|
|
169
|
+
* summarize followed by more stages loses its aggregation markers, so the
|
|
170
|
+
* `_time`/marker checks are what keep those rows a table. */
|
|
171
|
+
export function isEventTable(response, rows, marker) {
|
|
172
|
+
const table = response.tables?.[0];
|
|
173
|
+
if (!table || rows.length === 0)
|
|
174
|
+
return false;
|
|
175
|
+
if (table.fields.some((f) => f.agg) || (table.groups?.length ?? 0) > 0)
|
|
176
|
+
return false;
|
|
177
|
+
if (!table.fields.some((f) => f.name === '_time'))
|
|
178
|
+
return false;
|
|
179
|
+
return marker === undefined || rows[0][marker] != null;
|
|
180
|
+
}
|
|
181
|
+
/** Events as flat records: `_time` first, nulls (the dataset union's every
|
|
182
|
+
* other column) gone, Axiom's ingest time (`_sysTime`) dropped. */
|
|
183
|
+
export function eventRecords(rows) {
|
|
184
|
+
return rows.map(({ _time, _sysTime, ...rest }) => ({ _time, ...pruneNulls(rest) }));
|
|
141
185
|
}
|
|
142
186
|
/** One greppable line per event: the dataset's headline, then the rest as k=v. */
|
|
143
187
|
export function renderEvents(dataset, records, all) {
|
|
@@ -157,25 +201,6 @@ export function renderEvents(dataset, records, all) {
|
|
|
157
201
|
})
|
|
158
202
|
.join('\n');
|
|
159
203
|
}
|
|
160
|
-
/** Aggregation rows: group keys then aggregation aliases; a bucket time
|
|
161
|
-
* column when the query binned by time. min/max of _time come back as
|
|
162
|
-
* epoch nanoseconds and are shown as timestamps. */
|
|
163
|
-
export function aggregationRecords(response) {
|
|
164
|
-
const series = (response.buckets?.series ?? []).filter((s) => s.groups && s.groups.length > 0);
|
|
165
|
-
const binned = series.length > 1 || !series[0]?.startTime.startsWith('1970-');
|
|
166
|
-
const timeAggs = new Set((response.request?.aggregations ?? [])
|
|
167
|
-
.filter((a) => a.field === '_time' && (a.op === 'min' || a.op === 'max'))
|
|
168
|
-
.map((a) => a.alias));
|
|
169
|
-
return series.flatMap((s) => (s.groups ?? []).map((g) => {
|
|
170
|
-
const row = binned ? { _time: isoTime(s.startTime) } : {};
|
|
171
|
-
Object.assign(row, g.group);
|
|
172
|
-
for (const a of g.aggregations) {
|
|
173
|
-
row[a.op] =
|
|
174
|
-
timeAggs.has(a.op) && typeof a.value === 'number' ? new Date(Math.round(a.value / 1e6)).toISOString() : a.value;
|
|
175
|
-
}
|
|
176
|
-
return row;
|
|
177
|
-
}));
|
|
178
|
-
}
|
|
179
204
|
export function renderTable(records) {
|
|
180
205
|
const columns = [];
|
|
181
206
|
for (const r of records)
|
|
@@ -292,20 +317,20 @@ export async function runLogs(options) {
|
|
|
292
317
|
io.log(`query failed: ${err.message}\n${apl}`);
|
|
293
318
|
return 1;
|
|
294
319
|
}
|
|
295
|
-
|
|
320
|
+
// The limit is applied here too: with a time bin among a summarize's
|
|
321
|
+
// group keys, tabular Axiom returns whole groups past the `take` (6 rows
|
|
322
|
+
// for `take 3` on 2026-11-15; legacy returned 3), still in query order.
|
|
323
|
+
const rows = tableRows(response).slice(0, query.limit);
|
|
296
324
|
const window = `${body.startTime} .. ${body.endTime}`;
|
|
297
|
-
|
|
298
|
-
const events = matches.length > 0 && (marker === undefined || matches[0].data[marker] != null);
|
|
299
|
-
if (events) {
|
|
325
|
+
if (isEventTable(response, rows, datasetSpec(query.dataset).marker)) {
|
|
300
326
|
// Newest-first from the server; print oldest first so the log reads down.
|
|
301
|
-
const records = eventRecords(autoOrdered ? [...
|
|
327
|
+
const records = eventRecords(autoOrdered ? [...rows].reverse() : rows);
|
|
302
328
|
io.stdout(v.json ? JSON.stringify(records, null, 2) : renderEvents(query.dataset, records, v.all));
|
|
303
329
|
const matched = response.status?.rowsMatched;
|
|
304
330
|
const of = matched !== undefined && matched > records.length ? ` of ${matched} matching` : '';
|
|
305
331
|
io.log(`${records.length} event${records.length === 1 ? '' : 's'}${of}, ${window}`);
|
|
306
332
|
}
|
|
307
333
|
else {
|
|
308
|
-
const rows = matches.length > 0 ? eventRecords(matches) : aggregationRecords(response);
|
|
309
334
|
if (v.json)
|
|
310
335
|
io.stdout(JSON.stringify(rows, null, 2));
|
|
311
336
|
else
|
|
@@ -356,6 +356,17 @@ export declare class SyncClient<B, C extends EventBody, S extends EventBody, Sum
|
|
|
356
356
|
/** On return: a verdict needs 60 s of visible time (review B2). */
|
|
357
357
|
private rearmFailureTimers;
|
|
358
358
|
private failUnconfirmed;
|
|
359
|
+
/** Logs and closes the open outage, if any: on a live (re)connection, or
|
|
360
|
+
* (`via: 'background-catchup'`) when a hidden page's HTTP catch-up
|
|
361
|
+
* succeeds without a socket after the outage escalated to ERROR. A hidden
|
|
362
|
+
* page stops attempting its socket after one hidden failure, so an
|
|
363
|
+
* escalated outage that went hidden stayed open, its ERROR unanswered by
|
|
364
|
+
* any recovery line, until the page was next shown (notes 2026-11-16,
|
|
365
|
+
* task a0f43dda: a tab left hidden for 9+ hours). The page is current
|
|
366
|
+
* then; the return reconnects as usual and a failure there opens a new
|
|
367
|
+
* outage. An outage that never escalated keeps its single log on return,
|
|
368
|
+
* which reports the whole hidden spell. */
|
|
369
|
+
private endOutage;
|
|
359
370
|
private onSyncEstablished;
|
|
360
371
|
private requestReload;
|
|
361
372
|
private resyncFromServer;
|
|
@@ -1116,6 +1116,8 @@ export class SyncClient {
|
|
|
1116
1116
|
}
|
|
1117
1117
|
if (this.hub)
|
|
1118
1118
|
this.appSucceeded(this.establishesUnder(ackGen, complete));
|
|
1119
|
+
else if (kind === 'background' && complete && this.outageEscalated)
|
|
1120
|
+
this.endOutage('background-catchup');
|
|
1119
1121
|
return true;
|
|
1120
1122
|
}
|
|
1121
1123
|
catch {
|
|
@@ -1675,7 +1677,17 @@ export class SyncClient {
|
|
|
1675
1677
|
this.options.onEventFailed(entry, entry.error, false);
|
|
1676
1678
|
this.options.onSafetyChange?.();
|
|
1677
1679
|
}
|
|
1678
|
-
|
|
1680
|
+
/** Logs and closes the open outage, if any: on a live (re)connection, or
|
|
1681
|
+
* (`via: 'background-catchup'`) when a hidden page's HTTP catch-up
|
|
1682
|
+
* succeeds without a socket after the outage escalated to ERROR. A hidden
|
|
1683
|
+
* page stops attempting its socket after one hidden failure, so an
|
|
1684
|
+
* escalated outage that went hidden stayed open, its ERROR unanswered by
|
|
1685
|
+
* any recovery line, until the page was next shown (notes 2026-11-16,
|
|
1686
|
+
* task a0f43dda: a tab left hidden for 9+ hours). The page is current
|
|
1687
|
+
* then; the return reconnects as usual and a failure there opens a new
|
|
1688
|
+
* outage. An outage that never escalated keeps its single log on return,
|
|
1689
|
+
* which reports the whole hidden spell. */
|
|
1690
|
+
endOutage(via) {
|
|
1679
1691
|
if (this.outageStartedAt !== null) {
|
|
1680
1692
|
this.observeClockJump();
|
|
1681
1693
|
const durationMs = Math.max(0, this.options.runtime.now() - this.outageStartedAt);
|
|
@@ -1701,6 +1713,7 @@ export class SyncClient {
|
|
|
1701
1713
|
httpPostedEvents: delta?.httpPostedEvents,
|
|
1702
1714
|
freezes: delta?.freezes,
|
|
1703
1715
|
resumes: delta?.resumes,
|
|
1716
|
+
...(via ? { via } : {}),
|
|
1704
1717
|
};
|
|
1705
1718
|
if (this.outageEscalated) {
|
|
1706
1719
|
this.options.logger.info('sync outage recovered', fields);
|
|
@@ -1708,7 +1721,7 @@ export class SyncClient {
|
|
|
1708
1721
|
else if (attempts >= 2) {
|
|
1709
1722
|
this.options.logger.warn('sync outage recovered', fields);
|
|
1710
1723
|
}
|
|
1711
|
-
else if (attempts === 1) {
|
|
1724
|
+
else if (attempts === 1 && !via) {
|
|
1712
1725
|
this.options.logger.info('ws reconnected first try', fields);
|
|
1713
1726
|
}
|
|
1714
1727
|
else {
|
|
@@ -1717,7 +1730,15 @@ export class SyncClient {
|
|
|
1717
1730
|
this.outageStartedAt = null;
|
|
1718
1731
|
this.outageEscalated = false;
|
|
1719
1732
|
this.outageInfo = null;
|
|
1733
|
+
this.totalAttempts = 0;
|
|
1734
|
+
this.appFailuresInOutage = 0;
|
|
1735
|
+
if (this.escalateTimer !== null)
|
|
1736
|
+
this.options.runtime.clearTimeout(this.escalateTimer);
|
|
1737
|
+
this.escalateTimer = null;
|
|
1720
1738
|
}
|
|
1739
|
+
}
|
|
1740
|
+
onSyncEstablished() {
|
|
1741
|
+
this.endOutage();
|
|
1721
1742
|
if (this.returnWindow !== null && this.returnWindow.establishedAt === null) {
|
|
1722
1743
|
this.returnWindow.establishedAt = this.now();
|
|
1723
1744
|
this.maybeFinishReturnWindow();
|
package/package.json
CHANGED