@jeffusion/bungee-core 6.12.0 → 6.13.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.
Files changed (29) hide show
  1. package/dist/config-storage-worker.js +142 -7
  2. package/dist/gateway/plugin.js +3 -1
  3. package/dist/main.js +3290 -2992
  4. package/dist/observability-worker.js +948 -175
  5. package/dist/plugins/anthropic-request-sanitizer/index.js.map +2 -2
  6. package/dist/plugins/anthropic-tool-name-transformer/index.js.map +2 -2
  7. package/dist/plugins/chatgpt-oauth/index.js.map +2 -2
  8. package/dist/plugins/codex-router/index.js.map +2 -2
  9. package/dist/plugins/deepseek-reasoning-fix/index.js.map +2 -2
  10. package/dist/plugins/key-access/index.js.map +2 -2
  11. package/dist/plugins/key-rate-limit/index.js.map +2 -2
  12. package/dist/plugins/llm-protocol-adapter/index.js +4 -2
  13. package/dist/plugins/llm-protocol-adapter/index.js.map +4 -4
  14. package/dist/plugins/llm-tps/index.js.map +2 -2
  15. package/dist/plugins/model-mapping/index.js.map +2 -2
  16. package/dist/plugins/models-dev/index.js.map +2 -2
  17. package/dist/plugins/request-logs/index.js +1392 -0
  18. package/dist/plugins/request-logs/index.js.map +33 -0
  19. package/dist/plugins/request-logs/ingress.js +28 -0
  20. package/dist/plugins/request-logs/ingress.js.map +10 -0
  21. package/dist/plugins/request-logs/manifest.json +68 -0
  22. package/dist/plugins/request-logs/ui/RequestLogsPage.svelte +1130 -0
  23. package/dist/plugins/request-logs/ui/RequestLogsSettings.svelte +111 -0
  24. package/dist/plugins/signature-repair/index.js.map +2 -2
  25. package/dist/plugins/token-budget/index.js.map +2 -2
  26. package/dist/plugins/token-metering/index.js.map +2 -2
  27. package/dist/plugins/token-stats/index.js.map +2 -2
  28. package/dist/plugins/user-auth/index.js.map +2 -2
  29. package/package.json +2 -2
@@ -14771,7 +14771,7 @@ var require_winston_daily_rotate_file = __commonJS(function(exports, module) {
14771
14771
  });
14772
14772
 
14773
14773
  // src/master-runtime/observability-worker.ts
14774
- import { Database as Database5 } from "bun:sqlite";
14774
+ import { Database as Database6 } from "bun:sqlite";
14775
14775
 
14776
14776
  // src/master-runtime/master-stats.ts
14777
14777
  import { Database as Database2 } from "bun:sqlite";
@@ -14790,7 +14790,7 @@ var bodyResources = Object.freeze({
14790
14790
  observerBacklogEvents: positive("BUNGEE_BODY_OBSERVER_BACKLOG_EVENTS", 1024),
14791
14791
  mandatoryDecoders: positive("BUNGEE_BODY_MANDATORY_DECODERS", 8),
14792
14792
  optionalDecoders: positive("BUNGEE_BODY_OPTIONAL_DECODERS", 8),
14793
- loggerMemoryBytes: positive("BUNGEE_BODY_LOG_MEMORY_BYTES", 32 * 1024 * 1024),
14793
+ loggerMemoryBytes: 32 * 1024 * 1024,
14794
14794
  loggerConsumers: positive("BUNGEE_BODY_LOG_CONSUMERS", 64),
14795
14795
  callbackMs: positive("BUNGEE_BODY_CALLBACK_MS", 250),
14796
14796
  optionalDecodeMs: positive("BUNGEE_BODY_OPTIONAL_DECODE_MS", 1000),
@@ -14798,8 +14798,23 @@ var bodyResources = Object.freeze({
14798
14798
  });
14799
14799
 
14800
14800
  // src/gateway/body-service.ts
14801
+ class BodyProcessingError extends Error {
14802
+ status;
14803
+ code;
14804
+ limitBytes;
14805
+ receivedBytes;
14806
+ constructor(status, code, limitBytes, receivedBytes) {
14807
+ super(code);
14808
+ this.status = status;
14809
+ this.code = code;
14810
+ this.limitBytes = limitBytes;
14811
+ this.receivedBytes = receivedBytes;
14812
+ this.name = "BodyProcessingError";
14813
+ }
14814
+ }
14801
14815
  var handles = new WeakMap;
14802
14816
  var sources = new WeakMap;
14817
+ var observationSources = new WeakMap;
14803
14818
  var readerCancellations = new WeakMap;
14804
14819
  var defaultBodyIdentity = Object.freeze({ requestId: "", attemptId: "", direction: "request", stage: "original-request", version: 0, contentType: "", contentEncoding: "" });
14805
14820
 
@@ -15112,6 +15127,27 @@ class StatsHandler {
15112
15127
  }
15113
15128
  }
15114
15129
 
15130
+ // src/migrations/access-log-record-identity.ts
15131
+ var ACCESS_LOG_CHAIN_ID_SQL = "COALESCE(CASE WHEN transport_type = 'http' THEN access_id ELSE COALESCE(operation_id, access_id) END, parent_request_id, request_id)";
15132
+ var ACCESS_LOG_RECORD_IDENTITY = {
15133
+ version: "006",
15134
+ name: "access_log_record_identity",
15135
+ up(db) {
15136
+ db.run(`ALTER TABLE access_logs ADD COLUMN record_kind TEXT
15137
+ CHECK (record_kind IN ('access', 'operation', 'attempt'))`);
15138
+ db.run("ALTER TABLE access_logs ADD COLUMN access_id TEXT");
15139
+ db.run("ALTER TABLE access_logs ADD COLUMN operation_id TEXT");
15140
+ db.run("ALTER TABLE access_logs ADD COLUMN protocol TEXT");
15141
+ db.run("ALTER TABLE access_logs ADD COLUMN operation TEXT");
15142
+ db.run("ALTER TABLE access_logs ADD COLUMN close_code INTEGER");
15143
+ db.run(`ALTER TABLE access_logs ADD COLUMN observation_outcome TEXT
15144
+ CHECK (observation_outcome IN ('complete', 'incomplete'))`);
15145
+ db.run("CREATE INDEX idx_access_log_access_id ON access_logs(access_id) WHERE access_id IS NOT NULL");
15146
+ db.run("CREATE INDEX idx_access_log_operation_id ON access_logs(operation_id) WHERE operation_id IS NOT NULL");
15147
+ db.run(`CREATE INDEX idx_access_log_chain_id ON access_logs(${ACCESS_LOG_CHAIN_ID_SQL})`);
15148
+ }
15149
+ };
15150
+
15115
15151
  // src/api/logs.ts
15116
15152
  function outcomeSql(status, success, protocol) {
15117
15153
  return `CASE
@@ -15122,12 +15158,17 @@ function outcomeSql(status, success, protocol) {
15122
15158
  function transportSql(column) {
15123
15159
  return `CASE WHEN ${column} IN ('pending','completed','failed','cancelled') THEN ${column} ELSE 'unknown' END`;
15124
15160
  }
15125
- function countSql(status, transport) {
15161
+ function countSql(status, transport, acceptedDisconnect = "0", webSocketOperation) {
15162
+ const successStatus = `(${status} >= 200 AND ${status} < 300 OR ${acceptedDisconnect} = 1)`;
15163
+ const success = `${transport} = 'completed' AND ${successStatus}`;
15164
+ const failed = `${transport} = 'failed' OR (${transport} = 'completed' AND NOT COALESCE(${successStatus}, 0))`;
15165
+ const httpOnly = webSocketOperation ? `NOT ${webSocketOperation} AND ` : "";
15166
+ const requestOutcome = (name, httpOutcome) => webSocketOperation ? `CASE WHEN ${webSocketOperation} THEN chain_outcome = '${name}' ELSE ${httpOutcome} END` : httpOutcome;
15126
15167
  return [
15127
- ...[2, 3, 4, 5].map((n) => `SUM(${status} >= ${n}00 AND ${status} < ${n + 1}00) AS status${n}xx`),
15128
- `SUM(${status} < 200 OR ${status} >= 600 OR ${status} IS NULL) AS statusOther`,
15129
- `SUM(${transport} = 'completed' AND ${status} >= 200 AND ${status} < 300) AS request_success`,
15130
- `SUM(${transport} = 'failed' OR (${transport} = 'completed' AND (${status} < 200 OR ${status} >= 300 OR ${status} IS NULL))) AS request_failed`,
15168
+ ...[2, 3, 4, 5].map((n) => `SUM(${httpOnly}${status} >= ${n}00 AND ${status} < ${n + 1}00) AS status${n}xx`),
15169
+ `SUM(${httpOnly}(${status} < 200 OR ${status} >= 600 OR ${status} IS NULL)) AS statusOther`,
15170
+ `SUM(${requestOutcome("success", success)}) AS request_success`,
15171
+ `SUM(${requestOutcome("failed", failed)}) AS request_failed`,
15131
15172
  ...TRANSPORT_OUTCOMES.map((key) => `SUM(${transportSql(transport)} = '${key}') AS transport_${key}`)
15132
15173
  ].join(", ");
15133
15174
  }
@@ -15145,33 +15186,101 @@ class LogQueryService {
15145
15186
  db;
15146
15187
  transportColumn;
15147
15188
  transportCodeColumn;
15189
+ hasTransportType;
15190
+ recordKindColumn;
15191
+ chainIdSql;
15148
15192
  static CHAIN_SORT_COLUMNS = {
15149
15193
  timestamp: "chain_start_ts",
15150
15194
  duration: "chain_duration_ms",
15151
15195
  status: "chain_status"
15152
15196
  };
15153
- static CHAIN_STATS_CTES = `
15197
+ constructor(db) {
15198
+ this.db = db;
15199
+ const columns = db.query("PRAGMA table_info(access_logs)").all();
15200
+ this.transportColumn = columns.some((c) => c.name === "transport_outcome") ? "transport_outcome" : "NULL";
15201
+ this.transportCodeColumn = columns.some((c) => c.name === "transport_code") ? "transport_code" : "NULL";
15202
+ this.hasTransportType = columns.some((c) => c.name === "transport_type");
15203
+ this.recordKindColumn = columns.some((c) => c.name === "record_kind") ? "record_kind" : "NULL";
15204
+ this.chainIdSql = this.recordKindColumn === "NULL" ? "COALESCE(parent_request_id, request_id)" : ACCESS_LOG_CHAIN_ID_SQL;
15205
+ }
15206
+ get recordRankSql() {
15207
+ return `CASE ${this.recordKindColumn} WHEN 'access' THEN 0 WHEN 'operation' THEN 1 ELSE 2 END`;
15208
+ }
15209
+ get statusOrderSql() {
15210
+ return `${this.recordRankSql},
15211
+ CASE WHEN request_type = 'final' THEN 0 ELSE 1 END,
15212
+ COALESCE(attempt_number, -1) DESC, timestamp DESC, id DESC`;
15213
+ }
15214
+ get representativeOrderSql() {
15215
+ return `${this.recordRankSql},
15216
+ attempt_number ASC, timestamp ASC, id ASC`;
15217
+ }
15218
+ clientRequestSql(alias = "access_logs") {
15219
+ if (!this.hasTransportType)
15220
+ return "1";
15221
+ if (this.recordKindColumn === "NULL")
15222
+ return `${alias}.transport_type IS NOT 'websocket'`;
15223
+ return `NOT (${alias}.transport_type IS 'websocket' AND (${alias}.record_kind IS NULL OR ${alias}.record_kind = 'access'))
15224
+ AND NOT (${alias}.record_kind IS 'attempt' AND ${alias}.operation_id IS NOT NULL AND (
15225
+ ${alias}.transport_type IS 'websocket' OR EXISTS (
15226
+ SELECT 1 FROM access_logs op WHERE op.operation_id = ${alias}.operation_id
15227
+ AND op.record_kind = 'operation' AND op.transport_type = 'websocket'
15228
+ )
15229
+ ))`;
15230
+ }
15231
+ acceptedDisconnectSql(alias = "access_logs") {
15232
+ if (this.recordKindColumn === "NULL" || this.transportCodeColumn === "NULL")
15233
+ return "0";
15234
+ return `CASE WHEN ${alias}.record_kind = 'access' AND ${alias}.transport_type = 'http'
15235
+ AND ${alias}.status BETWEEN 200 AND 299 AND ${alias}.transport_outcome = 'cancelled'
15236
+ AND ${alias}.transport_code = 'client_cancelled' THEN COALESCE((
15237
+ SELECT op.transport_code = 'terminal_before_client_disconnect'
15238
+ FROM access_logs op WHERE op.access_id = ${alias}.access_id AND op.record_kind = 'operation'
15239
+ ORDER BY op.timestamp DESC, op.id DESC LIMIT 1
15240
+ ), 0) AND NOT EXISTS (
15241
+ SELECT 1 FROM access_logs op WHERE op.access_id = ${alias}.access_id AND op.record_kind = 'operation'
15242
+ AND op.observation_outcome IS NOT 'complete'
15243
+ ) ELSE 0 END`;
15244
+ }
15245
+ effectiveTransportSql(alias = "access_logs") {
15246
+ return `CASE WHEN ${this.acceptedDisconnectSql(alias)} THEN 'completed' ELSE ${this.transportColumn} END`;
15247
+ }
15248
+ get webSocketOperationSql() {
15249
+ return this.recordKindColumn === "NULL" || !this.hasTransportType ? "0" : "record_kind IS 'operation' AND transport_type IS 'websocket'";
15250
+ }
15251
+ get requestStatusSql() {
15252
+ return `CASE WHEN ${this.webSocketOperationSql} AND status = 0 THEN 101 ELSE status END`;
15253
+ }
15254
+ get requestMethodSql() {
15255
+ return `CASE WHEN ${this.webSocketOperationSql} AND status = 0 THEN 'GET' ELSE method END`;
15256
+ }
15257
+ get chainStatsCtes() {
15258
+ const webSocketOperation = this.webSocketOperationSql;
15259
+ const observationOutcome = this.recordKindColumn === "NULL" ? "NULL" : "observation_outcome";
15260
+ return `
15154
15261
  chain_rows AS (
15155
15262
  SELECT
15156
- COALESCE(parent_request_id, request_id) AS chain_id,
15263
+ ${this.chainIdSql} AS chain_id,
15157
15264
  id,
15158
15265
  timestamp,
15159
15266
  duration,
15160
15267
  status,
15161
15268
  success,
15162
15269
  protocol_outcome,
15163
- __TRANSPORT_COLUMN__ AS transport_outcome,
15270
+ ${observationOutcome} AS observation_outcome,
15271
+ (${webSocketOperation}) AS websocket_operation,
15272
+ ${this.effectiveTransportSql()} AS transport_outcome,
15273
+ ${this.acceptedDisconnectSql()} AS accepted_disconnect,
15164
15274
  request_type,
15165
15275
  attempt_number,
15166
15276
  ROW_NUMBER() OVER (
15167
- PARTITION BY COALESCE(parent_request_id, request_id)
15168
- ORDER BY
15169
- CASE WHEN request_type = 'final' THEN 0 ELSE 1 END,
15170
- CASE WHEN attempt_number IS NULL THEN -1 ELSE attempt_number END DESC,
15171
- timestamp DESC,
15172
- id DESC
15277
+ PARTITION BY ${this.chainIdSql}
15278
+ ORDER BY ${this.statusOrderSql}
15173
15279
  ) AS status_rank
15174
15280
  FROM access_logs
15281
+ WHERE (${this.recordKindColumn} IS NULL OR ${this.recordKindColumn} = 'access' OR (${webSocketOperation})
15282
+ OR (${this.recordKindColumn} = 'attempt' AND ${this.recordKindColumn === "NULL" ? "NULL" : "transport_type"} = 'http'))
15283
+ AND ${this.clientRequestSql()}
15175
15284
  ),
15176
15285
  chains AS (
15177
15286
  SELECT
@@ -15179,26 +15288,37 @@ class LogQueryService {
15179
15288
  MIN(timestamp) AS chain_start_ts,
15180
15289
  MAX(timestamp + duration) AS chain_end_ts,
15181
15290
  MAX(CASE WHEN status_rank = 1 THEN status END) AS chain_status,
15182
- MAX(CASE WHEN status_rank = 1 THEN success END) AS final_success,
15291
+ MAX(CASE WHEN status_rank = 1 THEN CASE WHEN accepted_disconnect THEN 1 ELSE success END END) AS final_success,
15183
15292
  MAX(CASE WHEN status_rank = 1 THEN protocol_outcome END) AS final_protocol_outcome,
15184
15293
  MAX(CASE WHEN status_rank = 1 THEN transport_outcome END) AS final_transport_outcome,
15294
+ MAX(CASE WHEN status_rank = 1 THEN observation_outcome END) AS final_observation_outcome,
15295
+ MAX(CASE WHEN status_rank = 1 THEN websocket_operation END) AS websocket_operation,
15296
+ MAX(CASE WHEN status_rank = 1 THEN accepted_disconnect END) AS accepted_disconnect,
15185
15297
  MAX(timestamp + duration) - MIN(timestamp) AS chain_duration_ms
15186
15298
  FROM chain_rows
15187
15299
  GROUP BY chain_id
15188
15300
  ),
15189
15301
  classified_chains AS (
15190
15302
  SELECT *,
15191
- ${outcomeSql("chain_status", "final_success", "final_protocol_outcome")} AS chain_outcome
15303
+ CASE WHEN websocket_operation THEN CASE
15304
+ WHEN final_transport_outcome = 'completed' AND final_protocol_outcome = 'completed' AND final_success = 1 THEN 'success'
15305
+ WHEN final_observation_outcome IS NOT NULL OR final_protocol_outcome IS NOT NULL
15306
+ OR final_transport_outcome IN ('completed', 'failed', 'cancelled') THEN 'failed'
15307
+ END ELSE ${outcomeSql("chain_status", "final_success", "final_protocol_outcome")} END AS chain_outcome
15192
15308
  FROM chains
15193
15309
  )`;
15194
- constructor(db) {
15195
- this.db = db;
15196
- const columns = db.query("PRAGMA table_info(access_logs)").all();
15197
- this.transportColumn = columns.some((c) => c.name === "transport_outcome") ? "transport_outcome" : "NULL";
15198
- this.transportCodeColumn = columns.some((c) => c.name === "transport_code") ? "transport_code" : "NULL";
15199
15310
  }
15200
- get chainStatsCtes() {
15201
- return LogQueryService.CHAIN_STATS_CTES.replace("__TRANSPORT_COLUMN__", this.transportColumn);
15311
+ addIdentityFilters(params, clauses, bindings) {
15312
+ for (const [column, value] of [
15313
+ ["record_kind", params.recordKind],
15314
+ ["access_id", params.accessId],
15315
+ ["operation_id", params.operationId]
15316
+ ]) {
15317
+ if (value === undefined)
15318
+ continue;
15319
+ clauses.push(this.recordKindColumn === "NULL" ? "NULL = ?" : `${column} = ?`);
15320
+ bindings.push(value);
15321
+ }
15202
15322
  }
15203
15323
  async query(params = {}) {
15204
15324
  const {
@@ -15220,8 +15340,9 @@ class LogQueryService {
15220
15340
  sortBy = "timestamp",
15221
15341
  sortOrder = "desc"
15222
15342
  } = params;
15223
- const whereClauses = [];
15343
+ const whereClauses = params.recordKind === undefined ? [this.clientRequestSql()] : [];
15224
15344
  const whereParams = [];
15345
+ this.addIdentityFilters(params, whereClauses, whereParams);
15225
15346
  if (startTime !== undefined) {
15226
15347
  whereClauses.push("timestamp >= ?");
15227
15348
  whereParams.push(startTime);
@@ -15237,7 +15358,7 @@ class LogQueryService {
15237
15358
  whereParams.push(transportType);
15238
15359
  }
15239
15360
  if (method) {
15240
- whereClauses.push("method = ?");
15361
+ whereClauses.push(`${this.requestMethodSql} = ?`);
15241
15362
  whereParams.push(method);
15242
15363
  }
15243
15364
  if (path) {
@@ -15246,10 +15367,10 @@ class LogQueryService {
15246
15367
  }
15247
15368
  if (status !== undefined) {
15248
15369
  if (Array.isArray(status)) {
15249
- whereClauses.push(`status IN (${status.map(() => "?").join(", ")})`);
15370
+ whereClauses.push(`${this.requestStatusSql} IN (${status.map(() => "?").join(", ")})`);
15250
15371
  whereParams.push(...status);
15251
15372
  } else {
15252
- whereClauses.push("status = ?");
15373
+ whereClauses.push(`${this.requestStatusSql} = ?`);
15253
15374
  whereParams.push(status);
15254
15375
  }
15255
15376
  }
@@ -15266,13 +15387,13 @@ class LogQueryService {
15266
15387
  whereParams.push(transformer);
15267
15388
  }
15268
15389
  if (success !== undefined) {
15269
- whereClauses.push("success = ?");
15390
+ whereClauses.push(`CASE WHEN ${this.acceptedDisconnectSql()} THEN 1 ELSE success END = ?`);
15270
15391
  whereParams.push(success ? 1 : 0);
15271
15392
  }
15272
15393
  if (transportOutcome !== undefined) {
15273
15394
  if (!TRANSPORT_OUTCOMES.includes(transportOutcome))
15274
15395
  throw new Error("Invalid transport outcome");
15275
- whereClauses.push(`${transportSql(this.transportColumn)} = ?`);
15396
+ whereClauses.push(`${transportSql(this.effectiveTransportSql())} = ?`);
15276
15397
  whereParams.push(transportOutcome);
15277
15398
  }
15278
15399
  if (searchTerm) {
@@ -15288,10 +15409,10 @@ class LogQueryService {
15288
15409
  const countResult = this.db.query(countQuery).get(...whereParams);
15289
15410
  const total = countResult.total;
15290
15411
  const offset = (page - 1) * limit;
15291
- const sortColumn = sortBy === "timestamp" ? "timestamp" : sortBy === "duration" ? "duration" : "status";
15412
+ const sortColumn = sortBy === "timestamp" ? "timestamp" : sortBy === "duration" ? "duration" : this.requestStatusSql;
15292
15413
  const order = sortOrder.toUpperCase();
15293
15414
  const dataQuery = `
15294
- SELECT * FROM access_logs
15415
+ SELECT *, ${this.acceptedDisconnectSql()} AS accepted_disconnect FROM access_logs
15295
15416
  ${whereClause}
15296
15417
  ORDER BY ${sortColumn} ${order}
15297
15418
  LIMIT ? OFFSET ?
@@ -15307,20 +15428,24 @@ class LogQueryService {
15307
15428
  };
15308
15429
  }
15309
15430
  async getById(requestId) {
15310
- const query = "SELECT * FROM access_logs WHERE request_id = ?";
15431
+ const query = `SELECT *, ${this.acceptedDisconnectSql()} AS accepted_disconnect FROM access_logs WHERE request_id = ?`;
15311
15432
  const row = this.db.query(query).get(requestId);
15312
15433
  if (!row) {
15313
15434
  return null;
15314
15435
  }
15315
15436
  return this.mapRowToLogEntry(row);
15316
15437
  }
15317
- async querySince(timestamp, id = 0) {
15438
+ getLatestLogId() {
15439
+ const row = this.db.query("SELECT MAX(id) AS id FROM access_logs").get();
15440
+ return row?.id ?? 0;
15441
+ }
15442
+ async querySince(id) {
15318
15443
  const rows = this.db.query(`
15319
15444
  SELECT * FROM access_logs
15320
- WHERE timestamp > ? OR (timestamp = ? AND id > ?)
15321
- ORDER BY timestamp ASC, id ASC
15445
+ WHERE id > ? AND ${this.clientRequestSql()}
15446
+ ORDER BY id ASC
15322
15447
  LIMIT 256
15323
- `).all(timestamp, timestamp, id);
15448
+ `).all(id);
15324
15449
  return rows.map((row) => this.mapRowToLogEntry(row));
15325
15450
  }
15326
15451
  async queryChains(params = {}) {
@@ -15348,8 +15473,9 @@ class LogQueryService {
15348
15473
  minChainDurationMs,
15349
15474
  maxChainDurationMs
15350
15475
  } = params;
15351
- const rowWhereClauses = [];
15476
+ const rowWhereClauses = params.recordKind === undefined ? [this.clientRequestSql()] : [];
15352
15477
  const rowWhereParams = [];
15478
+ this.addIdentityFilters(params, rowWhereClauses, rowWhereParams);
15353
15479
  if (transportType !== undefined) {
15354
15480
  if (transportType !== "http" && transportType !== "websocket")
15355
15481
  throw new Error("Invalid transport type");
@@ -15357,7 +15483,7 @@ class LogQueryService {
15357
15483
  rowWhereParams.push(transportType);
15358
15484
  }
15359
15485
  if (method) {
15360
- rowWhereClauses.push("method = ?");
15486
+ rowWhereClauses.push(`${this.requestMethodSql} = ?`);
15361
15487
  rowWhereParams.push(method);
15362
15488
  }
15363
15489
  if (path) {
@@ -15405,7 +15531,8 @@ class LogQueryService {
15405
15531
  }
15406
15532
  }
15407
15533
  if (success !== undefined) {
15408
- chainWhereClauses.push(success ? "chain_status < 400" : "chain_status >= 400");
15534
+ chainWhereClauses.push("chain_success = ?");
15535
+ chainWhereParams.push(success ? 1 : 0);
15409
15536
  }
15410
15537
  if (transportOutcome !== undefined) {
15411
15538
  if (!TRANSPORT_OUTCOMES.includes(transportOutcome))
@@ -15436,106 +15563,66 @@ class LogQueryService {
15436
15563
  const sortColumn = LogQueryService.CHAIN_SORT_COLUMNS[sortBy] ?? LogQueryService.CHAIN_SORT_COLUMNS.timestamp;
15437
15564
  const sortDirection = sortOrder === "asc" ? "ASC" : "DESC";
15438
15565
  const chainWhereClause = chainWhereClauses.length > 0 ? `WHERE ${chainWhereClauses.join(" AND ")}` : "";
15439
- const countQuery = `
15566
+ const chainCtes = `
15440
15567
  WITH filtered_chain_ids AS (
15441
- SELECT DISTINCT COALESCE(parent_request_id, request_id) AS chain_id
15568
+ SELECT DISTINCT ${this.chainIdSql} AS chain_id
15442
15569
  FROM access_logs
15443
15570
  ${rowWhereClause}
15444
15571
  ),
15445
15572
  chain_rows AS (
15446
15573
  SELECT
15447
15574
  al.*,
15448
- ${this.transportColumn} AS observed_transport_outcome,
15575
+ ${this.requestStatusSql} AS observed_http_status,
15576
+ ${this.recordKindColumn} AS observed_record_kind,
15577
+ ${this.effectiveTransportSql("al")} AS observed_transport_outcome,
15578
+ ${this.acceptedDisconnectSql("al")} AS accepted_disconnect,
15449
15579
  ${this.transportCodeColumn} AS observed_transport_code,
15450
- COALESCE(al.parent_request_id, al.request_id) AS chain_id,
15580
+ ${this.chainIdSql} AS chain_id,
15451
15581
  al.timestamp + al.duration AS end_ts,
15452
15582
  ROW_NUMBER() OVER (
15453
- PARTITION BY COALESCE(al.parent_request_id, al.request_id)
15454
- ORDER BY
15455
- CASE WHEN al.attempt_number IS NULL THEN 0 ELSE 1 END,
15456
- al.attempt_number ASC,
15457
- al.timestamp ASC,
15458
- al.id ASC
15583
+ PARTITION BY ${this.chainIdSql}
15584
+ ORDER BY ${this.representativeOrderSql}
15459
15585
  ) AS rep_rank,
15460
15586
  ROW_NUMBER() OVER (
15461
- PARTITION BY COALESCE(al.parent_request_id, al.request_id)
15462
- ORDER BY
15463
- CASE WHEN al.request_type = 'final' THEN 0 ELSE 1 END,
15464
- CASE WHEN al.attempt_number IS NULL THEN -1 ELSE al.attempt_number END DESC,
15465
- al.timestamp DESC,
15466
- al.id DESC
15587
+ PARTITION BY ${this.chainIdSql}
15588
+ ORDER BY ${this.statusOrderSql}
15467
15589
  ) AS status_rank
15468
15590
  FROM access_logs al
15469
- JOIN filtered_chain_ids f ON f.chain_id = COALESCE(al.parent_request_id, al.request_id)
15591
+ JOIN filtered_chain_ids f ON f.chain_id = ${this.chainIdSql}
15592
+ ${params.recordKind === undefined ? `WHERE ${this.clientRequestSql("al")}` : ""}
15470
15593
  ),
15471
15594
  agg AS (
15472
15595
  SELECT
15473
15596
  chain_id,
15474
15597
  MIN(timestamp) AS chain_start_ts,
15475
15598
  MAX(end_ts) AS chain_end_ts,
15476
- COUNT(*) AS chain_attempts,
15599
+ COUNT(CASE WHEN observed_record_kind IS NULL OR observed_record_kind = 'attempt' THEN 1 END) AS chain_attempts,
15477
15600
  MAX(CASE WHEN is_failover_attempt = 1 THEN 1 ELSE 0 END) AS has_retry,
15478
- MAX(CASE WHEN status_rank = 1 THEN status END) AS chain_status,
15601
+ MAX(CASE WHEN status_rank = 1 THEN observed_http_status END) AS chain_status,
15602
+ MAX(CASE WHEN status_rank = 1 THEN CASE WHEN accepted_disconnect THEN 1 WHEN observed_record_kind IS NULL THEN status < 400 ELSE success END END) AS chain_success,
15479
15603
  MAX(CASE WHEN status_rank = 1 THEN observed_transport_outcome END) AS final_transport_outcome,
15480
15604
  MAX(CASE WHEN status_rank = 1 THEN observed_transport_code END) AS final_transport_code,
15481
15605
  (MAX(end_ts) - MIN(timestamp)) AS chain_duration_ms
15482
15606
  FROM chain_rows
15483
15607
  GROUP BY chain_id
15484
15608
  )
15485
- SELECT COUNT(*) AS total FROM agg ${chainWhereClause}
15486
15609
  `;
15487
15610
  const countParams = [...rowWhereParams, ...chainWhereParams];
15488
- const countResult = this.db.query(countQuery).get(...countParams);
15611
+ const countResult = this.db.query(`${chainCtes} SELECT COUNT(*) AS total FROM agg ${chainWhereClause}`).get(...countParams);
15489
15612
  const total = countResult.total;
15490
15613
  const offset = Math.max(0, (page - 1) * limit);
15614
+ const protocolSummary = this.recordKindColumn === "record_kind" ? {
15615
+ columns: `app.protocol AS app_protocol, app.operation AS app_operation, app.operation_id AS app_operation_id,
15616
+ app.protocol_outcome AS app_outcome, app.protocol_code AS app_code, app.observation_outcome AS app_observation,`,
15617
+ join: `LEFT JOIN chain_rows app ON app.id = (
15618
+ SELECT id FROM chain_rows WHERE chain_id = agg.chain_id AND observed_record_kind = 'operation' ORDER BY id LIMIT 1
15619
+ )`
15620
+ } : { columns: "", join: "" };
15491
15621
  const dataQuery = `
15492
- WITH filtered_chain_ids AS (
15493
- SELECT DISTINCT COALESCE(parent_request_id, request_id) AS chain_id
15494
- FROM access_logs
15495
- ${rowWhereClause}
15496
- ),
15497
- chain_rows AS (
15498
- SELECT
15499
- al.*,
15500
- ${this.transportColumn} AS observed_transport_outcome,
15501
- ${this.transportCodeColumn} AS observed_transport_code,
15502
- COALESCE(al.parent_request_id, al.request_id) AS chain_id,
15503
- al.timestamp + al.duration AS end_ts,
15504
- ROW_NUMBER() OVER (
15505
- PARTITION BY COALESCE(al.parent_request_id, al.request_id)
15506
- ORDER BY
15507
- CASE WHEN al.attempt_number IS NULL THEN 0 ELSE 1 END,
15508
- al.attempt_number ASC,
15509
- al.timestamp ASC,
15510
- al.id ASC
15511
- ) AS rep_rank,
15512
- ROW_NUMBER() OVER (
15513
- PARTITION BY COALESCE(al.parent_request_id, al.request_id)
15514
- ORDER BY
15515
- CASE WHEN al.request_type = 'final' THEN 0 ELSE 1 END,
15516
- CASE WHEN al.attempt_number IS NULL THEN -1 ELSE al.attempt_number END DESC,
15517
- al.timestamp DESC,
15518
- al.id DESC
15519
- ) AS status_rank
15520
- FROM access_logs al
15521
- JOIN filtered_chain_ids f ON f.chain_id = COALESCE(al.parent_request_id, al.request_id)
15522
- ),
15523
- agg AS (
15524
- SELECT
15525
- chain_id,
15526
- MIN(timestamp) AS chain_start_ts,
15527
- MAX(end_ts) AS chain_end_ts,
15528
- COUNT(*) AS chain_attempts,
15529
- MAX(CASE WHEN is_failover_attempt = 1 THEN 1 ELSE 0 END) AS has_retry,
15530
- MAX(CASE WHEN status_rank = 1 THEN status END) AS chain_status,
15531
- MAX(CASE WHEN status_rank = 1 THEN observed_transport_outcome END) AS final_transport_outcome,
15532
- MAX(CASE WHEN status_rank = 1 THEN observed_transport_code END) AS final_transport_code,
15533
- (MAX(end_ts) - MIN(timestamp)) AS chain_duration_ms
15534
- FROM chain_rows
15535
- GROUP BY chain_id
15536
- )
15622
+ ${chainCtes}
15537
15623
  SELECT
15538
15624
  rep.*,
15625
+ ${protocolSummary.columns}
15539
15626
  agg.chain_start_ts,
15540
15627
  agg.chain_end_ts,
15541
15628
  agg.chain_attempts,
@@ -15543,9 +15630,20 @@ class LogQueryService {
15543
15630
  agg.chain_status,
15544
15631
  agg.final_transport_outcome,
15545
15632
  agg.final_transport_code,
15546
- agg.chain_duration_ms
15633
+ agg.chain_duration_ms,
15634
+ CASE WHEN rep.observed_record_kind IN ('access', 'operation') AND rep.route_path IS NULL THEN (
15635
+ SELECT route_path FROM chain_rows
15636
+ WHERE chain_id = agg.chain_id AND route_path IS NOT NULL
15637
+ ORDER BY rep_rank LIMIT 1
15638
+ ) END AS inherited_route_path,
15639
+ CASE WHEN rep.observed_record_kind IN ('access', 'operation') AND rep.upstream IS NULL THEN (
15640
+ SELECT upstream FROM chain_rows
15641
+ WHERE chain_id = agg.chain_id AND upstream IS NOT NULL
15642
+ ORDER BY status_rank LIMIT 1
15643
+ ) END AS inherited_upstream
15547
15644
  FROM agg
15548
15645
  JOIN chain_rows rep ON rep.chain_id = agg.chain_id AND rep.rep_rank = 1
15646
+ ${protocolSummary.join}
15549
15647
  ${chainWhereClause}
15550
15648
  ORDER BY ${sortColumn} ${sortDirection}
15551
15649
  LIMIT ? OFFSET ?
@@ -15554,6 +15652,16 @@ class LogQueryService {
15554
15652
  const rows = this.db.query(dataQuery).all(...dataParams);
15555
15653
  const data = rows.map((row) => ({
15556
15654
  ...this.mapRowToLogEntry(row),
15655
+ routePath: row.route_path ?? row.inherited_route_path ?? undefined,
15656
+ upstream: row.upstream ?? row.inherited_upstream ?? undefined,
15657
+ ...row.app_operation_id ? {
15658
+ operationId: row.app_operation_id,
15659
+ protocol: row.app_protocol,
15660
+ operation: row.app_operation,
15661
+ protocolOutcome: row.app_outcome ?? undefined,
15662
+ protocolCode: row.app_code ?? undefined,
15663
+ observationOutcome: row.app_observation ?? undefined
15664
+ } : {},
15557
15665
  chainId: row.chain_id,
15558
15666
  chainAttempts: row.chain_attempts,
15559
15667
  chainDurationMs: row.chain_duration_ms,
@@ -15580,11 +15688,14 @@ class LogQueryService {
15580
15688
  MIN(timestamp) AS first_ts,
15581
15689
  COUNT(*) AS count
15582
15690
  FROM access_logs
15583
- WHERE parent_request_id = ? OR request_id = ?
15691
+ WHERE ${this.chainIdSql} = ?
15692
+ AND (${this.recordKindColumn} IS NULL OR ${this.recordKindColumn} = 'attempt')
15693
+ AND ${this.clientRequestSql()}
15584
15694
  GROUP BY target
15695
+ HAVING target IS NOT NULL
15585
15696
  ORDER BY first_attempt, first_ts
15586
15697
  `;
15587
- const rows = this.db.query(query).all(chainId, chainId);
15698
+ const rows = this.db.query(query).all(chainId);
15588
15699
  return rows.map((row) => ({
15589
15700
  target: row.target,
15590
15701
  firstAttempt: row.first_attempt,
@@ -15594,59 +15705,61 @@ class LogQueryService {
15594
15705
  }
15595
15706
  async getChainDetail(chainId) {
15596
15707
  const query = `
15597
- SELECT * FROM access_logs
15598
- WHERE parent_request_id = ? OR request_id = ?
15599
- ORDER BY
15600
- CASE WHEN attempt_number IS NULL THEN 0 ELSE 1 END,
15601
- attempt_number ASC,
15602
- timestamp ASC,
15603
- id ASC
15708
+ SELECT *, ${this.acceptedDisconnectSql()} AS accepted_disconnect,
15709
+ ROW_NUMBER() OVER (ORDER BY ${this.statusOrderSql}) AS status_rank
15710
+ FROM access_logs
15711
+ WHERE ${this.chainIdSql} = ? AND ${this.clientRequestSql()}
15712
+ ORDER BY ${this.representativeOrderSql}
15604
15713
  `;
15605
- const rows = this.db.query(query).all(chainId, chainId);
15714
+ const rows = this.db.query(query).all(chainId);
15606
15715
  if (rows.length === 0) {
15607
15716
  return null;
15608
15717
  }
15609
- const attempts = rows.map((row) => this.mapRowToLogEntry(row));
15610
- const chainStartTs = Math.min(...attempts.map((a) => a.timestamp));
15611
- const chainEndTs = Math.max(...attempts.map((a) => a.timestamp + a.duration));
15718
+ const records = rows.map((row) => this.mapRowToLogEntry(row));
15719
+ const attempts = records.filter((row) => row.recordKind === undefined || row.recordKind === "attempt");
15720
+ const chainStartTs = Math.min(...records.map((a) => a.timestamp));
15721
+ const chainEndTs = Math.max(...records.map((a) => a.timestamp + a.duration));
15612
15722
  const chainAttempts = attempts.length;
15613
15723
  const hasRetry = attempts.some((a) => a.isFailoverAttempt);
15614
- const finalRows = attempts.filter((a) => a.requestType === "final");
15615
- let chainStatus;
15616
- let finalRow;
15617
- if (finalRows.length > 0) {
15618
- const finalSorted = finalRows.sort((a, b) => {
15619
- const aNum = a.attemptNumber ?? -1;
15620
- const bNum = b.attemptNumber ?? -1;
15621
- if (bNum !== aNum)
15622
- return bNum - aNum;
15623
- if (b.timestamp !== a.timestamp)
15624
- return b.timestamp - a.timestamp;
15625
- return b.id - a.id;
15626
- });
15627
- finalRow = finalSorted[0];
15628
- chainStatus = finalRow.status;
15629
- } else {
15630
- const sorted = attempts.sort((a, b) => {
15631
- const aNum = a.attemptNumber ?? -1;
15632
- const bNum = b.attemptNumber ?? -1;
15633
- if (bNum !== aNum)
15634
- return bNum - aNum;
15635
- if (b.timestamp !== a.timestamp)
15636
- return b.timestamp - a.timestamp;
15637
- return b.id - a.id;
15638
- });
15639
- finalRow = sorted[0];
15640
- chainStatus = finalRow.status;
15641
- }
15642
- const repRow = attempts[0];
15724
+ const finalRow = records[rows.findIndex((row) => row.status_rank === 1)];
15725
+ const repRow = records[0];
15726
+ const routePath = repRow.recordKind === "access" || repRow.recordKind === "operation" ? repRow.routePath ?? records.find((a) => a.routePath !== undefined)?.routePath : repRow.routePath;
15643
15727
  const upstreamsData = await this.getChainUpstreams(chainId);
15728
+ const operation = records.find((row) => row.recordKind === "operation");
15729
+ const finalAttempt = attempts.findLast((row) => row.requestType === "final") ?? attempts.at(-1);
15644
15730
  const chain = {
15645
15731
  ...repRow,
15732
+ status: finalRow.status,
15733
+ duration: chainEndTs - chainStartTs,
15734
+ transportOutcome: finalRow.transportOutcome,
15735
+ transportCode: finalRow.transportCode,
15736
+ success: finalRow.success,
15737
+ routePath,
15738
+ upstream: repRow.upstream ?? upstreamsData[0]?.target,
15739
+ transformer: repRow.transformer ?? finalAttempt?.transformer,
15740
+ transformedPath: repRow.transformedPath ?? finalAttempt?.transformedPath,
15741
+ processingSteps: repRow.processingSteps ?? operation?.processingSteps ?? finalAttempt?.processingSteps,
15742
+ errorMessage: repRow.errorMessage ?? operation?.errorMessage ?? finalAttempt?.errorMessage,
15743
+ originalReqBodyId: repRow.originalReqBodyId ?? operation?.originalReqBodyId ?? finalAttempt?.originalReqBodyId,
15744
+ originalReqHeaderId: repRow.originalReqHeaderId ?? operation?.originalReqHeaderId ?? finalAttempt?.originalReqHeaderId,
15745
+ reqBodyId: repRow.reqBodyId ?? finalAttempt?.reqBodyId,
15746
+ reqHeaderId: repRow.reqHeaderId ?? finalAttempt?.reqHeaderId,
15747
+ respBodyId: repRow.respBodyId ?? operation?.respBodyId ?? finalAttempt?.respBodyId,
15748
+ respHeaderId: repRow.respHeaderId ?? operation?.respHeaderId ?? finalAttempt?.respHeaderId,
15749
+ authLevel: repRow.authLevel ?? finalAttempt?.authLevel,
15750
+ authSuccess: repRow.authLevel ? repRow.authSuccess : finalAttempt?.authSuccess ?? repRow.authSuccess,
15751
+ ...operation ? {
15752
+ operationId: operation.operationId,
15753
+ protocol: operation.protocol,
15754
+ operation: operation.operation,
15755
+ protocolOutcome: operation.protocolOutcome,
15756
+ protocolCode: operation.protocolCode,
15757
+ observationOutcome: operation.observationOutcome
15758
+ } : {},
15646
15759
  chainId,
15647
15760
  chainAttempts,
15648
15761
  chainDurationMs: chainEndTs - chainStartTs,
15649
- chainStatus,
15762
+ chainStatus: finalRow.status,
15650
15763
  chainTransportOutcome: finalRow.transportOutcome,
15651
15764
  chainTransportCode: finalRow.transportCode,
15652
15765
  chainStartTs,
@@ -15660,17 +15773,10 @@ class LogQueryService {
15660
15773
  };
15661
15774
  }
15662
15775
  async* streamLogs(pollInterval = 1000) {
15663
- let lastTimestamp = Date.now();
15776
+ let lastId = this.getLatestLogId();
15664
15777
  while (true) {
15665
- const query = `
15666
- SELECT * FROM access_logs
15667
- WHERE timestamp > ?
15668
- ORDER BY timestamp ASC
15669
- `;
15670
- const rows = this.db.query(query).all(lastTimestamp);
15671
- for (const row of rows) {
15672
- const entry = this.mapRowToLogEntry(row);
15673
- lastTimestamp = entry.timestamp;
15778
+ for (const entry of await this.querySince(lastId)) {
15779
+ lastId = entry.id;
15674
15780
  yield entry;
15675
15781
  }
15676
15782
  await new Promise((resolve) => setTimeout(resolve, pollInterval));
@@ -15705,6 +15811,13 @@ class LogQueryService {
15705
15811
  "transportCode",
15706
15812
  "protocolOutcome",
15707
15813
  "protocolCode",
15814
+ "recordKind",
15815
+ "accessId",
15816
+ "operationId",
15817
+ "protocol",
15818
+ "operation",
15819
+ "closeCode",
15820
+ "observationOutcome",
15708
15821
  ...params.groupBy === "chain" ? ["chainId", "chainStatus", "chainDurationMs", "chainTransportOutcome", "chainTransportCode"] : []
15709
15822
  ];
15710
15823
  const csvRows = [
@@ -15732,6 +15845,10 @@ class LogQueryService {
15732
15845
  entry.transportCode || "",
15733
15846
  entry.protocolOutcome || "",
15734
15847
  entry.protocolCode || "",
15848
+ entry.recordKind ?? "",
15849
+ ...[entry.accessId, entry.operationId, entry.protocol, entry.operation].map((value) => value === undefined ? "" : /[",\r\n]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value),
15850
+ entry.closeCode ?? "",
15851
+ entry.observationOutcome ?? "",
15735
15852
  ...chain ? [chain.chainId, chain.chainStatus, chain.chainDurationMs, chain.chainTransportOutcome, chain.chainTransportCode || ""] : []
15736
15853
  ].join(",");
15737
15854
  })
@@ -15750,7 +15867,7 @@ class LogQueryService {
15750
15867
  SUM(CASE WHEN chain_outcome = 'success' THEN 1 ELSE 0 END) AS success_requests,
15751
15868
  SUM(CASE WHEN chain_outcome = 'failed' THEN 1 ELSE 0 END) AS failed_requests,
15752
15869
  AVG(chain_duration_ms) AS avg_response_time,
15753
- ${countSql("chain_status", "final_transport_outcome")}
15870
+ ${countSql("chain_status", "final_transport_outcome", "accepted_disconnect", "websocket_operation")}
15754
15871
  FROM classified_chains
15755
15872
  ${startTime !== undefined || endTime !== undefined ? `WHERE ${[
15756
15873
  startTime !== undefined ? "chain_start_ts >= ?" : "",
@@ -15840,7 +15957,7 @@ class LogQueryService {
15840
15957
  SUM(CASE WHEN chain_outcome = 'success' THEN 1 ELSE 0 END) AS success_requests,
15841
15958
  SUM(CASE WHEN chain_outcome = 'failed' THEN 1 ELSE 0 END) AS failed_requests,
15842
15959
  AVG(chain_duration_ms) AS avg_response_time,
15843
- ${countSql("chain_status", "final_transport_outcome")}
15960
+ ${countSql("chain_status", "final_transport_outcome", "accepted_disconnect", "websocket_operation")}
15844
15961
  FROM classified_chains
15845
15962
  WHERE chain_start_ts >= ? AND chain_start_ts < ?
15846
15963
  GROUP BY bucket
@@ -15883,6 +16000,8 @@ class LogQueryService {
15883
16000
  SELECT upstream, status, ${this.transportColumn} AS observed_transport_outcome, ${outcomeSql("status", "success", "protocol_outcome")} AS outcome
15884
16001
  FROM access_logs
15885
16002
  WHERE timestamp >= ? AND timestamp < ? AND upstream IS NOT NULL
16003
+ AND (${this.recordKindColumn} IS NULL OR ${this.recordKindColumn} = 'attempt')
16004
+ AND ${this.clientRequestSql()}
15886
16005
  )
15887
16006
  SELECT upstream, COUNT(*) AS total_requests,
15888
16007
  SUM(outcome = 'success') AS success_requests,
@@ -15957,15 +16076,23 @@ class LogQueryService {
15957
16076
  return result;
15958
16077
  }
15959
16078
  mapRowToLogEntry(row) {
16079
+ const missingUpgrade = row.record_kind === "operation" && row.transport_type === "websocket" && row.status === 0;
15960
16080
  return {
15961
16081
  id: row.id,
15962
16082
  requestId: row.request_id,
16083
+ recordKind: row.record_kind ?? undefined,
16084
+ accessId: row.access_id ?? undefined,
16085
+ operationId: row.operation_id ?? undefined,
16086
+ protocol: row.protocol ?? undefined,
16087
+ operation: row.operation ?? undefined,
16088
+ closeCode: row.close_code ?? undefined,
16089
+ observationOutcome: row.observation_outcome ?? undefined,
15963
16090
  timestamp: row.timestamp,
15964
- method: row.method,
16091
+ method: missingUpgrade ? "GET" : row.method,
15965
16092
  transportType: row.transport_type,
15966
16093
  path: row.path,
15967
16094
  query: row.query || undefined,
15968
- status: row.status,
16095
+ status: missingUpgrade ? 101 : row.status,
15969
16096
  duration: row.duration,
15970
16097
  routePath: row.route_path || undefined,
15971
16098
  upstream: row.upstream || undefined,
@@ -15974,8 +16101,8 @@ class LogQueryService {
15974
16101
  authSuccess: row.auth_success === 1,
15975
16102
  authLevel: row.auth_level || undefined,
15976
16103
  errorMessage: row.error_message || undefined,
15977
- success: row.success === 1,
15978
- transportOutcome: TRANSPORT_OUTCOMES.includes(row.transport_outcome) ? row.transport_outcome : "unknown",
16104
+ success: row.accepted_disconnect === 1 || row.success === 1,
16105
+ transportOutcome: row.accepted_disconnect === 1 ? "completed" : TRANSPORT_OUTCOMES.includes(row.transport_outcome) ? row.transport_outcome : "unknown",
15979
16106
  transportCode: row.transport_code ?? undefined,
15980
16107
  protocolOutcome: row.protocol_outcome ?? undefined,
15981
16108
  protocolCode: row.protocol_code ?? undefined,
@@ -16014,6 +16141,9 @@ function getLogFilters(url) {
16014
16141
  const statuses = values.map((value) => /^\d{3}$/.test(value) ? Number(value) : NaN);
16015
16142
  const transport = getSingleParam(url, "transportOutcome");
16016
16143
  const transportType = getSingleParam(url, "transportType");
16144
+ const recordKind = getSingleParam(url, "recordKind");
16145
+ const accessId = getSingleParam(url, "accessId");
16146
+ const operationId = getSingleParam(url, "operationId");
16017
16147
  if (transportType !== undefined && transportType !== "http" && transportType !== "websocket") {
16018
16148
  return Response.json({ error: "transportType must be http or websocket" }, { status: 400 });
16019
16149
  }
@@ -16023,10 +16153,19 @@ function getLogFilters(url) {
16023
16153
  if (transport === null || transport !== undefined && !TRANSPORT_OUTCOMES.includes(transport)) {
16024
16154
  return Response.json({ error: "transportOutcome must be one of pending, completed, failed, cancelled, unknown" }, { status: 400 });
16025
16155
  }
16156
+ if (recordKind !== undefined && recordKind !== "access" && recordKind !== "operation" && recordKind !== "attempt") {
16157
+ return Response.json({ error: "recordKind must be access, operation or attempt" }, { status: 400 });
16158
+ }
16159
+ if (accessId === null || operationId === null) {
16160
+ return Response.json({ error: "accessId and operationId must be nonempty single values" }, { status: 400 });
16161
+ }
16026
16162
  return {
16027
16163
  status: statuses.length === 0 ? undefined : statuses.length === 1 ? statuses[0] : [...new Set(statuses)],
16028
16164
  transportType,
16029
- transportOutcome: transport
16165
+ transportOutcome: transport,
16166
+ recordKind,
16167
+ accessId,
16168
+ operationId
16030
16169
  };
16031
16170
  }
16032
16171
  function getPollInterval(url) {
@@ -16132,6 +16271,12 @@ class LogsHandler {
16132
16271
  }
16133
16272
  async getBodyById(bodyId) {
16134
16273
  try {
16274
+ if (bodyId.endsWith(".stream") && this.dependencies.bodyStorage.openStream) {
16275
+ const file = await this.dependencies.bodyStorage.openStream(bodyId);
16276
+ if (file)
16277
+ return new Response(file, { headers: JSON_HEADERS });
16278
+ return Response.json({ error: "Body not found" }, { status: 404 });
16279
+ }
16135
16280
  const body = await this.dependencies.bodyStorage.load(bodyId);
16136
16281
  if (body === null || body === undefined) {
16137
16282
  return new Response(JSON.stringify({ error: "Body not found" }), { status: 404, headers: { "Content-Type": "application/json" } });
@@ -16174,8 +16319,6 @@ class LogsHandler {
16174
16319
  const stream = new ReadableStream({
16175
16320
  async start(controller) {
16176
16321
  const encoder = new TextEncoder;
16177
- let lastTimestamp = Date.now();
16178
- let lastId = 0;
16179
16322
  let lastHeartbeat = Date.now();
16180
16323
  let running = true;
16181
16324
  let controllerClosed = false;
@@ -16246,15 +16389,15 @@ class LogsHandler {
16246
16389
  lastHeartbeat = Date.now();
16247
16390
  };
16248
16391
  try {
16392
+ let lastId = logQueryService.getLatestLogId();
16249
16393
  while (running) {
16250
- const rows = await logQueryService.querySince(lastTimestamp, lastId);
16394
+ const rows = await logQueryService.querySince(lastId);
16251
16395
  for (const entry of rows) {
16252
16396
  if (!running)
16253
16397
  break;
16254
16398
  await waitForCapacity();
16255
16399
  if (!running)
16256
16400
  break;
16257
- lastTimestamp = entry.timestamp;
16258
16401
  lastId = entry.id;
16259
16402
  if (!safeEnqueue(encoder.encode(`data: ${JSON.stringify(entry)}
16260
16403
 
@@ -16392,9 +16535,22 @@ class LogsHandler {
16392
16535
  }
16393
16536
 
16394
16537
  // src/logger/body-storage.ts
16538
+ import { randomUUID } from "crypto";
16395
16539
  import fs from "fs";
16396
16540
  import path from "path";
16397
16541
 
16542
+ // ../types/src/daemon-control.ts
16543
+ var DAEMON_METADATA_MAX_BYTES = 4 * 1024;
16544
+
16545
+ // ../types/src/types.ts
16546
+ var DEFAULT_BODY_LOG_MAX_BYTES = 64 * 1024;
16547
+ var DEFAULT_WEBSOCKET_MAX_MESSAGE_BYTES = 16 * 1024 * 1024;
16548
+ // ../types/src/publication-policy.ts
16549
+ var DEFAULT_PUBLICATION_POLICY = Object.freeze({
16550
+ drain_start_timeout_ms: 5000,
16551
+ drain_timeout_ms: 300000,
16552
+ worker_exit_timeout_ms: 1e4
16553
+ });
16398
16554
  // src/logger.ts
16399
16555
  var import_winston = __toESM(require_winston());
16400
16556
  var import_winston_daily_rotate_file = __toESM(require_winston_daily_rotate_file());
@@ -16480,7 +16636,7 @@ installPluginLogSink(logger2);
16480
16636
  var BODY_TYPES = ["original-request", "request", "response"];
16481
16637
  var DEFAULT_CONFIG = {
16482
16638
  enabled: true,
16483
- maxSize: 5120,
16639
+ maxSize: DEFAULT_BODY_LOG_MAX_BYTES,
16484
16640
  retentionDays: 1
16485
16641
  };
16486
16642
 
@@ -16516,6 +16672,90 @@ class BodyStorageManager {
16516
16672
  return null;
16517
16673
  }
16518
16674
  }
16675
+ async saveStream(requestId, chunks, type, maxBytes, completed, signal, format) {
16676
+ if (!this.config.enabled)
16677
+ return null;
16678
+ const bodyId = `${this.getDateString()}/${type}-${requestId}.stream`;
16679
+ const filePath = this.getBodyFilePath(bodyId);
16680
+ if (!filePath)
16681
+ throw new Error("body_log_storage_failed");
16682
+ const temporary = `${filePath}.${randomUUID()}.part`;
16683
+ let file;
16684
+ let created = false;
16685
+ let renamed = false;
16686
+ let committed = false;
16687
+ let bytes = 0;
16688
+ let buffered = "";
16689
+ const write = async (chunk) => {
16690
+ try {
16691
+ await file.writeFile(chunk);
16692
+ } catch {
16693
+ throw new Error("body_log_storage_failed");
16694
+ }
16695
+ };
16696
+ try {
16697
+ for await (const chunk of chunks) {
16698
+ signal.throwIfAborted();
16699
+ bytes += Buffer.byteLength(chunk);
16700
+ if (bytes > maxBytes)
16701
+ throw new BodyProcessingError(413, "body_log_too_large");
16702
+ if (!file) {
16703
+ if (!this.ensureSafeDirectory(path.dirname(filePath)) || !this.isSafeRegularFile(filePath)) {
16704
+ throw new Error("body_log_storage_failed");
16705
+ }
16706
+ try {
16707
+ file = await fs.promises.open(temporary, "wx", 384);
16708
+ } catch {
16709
+ throw new Error("body_log_storage_failed");
16710
+ }
16711
+ created = true;
16712
+ buffered = `{"bodyId":${JSON.stringify(bodyId)},"content":${format === "text" ? '"' : ""}`;
16713
+ }
16714
+ buffered += format === "text" ? JSON.stringify(chunk).slice(1, -1) : chunk;
16715
+ if (buffered.length >= 64 * 1024) {
16716
+ await write(buffered);
16717
+ buffered = "";
16718
+ }
16719
+ }
16720
+ if (!file)
16721
+ return null;
16722
+ await completed;
16723
+ signal.throwIfAborted();
16724
+ await write(buffered + (format === "text" ? '"}' : "}"));
16725
+ try {
16726
+ await file.close();
16727
+ file = undefined;
16728
+ signal.throwIfAborted();
16729
+ await fs.promises.rename(temporary, filePath);
16730
+ renamed = true;
16731
+ signal.throwIfAborted();
16732
+ committed = true;
16733
+ return bodyId;
16734
+ } catch (error) {
16735
+ if (signal.aborted)
16736
+ throw error;
16737
+ throw new Error("body_log_storage_failed");
16738
+ }
16739
+ } finally {
16740
+ if (file)
16741
+ await file.close().catch(() => {
16742
+ return;
16743
+ });
16744
+ if (created && !committed)
16745
+ await fs.promises.rm(renamed ? filePath : temporary, { force: true }).catch(() => {
16746
+ return;
16747
+ });
16748
+ }
16749
+ }
16750
+ async openStream(bodyId) {
16751
+ if (!bodyId.endsWith(".stream"))
16752
+ return null;
16753
+ const filePath = this.getBodyFilePath(bodyId);
16754
+ if (!filePath || !await this.isSafePath(filePath))
16755
+ return null;
16756
+ const file = Bun.file(filePath);
16757
+ return await file.exists() ? file : null;
16758
+ }
16519
16759
  async load(bodyId) {
16520
16760
  try {
16521
16761
  const filePath = this.getBodyFilePath(bodyId);
@@ -16525,6 +16765,8 @@ class BodyStorageManager {
16525
16765
  return null;
16526
16766
  }
16527
16767
  const content = await fs.promises.readFile(filePath, "utf-8");
16768
+ if (bodyId.endsWith(".stream"))
16769
+ return JSON.parse(content).content;
16528
16770
  try {
16529
16771
  return JSON.parse(content);
16530
16772
  } catch {
@@ -18106,7 +18348,503 @@ class MigrationManager {
18106
18348
  }
18107
18349
 
18108
18350
  // src/migrations/index.ts
18109
- var migrations = [ACCESS_BASELINE, LLM_TPS_SAMPLES, LLM_TPS_MODEL, LLM_TPS_UPSTREAM_HOST, ACCESS_LOG_TRANSPORT_TYPE];
18351
+ var migrations = [ACCESS_BASELINE, LLM_TPS_SAMPLES, LLM_TPS_MODEL, LLM_TPS_UPSTREAM_HOST, ACCESS_LOG_TRANSPORT_TYPE, ACCESS_LOG_RECORD_IDENTITY];
18352
+
18353
+ // src/logger/access-log-writer.ts
18354
+ import { Database as Database5 } from "bun:sqlite";
18355
+ import path3 from "path";
18356
+ import fs3 from "fs";
18357
+ class AccessLogWriter {
18358
+ maxQueuedEntries;
18359
+ db;
18360
+ writeQueue = [];
18361
+ pendingBodyIdUpdates = new Map;
18362
+ pendingProtocolOutcomeUpdates = new Map;
18363
+ pendingTransportUpdates = new Map;
18364
+ static MAX_PENDING_UPDATES = 4096;
18365
+ inFlightFlush = null;
18366
+ flushInterval = null;
18367
+ droppedEntries = 0;
18368
+ constructor(databaseOrPath, maxQueuedEntries = Infinity) {
18369
+ this.maxQueuedEntries = maxQueuedEntries;
18370
+ let database;
18371
+ if (typeof databaseOrPath === "string") {
18372
+ const dir = path3.dirname(databaseOrPath);
18373
+ if (!fs3.existsSync(dir))
18374
+ fs3.mkdirSync(dir, { recursive: true });
18375
+ database = new Database5(databaseOrPath);
18376
+ } else {
18377
+ database = databaseOrPath;
18378
+ }
18379
+ try {
18380
+ initializeAccessDatabaseConnection(database);
18381
+ } catch (error) {
18382
+ database.close(true);
18383
+ throw error;
18384
+ }
18385
+ this.db = database;
18386
+ this.startFlushInterval();
18387
+ }
18388
+ write(entry) {
18389
+ if (this.writeQueue.length >= this.maxQueuedEntries) {
18390
+ const existing = this.writeQueue.findLastIndex((row) => row.requestId === entry.requestId);
18391
+ if (existing >= 0 && entry.replacePendingTransport) {
18392
+ this.writeQueue[existing] = entry;
18393
+ return;
18394
+ }
18395
+ this.droppedEntries++;
18396
+ return;
18397
+ }
18398
+ const pendingBodyIds = this.pendingBodyIdUpdates.get(entry.requestId);
18399
+ if (pendingBodyIds) {
18400
+ Object.assign(entry, pendingBodyIds);
18401
+ }
18402
+ const pendingOutcome = this.pendingProtocolOutcomeUpdates.get(entry.requestId);
18403
+ if (pendingOutcome) {
18404
+ entry.protocolOutcome = pendingOutcome.outcome;
18405
+ entry.protocolCode = pendingOutcome.code;
18406
+ entry.success = pendingOutcome.success;
18407
+ entry.errorMessage = pendingOutcome.detailed ? pendingOutcome.errorMessage : entry.errorMessage ?? pendingOutcome.errorMessage;
18408
+ }
18409
+ this.applyPendingTransport(entry);
18410
+ this.writeQueue.push(entry);
18411
+ if (this.writeQueue.length >= 100) {
18412
+ this.flush().catch((err) => {
18413
+ console.error("Background flush failed:", err);
18414
+ });
18415
+ }
18416
+ }
18417
+ async flush() {
18418
+ while (true) {
18419
+ const inFlightFlush = this.inFlightFlush;
18420
+ if (inFlightFlush) {
18421
+ await inFlightFlush;
18422
+ continue;
18423
+ }
18424
+ if (this.writeQueue.length === 0) {
18425
+ this.flushPendingTransportUpdates();
18426
+ return;
18427
+ }
18428
+ const nextFlush = Promise.resolve().then(() => this.drainQueue());
18429
+ this.inFlightFlush = nextFlush;
18430
+ nextFlush.then(() => {
18431
+ if (this.inFlightFlush === nextFlush)
18432
+ this.inFlightFlush = null;
18433
+ }, () => {
18434
+ if (this.inFlightFlush === nextFlush)
18435
+ this.inFlightFlush = null;
18436
+ });
18437
+ await nextFlush;
18438
+ }
18439
+ }
18440
+ async drainQueue() {
18441
+ while (this.writeQueue.length > 0) {
18442
+ const batch = this.writeQueue.splice(0);
18443
+ await this.flushBatch(batch);
18444
+ }
18445
+ }
18446
+ async flushBatch(batch) {
18447
+ let transactionStarted = false;
18448
+ try {
18449
+ const insert = this.db.query(`
18450
+ INSERT INTO access_logs (
18451
+ request_id, timestamp, method, path, query,
18452
+ status, duration, route_path, upstream, transformer,
18453
+ processing_steps, auth_success, auth_level,
18454
+ error_message, req_body_id, resp_body_id, req_header_id, resp_header_id,
18455
+ original_req_header_id, original_req_body_id, transformed_path, success, created_at,
18456
+ is_failover_attempt, parent_request_id, attempt_number, attempt_upstream, request_type,
18457
+ protocol_outcome, protocol_code, transport_outcome, transport_code, transport_type,
18458
+ record_kind, access_id, operation_id, protocol, operation, close_code, observation_outcome
18459
+ ) VALUES (
18460
+ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
18461
+ ?, ?, ?, ?, ?, ?, ?
18462
+ )
18463
+ ON CONFLICT(request_id) DO UPDATE SET
18464
+ timestamp = excluded.timestamp,
18465
+ method = excluded.method,
18466
+ path = excluded.path,
18467
+ query = excluded.query,
18468
+ status = excluded.status,
18469
+ duration = excluded.duration,
18470
+ route_path = excluded.route_path,
18471
+ upstream = excluded.upstream,
18472
+ transformer = excluded.transformer,
18473
+ processing_steps = excluded.processing_steps,
18474
+ auth_success = excluded.auth_success,
18475
+ auth_level = excluded.auth_level,
18476
+ error_message = excluded.error_message,
18477
+ req_body_id = excluded.req_body_id,
18478
+ resp_body_id = excluded.resp_body_id,
18479
+ req_header_id = excluded.req_header_id,
18480
+ resp_header_id = excluded.resp_header_id,
18481
+ original_req_header_id = excluded.original_req_header_id,
18482
+ original_req_body_id = excluded.original_req_body_id,
18483
+ transformed_path = excluded.transformed_path,
18484
+ success = excluded.success,
18485
+ created_at = excluded.created_at,
18486
+ is_failover_attempt = excluded.is_failover_attempt,
18487
+ parent_request_id = excluded.parent_request_id,
18488
+ attempt_number = excluded.attempt_number,
18489
+ attempt_upstream = excluded.attempt_upstream,
18490
+ request_type = excluded.request_type,
18491
+ protocol_outcome = excluded.protocol_outcome,
18492
+ protocol_code = excluded.protocol_code,
18493
+ transport_outcome = excluded.transport_outcome,
18494
+ transport_code = excluded.transport_code,
18495
+ transport_type = excluded.transport_type,
18496
+ record_kind = excluded.record_kind,
18497
+ access_id = excluded.access_id,
18498
+ operation_id = excluded.operation_id,
18499
+ protocol = excluded.protocol,
18500
+ operation = excluded.operation,
18501
+ close_code = excluded.close_code,
18502
+ observation_outcome = excluded.observation_outcome
18503
+ WHERE ? = 1
18504
+ `);
18505
+ this.db.run("BEGIN TRANSACTION");
18506
+ transactionStarted = true;
18507
+ const appliedBodyUpdates = new Set;
18508
+ const appliedProtocolOutcomeUpdates = new Set;
18509
+ const appliedTransportUpdates = new Set;
18510
+ const duplicateRequestIds = [];
18511
+ for (const entry of batch) {
18512
+ const pendingBodyIds = this.pendingBodyIdUpdates.get(entry.requestId);
18513
+ if (pendingBodyIds) {
18514
+ Object.assign(entry, pendingBodyIds);
18515
+ }
18516
+ const pendingOutcome = this.pendingProtocolOutcomeUpdates.get(entry.requestId);
18517
+ if (pendingOutcome) {
18518
+ entry.protocolOutcome = pendingOutcome.outcome;
18519
+ entry.protocolCode = pendingOutcome.code;
18520
+ entry.success = pendingOutcome.success;
18521
+ entry.errorMessage = pendingOutcome.detailed ? pendingOutcome.errorMessage : entry.errorMessage ?? pendingOutcome.errorMessage;
18522
+ }
18523
+ const pendingTransport = this.pendingTransportUpdates.get(entry.requestId);
18524
+ this.applyPendingTransport(entry);
18525
+ this.db.run("SAVEPOINT access_log_entry");
18526
+ try {
18527
+ const result = insert.run(entry.requestId, entry.timestamp, entry.method, entry.path, entry.query || null, entry.status, entry.duration, entry.routePath || null, entry.upstream || null, entry.transformer || null, entry.processingSteps ? JSON.stringify(entry.processingSteps) : null, entry.authSuccess !== undefined ? entry.authSuccess ? 1 : 0 : 1, entry.authLevel || null, entry.errorMessage || null, entry.reqBodyId || null, entry.respBodyId || null, entry.reqHeaderId || null, entry.respHeaderId || null, entry.originalReqHeaderId || null, entry.originalReqBodyId || null, entry.transformedPath || null, entry.success !== undefined ? entry.success ? 1 : 0 : entry.status < 400 ? 1 : 0, Math.floor(entry.timestamp / 1000), entry.isFailoverAttempt ? 1 : 0, entry.parentRequestId || null, entry.attemptNumber || null, entry.attemptUpstream || null, entry.requestType || "final", entry.protocolOutcome || null, entry.protocolCode || null, entry.transportOutcome ?? null, entry.transportCode ?? null, entry.transportType ?? null, entry.recordKind ?? null, entry.accessId ?? null, entry.operationId ?? null, entry.protocol ?? null, entry.operation ?? null, entry.closeCode ?? null, entry.observationOutcome ?? null, entry.replacePendingTransport ? 1 : 0);
18528
+ this.db.run("RELEASE SAVEPOINT access_log_entry");
18529
+ if (result.changes === 0)
18530
+ duplicateRequestIds.push(entry.requestId);
18531
+ if (pendingBodyIds)
18532
+ appliedBodyUpdates.add(entry.requestId);
18533
+ if (pendingOutcome)
18534
+ appliedProtocolOutcomeUpdates.add(entry.requestId);
18535
+ if (pendingTransport && result.changes > 0)
18536
+ appliedTransportUpdates.add(entry.requestId);
18537
+ } catch (error) {
18538
+ this.db.run("ROLLBACK TO SAVEPOINT access_log_entry");
18539
+ this.db.run("RELEASE SAVEPOINT access_log_entry");
18540
+ if (!isDeterministicEntryError(error))
18541
+ throw error;
18542
+ console.error("Dropped invalid access log entry:", { requestId: entry.requestId, error });
18543
+ }
18544
+ }
18545
+ this.db.run("COMMIT");
18546
+ transactionStarted = false;
18547
+ for (const requestId of appliedBodyUpdates)
18548
+ this.pendingBodyIdUpdates.delete(requestId);
18549
+ for (const requestId of appliedProtocolOutcomeUpdates)
18550
+ this.pendingProtocolOutcomeUpdates.delete(requestId);
18551
+ for (const requestId of appliedTransportUpdates)
18552
+ this.pendingTransportUpdates.delete(requestId);
18553
+ if (duplicateRequestIds.length > 0) {
18554
+ console.warn("Skipped duplicate access log entries:", { requestIds: duplicateRequestIds });
18555
+ }
18556
+ } catch (error) {
18557
+ if (transactionStarted) {
18558
+ try {
18559
+ this.db.run("ROLLBACK");
18560
+ } catch (rollbackError) {}
18561
+ }
18562
+ console.error("Failed to flush access logs:", error);
18563
+ this.writeQueue.unshift(...batch);
18564
+ throw error;
18565
+ }
18566
+ }
18567
+ startFlushInterval() {
18568
+ this.flushInterval = setInterval(() => {
18569
+ if (this.droppedEntries) {
18570
+ console.error("SQLite access log queue lost entries:", this.droppedEntries);
18571
+ this.droppedEntries = 0;
18572
+ }
18573
+ this.flush().catch((error) => console.error("Background flush failed:", error));
18574
+ }, 5000);
18575
+ }
18576
+ async close() {
18577
+ if (this.flushInterval) {
18578
+ clearInterval(this.flushInterval);
18579
+ this.flushInterval = null;
18580
+ }
18581
+ try {
18582
+ await this.flush();
18583
+ } catch (error) {
18584
+ console.error("Failed to flush access logs during close:", error);
18585
+ } finally {
18586
+ this.pendingProtocolOutcomeUpdates.clear();
18587
+ this.pendingBodyIdUpdates.clear();
18588
+ this.pendingTransportUpdates.clear();
18589
+ this.db.close(true);
18590
+ }
18591
+ }
18592
+ getDatabase() {
18593
+ return this.db;
18594
+ }
18595
+ updateResponseBodyId(requestId, respBodyId) {
18596
+ this.updateBodyId(requestId, "response", respBodyId);
18597
+ }
18598
+ updateBodyId(requestId, type, bodyId) {
18599
+ if (!requestId || !bodyId)
18600
+ return;
18601
+ const fields = {
18602
+ request: ["reqBodyId", "req_body_id"],
18603
+ response: ["respBodyId", "resp_body_id"],
18604
+ "original-request": ["originalReqBodyId", "original_req_body_id"]
18605
+ };
18606
+ const [field, column] = fields[type];
18607
+ if (!this.pendingBodyIdUpdates.has(requestId) && this.pendingBodyIdUpdates.size >= AccessLogWriter.MAX_PENDING_UPDATES) {
18608
+ const oldest = this.pendingBodyIdUpdates.keys().next().value;
18609
+ if (oldest)
18610
+ this.pendingBodyIdUpdates.delete(oldest);
18611
+ }
18612
+ const updates = { ...this.pendingBodyIdUpdates.get(requestId), [field]: bodyId };
18613
+ this.pendingBodyIdUpdates.set(requestId, updates);
18614
+ for (const entry of this.writeQueue)
18615
+ if (entry.requestId === requestId)
18616
+ Object.assign(entry, updates);
18617
+ try {
18618
+ const result = this.db.query(`UPDATE access_logs SET ${column} = ? WHERE request_id = ?`).run(bodyId, requestId);
18619
+ if (result.changes > 0)
18620
+ this.pendingBodyIdUpdates.delete(requestId);
18621
+ } catch (error) {
18622
+ this.pendingBodyIdUpdates.delete(requestId);
18623
+ console.error("Failed to update captured body id:", { requestId, type, error });
18624
+ }
18625
+ }
18626
+ flushPendingTransportUpdates() {
18627
+ if (this.pendingTransportUpdates.size === 0)
18628
+ return;
18629
+ const update = this.db.query("UPDATE access_logs SET transport_outcome = ?, transport_code = ? WHERE request_id = ?");
18630
+ for (const [requestId, pending] of this.pendingTransportUpdates) {
18631
+ const result = update.run(pending.outcome, pending.code ?? null, requestId);
18632
+ if (result.changes > 0)
18633
+ this.pendingTransportUpdates.delete(requestId);
18634
+ }
18635
+ }
18636
+ applyPendingTransport(entry) {
18637
+ const pending = this.pendingTransportUpdates.get(entry.requestId);
18638
+ if (pending) {
18639
+ entry.transportOutcome = pending.outcome;
18640
+ entry.transportCode = pending.code;
18641
+ }
18642
+ }
18643
+ updateTransportOutcome(requestId, outcome, code) {
18644
+ if (!requestId)
18645
+ return;
18646
+ if (!this.pendingTransportUpdates.has(requestId) && this.pendingTransportUpdates.size >= AccessLogWriter.MAX_PENDING_UPDATES) {
18647
+ const oldest = this.pendingTransportUpdates.keys().next().value;
18648
+ if (oldest)
18649
+ this.pendingTransportUpdates.delete(oldest);
18650
+ }
18651
+ this.pendingTransportUpdates.set(requestId, { outcome, code });
18652
+ for (const entry of this.writeQueue)
18653
+ if (entry.requestId === requestId)
18654
+ this.applyPendingTransport(entry);
18655
+ }
18656
+ appendProcessingStep(requestId, step) {
18657
+ for (const entry of this.writeQueue) {
18658
+ if (entry.requestId !== requestId)
18659
+ continue;
18660
+ entry.processingSteps ??= [];
18661
+ if (!entry.processingSteps.includes(step))
18662
+ entry.processingSteps.push(step);
18663
+ }
18664
+ try {
18665
+ this.db.query("UPDATE access_logs SET processing_steps=json_insert(COALESCE(processing_steps,'[]'),'$[#]',json(?)) WHERE request_id=?").run(JSON.stringify(step), requestId);
18666
+ } catch (error) {
18667
+ console.error("Failed to append body logging diagnostic:", { requestId, error });
18668
+ }
18669
+ }
18670
+ updateProtocolOutcome(requestId, outcome, success, code, diagnosticMessage) {
18671
+ if (!requestId)
18672
+ return;
18673
+ if (!this.pendingProtocolOutcomeUpdates.has(requestId) && this.pendingProtocolOutcomeUpdates.size >= AccessLogWriter.MAX_PENDING_UPDATES) {
18674
+ const oldest = this.pendingProtocolOutcomeUpdates.keys().next().value;
18675
+ if (oldest)
18676
+ this.pendingProtocolOutcomeUpdates.delete(oldest);
18677
+ }
18678
+ const errorMessage = diagnosticMessage ?? (outcome === "failed" || outcome === "incomplete" ? `Response stream ${outcome}${code ? ` (${code})` : ""}` : undefined);
18679
+ const detailed = diagnosticMessage !== undefined;
18680
+ this.pendingProtocolOutcomeUpdates.set(requestId, { outcome, success, code, errorMessage, detailed });
18681
+ for (const entry of this.writeQueue) {
18682
+ if (entry.requestId === requestId) {
18683
+ entry.protocolOutcome = outcome;
18684
+ entry.protocolCode = code;
18685
+ entry.success = success;
18686
+ entry.errorMessage = detailed ? errorMessage : entry.errorMessage ?? errorMessage;
18687
+ }
18688
+ }
18689
+ try {
18690
+ const result = this.db.query("UPDATE access_logs SET protocol_outcome = ?, protocol_code = ?, success = ?, error_message = CASE WHEN ? THEN ? ELSE COALESCE(error_message, ?) END WHERE request_id = ?").run(outcome, code || null, success ? 1 : 0, detailed ? 1 : 0, errorMessage ?? null, errorMessage ?? null, requestId);
18691
+ if (result.changes > 0)
18692
+ this.pendingProtocolOutcomeUpdates.delete(requestId);
18693
+ } catch (error) {
18694
+ this.pendingProtocolOutcomeUpdates.delete(requestId);
18695
+ console.error("Failed to update protocol outcome for streamed log:", { requestId, outcome, error });
18696
+ }
18697
+ }
18698
+ }
18699
+ function isDeterministicEntryError(error) {
18700
+ const message = error instanceof Error ? error.message : String(error);
18701
+ return /constraint failed|datatype mismatch/i.test(message);
18702
+ }
18703
+ var defaultDatabasePath = process.env.BUNGEE_ACCESS_DB_PATH ?? path3.resolve(process.cwd(), "logs", "access.db");
18704
+
18705
+ // src/logger/file-log-writer.ts
18706
+ import fs4 from "fs";
18707
+ import path4 from "path";
18708
+
18709
+ class FileLogWriter {
18710
+ maxQueuedEntries;
18711
+ writeQueue = [];
18712
+ inFlightFlush = null;
18713
+ flushInterval = null;
18714
+ currentDate;
18715
+ currentStream = null;
18716
+ logsDir;
18717
+ droppedEntries = 0;
18718
+ constructor(logsDir = path4.resolve(process.cwd(), "logs"), maxQueuedEntries = Infinity) {
18719
+ this.maxQueuedEntries = maxQueuedEntries;
18720
+ this.logsDir = logsDir;
18721
+ this.currentDate = this.getDateString();
18722
+ this.ensureLogsDir();
18723
+ this.openLogFile();
18724
+ this.startFlushInterval();
18725
+ }
18726
+ async write(entry) {
18727
+ if (this.writeQueue.length >= this.maxQueuedEntries) {
18728
+ this.droppedEntries++;
18729
+ return;
18730
+ }
18731
+ this.writeQueue.push(entry);
18732
+ if (this.writeQueue.length >= 100) {
18733
+ await this.flush();
18734
+ }
18735
+ }
18736
+ async flush() {
18737
+ if (this.inFlightFlush)
18738
+ return this.inFlightFlush;
18739
+ if (this.writeQueue.length === 0)
18740
+ return;
18741
+ this.inFlightFlush = this.flushBatch(this.writeQueue.splice(0));
18742
+ try {
18743
+ await this.inFlightFlush;
18744
+ } finally {
18745
+ this.inFlightFlush = null;
18746
+ }
18747
+ }
18748
+ async flushBatch(batch) {
18749
+ try {
18750
+ const currentDate = this.getDateString();
18751
+ if (currentDate !== this.currentDate) {
18752
+ await this.rotateLogFile();
18753
+ }
18754
+ const lines = batch.map((entry) => JSON.stringify(entry)).join(`
18755
+ `) + `
18756
+ `;
18757
+ const stream = this.currentStream ?? this.openLogFile();
18758
+ await new Promise((resolve, reject) => {
18759
+ stream.write(lines, (err) => {
18760
+ if (err)
18761
+ reject(err);
18762
+ else
18763
+ resolve();
18764
+ });
18765
+ });
18766
+ } catch (error) {
18767
+ console.error("Failed to write file logs:", error);
18768
+ const pending = batch.concat(this.writeQueue);
18769
+ this.droppedEntries += Math.max(0, pending.length - this.maxQueuedEntries);
18770
+ this.writeQueue = pending.slice(0, this.maxQueuedEntries);
18771
+ }
18772
+ }
18773
+ startFlushInterval() {
18774
+ this.flushInterval = setInterval(() => {
18775
+ if (this.droppedEntries) {
18776
+ console.error("File access log queue lost entries:", this.droppedEntries);
18777
+ this.droppedEntries = 0;
18778
+ }
18779
+ this.flush().catch((error) => console.error("Background file log flush failed:", error));
18780
+ }, 5000);
18781
+ }
18782
+ async rotateLogFile() {
18783
+ if (this.currentStream) {
18784
+ await new Promise((resolve) => {
18785
+ this.currentStream.end(() => resolve());
18786
+ });
18787
+ this.currentStream = null;
18788
+ }
18789
+ this.currentDate = this.getDateString();
18790
+ this.openLogFile();
18791
+ }
18792
+ openLogFile() {
18793
+ const logFilePath = path4.join(this.logsDir, `access-${this.currentDate}.log`);
18794
+ const stream = fs4.createWriteStream(logFilePath, { flags: "a" });
18795
+ stream.once("error", () => {
18796
+ if (this.currentStream === stream)
18797
+ this.currentStream = null;
18798
+ console.error("File access log stream unavailable");
18799
+ });
18800
+ return this.currentStream = stream;
18801
+ }
18802
+ ensureLogsDir() {
18803
+ if (!fs4.existsSync(this.logsDir)) {
18804
+ fs4.mkdirSync(this.logsDir, { recursive: true });
18805
+ }
18806
+ }
18807
+ getDateString() {
18808
+ const now = new Date;
18809
+ return now.toISOString().split("T")[0];
18810
+ }
18811
+ async close() {
18812
+ if (this.flushInterval) {
18813
+ clearInterval(this.flushInterval);
18814
+ this.flushInterval = null;
18815
+ }
18816
+ await this.inFlightFlush;
18817
+ await this.flush();
18818
+ if (this.currentStream) {
18819
+ await new Promise((resolve) => {
18820
+ this.currentStream.end(() => resolve());
18821
+ });
18822
+ this.currentStream = null;
18823
+ }
18824
+ }
18825
+ async cleanup(retentionDays = 30) {
18826
+ const files = fs4.readdirSync(this.logsDir);
18827
+ const cutoffDate = new Date;
18828
+ cutoffDate.setDate(cutoffDate.getDate() - retentionDays);
18829
+ let deletedCount = 0;
18830
+ for (const file of files) {
18831
+ if (!file.startsWith("access-") || !file.endsWith(".log")) {
18832
+ continue;
18833
+ }
18834
+ const dateMatch = file.match(/access-(\d{4}-\d{2}-\d{2})\.log/);
18835
+ if (!dateMatch)
18836
+ continue;
18837
+ const fileDate = new Date(dateMatch[1]);
18838
+ if (fileDate < cutoffDate) {
18839
+ const filePath = path4.join(this.logsDir, file);
18840
+ fs4.unlinkSync(filePath);
18841
+ deletedCount++;
18842
+ }
18843
+ }
18844
+ return deletedCount;
18845
+ }
18846
+ }
18847
+ var defaultLogsDirectory = process.env.BUNGEE_FILE_LOG_DIR ?? path4.resolve(process.cwd(), "logs");
18110
18848
 
18111
18849
  // src/master-runtime/observability-worker.ts
18112
18850
  function headerEntries(headers) {
@@ -18117,6 +18855,8 @@ function headerEntries(headers) {
18117
18855
  var scope = globalThis;
18118
18856
  var stats = null;
18119
18857
  var database = null;
18858
+ var accessLog;
18859
+ var accessFile;
18120
18860
  var adapters = new Map;
18121
18861
  var bodies = new Map;
18122
18862
  var sequence = 0;
@@ -18134,7 +18874,7 @@ async function execute(method, args) {
18134
18874
  if (method === "open") {
18135
18875
  if (stats)
18136
18876
  throw new Error("observability_already_open");
18137
- database = new Database5(args[0]);
18877
+ database = new Database6(args[0]);
18138
18878
  try {
18139
18879
  stats = createMasterStats({ accessDbPath: args[0], database });
18140
18880
  } catch (error) {
@@ -18143,6 +18883,39 @@ async function execute(method, args) {
18143
18883
  }
18144
18884
  return null;
18145
18885
  }
18886
+ if (method === "openAccessLog") {
18887
+ if (accessLog || accessFile)
18888
+ throw new Error("access_log_already_open");
18889
+ try {
18890
+ accessLog = new AccessLogWriter(args[0], 4096);
18891
+ } catch {
18892
+ console.error("Ingress request log database unavailable");
18893
+ }
18894
+ try {
18895
+ accessFile = new FileLogWriter(args[1], 4096);
18896
+ } catch {
18897
+ console.error("Ingress request log file storage unavailable");
18898
+ }
18899
+ if (!accessLog && !accessFile)
18900
+ throw new Error("access_log_storage_unavailable");
18901
+ return null;
18902
+ }
18903
+ if (method === "writeAccessLog" && (accessLog || accessFile)) {
18904
+ for (const entry of args[0]) {
18905
+ accessLog?.write(entry);
18906
+ if (entry.transportOutcome !== "pending") {
18907
+ accessFile?.write(entry).catch(() => console.error("Ingress file access log write failed"));
18908
+ }
18909
+ }
18910
+ return null;
18911
+ }
18912
+ if (method === "close" && (accessLog || accessFile)) {
18913
+ const results = await Promise.allSettled([accessLog?.close(), accessFile?.close()]);
18914
+ const errors = results.filter((result) => result.status === "rejected").map((result) => result.reason);
18915
+ if (errors.length)
18916
+ throw new AggregateError(errors, "Ingress access log close failed");
18917
+ return null;
18918
+ }
18146
18919
  if (!stats || !database)
18147
18920
  throw new Error("observability_unavailable");
18148
18921
  if (method === "register") {