target-supabase-sdk 0.2.12 → 0.2.14

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 (197) hide show
  1. package/dist/browser.d.ts +1 -1
  2. package/dist/browser.d.ts.map +1 -1
  3. package/dist/browser.js +1 -1
  4. package/dist/chunks/enable-C7lFooTG.js +874 -0
  5. package/dist/chunks/enable-C7lFooTG.js.map +1 -0
  6. package/dist/chunks/list.api-BzbTJBsM.js.map +1 -1
  7. package/dist/chunks/{task-queue-H4mpSW8R.js → task-queue-qSnsfiIg.js} +111 -4
  8. package/dist/chunks/task-queue-qSnsfiIg.js.map +1 -0
  9. package/dist/node/env/index.d.ts +1 -1
  10. package/dist/node/env/index.d.ts.map +1 -1
  11. package/dist/node/node-runtime.base.d.ts +14 -1
  12. package/dist/node/node-runtime.base.d.ts.map +1 -1
  13. package/dist/node/node.api.d.ts.map +1 -1
  14. package/dist/node/node.constant.d.ts +3 -0
  15. package/dist/node/node.constant.d.ts.map +1 -0
  16. package/dist/node/node.utils.d.ts +0 -2
  17. package/dist/node/node.utils.d.ts.map +1 -1
  18. package/dist/node/preload/run-service-preload.d.ts.map +1 -1
  19. package/dist/node/preload/service-preload.interface.d.ts +3 -1
  20. package/dist/node/preload/service-preload.interface.d.ts.map +1 -1
  21. package/dist/node/process/managed-child-processes.d.ts.map +1 -1
  22. package/dist/node/readiness/index.d.ts +2 -0
  23. package/dist/node/readiness/index.d.ts.map +1 -1
  24. package/dist/node/{service-guard → readiness}/run-readiness-gate.d.ts +1 -1
  25. package/dist/node/readiness/run-readiness-gate.d.ts.map +1 -0
  26. package/dist/node/readiness/service-ready-gate.d.ts.map +1 -1
  27. package/dist/node/runtime-state/create-service-runtime-state-store.d.ts.map +1 -1
  28. package/dist/node/runtime-state/service-runtime-state.types.d.ts +16 -0
  29. package/dist/node/runtime-state/service-runtime-state.types.d.ts.map +1 -1
  30. package/dist/node/service-guard/index.d.ts +4 -4
  31. package/dist/node/service-guard/index.d.ts.map +1 -1
  32. package/dist/node/service-guard/register-service-guard-runner.d.ts +1 -2
  33. package/dist/node/service-guard/register-service-guard-runner.d.ts.map +1 -1
  34. package/dist/node/service-guard/registry-slot-guard-step.d.ts.map +1 -0
  35. package/dist/node/service-guard/run-service-guard-tick.d.ts.map +1 -1
  36. package/dist/node/service-guard/service-guard-node.d.ts +25 -2
  37. package/dist/node/service-guard/service-guard-node.d.ts.map +1 -1
  38. package/dist/node/service-guard/service-guard.interface.d.ts +25 -10
  39. package/dist/node/service-guard/service-guard.interface.d.ts.map +1 -1
  40. package/dist/node/service-host/claim-registry-slot.d.ts +15 -0
  41. package/dist/node/service-host/claim-registry-slot.d.ts.map +1 -0
  42. package/dist/node/service-host/create-l3-child-launcher.d.ts +38 -0
  43. package/dist/node/service-host/create-l3-child-launcher.d.ts.map +1 -0
  44. package/dist/node/service-host/index.d.ts +2 -4
  45. package/dist/node/service-host/index.d.ts.map +1 -1
  46. package/dist/node/service-host/service-host.d.ts +8 -4
  47. package/dist/node/service-host/service-host.d.ts.map +1 -1
  48. package/dist/node/service-host/single-process-service.d.ts +3 -3
  49. package/dist/node/service-host/single-process-service.d.ts.map +1 -1
  50. package/dist/node.d.ts +17 -10
  51. package/dist/node.d.ts.map +1 -1
  52. package/dist/node.js +927 -119
  53. package/dist/node.js.map +1 -1
  54. package/dist/preload.js +9 -6
  55. package/dist/preload.js.map +1 -1
  56. package/dist/service/index.d.ts +2 -2
  57. package/dist/service/index.d.ts.map +1 -1
  58. package/dist/service/registry.service.d.ts +19 -0
  59. package/dist/service/registry.service.d.ts.map +1 -1
  60. package/dist/shared/log/core/create-logger.d.ts.map +1 -0
  61. package/dist/shared/log/{log-batch.d.ts → core/log-batch.d.ts} +4 -4
  62. package/dist/shared/log/core/log-batch.d.ts.map +1 -0
  63. package/dist/shared/log/core/log-manager.d.ts.map +1 -0
  64. package/dist/shared/log/core/log-min-level.d.ts.map +1 -0
  65. package/dist/shared/log/core/log-scope.d.ts.map +1 -0
  66. package/dist/shared/log/index.d.ts +13 -13
  67. package/dist/shared/log/index.d.ts.map +1 -1
  68. package/dist/shared/log/spool/collector.d.ts +21 -0
  69. package/dist/shared/log/spool/collector.d.ts.map +1 -0
  70. package/dist/shared/log/spool/config.d.ts +7 -0
  71. package/dist/shared/log/spool/config.d.ts.map +1 -0
  72. package/dist/shared/log/spool/coordinator.d.ts +18 -0
  73. package/dist/shared/log/spool/coordinator.d.ts.map +1 -0
  74. package/dist/shared/log/spool/enable.d.ts +23 -0
  75. package/dist/shared/log/spool/enable.d.ts.map +1 -0
  76. package/dist/shared/log/spool/file.d.ts +21 -0
  77. package/dist/shared/log/spool/file.d.ts.map +1 -0
  78. package/dist/shared/log/spool/interface.d.ts +55 -0
  79. package/dist/shared/log/spool/interface.d.ts.map +1 -0
  80. package/dist/shared/log/spool/paths.d.ts +6 -0
  81. package/dist/shared/log/spool/paths.d.ts.map +1 -0
  82. package/dist/shared/log/spool/process-roles.d.ts +17 -0
  83. package/dist/shared/log/spool/process-roles.d.ts.map +1 -0
  84. package/dist/shared/log/spool/register-collect-log-runner.d.ts +15 -0
  85. package/dist/shared/log/spool/register-collect-log-runner.d.ts.map +1 -0
  86. package/dist/shared/log/spool/service-lifecycle.d.ts +13 -0
  87. package/dist/shared/log/spool/service-lifecycle.d.ts.map +1 -0
  88. package/dist/shared/log/spool/writer.d.ts +32 -0
  89. package/dist/shared/log/spool/writer.d.ts.map +1 -0
  90. package/dist/shared/log/{log-persist-batch-id.d.ts → upload/batch-id.d.ts} +3 -3
  91. package/dist/shared/log/upload/batch-id.d.ts.map +1 -0
  92. package/dist/shared/log/upload/env.d.ts +7 -0
  93. package/dist/shared/log/upload/env.d.ts.map +1 -0
  94. package/dist/shared/log/{log-persist-flush.d.ts → upload/flush.d.ts} +3 -3
  95. package/dist/shared/log/upload/flush.d.ts.map +1 -0
  96. package/dist/shared/log/{log-persist-hook.d.ts → upload/hook.d.ts} +2 -2
  97. package/dist/shared/log/upload/hook.d.ts.map +1 -0
  98. package/dist/shared/log/upload/interface.d.ts +33 -0
  99. package/dist/shared/log/upload/interface.d.ts.map +1 -0
  100. package/dist/shared/log/upload/logger.d.ts +22 -0
  101. package/dist/shared/log/upload/logger.d.ts.map +1 -0
  102. package/package.json +1 -1
  103. package/src/browser.ts +1 -0
  104. package/src/node/env/index.ts +0 -4
  105. package/src/node/node-runtime.base.ts +33 -5
  106. package/src/node/node.api.ts +1 -1
  107. package/src/node/node.constant.ts +2 -0
  108. package/src/node/node.utils.ts +2 -2
  109. package/src/node/preload/run-service-preload.ts +11 -6
  110. package/src/node/preload/service-preload.interface.ts +3 -1
  111. package/src/node/process/create-managed-child-processes.ts +1 -1
  112. package/src/node/process/managed-child-processes.ts +8 -1
  113. package/src/node/readiness/index.ts +2 -0
  114. package/src/node/{service-guard → readiness}/run-readiness-gate.ts +2 -2
  115. package/src/node/readiness/service-ready-gate.ts +27 -23
  116. package/src/node/runtime-state/create-service-runtime-state-store.ts +11 -0
  117. package/src/node/runtime-state/service-runtime-state.types.ts +12 -0
  118. package/src/node/service-guard/index.ts +7 -8
  119. package/src/node/service-guard/register-service-guard-runner.ts +0 -2
  120. package/src/node/service-guard/run-service-guard-tick.ts +5 -2
  121. package/src/node/service-guard/service-guard-node.ts +234 -6
  122. package/src/node/service-guard/service-guard.interface.ts +35 -10
  123. package/src/node/service-host/claim-registry-slot.ts +33 -0
  124. package/src/node/service-host/create-l3-child-launcher.ts +157 -0
  125. package/src/node/service-host/index.ts +5 -20
  126. package/src/node/service-host/service-host.ts +33 -21
  127. package/src/node/service-host/single-process-service.ts +10 -20
  128. package/src/node.ts +45 -35
  129. package/src/service/index.ts +3 -0
  130. package/src/service/registry.service.ts +142 -0
  131. package/src/shared/log/README.md +206 -0
  132. package/src/shared/log/{log-batch.ts → core/log-batch.ts} +4 -4
  133. package/src/shared/log/{log-manager.ts → core/log-manager.ts} +3 -3
  134. package/src/shared/log/{log-min-level.ts → core/log-min-level.ts} +1 -1
  135. package/src/shared/log/{log-scope.ts → core/log-scope.ts} +1 -1
  136. package/src/shared/log/index.ts +13 -18
  137. package/src/shared/log/spool/collector.ts +330 -0
  138. package/src/shared/log/spool/config.ts +56 -0
  139. package/src/shared/log/spool/coordinator.ts +55 -0
  140. package/src/shared/log/spool/enable.ts +136 -0
  141. package/src/shared/log/spool/file.ts +75 -0
  142. package/src/shared/log/spool/interface.ts +62 -0
  143. package/src/shared/log/spool/paths.ts +30 -0
  144. package/src/shared/log/spool/process-roles.ts +75 -0
  145. package/src/shared/log/spool/register-collect-log-runner.ts +63 -0
  146. package/src/shared/log/spool/service-lifecycle.ts +35 -0
  147. package/src/shared/log/spool/writer.ts +273 -0
  148. package/src/shared/log/{log-persist-batch-id.ts → upload/batch-id.ts} +2 -2
  149. package/src/shared/log/upload/env.ts +26 -0
  150. package/src/shared/log/{log-persist-flush.ts → upload/flush.ts} +8 -7
  151. package/src/shared/log/{log-persist-hook.ts → upload/hook.ts} +1 -1
  152. package/src/shared/log/upload/interface.ts +38 -0
  153. package/src/shared/log/upload/logger.ts +37 -0
  154. package/dist/chunks/enable-log-persist-Dl55_mv2.js +0 -1674
  155. package/dist/chunks/enable-log-persist-Dl55_mv2.js.map +0 -1
  156. package/dist/chunks/task-queue-H4mpSW8R.js.map +0 -1
  157. package/dist/node/service-guard/run-readiness-gate.d.ts.map +0 -1
  158. package/dist/node/service-host/registry-slot-guard-step.d.ts.map +0 -1
  159. package/dist/shared/log/create-logger.d.ts.map +0 -1
  160. package/dist/shared/log/enable-log-persist.d.ts +0 -28
  161. package/dist/shared/log/enable-log-persist.d.ts.map +0 -1
  162. package/dist/shared/log/log-batch.d.ts.map +0 -1
  163. package/dist/shared/log/log-manager.d.ts.map +0 -1
  164. package/dist/shared/log/log-min-level.d.ts.map +0 -1
  165. package/dist/shared/log/log-persist-batch-id.d.ts.map +0 -1
  166. package/dist/shared/log/log-persist-coordinator.d.ts +0 -37
  167. package/dist/shared/log/log-persist-coordinator.d.ts.map +0 -1
  168. package/dist/shared/log/log-persist-errors.d.ts +0 -4
  169. package/dist/shared/log/log-persist-errors.d.ts.map +0 -1
  170. package/dist/shared/log/log-persist-flush.d.ts.map +0 -1
  171. package/dist/shared/log/log-persist-hook.d.ts.map +0 -1
  172. package/dist/shared/log/log-persist-logger.d.ts +0 -16
  173. package/dist/shared/log/log-persist-logger.d.ts.map +0 -1
  174. package/dist/shared/log/log-persist-registry.d.ts +0 -18
  175. package/dist/shared/log/log-persist-registry.d.ts.map +0 -1
  176. package/dist/shared/log/log-persist.config.d.ts +0 -9
  177. package/dist/shared/log/log-persist.config.d.ts.map +0 -1
  178. package/dist/shared/log/log-persist.d.ts +0 -62
  179. package/dist/shared/log/log-persist.d.ts.map +0 -1
  180. package/dist/shared/log/log-persist.interface.d.ts +0 -132
  181. package/dist/shared/log/log-persist.interface.d.ts.map +0 -1
  182. package/dist/shared/log/log-scope.d.ts.map +0 -1
  183. package/src/shared/log/enable-log-persist.ts +0 -225
  184. package/src/shared/log/log-persist-coordinator.ts +0 -107
  185. package/src/shared/log/log-persist-errors.ts +0 -16
  186. package/src/shared/log/log-persist-logger.ts +0 -61
  187. package/src/shared/log/log-persist-registry.ts +0 -252
  188. package/src/shared/log/log-persist.config.ts +0 -115
  189. package/src/shared/log/log-persist.interface.ts +0 -150
  190. package/src/shared/log/log-persist.ts +0 -822
  191. /package/dist/node/{service-host → service-guard}/registry-slot-guard-step.d.ts +0 -0
  192. /package/dist/shared/log/{create-logger.d.ts → core/create-logger.d.ts} +0 -0
  193. /package/dist/shared/log/{log-manager.d.ts → core/log-manager.d.ts} +0 -0
  194. /package/dist/shared/log/{log-min-level.d.ts → core/log-min-level.d.ts} +0 -0
  195. /package/dist/shared/log/{log-scope.d.ts → core/log-scope.d.ts} +0 -0
  196. /package/src/node/{service-host → service-guard}/registry-slot-guard-step.ts +0 -0
  197. /package/src/shared/log/{create-logger.ts → core/create-logger.ts} +0 -0
@@ -1,1674 +0,0 @@
1
- import { existsSync, readFileSync } from 'node:fs';
2
- import { resolve, dirname, join } from 'node:path';
3
- import { fileURLToPath } from 'node:url';
4
- import { readFile, unlink, mkdir, writeFile, rename, readdir } from 'node:fs/promises';
5
- import { g as createLogger, c as LOG_PERSIST_LOADER_KEY, a as CategoryList, D as postLogListCreate, q as isCreateTargetAlreadyExistsError, d as LogLevel, W as registerLogPersistOffer } from './list.api-BzbTJBsM.js';
6
- import 'lodash-es';
7
- import { randomBytes, createHash } from 'node:crypto';
8
-
9
- function readEnv(name, env = process.env) {
10
- const value = env[name]?.trim();
11
- if (value == null || value === "") {
12
- return undefined;
13
- }
14
- return value;
15
- }
16
- function requireEnv(name, env = process.env) {
17
- const value = readEnv(name, env);
18
- if (value == null) {
19
- throw new Error(`Missing required environment variable: ${name}`);
20
- }
21
- return value;
22
- }
23
-
24
- function envInt(name, defaultValue, options) {
25
- const env = options?.env ?? process.env;
26
- const raw = readEnv(name, env);
27
- if (raw == null) {
28
- return defaultValue;
29
- }
30
- const value = Number(raw);
31
- if (!Number.isInteger(value)) {
32
- throw new Error(`Invalid ${name}: ${raw}`);
33
- }
34
- const min = options?.min;
35
- if (min != null && value < min) {
36
- throw new Error(`Invalid ${name}: ${raw}`);
37
- }
38
- const max = options?.max;
39
- if (max != null && value > max) {
40
- throw new Error(`Invalid ${name}: ${raw}`);
41
- }
42
- return value;
43
- }
44
- function envMs(name, defaultMs, options) {
45
- return envInt(name, defaultMs, { ...options, min: options?.min ?? 1 });
46
- }
47
- function envPort(defaultPort = 3100, options) {
48
- const envKey = options?.envKey ?? "PORT";
49
- return envInt(envKey, defaultPort, { ...options, min: 1, max: 65535 });
50
- }
51
- function envNumber(name, defaultValue, options) {
52
- const env = options?.env ?? process.env;
53
- const raw = readEnv(name, env);
54
- if (raw == null) {
55
- return defaultValue;
56
- }
57
- const value = Number(raw);
58
- if (!Number.isFinite(value)) {
59
- throw new Error(`Invalid ${name}: ${raw}`);
60
- }
61
- const min = options?.min;
62
- const resolved = options?.floor === true ? Math.floor(value) : value;
63
- if (min != null && resolved < min) {
64
- throw new Error(`Invalid ${name}: ${raw}`);
65
- }
66
- return resolved;
67
- }
68
- function envBool(name, defaultValue = false, env = process.env) {
69
- const raw = readEnv(name, env)?.toLowerCase();
70
- if (raw == null) {
71
- return defaultValue;
72
- }
73
- return raw === "1" || raw === "true" || raw === "yes";
74
- }
75
-
76
- const DEFAULT_ENV_FILES = [".env.local", ".env"];
77
- const PROD_ENV_FILES = [".env.prod"];
78
- const SERVICE_ENV_PROFILE_ENV_KEY = "SERVICE_ENV_PROFILE";
79
- const SERVICE_ENV_PROFILE_PROD = "prod";
80
- const CLI_PROD_FLAG = "--prod";
81
- /** Resolve active env profile from `SERVICE_ENV_PROFILE` or `--prod` on argv. */
82
- function envProfileFromProcess(options) {
83
- const env = options?.env ?? process.env;
84
- const argv = options?.argv ?? process.argv;
85
- const fromEnv = env[SERVICE_ENV_PROFILE_ENV_KEY]?.trim();
86
- if (fromEnv != null && fromEnv !== "") {
87
- return fromEnv;
88
- }
89
- if (argv.includes(CLI_PROD_FLAG)) {
90
- return SERVICE_ENV_PROFILE_PROD;
91
- }
92
- return undefined;
93
- }
94
- /** Default env file list for a profile (`prod` → `.env.prod`; otherwise `.env.local` → `.env`). */
95
- function resolveDefaultEnvFiles(profile) {
96
- if (profile === SERVICE_ENV_PROFILE_PROD) {
97
- return PROD_ENV_FILES;
98
- }
99
- return DEFAULT_ENV_FILES;
100
- }
101
- /** Pin `SERVICE_ENV_PROFILE=prod` when `--prod` is on argv (for child process inheritance). */
102
- function pinEnvProfileFromArgv(env = process.env, argv = process.argv) {
103
- if (env[SERVICE_ENV_PROFILE_ENV_KEY]?.trim()) {
104
- return;
105
- }
106
- if (argv.includes(CLI_PROD_FLAG)) {
107
- env[SERVICE_ENV_PROFILE_ENV_KEY] = SERVICE_ENV_PROFILE_PROD;
108
- }
109
- }
110
- function stripQuotes(value) {
111
- return value.replace(/^["']|["']$/g, "");
112
- }
113
- /** Parse one KEY=VALUE line; returns null if line should be skipped. */
114
- function parseEnvLine(line) {
115
- const trimmed = line.trim();
116
- if (trimmed === "" || trimmed.startsWith("#")) {
117
- return null;
118
- }
119
- const eq = trimmed.indexOf("=");
120
- if (eq === -1) {
121
- return null;
122
- }
123
- const key = trimmed.slice(0, eq).trim();
124
- const raw = trimmed.slice(eq + 1).trim();
125
- return { key, value: stripQuotes(raw) };
126
- }
127
- function parseEnvFileContent(content, env) {
128
- for (const line of content.split("\n")) {
129
- const parsed = parseEnvLine(line);
130
- if (parsed == null) {
131
- continue;
132
- }
133
- if (env[parsed.key] == null || env[parsed.key] === "") {
134
- env[parsed.key] = parsed.value;
135
- }
136
- }
137
- }
138
- function parseEnvFile(filePath, env) {
139
- if (!existsSync(filePath)) {
140
- return;
141
- }
142
- parseEnvFileContent(readFileSync(filePath, "utf8"), env);
143
- }
144
- /**
145
- * Load env files into `process.env` (or `options.env`).
146
- * Default files: `.env.local` → `.env`, or `.env.prod` when profile is `prod` / `--prod`.
147
- * Existing non-empty env values are not overwritten.
148
- */
149
- function loadEnvFiles(root, options) {
150
- const env = options?.env ?? process.env;
151
- const files = options?.files ?? resolveDefaultEnvFiles(envProfileFromProcess({ env }));
152
- for (const name of files) {
153
- parseEnvFile(resolve(root, name), env);
154
- }
155
- options?.afterLoad?.();
156
- }
157
-
158
- /**
159
- * Resolve project root from a module URL (typically `import.meta.url`).
160
- * @param relativePath Path relative to the module file (default `".."` = parent directory).
161
- */
162
- function resolveProjectRootFromModule(importMetaUrl, relativePath = "..") {
163
- return resolve(fileURLToPath(new URL(relativePath, importMetaUrl)));
164
- }
165
- /**
166
- * Walk upward from `importMetaUrl` until a `package.json` with matching `name` is found.
167
- * Use for esbuild bundles under `dist/` where a single `..` hop lands in `dist/`, not repo root.
168
- */
169
- function resolveProjectRootByPackageName(importMetaUrl, packageName) {
170
- let dir = dirname(fileURLToPath(importMetaUrl));
171
- for (;;) {
172
- const packageJsonPath = resolve(dir, "package.json");
173
- if (existsSync(packageJsonPath)) {
174
- const pkg = JSON.parse(readFileSync(packageJsonPath, "utf8"));
175
- if (pkg.name === packageName) {
176
- return dir;
177
- }
178
- }
179
- const parent = dirname(dir);
180
- if (parent === dir) {
181
- break;
182
- }
183
- dir = parent;
184
- }
185
- throw new Error(`Could not find package root for "${packageName}" from ${importMetaUrl}`);
186
- }
187
-
188
- /** Per-file write queue — serializes read-modify-write for a single JSON path within one process. */
189
- const writeChains = new Map();
190
- function withSerializedFileWrites(filePath, operation) {
191
- const previous = writeChains.get(filePath) ?? Promise.resolve();
192
- const next = previous.then(operation, operation);
193
- writeChains.set(filePath, next.then(() => undefined, () => undefined));
194
- return next;
195
- }
196
-
197
- function mergeWithNested(defaults, current, patch, nestedKeys) {
198
- const merged = {
199
- ...defaults,
200
- ...current,
201
- ...patch,
202
- };
203
- for (const key of nestedKeys) {
204
- const defaultNested = defaults[key];
205
- if (defaultNested != null && typeof defaultNested === "object") {
206
- merged[key] = {
207
- ...defaultNested,
208
- ...current?.[key],
209
- ...patch[key],
210
- };
211
- }
212
- }
213
- return merged;
214
- }
215
- async function atomicWriteJson(filePath, data) {
216
- await mkdir(dirname(filePath), { recursive: true });
217
- const content = `${JSON.stringify(data, null, 2)}\n`;
218
- JSON.parse(content);
219
- const tempPath = `${filePath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
220
- try {
221
- await writeFile(tempPath, content, "utf8");
222
- await rename(tempPath, filePath);
223
- }
224
- catch (error) {
225
- await unlink(tempPath).catch(() => undefined);
226
- throw error;
227
- }
228
- }
229
- /** JSON file-backed state with optional nested key merge and atomic writes. */
230
- function createJsonFileStateStore(options) {
231
- const { filePath, defaultState, nestedKeys = [], updatedAtKey } = options;
232
- function touchUpdatedAt(state) {
233
- if (updatedAtKey == null) {
234
- return state;
235
- }
236
- return {
237
- ...state,
238
- [updatedAtKey]: new Date().toISOString(),
239
- };
240
- }
241
- async function readFromDisk() {
242
- try {
243
- const raw = await readFile(filePath, "utf8");
244
- const parsed = JSON.parse(raw);
245
- return mergeWithNested(defaultState, parsed, {}, nestedKeys);
246
- }
247
- catch (error) {
248
- if (error.code === "ENOENT") {
249
- return mergeWithNested(defaultState, {}, {}, nestedKeys);
250
- }
251
- if (error instanceof SyntaxError) {
252
- await unlink(filePath).catch(() => undefined);
253
- return mergeWithNested(defaultState, {}, {}, nestedKeys);
254
- }
255
- throw error;
256
- }
257
- }
258
- return {
259
- read() {
260
- return readFromDisk();
261
- },
262
- write(patch) {
263
- return withSerializedFileWrites(filePath, async () => {
264
- const current = await readFromDisk();
265
- const next = touchUpdatedAt(mergeWithNested(defaultState, current, patch, nestedKeys));
266
- await atomicWriteJson(filePath, next);
267
- return next;
268
- });
269
- },
270
- reset() {
271
- return withSerializedFileWrites(filePath, async () => {
272
- const next = touchUpdatedAt({ ...defaultState });
273
- await atomicWriteJson(filePath, next);
274
- return next;
275
- });
276
- },
277
- };
278
- }
279
-
280
- function sleep(ms) {
281
- return new Promise((resolve) => setTimeout(resolve, ms));
282
- }
283
- /**
284
- * Poll `until()` until it returns true or `timeoutMs` elapses.
285
- * @throws Error on timeout
286
- */
287
- async function pollUntil(options) {
288
- const intervalMs = options.intervalMs ?? 500;
289
- const deadline = Date.now() + options.timeoutMs;
290
- while (Date.now() < deadline) {
291
- if (await options.until()) {
292
- return;
293
- }
294
- await sleep(intervalMs);
295
- }
296
- throw new Error(`pollUntil timeout after ${options.timeoutMs}ms`);
297
- }
298
-
299
- const DEFAULT_LOG_PERSIST_CONFIG = {
300
- fast: {
301
- maxBufferEntries: 500,
302
- },
303
- medium: {
304
- debounceMs: 5_000,
305
- maxEntries: 20,
306
- maxBytes: 512 * 1024,
307
- maxBufferEntries: 1_000,
308
- },
309
- slow: {
310
- maxEntries: 400,
311
- maxBytes: 512 * 1024,
312
- maxAgeMs: 120_000,
313
- maxBufferEntries: 2_000,
314
- },
315
- postTimeoutMs: 30_000,
316
- shutdownDrainTimeoutMs: 15_000,
317
- laneRetryIntervalMs: 5_000,
318
- errorLogRateLimitMs: 5_000,
319
- circuitBreakerPermanentFailureThreshold: 3,
320
- };
321
- function resolveLogPersistConfig(partial) {
322
- const defaults = DEFAULT_LOG_PERSIST_CONFIG;
323
- return {
324
- fast: { ...defaults.fast, ...partial?.fast },
325
- medium: { ...defaults.medium, ...partial?.medium },
326
- slow: { ...defaults.slow, ...partial?.slow },
327
- postTimeoutMs: partial?.postTimeoutMs ?? defaults.postTimeoutMs,
328
- shutdownDrainTimeoutMs: partial?.shutdownDrainTimeoutMs ?? defaults.shutdownDrainTimeoutMs,
329
- laneRetryIntervalMs: partial?.laneRetryIntervalMs ?? defaults.laneRetryIntervalMs,
330
- errorLogRateLimitMs: partial?.errorLogRateLimitMs ?? defaults.errorLogRateLimitMs,
331
- circuitBreakerPermanentFailureThreshold: partial?.circuitBreakerPermanentFailureThreshold ?? defaults.circuitBreakerPermanentFailureThreshold,
332
- };
333
- }
334
- function logPersistEnabledFromEnv(env = process.env) {
335
- return envBool("LOG_PERSIST_ENABLED", false, env);
336
- }
337
- function logPersistServiceFromEnv(env = process.env) {
338
- const raw = env.LOG_PERSIST_SERVICE?.trim();
339
- return raw != null && raw !== "" ? raw : undefined;
340
- }
341
- function logPersistProcessFromEnv(env = process.env) {
342
- const raw = env.LOG_PERSIST_PROCESS?.trim();
343
- return raw != null && raw !== "" ? raw : undefined;
344
- }
345
- function logPersistRegistryDirFromEnv(env = process.env) {
346
- const configured = env.LOG_PERSIST_REGISTRY_DIR?.trim();
347
- if (configured != null && configured !== "") {
348
- return configured;
349
- }
350
- const runtime = env.RUNTIME_DATA_DIR?.trim();
351
- return runtime != null && runtime !== "" ? runtime : undefined;
352
- }
353
- function logPersistConfigFromEnv(env = process.env) {
354
- return resolveLogPersistConfig({
355
- fast: {
356
- maxBufferEntries: envInt("LOG_FAST_MAX_BUFFER_ENTRIES", DEFAULT_LOG_PERSIST_CONFIG.fast.maxBufferEntries, {
357
- env,
358
- min: 1,
359
- }),
360
- },
361
- medium: {
362
- debounceMs: envMs("LOG_MEDIUM_DEBOUNCE_MS", DEFAULT_LOG_PERSIST_CONFIG.medium.debounceMs, { env }),
363
- maxEntries: envInt("LOG_MEDIUM_MAX_ENTRIES", DEFAULT_LOG_PERSIST_CONFIG.medium.maxEntries, {
364
- env,
365
- min: 1,
366
- }),
367
- maxBytes: envInt("LOG_MEDIUM_MAX_BYTES", DEFAULT_LOG_PERSIST_CONFIG.medium.maxBytes, { env, min: 1 }),
368
- maxBufferEntries: envInt("LOG_MEDIUM_MAX_BUFFER_ENTRIES", DEFAULT_LOG_PERSIST_CONFIG.medium.maxBufferEntries, { env, min: 1 }),
369
- },
370
- slow: {
371
- maxEntries: envInt("LOG_SLOW_MAX_ENTRIES", DEFAULT_LOG_PERSIST_CONFIG.slow.maxEntries, { env, min: 1 }),
372
- maxBytes: envInt("LOG_SLOW_MAX_BYTES", DEFAULT_LOG_PERSIST_CONFIG.slow.maxBytes, { env, min: 1 }),
373
- maxAgeMs: envMs("LOG_SLOW_MAX_AGE_MS", DEFAULT_LOG_PERSIST_CONFIG.slow.maxAgeMs, { env }),
374
- maxBufferEntries: envInt("LOG_SLOW_MAX_BUFFER_ENTRIES", DEFAULT_LOG_PERSIST_CONFIG.slow.maxBufferEntries, {
375
- env,
376
- min: 1,
377
- }),
378
- },
379
- postTimeoutMs: envMs("LOG_PERSIST_POST_TIMEOUT_MS", DEFAULT_LOG_PERSIST_CONFIG.postTimeoutMs, { env }),
380
- shutdownDrainTimeoutMs: envMs("LOG_PERSIST_SHUTDOWN_DRAIN_MS", DEFAULT_LOG_PERSIST_CONFIG.shutdownDrainTimeoutMs, { env }),
381
- laneRetryIntervalMs: envMs("LOG_PERSIST_LANE_RETRY_MS", DEFAULT_LOG_PERSIST_CONFIG.laneRetryIntervalMs, {
382
- env,
383
- }),
384
- errorLogRateLimitMs: envMs("LOG_PERSIST_ERROR_LOG_RATE_LIMIT_MS", DEFAULT_LOG_PERSIST_CONFIG.errorLogRateLimitMs, { env }),
385
- circuitBreakerPermanentFailureThreshold: envInt("LOG_PERSIST_CIRCUIT_BREAKER_THRESHOLD", DEFAULT_LOG_PERSIST_CONFIG.circuitBreakerPermanentFailureThreshold, { env, min: 1 }),
386
- });
387
- }
388
-
389
- const BATCH_ID_VERSION = 1;
390
- /** Stable subset of LogEntry for idempotency hashing (same batch → same key). */
391
- function canonicalLogEntry(entry) {
392
- return {
393
- timestamp: entry.timestamp,
394
- level: entry.level,
395
- message: entry.message,
396
- topic: entry.topic,
397
- module: entry.module,
398
- traceId: entry.traceId,
399
- traceParentId: entry.traceParentId ?? null,
400
- extra: entry.extra ?? null,
401
- data: entry.data ?? null,
402
- labels: entry.labels ?? null,
403
- };
404
- }
405
- /**
406
- * Deterministic List.value for a log batch — retries after timeout map to the same row key.
407
- * SHA-256 over canonical JSON (service + process + lane + entries in order).
408
- */
409
- function computeLogBatchIdempotencyKey(input) {
410
- const payload = {
411
- v: BATCH_ID_VERSION,
412
- service: input.service,
413
- process: input.process,
414
- lane: input.lane,
415
- entries: input.entries.map(canonicalLogEntry),
416
- };
417
- const hash = createHash("sha256").update(JSON.stringify(payload), "utf8").digest("hex");
418
- return `${hash.slice(0, 32)}`;
419
- }
420
-
421
- const PERMANENT_LOG_PERSIST_ERROR_PATTERNS = [
422
- /not initialized/i,
423
- /call initialize\(\) first/i,
424
- /missing required supabase environment/i,
425
- /preload env incomplete/i,
426
- ];
427
- function formatLogPersistError(error) {
428
- return error instanceof Error ? error.message : String(error);
429
- }
430
- /** Errors that will not succeed on retry without fixing process configuration. */
431
- function isPermanentLogPersistError(error) {
432
- const message = formatLogPersistError(error);
433
- return PERMANENT_LOG_PERSIST_ERROR_PATTERNS.some((pattern) => pattern.test(message));
434
- }
435
-
436
- /** User-facing / lifecycle logs — may be persisted like normal app logs. */
437
- const LOG_PERSIST_TOPIC = "log-persist";
438
- /** Operational logs from the persist pipeline — never re-offered to avoid feedback loops. */
439
- const LOG_PERSIST_INTERNAL_TOPIC = "log-persist-internal";
440
- const logger = createLogger({ module: "log-persist" });
441
- let errorLogRateLimitMs = 5_000;
442
- const lastLoggedAt = new Map();
443
- function configurePersistLoggerRateLimit(ms) {
444
- errorLogRateLimitMs = Math.max(0, ms);
445
- }
446
- function isLogPersistInternalTopic(topic) {
447
- return topic === LOG_PERSIST_INTERNAL_TOPIC;
448
- }
449
- function shouldEmit(level, message) {
450
- if (level !== "error" && level !== "warn") {
451
- return true;
452
- }
453
- if (errorLogRateLimitMs <= 0) {
454
- return true;
455
- }
456
- const key = `${level}:${message}`;
457
- const now = Date.now();
458
- const last = lastLoggedAt.get(key);
459
- if (last != null && now - last < errorLogRateLimitMs) {
460
- return false;
461
- }
462
- lastLoggedAt.set(key, now);
463
- return true;
464
- }
465
- function write(level, message, data) {
466
- if (!shouldEmit(level, message)) {
467
- return;
468
- }
469
- logger[level](message, {
470
- topic: LOG_PERSIST_INTERNAL_TOPIC,
471
- ...(data != null ? { data } : {}),
472
- });
473
- }
474
- const persistLogger = {
475
- debug: (message, data) => write("debug", message, data),
476
- info: (message, data) => write("info", message, data),
477
- warn: (message, data) => write("warn", message, data),
478
- error: (message, data) => write("error", message, data),
479
- };
480
- function patchPersistLoggerScope(labels) {
481
- logger.resetScope({ labels });
482
- }
483
-
484
- function estimateEntriesBytes(entries) {
485
- if (entries.length === 0) {
486
- return 0;
487
- }
488
- try {
489
- return Buffer.byteLength(JSON.stringify(entries), "utf8");
490
- }
491
- catch {
492
- return entries.length * 512;
493
- }
494
- }
495
- function buildLogListDraft(input) {
496
- const { service, process, lane, idempotencyKey, entries } = input;
497
- const first = entries[0];
498
- const last = entries[entries.length - 1];
499
- return {
500
- name: `log-batch:${service}:${process}:${lane}`,
501
- value: idempotencyKey,
502
- category: CategoryList.LIST,
503
- tagList: ["log", lane, service],
504
- details: {
505
- manifestVersion: 0,
506
- loaderKey: LOG_PERSIST_LOADER_KEY,
507
- meta: {
508
- service,
509
- process,
510
- pid: globalThis.process.pid,
511
- lane,
512
- count: entries.length,
513
- from: first?.timestamp ?? null,
514
- to: last?.timestamp ?? null,
515
- flushedAt: Date.now(),
516
- idempotencyKey,
517
- },
518
- preview: first?.message ?? "",
519
- items: entries,
520
- },
521
- };
522
- }
523
- async function withTimeout(promise, timeoutMs, label) {
524
- let timer = null;
525
- try {
526
- return await Promise.race([
527
- promise,
528
- new Promise((_resolve, reject) => {
529
- timer = setTimeout(() => {
530
- reject(new Error(`${label} timed out after ${timeoutMs}ms`));
531
- }, timeoutMs);
532
- }),
533
- ]);
534
- }
535
- finally {
536
- if (timer != null) {
537
- clearTimeout(timer);
538
- }
539
- }
540
- }
541
- async function postLogBatch(draft, postTimeoutMs) {
542
- try {
543
- const result = await withTimeout(postLogListCreate({
544
- name: draft.name,
545
- value: draft.value,
546
- category: draft.category,
547
- details: draft.details,
548
- }), postTimeoutMs, "postLogListCreate");
549
- if (!result.success) {
550
- const message = result.error?.message ?? "postLogListCreate failed";
551
- persistLogger.error("post log batch failed", {
552
- idempotencyKey: draft.value,
553
- name: draft.name,
554
- error: message,
555
- });
556
- throw new Error(message);
557
- }
558
- }
559
- catch (error) {
560
- if (isCreateTargetAlreadyExistsError(error)) {
561
- persistLogger.error("post log batch idempotent duplicate — treating as success", {
562
- idempotencyKey: draft.value,
563
- name: draft.name,
564
- });
565
- return;
566
- }
567
- throw error;
568
- }
569
- }
570
- /** Take a prefix of entries that fits within maxBytes. */
571
- function takeEntriesWithinBytes(entries, maxBytes) {
572
- if (entries.length === 0) {
573
- return [];
574
- }
575
- const taken = [];
576
- for (const entry of entries) {
577
- const candidate = [...taken, entry];
578
- if (taken.length > 0 && estimateEntriesBytes(candidate) > maxBytes) {
579
- break;
580
- }
581
- taken.push(entry);
582
- }
583
- const result = taken.length > 0 ? taken : [entries[0]];
584
- if (result.length < entries.length) {
585
- persistLogger.warn("trimmed batch to maxBytes", {
586
- requested: entries.length,
587
- taken: result.length,
588
- maxBytes,
589
- takenBytes: estimateEntriesBytes(result),
590
- });
591
- }
592
- return result;
593
- }
594
-
595
- const DEFAULT_REGISTRY = {
596
- updatedAt: new Date(0).toISOString(),
597
- service: "",
598
- processes: {},
599
- };
600
- const DEFAULT_SHARD = {
601
- service: "",
602
- updatedAt: new Date(0).toISOString(),
603
- pid: 0,
604
- enabledAt: new Date(0).toISOString(),
605
- lastHeartbeatAt: new Date(0).toISOString(),
606
- };
607
- const legacyStores = new Map();
608
- const shardStores = new Map();
609
- function isLegacyRegistryFile(registryPath) {
610
- return registryPath.endsWith(".json");
611
- }
612
- function legacyStoreFor(filePath) {
613
- let store = legacyStores.get(filePath);
614
- if (store == null) {
615
- store = createJsonFileStateStore({
616
- filePath,
617
- defaultState: DEFAULT_REGISTRY,
618
- nestedKeys: ["processes"],
619
- updatedAtKey: "updatedAt",
620
- });
621
- legacyStores.set(filePath, store);
622
- }
623
- return store;
624
- }
625
- function shardStoreFor(shardFilePath) {
626
- let store = shardStores.get(shardFilePath);
627
- if (store == null) {
628
- store = createJsonFileStateStore({
629
- filePath: shardFilePath,
630
- defaultState: DEFAULT_SHARD,
631
- updatedAtKey: "updatedAt",
632
- });
633
- shardStores.set(shardFilePath, store);
634
- }
635
- return store;
636
- }
637
- function shardFilePath(registryDir, process) {
638
- return join(registryDir, `${process}.json`);
639
- }
640
- /** Registry root directory — one shard file per process under this path. */
641
- function defaultLogPersistRegistryPath(registryDir) {
642
- return join(registryDir, "log-persist-registry");
643
- }
644
- async function readShardedLogPersistRegistry(registryDir) {
645
- await mkdir(registryDir, { recursive: true });
646
- let entries;
647
- try {
648
- entries = await readdir(registryDir);
649
- }
650
- catch {
651
- return { ...DEFAULT_REGISTRY };
652
- }
653
- const processes = {};
654
- let service = "";
655
- let updatedAt = new Date(0).toISOString();
656
- for (const name of entries) {
657
- if (!name.endsWith(".json")) {
658
- continue;
659
- }
660
- const processName = name.slice(0, -".json".length);
661
- if (processName === "" || processName.startsWith("_")) {
662
- continue;
663
- }
664
- try {
665
- const raw = await readFile(join(registryDir, name), "utf8");
666
- const shard = JSON.parse(raw);
667
- if (shard.service != null && shard.service !== "") {
668
- service = shard.service;
669
- }
670
- if (shard.updatedAt != null && shard.updatedAt > updatedAt) {
671
- updatedAt = shard.updatedAt;
672
- }
673
- processes[processName] = {
674
- pid: shard.pid ?? 0,
675
- enabledAt: shard.enabledAt ?? new Date(0).toISOString(),
676
- lastHeartbeatAt: shard.lastHeartbeatAt ?? new Date(0).toISOString(),
677
- };
678
- }
679
- catch {
680
- persistLogger.warn("registry shard read skipped — corrupt or missing", {
681
- registryDir,
682
- shard: name,
683
- });
684
- }
685
- }
686
- return { updatedAt, service, processes };
687
- }
688
- async function registerLogPersistProcess(input) {
689
- const now = new Date().toISOString();
690
- const record = {
691
- pid: process.pid,
692
- enabledAt: now,
693
- lastHeartbeatAt: now,
694
- };
695
- if (isLegacyRegistryFile(input.registryFilePath)) {
696
- await legacyStoreFor(input.registryFilePath).write({
697
- service: input.service,
698
- processes: {
699
- [input.process]: record,
700
- },
701
- });
702
- }
703
- else {
704
- await shardStoreFor(shardFilePath(input.registryFilePath, input.process)).write({
705
- service: input.service,
706
- pid: record.pid,
707
- enabledAt: record.enabledAt,
708
- lastHeartbeatAt: record.lastHeartbeatAt,
709
- });
710
- }
711
- persistLogger.info("registry process registered", {
712
- registryFilePath: input.registryFilePath,
713
- service: input.service,
714
- process: input.process,
715
- pid: record.pid,
716
- });
717
- }
718
- async function heartbeatLogPersistProcess(input) {
719
- if (isLegacyRegistryFile(input.registryFilePath)) {
720
- const current = await legacyStoreFor(input.registryFilePath).read();
721
- const existing = current.processes[input.process];
722
- if (existing == null) {
723
- persistLogger.warn("registry heartbeat skipped — process not registered", {
724
- registryFilePath: input.registryFilePath,
725
- process: input.process,
726
- });
727
- return;
728
- }
729
- await legacyStoreFor(input.registryFilePath).write({
730
- processes: {
731
- [input.process]: {
732
- ...existing,
733
- lastHeartbeatAt: new Date().toISOString(),
734
- },
735
- },
736
- });
737
- return;
738
- }
739
- const store = shardStoreFor(shardFilePath(input.registryFilePath, input.process));
740
- const current = await store.read();
741
- if (current.pid === 0) {
742
- persistLogger.warn("registry heartbeat skipped — process not registered", {
743
- registryFilePath: input.registryFilePath,
744
- process: input.process,
745
- });
746
- return;
747
- }
748
- await store.write({
749
- lastHeartbeatAt: new Date().toISOString(),
750
- });
751
- }
752
- async function unregisterLogPersistProcess(input) {
753
- if (isLegacyRegistryFile(input.registryFilePath)) {
754
- const current = await legacyStoreFor(input.registryFilePath).read();
755
- const existing = current.processes[input.process];
756
- if (existing == null) {
757
- persistLogger.warn("registry unregister skipped — process not found", {
758
- registryFilePath: input.registryFilePath,
759
- process: input.process,
760
- });
761
- return;
762
- }
763
- await legacyStoreFor(input.registryFilePath).write({
764
- processes: {
765
- [input.process]: {
766
- ...existing,
767
- pid: 0,
768
- lastHeartbeatAt: new Date(0).toISOString(),
769
- },
770
- },
771
- });
772
- persistLogger.info("registry process unregistered", {
773
- registryFilePath: input.registryFilePath,
774
- process: input.process,
775
- });
776
- return;
777
- }
778
- const store = shardStoreFor(shardFilePath(input.registryFilePath, input.process));
779
- const current = await store.read();
780
- if (current.pid === 0) {
781
- persistLogger.warn("registry unregister skipped — process not found", {
782
- registryFilePath: input.registryFilePath,
783
- process: input.process,
784
- });
785
- return;
786
- }
787
- await store.write({
788
- pid: 0,
789
- lastHeartbeatAt: new Date(0).toISOString(),
790
- });
791
- persistLogger.info("registry process unregistered", {
792
- registryFilePath: input.registryFilePath,
793
- process: input.process,
794
- });
795
- }
796
- async function readLogPersistRegistry(registryFilePath) {
797
- if (isLegacyRegistryFile(registryFilePath)) {
798
- return legacyStoreFor(registryFilePath).read();
799
- }
800
- return readShardedLogPersistRegistry(registryFilePath);
801
- }
802
-
803
- var logPersistRegistry = /*#__PURE__*/Object.freeze({
804
- __proto__: null,
805
- defaultLogPersistRegistryPath: defaultLogPersistRegistryPath,
806
- heartbeatLogPersistProcess: heartbeatLogPersistProcess,
807
- readLogPersistRegistry: readLogPersistRegistry,
808
- registerLogPersistProcess: registerLogPersistProcess,
809
- unregisterLogPersistProcess: unregisterLogPersistProcess
810
- });
811
-
812
- const HEARTBEAT_INTERVAL_MS = 30_000;
813
- function routeLane(level) {
814
- if (level === LogLevel.CRITICAL) {
815
- return "fast";
816
- }
817
- if (level === LogLevel.ERROR || level === LogLevel.SUCCESS) {
818
- return "medium";
819
- }
820
- return "slow";
821
- }
822
- class LogPersist {
823
- static instance = null;
824
- enabled = false;
825
- draining = false;
826
- service = null;
827
- processName = null;
828
- registryFilePath = null;
829
- config = DEFAULT_LOG_PERSIST_CONFIG;
830
- fastQueue = [];
831
- fastRetryQueue = [];
832
- mediumQueue = [];
833
- slowQueue = [];
834
- mediumDebounceTimer = null;
835
- slowQueueStartedAt = null;
836
- fastRetryTimer = null;
837
- mediumRetryTimer = null;
838
- slowRetryTimer = null;
839
- heartbeatTimer = null;
840
- lastHeartbeatAt = 0;
841
- permanentFailureCount = 0;
842
- circuitBreakerTripped = false;
843
- laneFlushing = {
844
- fast: false,
845
- medium: false,
846
- slow: false,
847
- };
848
- consecutiveFailures = {
849
- fast: 0,
850
- medium: 0,
851
- slow: 0,
852
- };
853
- lastFlushAt = {
854
- fast: null,
855
- medium: null,
856
- slow: null,
857
- };
858
- lastError = null;
859
- lastErrorAt = null;
860
- shutdownHookInstalled = false;
861
- shutdownPromise = null;
862
- static getInstance() {
863
- LogPersist.instance ??= new LogPersist();
864
- return LogPersist.instance;
865
- }
866
- async enable(options) {
867
- if (this.enabled) {
868
- persistLogger.warn("log persist core enable skipped — already enabled", {
869
- service: this.service,
870
- process: this.processName,
871
- });
872
- return;
873
- }
874
- this.service = options.service;
875
- this.processName = options.process;
876
- this.registryFilePath = options.registryFilePath ?? null;
877
- this.config = resolveLogPersistConfig(options.config);
878
- configurePersistLoggerRateLimit(this.config.errorLogRateLimitMs);
879
- this.draining = false;
880
- this.shutdownPromise = null;
881
- this.consecutiveFailures = { fast: 0, medium: 0, slow: 0 };
882
- this.permanentFailureCount = 0;
883
- this.circuitBreakerTripped = false;
884
- this.lastError = null;
885
- this.lastErrorAt = null;
886
- this.enabled = true;
887
- patchPersistLoggerScope({
888
- service: options.service,
889
- process: options.process,
890
- });
891
- persistLogger.info("log persist core enabled", {
892
- service: options.service,
893
- process: options.process,
894
- registryFilePath: this.registryFilePath,
895
- config: this.config,
896
- pid: process.pid,
897
- });
898
- registerLogPersistOffer((entry) => {
899
- this.offer(entry);
900
- });
901
- if (this.registryFilePath != null) {
902
- const { registerLogPersistProcess } = await Promise.resolve().then(function () { return logPersistRegistry; });
903
- await registerLogPersistProcess({
904
- registryFilePath: this.registryFilePath,
905
- service: options.service,
906
- process: options.process,
907
- });
908
- this.startHeartbeat();
909
- }
910
- this.installShutdownHook();
911
- }
912
- async disable() {
913
- if (!this.enabled && !this.draining) {
914
- persistLogger.debug("disable skipped — not enabled");
915
- return;
916
- }
917
- persistLogger.info("log persist core disabling", this.queueSnapshot());
918
- this.cancelMediumDebounce();
919
- this.cancelLaneRetryTimers();
920
- this.stopHeartbeat();
921
- await this.shutdown();
922
- persistLogger.info("log persist core disabled");
923
- }
924
- offer(entry) {
925
- if (isLogPersistInternalTopic(entry.topic)) {
926
- return;
927
- }
928
- if (!this.enabled || this.draining || this.service == null || this.processName == null) {
929
- return;
930
- }
931
- void this.touchRegistryHeartbeat();
932
- const lane = routeLane(entry.level);
933
- if (lane === "fast") {
934
- this.fastQueue.push(entry);
935
- this.evictFastOverflow();
936
- void this.flushFast();
937
- return;
938
- }
939
- if (lane === "medium") {
940
- this.mediumQueue.push(entry);
941
- this.evictMediumOverflow();
942
- this.scheduleMediumFlush();
943
- return;
944
- }
945
- this.slowQueue.push(entry);
946
- if (this.slowQueueStartedAt == null) {
947
- this.slowQueueStartedAt = Date.now();
948
- }
949
- this.evictSlowOverflow();
950
- this.scheduleSlowFlush();
951
- }
952
- getStats() {
953
- return {
954
- enabled: this.enabled,
955
- draining: this.draining,
956
- circuitBreakerTripped: this.circuitBreakerTripped,
957
- permanentFailureCount: this.permanentFailureCount,
958
- service: this.service,
959
- process: this.processName,
960
- queues: {
961
- fast: this.fastQueue.length,
962
- fastRetry: this.fastRetryQueue.length,
963
- medium: this.mediumQueue.length,
964
- slow: this.slowQueue.length,
965
- },
966
- queueBytes: {
967
- fast: estimateEntriesBytes(this.fastQueue),
968
- fastRetry: estimateEntriesBytes(this.fastRetryQueue),
969
- medium: estimateEntriesBytes(this.mediumQueue),
970
- slow: estimateEntriesBytes(this.slowQueue),
971
- },
972
- mediumDebouncePending: this.mediumDebounceTimer != null,
973
- laneFlushing: { ...this.laneFlushing },
974
- consecutiveFailures: { ...this.consecutiveFailures },
975
- config: this.config,
976
- lastFlushAt: { ...this.lastFlushAt },
977
- lastError: this.lastError,
978
- lastErrorAt: this.lastErrorAt,
979
- };
980
- }
981
- async shutdown() {
982
- if (this.shutdownPromise != null) {
983
- return this.shutdownPromise;
984
- }
985
- this.shutdownPromise = this.shutdownInner();
986
- return this.shutdownPromise;
987
- }
988
- async shutdownInner() {
989
- if (this.draining) {
990
- return;
991
- }
992
- this.draining = true;
993
- this.enabled = false;
994
- registerLogPersistOffer(null);
995
- persistLogger.info("shutdown flush started", this.queueSnapshot());
996
- this.cancelMediumDebounce();
997
- await this.drainQueues(this.config.shutdownDrainTimeoutMs);
998
- if (this.registryFilePath != null && this.processName != null) {
999
- const { unregisterLogPersistProcess } = await Promise.resolve().then(function () { return logPersistRegistry; });
1000
- await unregisterLogPersistProcess({
1001
- registryFilePath: this.registryFilePath,
1002
- process: this.processName,
1003
- });
1004
- }
1005
- if (this.hasQueued()) {
1006
- persistLogger.warn("shutdown drain incomplete — queued logs dropped", {
1007
- ...this.queueSnapshot(),
1008
- shutdownDrainTimeoutMs: this.config.shutdownDrainTimeoutMs,
1009
- });
1010
- this.fastQueue = [];
1011
- this.fastRetryQueue = [];
1012
- this.mediumQueue = [];
1013
- this.slowQueue = [];
1014
- this.slowQueueStartedAt = null;
1015
- }
1016
- persistLogger.info("shutdown flush completed", this.queueSnapshot());
1017
- }
1018
- hasQueued() {
1019
- return (this.fastQueue.length > 0 ||
1020
- this.fastRetryQueue.length > 0 ||
1021
- this.mediumQueue.length > 0 ||
1022
- this.slowQueue.length > 0);
1023
- }
1024
- async drainQueues(timeoutMs) {
1025
- const deadline = Date.now() + timeoutMs;
1026
- while (this.hasQueued() && Date.now() < deadline) {
1027
- await this.flushFast();
1028
- await this.flushMedium();
1029
- await this.flushSlow();
1030
- }
1031
- }
1032
- recordLaneError(lane, error) {
1033
- const message = error instanceof Error ? error.message : String(error);
1034
- this.lastError = message;
1035
- this.lastErrorAt = new Date().toISOString();
1036
- this.consecutiveFailures[lane] += 1;
1037
- }
1038
- recordLaneSuccess(lane) {
1039
- this.lastError = null;
1040
- this.consecutiveFailures[lane] = 0;
1041
- this.permanentFailureCount = 0;
1042
- }
1043
- handleLaneFlushFailure(lane, error, scheduleRetry, logMessage, context) {
1044
- this.recordLaneError(lane, error);
1045
- const message = this.lastError ?? formatLogPersistError(error);
1046
- if (isPermanentLogPersistError(error)) {
1047
- this.permanentFailureCount += 1;
1048
- if (this.permanentFailureCount >= this.config.circuitBreakerPermanentFailureThreshold) {
1049
- this.tripCircuitBreaker(message);
1050
- return;
1051
- }
1052
- }
1053
- persistLogger.error(logMessage, {
1054
- ...context,
1055
- error: message,
1056
- retryInMs: this.config.laneRetryIntervalMs,
1057
- permanentFailureCount: this.permanentFailureCount,
1058
- });
1059
- scheduleRetry();
1060
- }
1061
- tripCircuitBreaker(reason) {
1062
- if (this.circuitBreakerTripped) {
1063
- return;
1064
- }
1065
- this.circuitBreakerTripped = true;
1066
- this.cancelMediumDebounce();
1067
- this.cancelLaneRetryTimers();
1068
- this.stopHeartbeat();
1069
- const dropped = this.queueSnapshot();
1070
- this.fastQueue = [];
1071
- this.fastRetryQueue = [];
1072
- this.mediumQueue = [];
1073
- this.slowQueue = [];
1074
- this.slowQueueStartedAt = null;
1075
- this.enabled = false;
1076
- registerLogPersistOffer(null);
1077
- persistLogger.error("circuit breaker tripped — log persist disabled", {
1078
- reason,
1079
- permanentFailureCount: this.permanentFailureCount,
1080
- threshold: this.config.circuitBreakerPermanentFailureThreshold,
1081
- dropped,
1082
- });
1083
- }
1084
- cancelLaneRetryTimers() {
1085
- if (this.fastRetryTimer != null) {
1086
- clearTimeout(this.fastRetryTimer);
1087
- this.fastRetryTimer = null;
1088
- }
1089
- if (this.mediumRetryTimer != null) {
1090
- clearTimeout(this.mediumRetryTimer);
1091
- this.mediumRetryTimer = null;
1092
- }
1093
- if (this.slowRetryTimer != null) {
1094
- clearTimeout(this.slowRetryTimer);
1095
- this.slowRetryTimer = null;
1096
- }
1097
- }
1098
- scheduleLaneRetry(lane, flush) {
1099
- const retryMs = this.config.laneRetryIntervalMs;
1100
- const existing = lane === "fast" ? this.fastRetryTimer : lane === "medium" ? this.mediumRetryTimer : this.slowRetryTimer;
1101
- if (existing != null) {
1102
- return;
1103
- }
1104
- persistLogger.warn(`${lane} flush retry scheduled`, { retryInMs: retryMs });
1105
- const timer = setTimeout(() => {
1106
- if (lane === "fast") {
1107
- this.fastRetryTimer = null;
1108
- }
1109
- else if (lane === "medium") {
1110
- this.mediumRetryTimer = null;
1111
- }
1112
- else {
1113
- this.slowRetryTimer = null;
1114
- }
1115
- persistLogger.debug(`${lane} flush retry timer fired`);
1116
- flush();
1117
- }, retryMs);
1118
- timer.unref?.();
1119
- if (lane === "fast") {
1120
- this.fastRetryTimer = timer;
1121
- }
1122
- else if (lane === "medium") {
1123
- this.mediumRetryTimer = timer;
1124
- }
1125
- else {
1126
- this.slowRetryTimer = timer;
1127
- }
1128
- }
1129
- queueSnapshot() {
1130
- return {
1131
- queues: {
1132
- fast: this.fastQueue.length,
1133
- fastRetry: this.fastRetryQueue.length,
1134
- medium: this.mediumQueue.length,
1135
- slow: this.slowQueue.length,
1136
- },
1137
- queueBytes: {
1138
- fast: estimateEntriesBytes(this.fastQueue),
1139
- fastRetry: estimateEntriesBytes(this.fastRetryQueue),
1140
- medium: estimateEntriesBytes(this.mediumQueue),
1141
- slow: estimateEntriesBytes(this.slowQueue),
1142
- },
1143
- laneFlushing: { ...this.laneFlushing },
1144
- consecutiveFailures: { ...this.consecutiveFailures },
1145
- lastError: this.lastError,
1146
- };
1147
- }
1148
- installShutdownHook() {
1149
- if (this.shutdownHookInstalled) {
1150
- return;
1151
- }
1152
- this.shutdownHookInstalled = true;
1153
- const handler = (signal) => {
1154
- persistLogger.info("shutdown signal received", { signal });
1155
- void this.shutdown();
1156
- };
1157
- process.once("SIGTERM", handler);
1158
- process.once("SIGINT", handler);
1159
- }
1160
- startHeartbeat() {
1161
- this.stopHeartbeat();
1162
- this.heartbeatTimer = setInterval(() => {
1163
- void this.touchRegistryHeartbeat(true);
1164
- }, HEARTBEAT_INTERVAL_MS);
1165
- this.heartbeatTimer.unref?.();
1166
- }
1167
- stopHeartbeat() {
1168
- if (this.heartbeatTimer != null) {
1169
- clearInterval(this.heartbeatTimer);
1170
- this.heartbeatTimer = null;
1171
- }
1172
- }
1173
- async touchRegistryHeartbeat(force = false) {
1174
- if (this.registryFilePath == null || this.processName == null) {
1175
- return;
1176
- }
1177
- const now = Date.now();
1178
- if (!force && now - this.lastHeartbeatAt < HEARTBEAT_INTERVAL_MS) {
1179
- return;
1180
- }
1181
- this.lastHeartbeatAt = now;
1182
- await heartbeatLogPersistProcess({
1183
- registryFilePath: this.registryFilePath,
1184
- process: this.processName,
1185
- });
1186
- }
1187
- scheduleMediumFlush() {
1188
- if (this.mediumRetryTimer != null) {
1189
- return;
1190
- }
1191
- const { debounceMs, maxEntries, maxBytes } = this.config.medium;
1192
- const queueBytes = estimateEntriesBytes(this.mediumQueue);
1193
- if (this.mediumQueue.length >= maxEntries || queueBytes >= maxBytes) {
1194
- persistLogger.warn("medium flush scheduled — threshold", {
1195
- reason: this.mediumQueue.length >= maxEntries ? "maxEntries" : "maxBytes",
1196
- queueLength: this.mediumQueue.length,
1197
- maxEntries,
1198
- queueBytes,
1199
- maxBytes,
1200
- });
1201
- this.cancelMediumDebounce();
1202
- void this.flushMedium();
1203
- return;
1204
- }
1205
- if (this.mediumDebounceTimer == null && this.mediumQueue.length > 0) {
1206
- persistLogger.debug("medium flush debounce scheduled", {
1207
- debounceMs,
1208
- queueLength: this.mediumQueue.length,
1209
- queueBytes,
1210
- });
1211
- this.mediumDebounceTimer = setTimeout(() => {
1212
- this.mediumDebounceTimer = null;
1213
- persistLogger.debug("medium flush debounce fired");
1214
- void this.flushMedium();
1215
- }, debounceMs);
1216
- this.mediumDebounceTimer.unref?.();
1217
- }
1218
- }
1219
- cancelMediumDebounce() {
1220
- if (this.mediumDebounceTimer != null) {
1221
- clearTimeout(this.mediumDebounceTimer);
1222
- this.mediumDebounceTimer = null;
1223
- persistLogger.debug("medium flush debounce cancelled");
1224
- }
1225
- }
1226
- scheduleSlowFlush() {
1227
- if (this.slowRetryTimer != null) {
1228
- return;
1229
- }
1230
- const { maxEntries, maxBytes, maxAgeMs } = this.config.slow;
1231
- const queueBytes = estimateEntriesBytes(this.slowQueue);
1232
- const ageMs = this.slowQueueStartedAt != null ? Date.now() - this.slowQueueStartedAt : 0;
1233
- if (this.slowQueue.length >= maxEntries || queueBytes >= maxBytes || ageMs >= maxAgeMs) {
1234
- persistLogger.debug("slow flush scheduled — threshold", {
1235
- reason: this.slowQueue.length >= maxEntries
1236
- ? "maxEntries"
1237
- : queueBytes >= maxBytes
1238
- ? "maxBytes"
1239
- : "maxAgeMs",
1240
- queueLength: this.slowQueue.length,
1241
- maxEntries,
1242
- queueBytes,
1243
- maxBytes,
1244
- ageMs,
1245
- maxAgeMs,
1246
- });
1247
- void this.flushSlow();
1248
- }
1249
- }
1250
- evictFastOverflow() {
1251
- const { maxBufferEntries } = this.config.fast;
1252
- let evicted = 0;
1253
- while (this.fastQueue.length + this.fastRetryQueue.length > maxBufferEntries) {
1254
- const removed = this.fastQueue.length > 0 ? this.fastQueue.shift() : this.fastRetryQueue.shift();
1255
- evicted += 1;
1256
- persistLogger.warn("fast queue overflow — evicted entry", {
1257
- evictedLevel: removed?.level,
1258
- evictedTopic: removed?.topic,
1259
- fromRetryQueue: this.fastQueue.length === 0,
1260
- maxBufferEntries,
1261
- });
1262
- }
1263
- if (evicted > 0) {
1264
- persistLogger.warn("fast queue overflow summary", { evicted, maxBufferEntries });
1265
- }
1266
- }
1267
- evictMediumOverflow() {
1268
- const { maxBufferEntries } = this.config.medium;
1269
- let evicted = 0;
1270
- while (this.mediumQueue.length > maxBufferEntries) {
1271
- const successIndex = this.mediumQueue.findIndex((entry) => entry.level === LogLevel.SUCCESS);
1272
- const removed = successIndex >= 0 ? this.mediumQueue.splice(successIndex, 1)[0] : this.mediumQueue.shift();
1273
- evicted += 1;
1274
- persistLogger.warn("medium queue overflow — evicted entry", {
1275
- evictedLevel: removed?.level,
1276
- evictedTopic: removed?.topic,
1277
- queueLength: this.mediumQueue.length,
1278
- maxBufferEntries,
1279
- });
1280
- }
1281
- if (evicted > 0) {
1282
- persistLogger.warn("medium queue overflow summary", {
1283
- evicted,
1284
- queueLength: this.mediumQueue.length,
1285
- maxBufferEntries,
1286
- });
1287
- }
1288
- }
1289
- evictSlowOverflow() {
1290
- const { maxBufferEntries } = this.config.slow;
1291
- let evicted = 0;
1292
- while (this.slowQueue.length > maxBufferEntries) {
1293
- const debugIndex = this.slowQueue.findIndex((entry) => entry.level === LogLevel.DEBUG);
1294
- const removed = debugIndex >= 0 ? this.slowQueue.splice(debugIndex, 1)[0] : this.slowQueue.shift();
1295
- evicted += 1;
1296
- persistLogger.warn("slow queue overflow — evicted entry", {
1297
- evictedLevel: removed?.level,
1298
- evictedTopic: removed?.topic,
1299
- queueLength: this.slowQueue.length,
1300
- maxBufferEntries,
1301
- });
1302
- }
1303
- if (evicted > 0) {
1304
- persistLogger.warn("slow queue overflow summary", {
1305
- evicted,
1306
- queueLength: this.slowQueue.length,
1307
- maxBufferEntries,
1308
- });
1309
- }
1310
- if (this.slowQueue.length === 0) {
1311
- this.slowQueueStartedAt = null;
1312
- }
1313
- }
1314
- async flushFast() {
1315
- if (this.laneFlushing.fast) {
1316
- persistLogger.debug("fast flush skipped — already flushing");
1317
- return;
1318
- }
1319
- if (this.service == null || this.processName == null) {
1320
- return;
1321
- }
1322
- this.laneFlushing.fast = true;
1323
- try {
1324
- while (this.fastQueue.length > 0 || this.fastRetryQueue.length > 0) {
1325
- const fromRetry = this.fastQueue.length === 0;
1326
- const entry = this.fastQueue.shift() ?? this.fastRetryQueue.shift();
1327
- if (entry == null) {
1328
- break;
1329
- }
1330
- const idempotencyKey = computeLogBatchIdempotencyKey({
1331
- service: this.service,
1332
- process: this.processName,
1333
- lane: "fast",
1334
- entries: [entry],
1335
- });
1336
- try {
1337
- const draft = buildLogListDraft({
1338
- service: this.service,
1339
- process: this.processName,
1340
- lane: "fast",
1341
- idempotencyKey,
1342
- entries: [entry],
1343
- });
1344
- persistLogger.debug("fast flush posting batch", {
1345
- idempotencyKey,
1346
- fromRetry,
1347
- level: entry.level,
1348
- topic: entry.topic,
1349
- });
1350
- await postLogBatch(draft, this.config.postTimeoutMs);
1351
- this.lastFlushAt.fast = new Date().toISOString();
1352
- this.recordLaneSuccess("fast");
1353
- persistLogger.info("fast lane flushed", {
1354
- idempotencyKey,
1355
- level: entry.level,
1356
- topic: entry.topic,
1357
- fastRetryRemaining: this.fastRetryQueue.length,
1358
- });
1359
- }
1360
- catch (error) {
1361
- this.fastRetryQueue.push(entry);
1362
- this.handleLaneFlushFailure("fast", error, () => this.scheduleLaneRetry("fast", () => void this.flushFast()), "fast flush failed — queued for retry", {
1363
- idempotencyKey,
1364
- fastRetryQueue: this.fastRetryQueue.length,
1365
- });
1366
- break;
1367
- }
1368
- }
1369
- }
1370
- finally {
1371
- this.laneFlushing.fast = false;
1372
- }
1373
- }
1374
- async flushMedium() {
1375
- if (this.laneFlushing.medium) {
1376
- persistLogger.debug("medium flush skipped — already flushing");
1377
- return;
1378
- }
1379
- if (this.mediumQueue.length === 0) {
1380
- return;
1381
- }
1382
- if (this.service == null || this.processName == null) {
1383
- return;
1384
- }
1385
- this.laneFlushing.medium = true;
1386
- try {
1387
- while (this.mediumQueue.length > 0) {
1388
- const batch = takeEntriesWithinBytes(this.mediumQueue, this.config.medium.maxBytes);
1389
- if (batch.length === 0) {
1390
- break;
1391
- }
1392
- const idempotencyKey = computeLogBatchIdempotencyKey({
1393
- service: this.service,
1394
- process: this.processName,
1395
- lane: "medium",
1396
- entries: batch,
1397
- });
1398
- const batchBytes = estimateEntriesBytes(batch);
1399
- try {
1400
- persistLogger.debug("medium flush posting batch", {
1401
- idempotencyKey,
1402
- batchSize: batch.length,
1403
- batchBytes,
1404
- queueRemaining: this.mediumQueue.length,
1405
- });
1406
- const draft = buildLogListDraft({
1407
- service: this.service,
1408
- process: this.processName,
1409
- lane: "medium",
1410
- idempotencyKey,
1411
- entries: batch,
1412
- });
1413
- await postLogBatch(draft, this.config.postTimeoutMs);
1414
- this.mediumQueue.splice(0, batch.length);
1415
- this.lastFlushAt.medium = new Date().toISOString();
1416
- this.recordLaneSuccess("medium");
1417
- persistLogger.info("medium lane flushed", {
1418
- idempotencyKey,
1419
- batchSize: batch.length,
1420
- batchBytes,
1421
- queueRemaining: this.mediumQueue.length,
1422
- });
1423
- }
1424
- catch (error) {
1425
- this.handleLaneFlushFailure("medium", error, () => this.scheduleLaneRetry("medium", () => void this.flushMedium()), "medium flush failed — entries retained", {
1426
- idempotencyKey,
1427
- batchSize: batch.length,
1428
- batchBytes,
1429
- queueRemaining: this.mediumQueue.length,
1430
- });
1431
- break;
1432
- }
1433
- }
1434
- }
1435
- finally {
1436
- this.laneFlushing.medium = false;
1437
- }
1438
- if (this.mediumQueue.length > 0 && !this.laneFlushing.medium && this.mediumRetryTimer == null) {
1439
- this.scheduleMediumFlush();
1440
- }
1441
- }
1442
- async flushSlow() {
1443
- if (this.laneFlushing.slow) {
1444
- persistLogger.debug("slow flush skipped — already flushing");
1445
- return;
1446
- }
1447
- if (this.slowQueue.length === 0) {
1448
- return;
1449
- }
1450
- if (this.service == null || this.processName == null) {
1451
- return;
1452
- }
1453
- this.laneFlushing.slow = true;
1454
- try {
1455
- while (this.slowQueue.length > 0) {
1456
- const batch = takeEntriesWithinBytes(this.slowQueue, this.config.slow.maxBytes);
1457
- if (batch.length === 0) {
1458
- break;
1459
- }
1460
- const idempotencyKey = computeLogBatchIdempotencyKey({
1461
- service: this.service,
1462
- process: this.processName,
1463
- lane: "slow",
1464
- entries: batch,
1465
- });
1466
- const batchBytes = estimateEntriesBytes(batch);
1467
- try {
1468
- persistLogger.debug("slow flush posting batch", {
1469
- idempotencyKey,
1470
- batchSize: batch.length,
1471
- batchBytes,
1472
- queueRemaining: this.slowQueue.length,
1473
- });
1474
- const draft = buildLogListDraft({
1475
- service: this.service,
1476
- process: this.processName,
1477
- lane: "slow",
1478
- idempotencyKey,
1479
- entries: batch,
1480
- });
1481
- await postLogBatch(draft, this.config.postTimeoutMs);
1482
- this.slowQueue.splice(0, batch.length);
1483
- this.lastFlushAt.slow = new Date().toISOString();
1484
- this.recordLaneSuccess("slow");
1485
- persistLogger.info("slow lane flushed", {
1486
- idempotencyKey,
1487
- batchSize: batch.length,
1488
- batchBytes,
1489
- queueRemaining: this.slowQueue.length,
1490
- });
1491
- }
1492
- catch (error) {
1493
- this.handleLaneFlushFailure("slow", error, () => this.scheduleLaneRetry("slow", () => void this.flushSlow()), "slow flush failed — entries retained", {
1494
- idempotencyKey,
1495
- batchSize: batch.length,
1496
- batchBytes,
1497
- queueRemaining: this.slowQueue.length,
1498
- });
1499
- break;
1500
- }
1501
- }
1502
- if (this.slowQueue.length === 0) {
1503
- this.slowQueueStartedAt = null;
1504
- }
1505
- }
1506
- finally {
1507
- this.laneFlushing.slow = false;
1508
- }
1509
- if (this.slowQueue.length > 0 && !this.laneFlushing.slow && this.slowRetryTimer == null) {
1510
- this.scheduleSlowFlush();
1511
- }
1512
- }
1513
- }
1514
-
1515
- function resolveRegistryFilePath(explicit) {
1516
- const dir = logPersistRegistryDirFromEnv();
1517
- if (dir == null) {
1518
- throw new Error("[LogPersist] registry path required: set registryFilePath option or LOG_PERSIST_REGISTRY_DIR / RUNTIME_DATA_DIR");
1519
- }
1520
- return defaultLogPersistRegistryPath(resolve(dir));
1521
- }
1522
- async function enableLogPersist(options) {
1523
- const registryFilePath = options.registryFilePath != null ? resolve(options.registryFilePath) : undefined;
1524
- const resolvedRegistry = registryFilePath ?? resolveRegistryFilePath();
1525
- const envConfig = logPersistConfigFromEnv();
1526
- await LogPersist.getInstance().enable({
1527
- ...options,
1528
- registryFilePath: resolvedRegistry,
1529
- config: resolveLogPersistConfig({
1530
- fast: { ...envConfig.fast, ...options.config?.fast },
1531
- medium: { ...envConfig.medium, ...options.config?.medium },
1532
- slow: { ...envConfig.slow, ...options.config?.slow },
1533
- postTimeoutMs: options.config?.postTimeoutMs ?? envConfig.postTimeoutMs,
1534
- shutdownDrainTimeoutMs: options.config?.shutdownDrainTimeoutMs ?? envConfig.shutdownDrainTimeoutMs,
1535
- }),
1536
- });
1537
- }
1538
- async function disableLogPersist() {
1539
- await LogPersist.getInstance().disable();
1540
- }
1541
- function getLogPersistStats() {
1542
- return LogPersist.getInstance().getStats();
1543
- }
1544
- /**
1545
- * Enable log persistence when LOG_PERSIST_ENABLED=true.
1546
- * `process` / `service` can be passed explicitly or via LOG_PERSIST_PROCESS / LOG_PERSIST_SERVICE.
1547
- */
1548
- async function ensureLogPersistFromEnv(options = {}) {
1549
- if (!logPersistEnabledFromEnv()) {
1550
- registerLogPersistOffer(null);
1551
- return false;
1552
- }
1553
- const service = options.service ?? logPersistServiceFromEnv();
1554
- const processName = options.process ?? logPersistProcessFromEnv();
1555
- if (service == null || service === "") {
1556
- throw new Error("[LogPersist] LOG_PERSIST_SERVICE is required when LOG_PERSIST_ENABLED=true");
1557
- }
1558
- if (processName == null || processName === "") {
1559
- throw new Error("[LogPersist] LOG_PERSIST_PROCESS is required when LOG_PERSIST_ENABLED=true (or pass process option)");
1560
- }
1561
- const registryFilePath = options.registryFilePath != null ? resolve(options.registryFilePath) : resolveRegistryFilePath();
1562
- await enableLogPersist({
1563
- service,
1564
- process: processName,
1565
- registryFilePath,
1566
- config: options.config,
1567
- });
1568
- const lifecycleLogger = createLogger({ module: "log-persist" });
1569
- lifecycleLogger.info("log persist enabled from env", {
1570
- topic: LOG_PERSIST_TOPIC,
1571
- data: { service, process: processName, registryFilePath },
1572
- });
1573
- return true;
1574
- }
1575
- /**
1576
- * Preload guard: when persistence is enabled, required env must be present before app code runs.
1577
- */
1578
- function validateLogPersistPreloadEnv(env = process.env) {
1579
- if (!envBool("LOG_PERSIST_ENABLED", false, env)) {
1580
- return;
1581
- }
1582
- const missing = [];
1583
- if (readEnv("LOG_PERSIST_SERVICE", env) == null) {
1584
- missing.push("LOG_PERSIST_SERVICE");
1585
- }
1586
- const registryDir = logPersistRegistryDirFromEnv(env);
1587
- if (registryDir == null) {
1588
- missing.push("LOG_PERSIST_REGISTRY_DIR or RUNTIME_DATA_DIR");
1589
- }
1590
- if (missing.length > 0) {
1591
- throw new Error(`[LogPersist] preload env incomplete: ${missing.join(", ")}`);
1592
- }
1593
- }
1594
- function evaluateLogPersistReady(state, expectedProcesses, staleMs, now) {
1595
- const missing = [];
1596
- const stale = [];
1597
- const registered = [];
1598
- for (const processName of expectedProcesses) {
1599
- const record = state.processes[processName];
1600
- if (record == null) {
1601
- missing.push(processName);
1602
- continue;
1603
- }
1604
- const heartbeatAt = Date.parse(record.lastHeartbeatAt);
1605
- if (!Number.isFinite(heartbeatAt) || now - heartbeatAt > staleMs) {
1606
- stale.push(processName);
1607
- continue;
1608
- }
1609
- registered.push(processName);
1610
- }
1611
- return {
1612
- ok: missing.length === 0 && stale.length === 0,
1613
- missing,
1614
- stale,
1615
- registered,
1616
- };
1617
- }
1618
- /**
1619
- * Wait until every expected process has registered in the shared registry with a fresh heartbeat.
1620
- * Call from the service main process after spawning children.
1621
- */
1622
- async function waitForLogPersistReady(options) {
1623
- const timeoutMs = options.timeoutMs ?? 60_000;
1624
- const pollIntervalMs = options.pollIntervalMs ?? 500;
1625
- const staleMs = options.staleMs ?? 90_000;
1626
- let last = {
1627
- ok: false,
1628
- missing: [...options.expectedProcesses],
1629
- stale: [],
1630
- registered: [],
1631
- };
1632
- try {
1633
- await pollUntil({
1634
- intervalMs: pollIntervalMs,
1635
- timeoutMs,
1636
- until: async () => {
1637
- const state = await readLogPersistRegistry(options.registryFilePath);
1638
- if (state.service !== options.service) {
1639
- last = {
1640
- ok: false,
1641
- missing: options.expectedProcesses,
1642
- stale: [],
1643
- registered: [],
1644
- };
1645
- return false;
1646
- }
1647
- last = evaluateLogPersistReady(state, options.expectedProcesses, staleMs, Date.now());
1648
- return last.ok;
1649
- },
1650
- });
1651
- }
1652
- catch {
1653
- persistLogger.warn("waitForLogPersistReady timed out", {
1654
- timeoutMs,
1655
- expectedProcesses: options.expectedProcesses,
1656
- ...last,
1657
- });
1658
- }
1659
- return last;
1660
- }
1661
- async function snapshotLogPersistReady(options) {
1662
- const state = await readLogPersistRegistry(options.registryFilePath);
1663
- return evaluateLogPersistReady(state, options.expectedProcesses, options.staleMs ?? 90_000, Date.now());
1664
- }
1665
- function resolveLogPersistRegistryPath(registryDir) {
1666
- const dir = registryDir ?? logPersistRegistryDirFromEnv();
1667
- if (dir == null) {
1668
- requireEnv("LOG_PERSIST_REGISTRY_DIR");
1669
- }
1670
- return defaultLogPersistRegistryPath(resolve(dir ?? ""));
1671
- }
1672
-
1673
- export { resolveProjectRootFromModule as A, CLI_PROD_FLAG as C, SERVICE_ENV_PROFILE_ENV_KEY as S, logPersistEnabledFromEnv as a, readEnv as b, requireEnv as c, createJsonFileStateStore as d, disableLogPersist as e, ensureLogPersistFromEnv as f, getLogPersistStats as g, SERVICE_ENV_PROFILE_PROD as h, enableLogPersist as i, envBool as j, envInt as k, loadEnvFiles as l, envMs as m, envNumber as n, envPort as o, pinEnvProfileFromArgv as p, envProfileFromProcess as q, resolveProjectRootByPackageName as r, snapshotLogPersistReady as s, parseEnvFile as t, parseEnvLine as u, validateLogPersistPreloadEnv as v, waitForLogPersistReady as w, pollUntil as x, resolveDefaultEnvFiles as y, resolveLogPersistRegistryPath as z };
1674
- //# sourceMappingURL=enable-log-persist-Dl55_mv2.js.map