@jeffusion/bungee-core 6.19.0 → 6.19.1

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.
@@ -16823,30 +16823,18 @@ class LogsHandler {
16823
16823
  const data = await this.dependencies.logQueryService.getTimeSeriesStats(startTime, endTime, interval ?? "minute");
16824
16824
  return new Response(JSON.stringify(data), { headers: { "Content-Type": "application/json" } });
16825
16825
  }
16826
- async triggerCleanup() {
16827
- try {
16828
- const result = await this.dependencies.cleanupService.runCleanup();
16829
- return new Response(JSON.stringify(result), {
16830
- headers: { "Content-Type": "application/json" }
16831
- });
16832
- } catch (error) {
16833
- console.error("Failed to trigger cleanup:", error);
16834
- return databaseFailure(error) ?? new Response(JSON.stringify({ error: "Failed to trigger cleanup" }), { status: 500, headers: { "Content-Type": "application/json" } });
16835
- }
16836
- }
16837
- getCleanupConfig() {
16838
- const config = this.dependencies.cleanupService.getConfig();
16839
- const isActive = this.dependencies.cleanupService.isActive();
16840
- return new Response(JSON.stringify({ ...config, isActive }), {
16841
- headers: { "Content-Type": "application/json" }
16842
- });
16843
- }
16826
+ }
16827
+ function logCleanupMethod(path) {
16828
+ if (path === "/api/logs/cleanup")
16829
+ return "POST";
16830
+ if (path === "/api/logs/cleanup/config")
16831
+ return "GET";
16844
16832
  }
16845
16833
 
16846
16834
  // src/logger/body-storage.ts
16847
16835
  import { randomUUID } from "crypto";
16848
16836
  import fs from "fs";
16849
- import path from "path";
16837
+ import path2 from "path";
16850
16838
 
16851
16839
  // ../types/src/daemon-control.ts
16852
16840
  var DAEMON_METADATA_MAX_BYTES = 4 * 1024;
@@ -16941,6 +16929,98 @@ function createLogger2(defaultMeta = {}) {
16941
16929
  var logger2 = createLogger2();
16942
16930
  installPluginLogSink(logger2);
16943
16931
 
16932
+ // src/logger/dated-log-files.ts
16933
+ import { promises as files } from "fs";
16934
+ import path from "path";
16935
+ var LOG_RETENTION_DAY_MS = 24 * 60 * 60 * 1000;
16936
+ async function verifyCanonicalPath(directory, signal) {
16937
+ signal?.throwIfAborted();
16938
+ if (await files.realpath(directory) !== directory)
16939
+ throw new Error("Log cleanup path changed");
16940
+ signal?.throwIfAborted();
16941
+ }
16942
+ async function removeDirectory(directory, signal) {
16943
+ await verifyCanonicalPath(directory, signal);
16944
+ signal?.throwIfAborted();
16945
+ const entries = await files.readdir(directory, { withFileTypes: true });
16946
+ let deleted = 0;
16947
+ for (const entry of entries) {
16948
+ signal?.throwIfAborted();
16949
+ const target = path.join(directory, entry.name);
16950
+ if (entry.isDirectory()) {
16951
+ deleted += await removeDirectory(target, signal);
16952
+ } else {
16953
+ await files.unlink(target);
16954
+ deleted++;
16955
+ }
16956
+ }
16957
+ await verifyCanonicalPath(directory, signal);
16958
+ signal?.throwIfAborted();
16959
+ await files.rmdir(directory);
16960
+ signal?.throwIfAborted();
16961
+ return deleted;
16962
+ }
16963
+ async function cleanupDatedLogFiles(directory, cutoffTime, storage, signal) {
16964
+ signal?.throwIfAborted();
16965
+ const cutoffDate = new Date(Math.floor(cutoffTime));
16966
+ cutoffDate.setUTCHours(0, 0, 0, 0);
16967
+ const result = { deletedDirs: 0, deletedFiles: 0 };
16968
+ let root;
16969
+ try {
16970
+ const stat = await files.lstat(directory, { bigint: true });
16971
+ signal?.throwIfAborted();
16972
+ if (!stat.isDirectory()) {
16973
+ logger2.warn({ directory, storage }, "Skipping log cleanup: root is not a real directory");
16974
+ return result;
16975
+ }
16976
+ root = await files.realpath(directory);
16977
+ signal?.throwIfAborted();
16978
+ const canonical = await files.lstat(root, { bigint: true });
16979
+ if (!canonical.isDirectory() || canonical.dev !== stat.dev || canonical.ino !== stat.ino) {
16980
+ throw new Error("Log cleanup root changed");
16981
+ }
16982
+ signal?.throwIfAborted();
16983
+ } catch (error) {
16984
+ signal?.throwIfAborted();
16985
+ if (error.code !== "ENOENT") {
16986
+ logger2.warn({ error, directory, storage }, "Skipping log cleanup: root cannot be verified");
16987
+ }
16988
+ return result;
16989
+ }
16990
+ try {
16991
+ const entries = await files.readdir(root, { withFileTypes: true });
16992
+ let scanned = 0;
16993
+ for (const entry of entries) {
16994
+ if (++scanned % 128 === 0)
16995
+ await new Promise((resolve) => setImmediate(resolve));
16996
+ signal?.throwIfAborted();
16997
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(entry.name))
16998
+ continue;
16999
+ const date = new Date(entry.name);
17000
+ if (!(date < cutoffDate) || date.toISOString().slice(0, 10) !== entry.name)
17001
+ continue;
17002
+ const candidate = path.join(root, entry.name);
17003
+ if (!entry.isDirectory()) {
17004
+ logger2.warn({ directory: candidate, storage }, "Skipping log cleanup entry: not a real directory");
17005
+ continue;
17006
+ }
17007
+ try {
17008
+ result.deletedFiles += await removeDirectory(candidate, signal);
17009
+ result.deletedDirs++;
17010
+ } catch (error) {
17011
+ signal?.throwIfAborted();
17012
+ logger2.warn({ error, directory: candidate, storage }, "Skipping log cleanup entry after verification failure");
17013
+ }
17014
+ }
17015
+ signal?.throwIfAborted();
17016
+ logger2.info({ ...result, cutoffTime, storage }, "Log file cleanup completed");
17017
+ } catch (error) {
17018
+ signal?.throwIfAborted();
17019
+ logger2.warn({ error, directory, storage }, "Log file cleanup skipped after verification failure");
17020
+ }
17021
+ return result;
17022
+ }
17023
+
16944
17024
  // src/logger/body-log-redaction.ts
16945
17025
  var import_stream_json = __toESM(require_stream_json());
16946
17026
  var import_Stringer = __toESM(require_Stringer());
@@ -17252,7 +17332,7 @@ var DEFAULT_CONFIG = {
17252
17332
  class BodyStorageManager {
17253
17333
  config;
17254
17334
  bodiesDir;
17255
- constructor(config = {}, bodiesDir = path.resolve(process.cwd(), "logs", "bodies")) {
17335
+ constructor(config = {}, bodiesDir = path2.resolve(process.cwd(), "logs", "bodies")) {
17256
17336
  this.config = { ...DEFAULT_CONFIG, ...config };
17257
17337
  this.bodiesDir = bodiesDir;
17258
17338
  }
@@ -17289,7 +17369,7 @@ class BodyStorageManager {
17289
17369
  const filePath = this.getBodyFilePath(bodyId);
17290
17370
  if (filePath === null)
17291
17371
  return null;
17292
- const dateDir = path.dirname(filePath);
17372
+ const dateDir = path2.dirname(filePath);
17293
17373
  if (!this.ensureSafeDirectory(dateDir) || !this.isSafeRegularFile(filePath))
17294
17374
  return null;
17295
17375
  await fs.promises.writeFile(filePath, bodyStr, "utf-8");
@@ -17329,7 +17409,7 @@ class BodyStorageManager {
17329
17409
  if (bytes > maxBytes)
17330
17410
  throw new BodyProcessingError(413, "body_log_too_large");
17331
17411
  if (!file) {
17332
- if (!this.ensureSafeDirectory(path.dirname(filePath)) || !this.isSafeRegularFile(filePath)) {
17412
+ if (!this.ensureSafeDirectory(path2.dirname(filePath)) || !this.isSafeRegularFile(filePath)) {
17333
17413
  throw new Error("body_log_storage_failed");
17334
17414
  }
17335
17415
  try {
@@ -17410,61 +17490,8 @@ class BodyStorageManager {
17410
17490
  return { found: false };
17411
17491
  }
17412
17492
  }
17413
- async cleanup() {
17414
- const cutoffDate = new Date;
17415
- cutoffDate.setUTCHours(0, 0, 0, 0);
17416
- cutoffDate.setUTCDate(cutoffDate.getUTCDate() - this.config.retentionDays);
17417
- let deletedDirs = 0;
17418
- let deletedFiles = 0;
17419
- try {
17420
- let root;
17421
- try {
17422
- const stat = fs.lstatSync(this.bodiesDir);
17423
- if (!stat.isDirectory() || stat.isSymbolicLink()) {
17424
- logger2.warn({ directory: this.bodiesDir }, "Skipping body cleanup: root is not a real directory");
17425
- return { deletedDirs, deletedFiles };
17426
- }
17427
- root = fs.realpathSync(this.bodiesDir);
17428
- } catch (error) {
17429
- if (error?.code === "ENOENT")
17430
- return { deletedDirs, deletedFiles };
17431
- logger2.warn({ error, directory: this.bodiesDir }, "Skipping body cleanup: root cannot be verified");
17432
- return { deletedDirs, deletedFiles };
17433
- }
17434
- const dirs = fs.readdirSync(this.bodiesDir);
17435
- for (const dir of dirs) {
17436
- if (!/^\d{4}-\d{2}-\d{2}$/.test(dir)) {
17437
- continue;
17438
- }
17439
- const dirDate = new Date(dir);
17440
- if (dirDate < cutoffDate) {
17441
- const dirPath = path.join(this.bodiesDir, dir);
17442
- try {
17443
- const stat = fs.lstatSync(dirPath);
17444
- if (!stat.isDirectory() || stat.isSymbolicLink()) {
17445
- logger2.warn({ directory: dirPath }, "Skipping body cleanup entry: not a real directory");
17446
- continue;
17447
- }
17448
- const canonical = fs.realpathSync(dirPath);
17449
- const relative = path.relative(root, canonical);
17450
- if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) {
17451
- logger2.warn({ directory: dirPath, canonical }, "Skipping body cleanup entry outside root");
17452
- continue;
17453
- }
17454
- deletedFiles += fs.readdirSync(dirPath).length;
17455
- fs.rmSync(dirPath, { recursive: true });
17456
- deletedDirs++;
17457
- } catch (error) {
17458
- logger2.warn({ error, directory: dirPath }, "Skipping body cleanup entry after verification failure");
17459
- }
17460
- }
17461
- }
17462
- logger2.info({ deletedDirs, deletedFiles, retentionDays: this.config.retentionDays }, "Body cleanup completed");
17463
- return { deletedDirs, deletedFiles };
17464
- } catch (error) {
17465
- logger2.warn({ error }, "Body cleanup skipped after verification failure");
17466
- return { deletedDirs, deletedFiles };
17467
- }
17493
+ cleanup(cutoffTime = Date.now() - this.config.retentionDays * LOG_RETENTION_DAY_MS, signal) {
17494
+ return cleanupDatedLogFiles(this.bodiesDir, cutoffTime, "body", signal);
17468
17495
  }
17469
17496
  updateConfig(config) {
17470
17497
  this.config = { ...this.config, ...config };
@@ -17493,12 +17520,12 @@ class BodyStorageManager {
17493
17520
  const requestId = typeAndId.slice(type.length + 1);
17494
17521
  if (requestId.length === 0 || requestId === "." || requestId === ".." || requestId.includes("/"))
17495
17522
  return null;
17496
- const base = path.resolve(this.bodiesDir);
17497
- const dateDir = path.resolve(base, parts[0]);
17498
- const filePath = path.resolve(dateDir, `${type}-${requestId}.json`);
17499
- if (dateDir !== base && !dateDir.startsWith(`${base}${path.sep}`))
17523
+ const base = path2.resolve(this.bodiesDir);
17524
+ const dateDir = path2.resolve(base, parts[0]);
17525
+ const filePath = path2.resolve(dateDir, `${type}-${requestId}.json`);
17526
+ if (dateDir !== base && !dateDir.startsWith(`${base}${path2.sep}`))
17500
17527
  return null;
17501
- if (!filePath.startsWith(`${dateDir}${path.sep}`) || !filePath.startsWith(`${base}${path.sep}`))
17528
+ if (!filePath.startsWith(`${dateDir}${path2.sep}`) || !filePath.startsWith(`${base}${path2.sep}`))
17502
17529
  return null;
17503
17530
  return filePath;
17504
17531
  }
@@ -17509,13 +17536,13 @@ class BodyStorageManager {
17509
17536
  return date.getUTCFullYear() === Number(value.slice(0, 4)) && date.getUTCMonth() + 1 === Number(value.slice(5, 7)) && date.getUTCDate() === Number(value.slice(8, 10));
17510
17537
  }
17511
17538
  isSafeDirectory(directory) {
17512
- const base = path.resolve(this.bodiesDir);
17513
- const target = path.resolve(directory);
17514
- if (target !== base && !target.startsWith(`${base}${path.sep}`))
17539
+ const base = path2.resolve(this.bodiesDir);
17540
+ const target = path2.resolve(directory);
17541
+ if (target !== base && !target.startsWith(`${base}${path2.sep}`))
17515
17542
  return false;
17516
- let current = path.parse(base).root;
17517
- for (const segment of path.relative(current, target).split(path.sep).filter(Boolean)) {
17518
- current = path.join(current, segment);
17543
+ let current = path2.parse(base).root;
17544
+ for (const segment of path2.relative(current, target).split(path2.sep).filter(Boolean)) {
17545
+ current = path2.join(current, segment);
17519
17546
  try {
17520
17547
  const stat = fs.lstatSync(current);
17521
17548
  if (!stat.isDirectory() || stat.isSymbolicLink())
@@ -17527,13 +17554,13 @@ class BodyStorageManager {
17527
17554
  return true;
17528
17555
  }
17529
17556
  ensureSafeDirectory(directory) {
17530
- const base = path.resolve(this.bodiesDir);
17531
- const target = path.resolve(directory);
17532
- if (target !== base && !target.startsWith(`${base}${path.sep}`))
17557
+ const base = path2.resolve(this.bodiesDir);
17558
+ const target = path2.resolve(directory);
17559
+ if (target !== base && !target.startsWith(`${base}${path2.sep}`))
17533
17560
  return false;
17534
- let current = path.parse(base).root;
17535
- for (const segment of path.relative(current, target).split(path.sep).filter(Boolean)) {
17536
- current = path.join(current, segment);
17561
+ let current = path2.parse(base).root;
17562
+ for (const segment of path2.relative(current, target).split(path2.sep).filter(Boolean)) {
17563
+ current = path2.join(current, segment);
17537
17564
  try {
17538
17565
  const stat = fs.lstatSync(current);
17539
17566
  if (!stat.isDirectory() || stat.isSymbolicLink())
@@ -17566,7 +17593,7 @@ class BodyStorageManager {
17566
17593
  }
17567
17594
  }
17568
17595
  async isSafePath(filePath) {
17569
- const dateDir = path.dirname(filePath);
17596
+ const dateDir = path2.dirname(filePath);
17570
17597
  if (!this.isSafeDirectory(dateDir))
17571
17598
  return false;
17572
17599
  try {
@@ -17584,7 +17611,7 @@ class BodyStorageManager {
17584
17611
 
17585
17612
  // src/logger/header-storage.ts
17586
17613
  import fs2 from "fs";
17587
- import path2 from "path";
17614
+ import path3 from "path";
17588
17615
  var HEADER_TYPES = ["original-request", "request", "response"];
17589
17616
  var DEFAULT_CONFIG2 = {
17590
17617
  enabled: true,
@@ -17602,7 +17629,7 @@ var SENSITIVE_HEADERS = new Set([
17602
17629
  class HeaderStorageManager {
17603
17630
  config;
17604
17631
  headersDir;
17605
- constructor(config = {}, headersDir = process.env.BUNGEE_HEADER_LOG_DIR ?? path2.resolve(process.cwd(), "logs", "headers")) {
17632
+ constructor(config = {}, headersDir = process.env.BUNGEE_HEADER_LOG_DIR ?? path3.resolve(process.cwd(), "logs", "headers")) {
17606
17633
  this.config = { ...DEFAULT_CONFIG2, ...config };
17607
17634
  this.headersDir = headersDir;
17608
17635
  }
@@ -17621,7 +17648,7 @@ class HeaderStorageManager {
17621
17648
  const filePath = this.getHeaderFilePath(headerId);
17622
17649
  if (filePath === null)
17623
17650
  return null;
17624
- const dateDir = path2.dirname(filePath);
17651
+ const dateDir = path3.dirname(filePath);
17625
17652
  if (!this.ensureSafeDirectory(dateDir) || !this.isSafeRegularFile(filePath))
17626
17653
  return null;
17627
17654
  await fs2.promises.writeFile(filePath, headersStr, "utf-8");
@@ -17646,61 +17673,8 @@ class HeaderStorageManager {
17646
17673
  return null;
17647
17674
  }
17648
17675
  }
17649
- async cleanup() {
17650
- const cutoffDate = new Date;
17651
- cutoffDate.setUTCHours(0, 0, 0, 0);
17652
- cutoffDate.setUTCDate(cutoffDate.getUTCDate() - this.config.retentionDays);
17653
- let deletedDirs = 0;
17654
- let deletedFiles = 0;
17655
- try {
17656
- let root;
17657
- try {
17658
- const stat = fs2.lstatSync(this.headersDir);
17659
- if (!stat.isDirectory() || stat.isSymbolicLink()) {
17660
- logger2.warn({ directory: this.headersDir }, "Skipping header cleanup: root is not a real directory");
17661
- return { deletedDirs, deletedFiles };
17662
- }
17663
- root = fs2.realpathSync(this.headersDir);
17664
- } catch (error) {
17665
- if (error?.code === "ENOENT")
17666
- return { deletedDirs, deletedFiles };
17667
- logger2.warn({ error, directory: this.headersDir }, "Skipping header cleanup: root cannot be verified");
17668
- return { deletedDirs, deletedFiles };
17669
- }
17670
- const dirs = fs2.readdirSync(this.headersDir);
17671
- for (const dir of dirs) {
17672
- if (!/^\d{4}-\d{2}-\d{2}$/.test(dir)) {
17673
- continue;
17674
- }
17675
- const dirDate = new Date(dir);
17676
- if (dirDate < cutoffDate) {
17677
- const dirPath = path2.join(this.headersDir, dir);
17678
- try {
17679
- const stat = fs2.lstatSync(dirPath);
17680
- if (!stat.isDirectory() || stat.isSymbolicLink()) {
17681
- logger2.warn({ directory: dirPath }, "Skipping header cleanup entry: not a real directory");
17682
- continue;
17683
- }
17684
- const canonical = fs2.realpathSync(dirPath);
17685
- const relative = path2.relative(root, canonical);
17686
- if (relative === "" || relative.startsWith("..") || path2.isAbsolute(relative)) {
17687
- logger2.warn({ directory: dirPath, canonical }, "Skipping header cleanup entry outside root");
17688
- continue;
17689
- }
17690
- deletedFiles += fs2.readdirSync(dirPath).length;
17691
- fs2.rmSync(dirPath, { recursive: true });
17692
- deletedDirs++;
17693
- } catch (error) {
17694
- logger2.warn({ error, directory: dirPath }, "Skipping header cleanup entry after verification failure");
17695
- }
17696
- }
17697
- }
17698
- logger2.info({ deletedDirs, deletedFiles, retentionDays: this.config.retentionDays }, "Header cleanup completed");
17699
- return { deletedDirs, deletedFiles };
17700
- } catch (error) {
17701
- logger2.warn({ error }, "Header cleanup skipped after verification failure");
17702
- return { deletedDirs, deletedFiles };
17703
- }
17676
+ cleanup(cutoffTime = Date.now() - this.config.retentionDays * LOG_RETENTION_DAY_MS, signal) {
17677
+ return cleanupDatedLogFiles(this.headersDir, cutoffTime, "header", signal);
17704
17678
  }
17705
17679
  updateConfig(config) {
17706
17680
  this.config = { ...this.config, ...config };
@@ -17729,12 +17703,12 @@ class HeaderStorageManager {
17729
17703
  const requestId = typeAndId.slice(type.length + 1);
17730
17704
  if (requestId.length === 0 || requestId === "." || requestId === ".." || requestId.includes("/"))
17731
17705
  return null;
17732
- const base = path2.resolve(this.headersDir);
17733
- const dateDir = path2.resolve(base, parts[0]);
17734
- const filePath = path2.resolve(dateDir, `${type}-${requestId}.json`);
17735
- if (dateDir !== base && !dateDir.startsWith(`${base}${path2.sep}`))
17706
+ const base = path3.resolve(this.headersDir);
17707
+ const dateDir = path3.resolve(base, parts[0]);
17708
+ const filePath = path3.resolve(dateDir, `${type}-${requestId}.json`);
17709
+ if (dateDir !== base && !dateDir.startsWith(`${base}${path3.sep}`))
17736
17710
  return null;
17737
- if (!filePath.startsWith(`${dateDir}${path2.sep}`) || !filePath.startsWith(`${base}${path2.sep}`))
17711
+ if (!filePath.startsWith(`${dateDir}${path3.sep}`) || !filePath.startsWith(`${base}${path3.sep}`))
17738
17712
  return null;
17739
17713
  return filePath;
17740
17714
  }
@@ -17745,13 +17719,13 @@ class HeaderStorageManager {
17745
17719
  return date.getUTCFullYear() === Number(value.slice(0, 4)) && date.getUTCMonth() + 1 === Number(value.slice(5, 7)) && date.getUTCDate() === Number(value.slice(8, 10));
17746
17720
  }
17747
17721
  isSafeDirectory(directory) {
17748
- const base = path2.resolve(this.headersDir);
17749
- const target = path2.resolve(directory);
17750
- if (target !== base && !target.startsWith(`${base}${path2.sep}`))
17722
+ const base = path3.resolve(this.headersDir);
17723
+ const target = path3.resolve(directory);
17724
+ if (target !== base && !target.startsWith(`${base}${path3.sep}`))
17751
17725
  return false;
17752
- let current = path2.parse(base).root;
17753
- for (const segment of path2.relative(current, target).split(path2.sep).filter(Boolean)) {
17754
- current = path2.join(current, segment);
17726
+ let current = path3.parse(base).root;
17727
+ for (const segment of path3.relative(current, target).split(path3.sep).filter(Boolean)) {
17728
+ current = path3.join(current, segment);
17755
17729
  try {
17756
17730
  const stat = fs2.lstatSync(current);
17757
17731
  if (!stat.isDirectory() || stat.isSymbolicLink())
@@ -17763,13 +17737,13 @@ class HeaderStorageManager {
17763
17737
  return true;
17764
17738
  }
17765
17739
  ensureSafeDirectory(directory) {
17766
- const base = path2.resolve(this.headersDir);
17767
- const target = path2.resolve(directory);
17768
- if (target !== base && !target.startsWith(`${base}${path2.sep}`))
17740
+ const base = path3.resolve(this.headersDir);
17741
+ const target = path3.resolve(directory);
17742
+ if (target !== base && !target.startsWith(`${base}${path3.sep}`))
17769
17743
  return false;
17770
- let current = path2.parse(base).root;
17771
- for (const segment of path2.relative(current, target).split(path2.sep).filter(Boolean)) {
17772
- current = path2.join(current, segment);
17744
+ let current = path3.parse(base).root;
17745
+ for (const segment of path3.relative(current, target).split(path3.sep).filter(Boolean)) {
17746
+ current = path3.join(current, segment);
17773
17747
  try {
17774
17748
  const stat = fs2.lstatSync(current);
17775
17749
  if (!stat.isDirectory() || stat.isSymbolicLink())
@@ -17802,7 +17776,7 @@ class HeaderStorageManager {
17802
17776
  }
17803
17777
  }
17804
17778
  async isSafePath(filePath) {
17805
- const dateDir = path2.dirname(filePath);
17779
+ const dateDir = path3.dirname(filePath);
17806
17780
  if (!this.isSafeDirectory(dateDir))
17807
17781
  return false;
17808
17782
  try {
@@ -17818,164 +17792,6 @@ class HeaderStorageManager {
17818
17792
  }
17819
17793
  }
17820
17794
 
17821
- // src/logger/log-cleanup.ts
17822
- var DEFAULT_CONFIG3 = {
17823
- enabled: true,
17824
- retentionDays: 1,
17825
- scheduleIntervalHours: 1
17826
- };
17827
-
17828
- class LogCleanupService {
17829
- config;
17830
- cleanupTimer = null;
17831
- initialCleanupTimer = null;
17832
- isRunning = false;
17833
- activeRun = null;
17834
- database;
17835
- bodyStorage;
17836
- headerStorage;
17837
- constructor(optionsOrDatabase = {}, bodyStorage, headerStorage, config = {}) {
17838
- if (bodyStorage !== undefined && headerStorage !== undefined && "prepare" in optionsOrDatabase) {
17839
- this.config = { ...DEFAULT_CONFIG3, ...config };
17840
- this.database = optionsOrDatabase;
17841
- this.bodyStorage = bodyStorage;
17842
- this.headerStorage = headerStorage;
17843
- } else if ("database" in optionsOrDatabase && "bodyStorage" in optionsOrDatabase && "headerStorage" in optionsOrDatabase) {
17844
- this.config = {
17845
- ...DEFAULT_CONFIG3,
17846
- enabled: optionsOrDatabase.enabled ?? DEFAULT_CONFIG3.enabled,
17847
- retentionDays: optionsOrDatabase.retentionDays ?? DEFAULT_CONFIG3.retentionDays,
17848
- scheduleIntervalHours: optionsOrDatabase.scheduleIntervalHours ?? DEFAULT_CONFIG3.scheduleIntervalHours,
17849
- ...optionsOrDatabase.config ?? {}
17850
- };
17851
- this.database = optionsOrDatabase.database;
17852
- this.bodyStorage = optionsOrDatabase.bodyStorage;
17853
- this.headerStorage = optionsOrDatabase.headerStorage;
17854
- } else {
17855
- this.config = { ...DEFAULT_CONFIG3, ...optionsOrDatabase };
17856
- this.database = null;
17857
- this.bodyStorage = null;
17858
- this.headerStorage = null;
17859
- }
17860
- }
17861
- start() {
17862
- if (!this.config.enabled) {
17863
- logger2.info("Log cleanup service is disabled");
17864
- return;
17865
- }
17866
- if (this.cleanupTimer) {
17867
- logger2.warn("Log cleanup service is already running");
17868
- return;
17869
- }
17870
- logger2.info({ config: this.config }, "Starting log cleanup service");
17871
- this.initialCleanupTimer = setTimeout(() => {
17872
- this.initialCleanupTimer = null;
17873
- this.runCleanup().catch((error) => {
17874
- logger2.error({ error }, "Initial log cleanup failed");
17875
- });
17876
- }, 0);
17877
- const intervalMs = this.config.scheduleIntervalHours * 60 * 60 * 1000;
17878
- this.cleanupTimer = setInterval(() => {
17879
- this.runCleanup().catch((error) => {
17880
- logger2.error({ error }, "Scheduled log cleanup failed");
17881
- });
17882
- }, intervalMs);
17883
- logger2.info({ intervalHours: this.config.scheduleIntervalHours }, "Log cleanup service started");
17884
- }
17885
- async stop() {
17886
- if (this.initialCleanupTimer !== null) {
17887
- clearTimeout(this.initialCleanupTimer);
17888
- this.initialCleanupTimer = null;
17889
- }
17890
- if (this.cleanupTimer) {
17891
- clearInterval(this.cleanupTimer);
17892
- this.cleanupTimer = null;
17893
- logger2.info("Log cleanup service stopped");
17894
- }
17895
- await this.activeRun;
17896
- }
17897
- configure(config) {
17898
- this.config = { ...this.config, ...config };
17899
- }
17900
- async runCleanup() {
17901
- if (this.isRunning) {
17902
- logger2.warn("Cleanup is already running, skipping this run");
17903
- return {
17904
- deletedSqliteRecords: 0,
17905
- deletedFileLogFiles: 0,
17906
- deletedBodyDirs: 0,
17907
- deletedBodyFiles: 0,
17908
- durationMs: 0
17909
- };
17910
- }
17911
- if (this.database === null || this.bodyStorage === null || this.headerStorage === null) {
17912
- throw new Error("log cleanup dependencies are unavailable");
17913
- }
17914
- this.isRunning = true;
17915
- const startTime = Date.now();
17916
- const config = { ...this.config };
17917
- const database = this.database;
17918
- const bodyStorage = this.bodyStorage;
17919
- const headerStorage = this.headerStorage;
17920
- const run = (async () => {
17921
- try {
17922
- logger2.info({ retentionDays: config.retentionDays }, "Starting log cleanup");
17923
- const cutoffTime = Date.now() - config.retentionDays * 24 * 60 * 60 * 1000;
17924
- database.run("BEGIN IMMEDIATE");
17925
- let deletedSqliteRecords;
17926
- try {
17927
- database.query("UPDATE request_log_retention SET cutoff=MAX(cutoff,?) WHERE id=1").run(cutoffTime);
17928
- database.query(`DELETE FROM request_log_facts WHERE request_id IN
17929
- (SELECT request_id FROM access_logs WHERE timestamp<? AND result_state IS NOT 'running')`).run(cutoffTime);
17930
- deletedSqliteRecords = database.query("DELETE FROM access_logs WHERE timestamp<? AND result_state IS NOT 'running'").run(cutoffTime).changes;
17931
- database.query("DELETE FROM request_log_facts WHERE received_at<? AND json_extract(facts,'$.init') IS NULL").run(cutoffTime);
17932
- database.run("COMMIT");
17933
- } catch (error) {
17934
- database.run("ROLLBACK");
17935
- throw error;
17936
- }
17937
- const { deletedDirs: deletedBodyDirs, deletedFiles: deletedBodyFiles } = await bodyStorage.cleanup();
17938
- await headerStorage.cleanup();
17939
- const deletedFileLogFiles = 0;
17940
- const durationMs = Date.now() - startTime;
17941
- logger2.info({
17942
- deletedSqliteRecords,
17943
- deletedFileLogFiles,
17944
- deletedBodyDirs,
17945
- deletedBodyFiles,
17946
- durationMs,
17947
- retentionDays: config.retentionDays
17948
- }, "Log cleanup completed");
17949
- return {
17950
- deletedSqliteRecords,
17951
- deletedFileLogFiles,
17952
- deletedBodyDirs,
17953
- deletedBodyFiles,
17954
- durationMs
17955
- };
17956
- } catch (error) {
17957
- logger2.error({ error }, "Log cleanup failed");
17958
- throw error;
17959
- } finally {
17960
- this.isRunning = false;
17961
- }
17962
- })();
17963
- this.activeRun = run;
17964
- try {
17965
- return await run;
17966
- } finally {
17967
- if (this.activeRun === run)
17968
- this.activeRun = null;
17969
- }
17970
- }
17971
- getConfig() {
17972
- return { ...this.config };
17973
- }
17974
- isActive() {
17975
- return this.cleanupTimer !== null;
17976
- }
17977
- }
17978
-
17979
17795
  // src/access-database.ts
17980
17796
  import { Database } from "bun:sqlite";
17981
17797
  import { mkdirSync } from "fs";
@@ -18121,9 +17937,7 @@ var LOG_PATHS = new Set([
18121
17937
  "/api/logs/stream",
18122
17938
  "/api/logs/export",
18123
17939
  "/api/logs/stats",
18124
- "/api/logs/stats/timeseries",
18125
- "/api/logs/cleanup",
18126
- "/api/logs/cleanup/config"
17940
+ "/api/logs/stats/timeseries"
18127
17941
  ]);
18128
17942
 
18129
17943
  class MasterStatsInitializationError extends AggregateError {
@@ -18136,6 +17950,13 @@ class MasterStatsInitializationError extends AggregateError {
18136
17950
  function notFound() {
18137
17951
  return Response.json({ error: "not_found" }, { status: 404, headers: JSON_HEADERS2 });
18138
17952
  }
17953
+ function createMasterLogStorage(accessDbPath) {
17954
+ const root = accessDbPath === undefined ? join(process.cwd(), "logs") : dirname2(accessDbPath);
17955
+ return {
17956
+ bodyStorage: new BodyStorageManager({}, process.env.BUNGEE_BODY_LOG_DIR ?? join(root, "bodies")),
17957
+ headerStorage: new HeaderStorageManager({}, process.env.BUNGEE_HEADER_LOG_DIR ?? join(root, "headers"))
17958
+ };
17959
+ }
18139
17960
  function createMasterStats(input, legacyOpenDatabase) {
18140
17961
  const options = typeof input === "string" ? { accessDbPath: input, openDatabase: legacyOpenDatabase } : input;
18141
17962
  const accessDbPath = options.accessDbPath;
@@ -18143,25 +17964,13 @@ function createMasterStats(input, legacyOpenDatabase) {
18143
17964
  throw new TypeError("accessDbPath or database is required");
18144
17965
  }
18145
17966
  let database = options.database;
18146
- let bodyStorage = options.bodyStorage;
18147
- let headerStorage = options.headerStorage;
18148
- let cleanupService = options.cleanupService;
18149
17967
  let logQueryService;
18150
- const storageRoot = accessDbPath === undefined ? join(process.cwd(), "logs") : dirname2(accessDbPath);
18151
17968
  try {
18152
17969
  if (database === undefined) {
18153
17970
  database = (options.openDatabase ?? ((databasePath) => new Database2(databasePath)))(accessDbPath);
18154
17971
  }
18155
17972
  initializeAccessDatabaseConnection(database);
18156
17973
  logQueryService = new LogQueryService(database);
18157
- bodyStorage ??= new BodyStorageManager({}, process.env.BUNGEE_BODY_LOG_DIR ?? join(storageRoot, "bodies"));
18158
- headerStorage ??= new HeaderStorageManager({}, process.env.BUNGEE_HEADER_LOG_DIR ?? join(storageRoot, "headers"));
18159
- cleanupService ??= new LogCleanupService({
18160
- database,
18161
- bodyStorage,
18162
- headerStorage,
18163
- config: options.cleanupConfig
18164
- });
18165
17974
  } catch (error) {
18166
17975
  try {
18167
17976
  database?.close();
@@ -18170,17 +17979,14 @@ function createMasterStats(input, legacyOpenDatabase) {
18170
17979
  }
18171
17980
  throw error;
18172
17981
  }
18173
- if (database === undefined || bodyStorage === undefined || headerStorage === undefined || cleanupService === undefined) {
18174
- throw new Error("master observability resources were not initialized");
18175
- }
17982
+ const storage = createMasterLogStorage(accessDbPath);
18176
17983
  const stats = new StatsHandler(logQueryService);
18177
17984
  const shutdown = new AbortController;
18178
17985
  const logs = new LogsHandler({
18179
17986
  database,
18180
17987
  logQueryService,
18181
- bodyStorage,
18182
- headerStorage,
18183
- cleanupService,
17988
+ bodyStorage: options.bodyStorage ?? storage.bodyStorage,
17989
+ headerStorage: options.headerStorage ?? storage.headerStorage,
18184
17990
  shutdownSignal: shutdown.signal
18185
17991
  });
18186
17992
  let closed = false;
@@ -18208,6 +18014,8 @@ function createMasterStats(input, legacyOpenDatabase) {
18208
18014
  const knownLogPath = (requestPath) => {
18209
18015
  if (LOG_PATHS.has(requestPath))
18210
18016
  return true;
18017
+ if (logCleanupMethod(requestPath))
18018
+ return false;
18211
18019
  if (!requestPath.startsWith("/api/logs/"))
18212
18020
  return false;
18213
18021
  const suffix = requestPath.slice("/api/logs/".length);
@@ -18224,7 +18032,6 @@ function createMasterStats(input, legacyOpenDatabase) {
18224
18032
  };
18225
18033
  const knownPath = (requestPath) => DATABASE_STATS_PATHS.has(requestPath) || knownLogPath(requestPath);
18226
18034
  const statsPath = (requestPath) => DATABASE_STATS_PATHS.has(requestPath);
18227
- const logsPath = (requestPath) => knownLogPath(requestPath);
18228
18035
  const handleStats = async (request, requestPath) => {
18229
18036
  switch (requestPath) {
18230
18037
  case "/api/stats":
@@ -18263,10 +18070,6 @@ function createMasterStats(input, legacyOpenDatabase) {
18263
18070
  return { response: await logs.getStats(request), stream: false };
18264
18071
  if (requestPath === "/api/logs/stats/timeseries")
18265
18072
  return { response: await logs.getTimeSeriesStats(request), stream: false };
18266
- if (requestPath === "/api/logs/cleanup")
18267
- return { response: await logs.triggerCleanup(), stream: false };
18268
- if (requestPath === "/api/logs/cleanup/config")
18269
- return { response: logs.getCleanupConfig(), stream: false };
18270
18073
  if (requestPath.startsWith("/api/logs/body/"))
18271
18074
  return { response: await logs.getBodyById(decodeStorageId(requestPath.slice("/api/logs/body/".length))), stream: false };
18272
18075
  if (requestPath.startsWith("/api/logs/headers/"))
@@ -18296,21 +18099,6 @@ function createMasterStats(input, legacyOpenDatabase) {
18296
18099
  activeRequests() {
18297
18100
  return activeRequests;
18298
18101
  },
18299
- configureLogging(logging) {
18300
- const retentionDays = logging?.body?.retention_days ?? 30;
18301
- const enabled = logging?.body?.enabled ?? true;
18302
- const maxSize = logging?.body?.max_size;
18303
- bodyStorage.updateConfig?.({
18304
- enabled,
18305
- ...maxSize === undefined ? {} : { maxSize },
18306
- retentionDays
18307
- });
18308
- headerStorage.updateConfig?.({ enabled, retentionDays });
18309
- cleanupService.configure?.({ retentionDays });
18310
- },
18311
- startCleanup() {
18312
- cleanupService.start?.();
18313
- },
18314
18102
  matches(requestPath) {
18315
18103
  const normalized = requestPath;
18316
18104
  return normalized !== "/api/stats/upstreams/last-used" && knownPath(normalized);
@@ -18321,8 +18109,7 @@ function createMasterStats(input, legacyOpenDatabase) {
18321
18109
  return notFound();
18322
18110
  if (closed)
18323
18111
  return notFound();
18324
- const expectedMethod = statsPath(requestPath) || logsPath(requestPath) ? requestPath === "/api/logs/cleanup" ? "POST" : "GET" : "GET";
18325
- if (request.method !== expectedMethod) {
18112
+ if (request.method !== "GET") {
18326
18113
  return Response.json({ error: "method_not_allowed" }, { status: 405, headers: JSON_HEADERS2 });
18327
18114
  }
18328
18115
  activeRequests += 1;
@@ -18346,20 +18133,8 @@ function createMasterStats(input, legacyOpenDatabase) {
18346
18133
  closed = true;
18347
18134
  shutdown.abort("master observability stopped");
18348
18135
  closePromise = (async () => {
18349
- let cleanupError;
18350
- try {
18351
- await cleanupService.stop?.();
18352
- } catch (error) {
18353
- cleanupError = error;
18354
- }
18355
18136
  await waitForIdle();
18356
- try {
18357
- database.close(true);
18358
- } catch (error) {
18359
- throw cleanupError === undefined ? error : new AggregateError([cleanupError, error], "master observability close failed");
18360
- }
18361
- if (cleanupError !== undefined)
18362
- throw cleanupError;
18137
+ database.close(true);
18363
18138
  })();
18364
18139
  return closePromise;
18365
18140
  }
@@ -19343,7 +19118,7 @@ var migrations = [ACCESS_BASELINE, LLM_TPS_SAMPLES, LLM_TPS_MODEL, LLM_TPS_UPSTR
19343
19118
 
19344
19119
  // src/logger/access-log-writer.ts
19345
19120
  import { Database as Database5 } from "bun:sqlite";
19346
- import path3 from "path";
19121
+ import path4 from "path";
19347
19122
  import fs3 from "fs";
19348
19123
 
19349
19124
  // src/plugin-state/message-size.ts
@@ -19473,7 +19248,7 @@ class AccessLogWriter {
19473
19248
  this.maxQueuedEntries = maxQueuedEntries;
19474
19249
  this.kernelBootId = kernelBootId;
19475
19250
  if (typeof databaseOrPath === "string")
19476
- fs3.mkdirSync(path3.dirname(databaseOrPath), { recursive: true });
19251
+ fs3.mkdirSync(path4.dirname(databaseOrPath), { recursive: true });
19477
19252
  this.db = typeof databaseOrPath === "string" ? new Database5(databaseOrPath) : databaseOrPath;
19478
19253
  try {
19479
19254
  initializeAccessDatabaseConnection(this.db);
@@ -20064,11 +19839,11 @@ class AccessLogWriter {
20064
19839
  }
20065
19840
  }
20066
19841
  }
20067
- var defaultDatabasePath = process.env.BUNGEE_ACCESS_DB_PATH ?? path3.resolve(process.cwd(), "logs", "access.db");
19842
+ var defaultDatabasePath = process.env.BUNGEE_ACCESS_DB_PATH ?? path4.resolve(process.cwd(), "logs", "access.db");
20068
19843
 
20069
19844
  // src/logger/file-log-writer.ts
20070
19845
  import fs4 from "fs";
20071
- import path4 from "path";
19846
+ import path5 from "path";
20072
19847
  import { finished } from "stream/promises";
20073
19848
  var MAX_RETAINED_BYTES2 = 64 * 1024 * 1024;
20074
19849
  var releasedDataLoss = new WeakSet;
@@ -20091,7 +19866,7 @@ class FileLogWriter {
20091
19866
  streamCloseFailure;
20092
19867
  streamDataFailure;
20093
19868
  streamDataErrors = new WeakSet;
20094
- constructor(logsDir = path4.resolve(process.cwd(), "logs"), maxQueuedEntries = 4096) {
19869
+ constructor(logsDir = path5.resolve(process.cwd(), "logs"), maxQueuedEntries = 4096) {
20095
19870
  this.maxQueuedEntries = maxQueuedEntries;
20096
19871
  this.logsDir = logsDir;
20097
19872
  this.currentDate = this.getDateString();
@@ -20227,7 +20002,7 @@ class FileLogWriter {
20227
20002
  }
20228
20003
  }
20229
20004
  openLogFile() {
20230
- const logFilePath = path4.join(this.logsDir, `access-${this.currentDate}.log`);
20005
+ const logFilePath = path5.join(this.logsDir, `access-${this.currentDate}.log`);
20231
20006
  const stream = fs4.createWriteStream(logFilePath, { flags: "a" });
20232
20007
  this.streams.set(stream, new Promise((resolve) => stream.once("close", () => {
20233
20008
  this.streams.delete(stream);
@@ -20308,7 +20083,7 @@ class FileLogWriter {
20308
20083
  continue;
20309
20084
  const fileDate = new Date(dateMatch[1]);
20310
20085
  if (fileDate < cutoffDate) {
20311
- const filePath = path4.join(this.logsDir, file);
20086
+ const filePath = path5.join(this.logsDir, file);
20312
20087
  fs4.unlinkSync(filePath);
20313
20088
  deletedCount++;
20314
20089
  }
@@ -20316,7 +20091,7 @@ class FileLogWriter {
20316
20091
  return deletedCount;
20317
20092
  }
20318
20093
  }
20319
- var defaultLogsDirectory = process.env.BUNGEE_FILE_LOG_DIR ?? path4.resolve(process.cwd(), "logs");
20094
+ var defaultLogsDirectory = process.env.BUNGEE_FILE_LOG_DIR ?? path5.resolve(process.cwd(), "logs");
20320
20095
 
20321
20096
  // src/master-runtime/process-identity.ts
20322
20097
  import { execFile as nodeExecFile } from "child_process";
@@ -20490,6 +20265,273 @@ function kernelMonotonicNowMs() {
20490
20265
  // src/data-admission/errors.ts
20491
20266
  var WORKER_RPC_ATTEMPT_TIMEOUT_MS = 1000;
20492
20267
 
20268
+ // src/config-storage/sqlite-errors.ts
20269
+ function isSqliteBusyError(error) {
20270
+ if (!(error instanceof Error))
20271
+ return false;
20272
+ const sqliteError = error;
20273
+ const errno = sqliteError.errno;
20274
+ if (typeof errno === "number" && ((errno & 255) === 5 || (errno & 255) === 6))
20275
+ return true;
20276
+ const code = sqliteError.code;
20277
+ return code === "SQLITE_BUSY" || code === "SQLITE_LOCKED" || code?.startsWith("SQLITE_BUSY_") === true || code?.startsWith("SQLITE_LOCKED_") === true;
20278
+ }
20279
+
20280
+ // src/logger/log-cleanup.ts
20281
+ var DEFAULT_CLEANUP_CONFIG = Object.freeze({
20282
+ enabled: true,
20283
+ retentionDays: 1,
20284
+ scheduleIntervalHours: 1
20285
+ });
20286
+ var BATCH_SIZE = 128;
20287
+ var MIN_ROWID = -9223372036854775808n;
20288
+ var BUSY_RETRY_DELAY_MS = 20;
20289
+
20290
+ class LogCleanupStopped extends Error {
20291
+ code = "log_cleanup_stopped";
20292
+ constructor() {
20293
+ super("log_cleanup_stopped");
20294
+ }
20295
+ }
20296
+ function waitForRetry(delay, signal) {
20297
+ return new Promise((resolve) => {
20298
+ const wake = () => {
20299
+ clearTimeout(timer);
20300
+ signal.removeEventListener("abort", wake);
20301
+ resolve();
20302
+ };
20303
+ const timer = setTimeout(wake, delay);
20304
+ signal.addEventListener("abort", wake, { once: true });
20305
+ });
20306
+ }
20307
+
20308
+ class LogCleanupService {
20309
+ config;
20310
+ cleanupTimer = null;
20311
+ initialCleanupTimer = null;
20312
+ stopping = new AbortController;
20313
+ activeRun = null;
20314
+ database;
20315
+ bodyStorage;
20316
+ headerStorage;
20317
+ readRetentionDays;
20318
+ constructor(optionsOrDatabase = {}, bodyStorage, headerStorage, config = {}) {
20319
+ if (bodyStorage !== undefined && headerStorage !== undefined && "prepare" in optionsOrDatabase) {
20320
+ this.config = { ...DEFAULT_CLEANUP_CONFIG, ...config };
20321
+ this.database = optionsOrDatabase;
20322
+ this.bodyStorage = bodyStorage;
20323
+ this.headerStorage = headerStorage;
20324
+ } else if ("database" in optionsOrDatabase && "bodyStorage" in optionsOrDatabase && "headerStorage" in optionsOrDatabase) {
20325
+ this.config = {
20326
+ ...DEFAULT_CLEANUP_CONFIG,
20327
+ enabled: optionsOrDatabase.enabled ?? DEFAULT_CLEANUP_CONFIG.enabled,
20328
+ retentionDays: optionsOrDatabase.retentionDays ?? DEFAULT_CLEANUP_CONFIG.retentionDays,
20329
+ scheduleIntervalHours: optionsOrDatabase.scheduleIntervalHours ?? DEFAULT_CLEANUP_CONFIG.scheduleIntervalHours,
20330
+ ...optionsOrDatabase.config ?? {}
20331
+ };
20332
+ this.database = optionsOrDatabase.database;
20333
+ this.bodyStorage = optionsOrDatabase.bodyStorage;
20334
+ this.headerStorage = optionsOrDatabase.headerStorage;
20335
+ this.readRetentionDays = optionsOrDatabase.readRetentionDays;
20336
+ } else {
20337
+ this.config = { ...DEFAULT_CLEANUP_CONFIG, ...optionsOrDatabase };
20338
+ this.database = null;
20339
+ this.bodyStorage = null;
20340
+ this.headerStorage = null;
20341
+ }
20342
+ }
20343
+ start() {
20344
+ if (this.stopping.signal.aborted) {
20345
+ if (this.activeRun)
20346
+ return;
20347
+ this.stopping = new AbortController;
20348
+ }
20349
+ if (!this.config.enabled) {
20350
+ logger2.info("Log cleanup service is disabled");
20351
+ return;
20352
+ }
20353
+ if (this.cleanupTimer) {
20354
+ logger2.warn("Log cleanup service is already running");
20355
+ return;
20356
+ }
20357
+ logger2.info({ config: this.getConfig() }, "Starting log cleanup service");
20358
+ this.initialCleanupTimer = setTimeout(() => {
20359
+ this.initialCleanupTimer = null;
20360
+ this.runCleanup().catch((error) => {
20361
+ if (!(error instanceof LogCleanupStopped))
20362
+ logger2.error({ error }, "Initial log cleanup failed");
20363
+ });
20364
+ }, 0);
20365
+ const intervalMs = this.config.scheduleIntervalHours * 60 * 60 * 1000;
20366
+ this.cleanupTimer = setInterval(() => {
20367
+ this.runCleanup().catch((error) => {
20368
+ if (!(error instanceof LogCleanupStopped))
20369
+ logger2.error({ error }, "Scheduled log cleanup failed");
20370
+ });
20371
+ }, intervalMs);
20372
+ logger2.info({ intervalHours: this.config.scheduleIntervalHours }, "Log cleanup service started");
20373
+ }
20374
+ async stop() {
20375
+ this.stopping.abort(new LogCleanupStopped);
20376
+ if (this.initialCleanupTimer !== null) {
20377
+ clearTimeout(this.initialCleanupTimer);
20378
+ this.initialCleanupTimer = null;
20379
+ }
20380
+ if (this.cleanupTimer) {
20381
+ clearInterval(this.cleanupTimer);
20382
+ this.cleanupTimer = null;
20383
+ logger2.info("Log cleanup service stopped");
20384
+ }
20385
+ await this.activeRun?.catch(() => {
20386
+ return;
20387
+ });
20388
+ }
20389
+ configure(config) {
20390
+ this.config = { ...this.config, ...config };
20391
+ }
20392
+ async runCleanup() {
20393
+ const { signal } = this.stopping;
20394
+ signal.throwIfAborted();
20395
+ if (this.activeRun)
20396
+ return this.activeRun;
20397
+ if (this.database === null || this.bodyStorage === null || this.headerStorage === null) {
20398
+ throw new Error("log cleanup dependencies are unavailable");
20399
+ }
20400
+ const startTime = Date.now();
20401
+ const config = this.getConfig();
20402
+ const database = this.database;
20403
+ const bodyStorage = this.bodyStorage;
20404
+ const headerStorage = this.headerStorage;
20405
+ const run = (async () => {
20406
+ try {
20407
+ logger2.info({ retentionDays: config.retentionDays }, "Starting log cleanup");
20408
+ const cutoffTime = startTime - config.retentionDays * LOG_RETENTION_DAY_MS;
20409
+ const deletedSqliteRecords = await this.cleanupDatabase(database, cutoffTime, signal);
20410
+ signal.throwIfAborted();
20411
+ const { deletedDirs: deletedBodyDirs, deletedFiles: deletedBodyFiles } = await bodyStorage.cleanup(cutoffTime, signal);
20412
+ signal.throwIfAborted();
20413
+ await headerStorage.cleanup(cutoffTime, signal);
20414
+ signal.throwIfAborted();
20415
+ const deletedFileLogFiles = 0;
20416
+ const durationMs = Date.now() - startTime;
20417
+ const result = {
20418
+ deletedSqliteRecords,
20419
+ deletedFileLogFiles,
20420
+ deletedBodyDirs,
20421
+ deletedBodyFiles,
20422
+ durationMs
20423
+ };
20424
+ logger2.info({ ...result, retentionDays: config.retentionDays }, "Log cleanup completed");
20425
+ return result;
20426
+ } catch (error) {
20427
+ if (!(error instanceof LogCleanupStopped))
20428
+ logger2.error({ error }, "Log cleanup failed");
20429
+ throw error;
20430
+ }
20431
+ })();
20432
+ this.activeRun = run;
20433
+ try {
20434
+ return await run;
20435
+ } finally {
20436
+ this.activeRun = null;
20437
+ }
20438
+ }
20439
+ async cleanupDatabase(database, cutoff, signal) {
20440
+ const { timeout } = database.query("PRAGMA busy_timeout").get();
20441
+ const bounds = await this.runSqliteStep(database, signal, timeout, true, () => {
20442
+ database.query("UPDATE request_log_retention SET cutoff=MAX(cutoff,?) WHERE id=1").run(cutoff);
20443
+ return database.query(`SELECT
20444
+ (SELECT CAST(MAX(id) AS TEXT) FROM access_logs) AS logs,
20445
+ (SELECT CAST(MAX(rowid) AS TEXT) FROM request_log_facts) AS facts`).get();
20446
+ });
20447
+ await new Promise((resolve) => setImmediate(resolve));
20448
+ const hasOldLogs = bounds.logs !== null && await this.runSqliteStep(database, signal, timeout, false, () => database.query("SELECT 1 FROM access_logs INDEXED BY idx_timestamp WHERE timestamp<? LIMIT 1").get(cutoff) !== null);
20449
+ let deletedLogs = 0;
20450
+ for (const [table, key, bound, columns, eligible] of [
20451
+ ["access_logs", "id", hasOldLogs ? bounds.logs : null, "timestamp, result_state", "timestamp<? AND result_state IS NOT 'running'"],
20452
+ ["request_log_facts", "rowid", bounds.facts, "received_at, facts", "CASE WHEN received_at<? THEN json_extract(facts,'$.init') IS NULL ELSE 0 END"]
20453
+ ]) {
20454
+ if (bound === null)
20455
+ continue;
20456
+ const last = BigInt(bound);
20457
+ for (let from = MIN_ROWID;from <= last; ) {
20458
+ const page = await this.runSqliteStep(database, signal, timeout, false, () => database.query(`SELECT CAST(MAX(page_key) AS TEXT) AS end,
20459
+ MAX(CASE WHEN ${eligible} THEN 1 ELSE 0 END) AS has_expired FROM
20460
+ (SELECT ${key} AS page_key, ${columns} FROM ${table} WHERE ${key} BETWEEN ? AND ? ORDER BY ${key} LIMIT ?)`).get(cutoff, from, last, BATCH_SIZE));
20461
+ if (page.end === null)
20462
+ break;
20463
+ const to = BigInt(page.end);
20464
+ if (page.has_expired === 1) {
20465
+ deletedLogs += await this.runSqliteStep(database, signal, timeout, true, () => {
20466
+ const expired = `${key} BETWEEN ? AND ? AND (${eligible})`;
20467
+ if (table === "access_logs") {
20468
+ database.query(`DELETE FROM request_log_facts INDEXED BY sqlite_autoindex_request_log_facts_1
20469
+ WHERE request_id IN (SELECT request_id FROM access_logs NOT INDEXED WHERE ${expired})`).run(from, to, cutoff);
20470
+ return database.query(`DELETE FROM access_logs NOT INDEXED WHERE ${expired}`).run(from, to, cutoff).changes;
20471
+ }
20472
+ database.query(`DELETE FROM request_log_facts WHERE ${expired}`).run(from, to, cutoff);
20473
+ return 0;
20474
+ });
20475
+ }
20476
+ from = to + 1n;
20477
+ await new Promise((resolve) => setImmediate(resolve));
20478
+ }
20479
+ }
20480
+ return deletedLogs;
20481
+ }
20482
+ async runSqliteStep(database, signal, timeout, transactional, operation) {
20483
+ signal.throwIfAborted();
20484
+ const deadline = performance.now() + timeout;
20485
+ for (;; ) {
20486
+ if (database.inTransaction)
20487
+ throw new Error("log_cleanup_requires_idle_connection");
20488
+ let began = false;
20489
+ let busyError;
20490
+ if (timeout !== 0)
20491
+ database.run("PRAGMA busy_timeout=0");
20492
+ try {
20493
+ if (transactional) {
20494
+ database.run("BEGIN IMMEDIATE");
20495
+ began = true;
20496
+ }
20497
+ const result = operation();
20498
+ if (began)
20499
+ database.run("COMMIT");
20500
+ return result;
20501
+ } catch (error) {
20502
+ const open = database.inTransaction;
20503
+ if (open) {
20504
+ try {
20505
+ database.run("ROLLBACK");
20506
+ } catch (rollbackError) {
20507
+ throw new AggregateError([error, rollbackError], "log_cleanup_rollback_failed");
20508
+ }
20509
+ }
20510
+ if (began && !open || database.inTransaction || !isSqliteBusyError(error)) {
20511
+ throw error;
20512
+ }
20513
+ busyError = error;
20514
+ } finally {
20515
+ if (timeout !== 0)
20516
+ database.run(`PRAGMA busy_timeout=${timeout}`);
20517
+ }
20518
+ const remaining = deadline - performance.now();
20519
+ if (remaining <= 0)
20520
+ throw busyError;
20521
+ await waitForRetry(Math.min(BUSY_RETRY_DELAY_MS, remaining), signal);
20522
+ signal.throwIfAborted();
20523
+ if (performance.now() >= deadline)
20524
+ throw busyError;
20525
+ }
20526
+ }
20527
+ getConfig() {
20528
+ return { ...this.config, retentionDays: this.readRetentionDays?.() ?? this.config.retentionDays };
20529
+ }
20530
+ isActive() {
20531
+ return this.cleanupTimer !== null;
20532
+ }
20533
+ }
20534
+
20493
20535
  // src/master-runtime/observability-worker.ts
20494
20536
  function headerEntries(headers) {
20495
20537
  const values = [];
@@ -20499,6 +20541,8 @@ function headerEntries(headers) {
20499
20541
  var scope = globalThis;
20500
20542
  var stats = null;
20501
20543
  var database = null;
20544
+ var cleanupDatabase = null;
20545
+ var cleanup = null;
20502
20546
  var accessLog;
20503
20547
  var accessFile;
20504
20548
  var accessLogLabel = "Ingress";
@@ -20554,7 +20598,65 @@ async function closeAccessLog() {
20554
20598
  accessLog = undefined;
20555
20599
  accessFile = undefined;
20556
20600
  }
20601
+ function openCleanup(path, retention) {
20602
+ if (cleanupDatabase)
20603
+ throw new Error("log_cleanup_already_open");
20604
+ const database = cleanupDatabase = new Database6(path, { create: false, readwrite: true });
20605
+ try {
20606
+ initializeAccessDatabaseConnection(database);
20607
+ const { bodyStorage, headerStorage } = createMasterLogStorage(path);
20608
+ const retentionBits = new DataView(new ArrayBuffer(8));
20609
+ cleanup = new LogCleanupService({
20610
+ database,
20611
+ bodyStorage,
20612
+ headerStorage,
20613
+ readRetentionDays() {
20614
+ retentionBits.setBigInt64(0, Atomics.load(retention, 0));
20615
+ return retentionBits.getFloat64(0);
20616
+ }
20617
+ });
20618
+ } catch (error) {
20619
+ try {
20620
+ database.close(true);
20621
+ cleanupDatabase = null;
20622
+ } catch (closeError) {
20623
+ throw new MasterStatsInitializationError(error, closeError);
20624
+ }
20625
+ throw error;
20626
+ }
20627
+ }
20628
+ async function closeCleanup(database) {
20629
+ const errors = [];
20630
+ try {
20631
+ await cleanup?.stop();
20632
+ } catch (error) {
20633
+ errors.push(error);
20634
+ }
20635
+ await Promise.allSettled([...operations]);
20636
+ try {
20637
+ database.close(true);
20638
+ } catch (error) {
20639
+ errors.push(error);
20640
+ }
20641
+ if (errors.length)
20642
+ throw Object.assign(new AggregateError(errors, "Log cleanup close failed"), { resourceUnreleased: true });
20643
+ cleanup = null;
20644
+ cleanupDatabase = null;
20645
+ }
20557
20646
  async function execute(method, args) {
20647
+ if (method === "openCleanup") {
20648
+ openCleanup(args[0], args[1]);
20649
+ return null;
20650
+ }
20651
+ if (cleanup) {
20652
+ if (method === "runCleanup")
20653
+ return cleanup.runCleanup();
20654
+ if (method === "startCleanup") {
20655
+ cleanup.start();
20656
+ return null;
20657
+ }
20658
+ throw new Error("unknown_log_cleanup_operation");
20659
+ }
20558
20660
  if (method === "migrate") {
20559
20661
  const settings = initializeAccessDatabaseForMaster(args[0]);
20560
20662
  const result = await new MigrationManager(args[0]).migrate();
@@ -20724,14 +20826,6 @@ async function execute(method, args) {
20724
20826
  throw new Error("observation_capability_unavailable");
20725
20827
  return await adapter[operation](...values) ?? null;
20726
20828
  }
20727
- if (method === "configure") {
20728
- stats.configureLogging?.(args[0]);
20729
- return null;
20730
- }
20731
- if (method === "cleanup") {
20732
- stats.startCleanup?.();
20733
- return null;
20734
- }
20735
20829
  if (method === "request") {
20736
20830
  if (bodies.size + creatingResponses >= 128)
20737
20831
  throw new Error("observability_response_capacity");
@@ -20778,13 +20872,21 @@ async function execute(method, args) {
20778
20872
  }
20779
20873
  scope.onmessage = (event) => {
20780
20874
  const { id, method, args } = event.data;
20781
- const reply = (work) => work.then((value) => scope.postMessage({ id, value }), (error) => scope.postMessage({ id, error: { code: "observability_storage_failure", message: error instanceof Error ? error.message : "storage failure", resourceUnreleased: error?.resourceUnreleased === true } }));
20875
+ const reply = (work) => work.then((value) => scope.postMessage({ id, value }), (error) => scope.postMessage({ id, error: {
20876
+ code: method === "runCleanup" && typeof error?.code === "string" ? error.code : "observability_storage_failure",
20877
+ message: error instanceof Error ? error.message : "storage failure",
20878
+ resourceUnreleased: error?.resourceUnreleased === true
20879
+ } }));
20782
20880
  if (closing) {
20783
20881
  reply(Promise.reject(new Error("observability_closing")));
20784
20882
  return;
20785
20883
  }
20786
20884
  if (method === "close") {
20787
20885
  closing = true;
20886
+ if (cleanupDatabase) {
20887
+ reply(closeCleanup(cleanupDatabase));
20888
+ return;
20889
+ }
20788
20890
  reply((async () => {
20789
20891
  await Promise.all([...bodies.values()].map(async (body) => {
20790
20892
  body.lifetime.abort();