@steve31415/baselib 3.62.2 → 3.63.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 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`) and,
147
- * given a Cloud SQL credential reader,
148
- * `credentialRemainingMs`; the logger adds request activity, as on every
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`) and,
202
- * given a Cloud SQL credential reader,
203
- * `credentialRemainingMs`; the logger adds request activity, as on every
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
  *
@@ -8,6 +8,10 @@ export declare const HUB_DEGRADED_SLEEP_MS = 2000;
8
8
  export declare const HUB_MINT_FLOOR_MS: number;
9
9
  /** A token is replaced once it is this old (the hub's TTL is one hour). */
10
10
  export declare const HUB_TOKEN_REFRESH_MS: number;
11
+ /** The longest a park waits for a refresh in flight before parking on the
12
+ * old token anyway; above the callers' 10 s bound on one mint, so in
13
+ * practice the mint always settles first. */
14
+ export declare const HUB_REFRESH_WAIT_MS = 15000;
11
15
  /** Added to the caller's lookback (review S2), and the hub's cap on it. */
12
16
  export declare const HUB_LOOKBACK_SLACK_MS = 1000;
13
17
  export declare const HUB_LOOKBACK_MAX_MS = 60000;
@@ -36,6 +40,7 @@ export interface HubDaemonClientOptions {
36
40
  degradedSleepMs?: number;
37
41
  mintFloorMs?: number;
38
42
  refreshAfterMs?: number;
43
+ refreshWaitMs?: number;
39
44
  /** Injectable for tests. */
40
45
  fetch?: typeof fetch;
41
46
  /** Monotonic milliseconds (tests). */
@@ -53,6 +58,7 @@ export declare class HubDaemonClient {
53
58
  private readonly degradedSleepMs;
54
59
  private readonly mintFloorMs;
55
60
  private readonly refreshAfterMs;
61
+ private readonly refreshWaitMs;
56
62
  private readonly fetchFn;
57
63
  private readonly now;
58
64
  private readonly sleepFn;
@@ -76,6 +82,8 @@ export declare class HubDaemonClient {
76
82
  * caller's monotonic clock. Never throws. */
77
83
  park(lookbackMs: number, signal?: AbortSignal): Promise<HubParkOutcome>;
78
84
  private usableToken;
85
+ /** Wait for the mint in flight, at most refreshWaitMs or until `signal`. */
86
+ private awaitMint;
79
87
  private maybeMint;
80
88
  private enterDegraded;
81
89
  private leaveDegraded;
@@ -15,9 +15,13 @@
15
15
  // - It never sends Authorization: the app's device bearer stays on the
16
16
  // daemon ↔ app path (review S4). The hub token goes in X-Hub-Token.
17
17
  // - One attempt per park, bounded at the park plus 10 s; no retry budget.
18
- // - The token is minted off the loop's critical path, at most once per
19
- // HUB_MINT_FLOOR_MS whatever the outcome (review S3); until a token
18
+ // - The first token is minted off the loop's critical path, at most once
19
+ // per HUB_MINT_FLOOR_MS whatever the outcome (review S3); until a token
20
20
  // exists the loop runs degraded (direct requests every 2 s).
21
+ // - The park that starts a refresh waits for it (bounded) before sending
22
+ // its wait: the hub kills the old token the moment the new one
23
+ // registers, so a wait sent on the old token alongside the refresh
24
+ // could reach the hub's token lookup after that and be refused (3.62.3).
21
25
  // - After a 401 it never presents that token again until a new mint
22
26
  // (§14.4: the hub's per-address limit on bad tokens is shared by every
23
27
  // daemon on the host).
@@ -36,6 +40,10 @@ export const HUB_DEGRADED_SLEEP_MS = 2_000;
36
40
  export const HUB_MINT_FLOOR_MS = 5 * 60_000;
37
41
  /** A token is replaced once it is this old (the hub's TTL is one hour). */
38
42
  export const HUB_TOKEN_REFRESH_MS = 50 * 60_000;
43
+ /** The longest a park waits for a refresh in flight before parking on the
44
+ * old token anyway; above the callers' 10 s bound on one mint, so in
45
+ * practice the mint always settles first. */
46
+ export const HUB_REFRESH_WAIT_MS = 15_000;
39
47
  /** Added to the caller's lookback (review S2), and the hub's cap on it. */
40
48
  export const HUB_LOOKBACK_SLACK_MS = 1_000;
41
49
  export const HUB_LOOKBACK_MAX_MS = 60_000;
@@ -50,6 +58,7 @@ export class HubDaemonClient {
50
58
  degradedSleepMs;
51
59
  mintFloorMs;
52
60
  refreshAfterMs;
61
+ refreshWaitMs;
53
62
  fetchFn;
54
63
  now;
55
64
  sleepFn;
@@ -68,6 +77,7 @@ export class HubDaemonClient {
68
77
  this.degradedSleepMs = opts.degradedSleepMs ?? HUB_DEGRADED_SLEEP_MS;
69
78
  this.mintFloorMs = opts.mintFloorMs ?? HUB_MINT_FLOOR_MS;
70
79
  this.refreshAfterMs = opts.refreshAfterMs ?? HUB_TOKEN_REFRESH_MS;
80
+ this.refreshWaitMs = opts.refreshWaitMs ?? HUB_REFRESH_WAIT_MS;
71
81
  this.fetchFn = opts.fetch ?? fetch;
72
82
  this.now = opts.now ?? (() => performance.now());
73
83
  this.sleepFn = opts.sleep ?? sleep;
@@ -91,6 +101,19 @@ export class HubDaemonClient {
91
101
  if (signal?.aborted)
92
102
  return 'stopped';
93
103
  this.maybeMint();
104
+ if (this.minting && this.usableToken()) {
105
+ // A refresh is in flight (we hold a token, so it is not the first
106
+ // mint). Its register replaces our row and kills the token we hold the
107
+ // instant it commits, while a wait sent now on that token could reach
108
+ // the hub's lookup after that commit and be refused with 401 — the
109
+ // daemon racing itself (task 105aa5f6: four WARNs a day on lurch). So
110
+ // park on the new token: one mint's latency every 50 minutes, in idle
111
+ // time. A refresh that fails or overruns leaves the old token, still
112
+ // valid, in place.
113
+ await this.awaitMint(signal);
114
+ if (signal?.aborted)
115
+ return 'stopped';
116
+ }
94
117
  const token = this.usableToken();
95
118
  if (!token) {
96
119
  // Quiet while the very first mint is still in flight; degraded after.
@@ -153,6 +176,19 @@ export class HubDaemonClient {
153
176
  this.token = null;
154
177
  return this.token;
155
178
  }
179
+ /** Wait for the mint in flight, at most refreshWaitMs or until `signal`. */
180
+ async awaitMint(signal) {
181
+ const minting = this.minting;
182
+ if (!minting)
183
+ return;
184
+ const settled = new AbortController();
185
+ try {
186
+ await Promise.race([minting, sleep(this.refreshWaitMs, signal ? AbortSignal.any([signal, settled.signal]) : settled.signal)]);
187
+ }
188
+ finally {
189
+ settled.abort();
190
+ }
191
+ }
156
192
  maybeMint() {
157
193
  const t = this.now();
158
194
  const needed = this.token === null || t - this.token.mintedAt >= this.refreshAfterMs;
@@ -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 legacy query format returns every field of the dataset'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;
@@ -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 legacy query format returns every field of the dataset'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) {
@@ -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=legacy";
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 LegacyMatch {
38
- _time: string;
39
- data: Fields;
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 LegacyGroup {
42
- group: Fields;
43
- aggregations: {
44
- op: string;
45
- value: unknown;
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 LegacyResponse {
54
+ export interface TabularResponse {
49
55
  status?: {
50
56
  isPartial?: boolean;
51
57
  rowsMatched?: number;
52
58
  elapsedTime?: number;
53
59
  };
54
- matches?: LegacyMatch[];
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
- /** Events as flat records: `_time` first, nulls gone. */
72
- export declare function eventRecords(matches: LegacyMatch[]): Fields[];
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<LegacyResponse>;
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=legacy';
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
- /** Events as flat records: `_time` first, nulls gone. */
139
- export function eventRecords(matches) {
140
- return matches.map((m) => ({ _time: isoTime(m._time), ...pruneNulls(m.data) }));
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
- const matches = response.matches ?? [];
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
- const marker = datasetSpec(query.dataset).marker;
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 ? [...matches].reverse() : matches);
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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@steve31415/baselib",
3
- "version": "3.62.2",
3
+ "version": "3.63.0",
4
4
  "description": "Plasticine new-world shared platform library: logging, auth, service-to-service auth, db, HTTP, sync, app updates",
5
5
  "type": "module",
6
6
  "license": "MIT",