express-file-cluster 0.9.2 → 0.9.6

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 (136) hide show
  1. package/dist/auth/index.cjs +4 -5
  2. package/dist/auth/index.cjs.map +1 -1
  3. package/dist/auth/index.d.cts +7 -2
  4. package/dist/auth/index.d.ts +7 -2
  5. package/dist/auth/index.js +3 -4
  6. package/dist/{chunk-ATL4GYFU.js → chunk-2SETEVMO.js} +10 -8
  7. package/dist/{chunk-ATL4GYFU.js.map → chunk-2SETEVMO.js.map} +1 -1
  8. package/dist/{chunk-UBQYQPBU.js → chunk-45BWAR6P.js} +2 -2
  9. package/dist/{chunk-TYR2GZZE.cjs → chunk-6KHBJOLB.cjs} +13 -8
  10. package/dist/chunk-6KHBJOLB.cjs.map +1 -0
  11. package/dist/chunk-73XJUT2S.js +366 -0
  12. package/dist/chunk-73XJUT2S.js.map +1 -0
  13. package/dist/{chunk-UTM4PEVG.js → chunk-7ZESZG3J.js} +8 -3
  14. package/dist/chunk-7ZESZG3J.js.map +1 -0
  15. package/dist/{chunk-R34R7QPD.cjs → chunk-DCJOWFVD.cjs} +3 -3
  16. package/dist/{chunk-R34R7QPD.cjs.map → chunk-DCJOWFVD.cjs.map} +1 -1
  17. package/dist/chunk-DUADUR6R.cjs +366 -0
  18. package/dist/chunk-DUADUR6R.cjs.map +1 -0
  19. package/dist/{chunk-T4OHFU5T.cjs → chunk-FMA76PRH.cjs} +8 -8
  20. package/dist/{chunk-T4OHFU5T.cjs.map → chunk-FMA76PRH.cjs.map} +1 -1
  21. package/dist/{chunk-RS4MXCPW.js → chunk-NI2BNGGV.js} +2 -2
  22. package/dist/{chunk-RRQ2RK5M.js → chunk-OFA7OGN5.js} +26 -6
  23. package/dist/chunk-OFA7OGN5.js.map +1 -0
  24. package/dist/{chunk-ANUSWEAP.cjs → chunk-RGT4ZVHL.cjs} +17 -15
  25. package/dist/chunk-RGT4ZVHL.cjs.map +1 -0
  26. package/dist/{chunk-X2US4RAM.cjs → chunk-TYCYYLLM.cjs} +11 -13
  27. package/dist/chunk-TYCYYLLM.cjs.map +1 -0
  28. package/dist/{chunk-QKQZF573.js → chunk-ULWNHN6P.js} +4 -6
  29. package/dist/{chunk-QKQZF573.js.map → chunk-ULWNHN6P.js.map} +1 -1
  30. package/dist/{chunk-RTF7PHS2.cjs → chunk-VWSUQKCJ.cjs} +116 -96
  31. package/dist/chunk-VWSUQKCJ.cjs.map +1 -0
  32. package/dist/cli/db-runner.cjs +20 -22
  33. package/dist/cli/db-runner.cjs.map +1 -1
  34. package/dist/cli/db-runner.js +4 -6
  35. package/dist/cli/db-runner.js.map +1 -1
  36. package/dist/cli/index.cjs +95 -58
  37. package/dist/cli/index.cjs.map +1 -1
  38. package/dist/cli/index.js +126 -89
  39. package/dist/cli/index.js.map +1 -1
  40. package/dist/docs/api-reference/auth.md +10 -8
  41. package/dist/docs/api-reference/ignite.md +13 -3
  42. package/dist/docs/cli/add.md +1 -1
  43. package/dist/docs/cli/start.md +1 -1
  44. package/dist/docs/contributing/index.md +1 -1
  45. package/dist/docs/getting-started/index.md +1 -1
  46. package/dist/docs/guides/authentication.md +34 -24
  47. package/dist/docs/guides/database.md +12 -0
  48. package/dist/docs/guides/deployment.md +1 -1
  49. package/dist/docs/guides/environment-variables.md +1 -1
  50. package/dist/docs/guides/oauth.md +15 -1
  51. package/dist/docs/index.md +2 -1
  52. package/dist/docs/skills/SKILL.md +2 -2
  53. package/dist/docs/skills/api-surface.md +5 -4
  54. package/dist/docs/skills/auth-internals.md +3 -3
  55. package/dist/docs/versioning.md +42 -0
  56. package/dist/index.cjs +73 -49
  57. package/dist/index.cjs.map +1 -1
  58. package/dist/index.d.cts +2 -2
  59. package/dist/index.d.ts +2 -2
  60. package/dist/index.js +36 -12
  61. package/dist/index.js.map +1 -1
  62. package/dist/pgboss-backend-DSO3QTNK.cjs +14 -0
  63. package/dist/{pgboss-backend-TCHI7CHM.cjs.map → pgboss-backend-DSO3QTNK.cjs.map} +1 -1
  64. package/dist/{pgboss-backend-QKBXVJ6B.js → pgboss-backend-I6DFUNRM.js} +3 -3
  65. package/dist/registry/index.json +22 -3
  66. package/dist/registry/js-mongo/account-security.json +1 -1
  67. package/dist/registry/js-mongo/admin-users.json +1 -1
  68. package/dist/registry/js-mongo/auth.json +1 -1
  69. package/dist/registry/js-mongo/auth@apple.json +1 -1
  70. package/dist/registry/js-mongo/auth@google.json +1 -1
  71. package/dist/registry/js-mongo/email-verification.json +1 -1
  72. package/dist/registry/js-mongo/forgot-password.json +1 -1
  73. package/dist/registry/js-mongo/user-profile.json +1 -1
  74. package/dist/registry/js-pg-model/account-security.json +1 -1
  75. package/dist/registry/js-pg-model/admin-users.json +1 -1
  76. package/dist/registry/js-pg-model/auth.json +1 -1
  77. package/dist/registry/js-pg-model/auth@apple.json +1 -1
  78. package/dist/registry/js-pg-model/auth@google.json +1 -1
  79. package/dist/registry/js-pg-model/email-verification.json +1 -1
  80. package/dist/registry/js-pg-model/forgot-password.json +1 -1
  81. package/dist/registry/js-pg-model/user-profile.json +1 -1
  82. package/dist/registry/js-pg-table/account-security.json +1 -1
  83. package/dist/registry/js-pg-table/admin-users.json +1 -1
  84. package/dist/registry/js-pg-table/auth.json +1 -1
  85. package/dist/registry/js-pg-table/auth@apple.json +1 -1
  86. package/dist/registry/js-pg-table/auth@google.json +1 -1
  87. package/dist/registry/js-pg-table/email-verification.json +1 -1
  88. package/dist/registry/js-pg-table/forgot-password.json +1 -1
  89. package/dist/registry/js-pg-table/user-profile.json +1 -1
  90. package/dist/registry/ts-mongo/account-security.json +1 -1
  91. package/dist/registry/ts-mongo/admin-users.json +1 -1
  92. package/dist/registry/ts-mongo/auth.json +1 -1
  93. package/dist/registry/ts-mongo/auth@apple.json +1 -1
  94. package/dist/registry/ts-mongo/auth@google.json +1 -1
  95. package/dist/registry/ts-mongo/email-verification.json +1 -1
  96. package/dist/registry/ts-mongo/forgot-password.json +1 -1
  97. package/dist/registry/ts-mongo/user-profile.json +1 -1
  98. package/dist/registry/ts-pg-model/account-security.json +1 -1
  99. package/dist/registry/ts-pg-model/admin-users.json +1 -1
  100. package/dist/registry/ts-pg-model/auth.json +1 -1
  101. package/dist/registry/ts-pg-model/auth@apple.json +1 -1
  102. package/dist/registry/ts-pg-model/auth@google.json +1 -1
  103. package/dist/registry/ts-pg-model/email-verification.json +1 -1
  104. package/dist/registry/ts-pg-model/forgot-password.json +1 -1
  105. package/dist/registry/ts-pg-model/user-profile.json +1 -1
  106. package/dist/registry/ts-pg-table/account-security.json +1 -1
  107. package/dist/registry/ts-pg-table/admin-users.json +1 -1
  108. package/dist/registry/ts-pg-table/auth.json +1 -1
  109. package/dist/registry/ts-pg-table/auth@apple.json +1 -1
  110. package/dist/registry/ts-pg-table/auth@google.json +1 -1
  111. package/dist/registry/ts-pg-table/email-verification.json +1 -1
  112. package/dist/registry/ts-pg-table/forgot-password.json +1 -1
  113. package/dist/registry/ts-pg-table/user-profile.json +1 -1
  114. package/dist/tasks/index.d.cts +1 -1
  115. package/dist/tasks/index.d.ts +1 -1
  116. package/dist/{types-BY-ObnZH.d.cts → types-DAsBKVM-.d.cts} +7 -1
  117. package/dist/{types-BY-ObnZH.d.ts → types-DAsBKVM-.d.ts} +7 -1
  118. package/package.json +1 -1
  119. package/dist/chunk-277BSYVH.js +0 -127
  120. package/dist/chunk-277BSYVH.js.map +0 -1
  121. package/dist/chunk-ANUSWEAP.cjs.map +0 -1
  122. package/dist/chunk-HXV543HZ.js +0 -177
  123. package/dist/chunk-HXV543HZ.js.map +0 -1
  124. package/dist/chunk-RRQ2RK5M.js.map +0 -1
  125. package/dist/chunk-RTF7PHS2.cjs.map +0 -1
  126. package/dist/chunk-TYR2GZZE.cjs.map +0 -1
  127. package/dist/chunk-UTM4PEVG.js.map +0 -1
  128. package/dist/chunk-VQSWSYK6.cjs +0 -177
  129. package/dist/chunk-VQSWSYK6.cjs.map +0 -1
  130. package/dist/chunk-X2US4RAM.cjs.map +0 -1
  131. package/dist/chunk-YL37D6KM.cjs +0 -127
  132. package/dist/chunk-YL37D6KM.cjs.map +0 -1
  133. package/dist/pgboss-backend-TCHI7CHM.cjs +0 -14
  134. /package/dist/{chunk-UBQYQPBU.js.map → chunk-45BWAR6P.js.map} +0 -0
  135. /package/dist/{chunk-RS4MXCPW.js.map → chunk-NI2BNGGV.js.map} +0 -0
  136. /package/dist/{pgboss-backend-QKBXVJ6B.js.map → pgboss-backend-I6DFUNRM.js.map} +0 -0
@@ -0,0 +1,366 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/context.ts
2
+ var _async_hooks = require('async_hooks');
3
+ var storage = new (0, _async_hooks.AsyncLocalStorage)();
4
+ function runWithContext(ctx, fn) {
5
+ return storage.run(ctx, fn);
6
+ }
7
+ function getRequestContext() {
8
+ return storage.getStore();
9
+ }
10
+ function setCurrentUser(user) {
11
+ const store = storage.getStore();
12
+ if (store) store.user = user;
13
+ }
14
+ function getCurrentUser() {
15
+ return _optionalChain([storage, 'access', _ => _.getStore, 'call', _2 => _2(), 'optionalAccess', _3 => _3.user]);
16
+ }
17
+
18
+ // src/logger.ts
19
+ var _cluster = require('cluster'); var _cluster2 = _interopRequireDefault(_cluster);
20
+ var _crypto = require('crypto');
21
+ var _picocolors = require('picocolors'); var _picocolors2 = _interopRequireDefault(_picocolors);
22
+ var _pino = require('pino');
23
+ var LEVEL_LABELS = {
24
+ 10: _picocolors2.default.gray("TRACE"),
25
+ 20: _picocolors2.default.blue("DEBUG"),
26
+ 30: _picocolors2.default.green("INFO "),
27
+ 40: _picocolors2.default.yellow("WARN "),
28
+ 50: _picocolors2.default.red("ERROR"),
29
+ 60: _picocolors2.default.bgRed("FATAL")
30
+ };
31
+ var OMIT = /* @__PURE__ */ new Set(["level", "time", "msg", "pid", "hostname", "worker", "reqId"]);
32
+ function prettyStream(out = process.stdout) {
33
+ return {
34
+ write(line) {
35
+ let rec;
36
+ try {
37
+ rec = JSON.parse(line);
38
+ } catch (e2) {
39
+ out.write(line);
40
+ return;
41
+ }
42
+ const time = new Date(rec["time"]).toTimeString().slice(0, 8);
43
+ const level = _nullishCoalesce(LEVEL_LABELS[rec["level"]], () => ( String(rec["level"])));
44
+ const worker = rec["worker"] !== void 0 ? _picocolors2.default.dim(`[${String(rec["worker"])}] `) : "";
45
+ const reqId = rec["reqId"] ? _picocolors2.default.magenta(String(rec["reqId"]).slice(0, 8)) + " " : "";
46
+ const extra = Object.entries(rec).filter(([k]) => !OMIT.has(k));
47
+ const err = rec["err"];
48
+ const fields = extra.filter(([k]) => k !== "err").map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`).join(" ");
49
+ out.write(
50
+ `${_picocolors2.default.dim(time)} ${level} ${worker}${reqId}${String(_nullishCoalesce(rec["msg"], () => ( "")))}` + (fields ? " " + _picocolors2.default.dim(fields) : "") + (_optionalChain([err, 'optionalAccess', _4 => _4.stack]) ? "\n" + _picocolors2.default.red(err.stack) : "") + "\n"
51
+ );
52
+ }
53
+ };
54
+ }
55
+ function workerLabel() {
56
+ return _cluster2.default.isWorker ? `w${_nullishCoalesce(_optionalChain([_cluster2.default, 'access', _5 => _5.worker, 'optionalAccess', _6 => _6.id]), () => ( "?"))}` : "primary";
57
+ }
58
+ function build(config2) {
59
+ if (config2 === false) return _pino.pino.call(void 0, { level: "silent" });
60
+ const opts = _nullishCoalesce(config2, () => ( {}));
61
+ const pretty = _nullishCoalesce(opts.pretty, () => ( (process.env["NODE_ENV"] !== "production" && process.stdout.isTTY === true)));
62
+ const base = { worker: workerLabel() };
63
+ const level = _nullishCoalesce(opts.level, () => ( "info"));
64
+ return pretty ? _pino.pino.call(void 0, { level, base, errorKey: "err" }, prettyStream()) : _pino.pino.call(void 0, { level, base, errorKey: "err", timestamp: _pino.pino.stdTimeFunctions.isoTime });
65
+ }
66
+ var rootLogger = build(void 0);
67
+ var logRequests = true;
68
+ function configureLogger(config2) {
69
+ rootLogger = build(config2);
70
+ logRequests = config2 !== false && (_nullishCoalesce(_optionalChain([config2, 'optionalAccess', _7 => _7.requests]), () => ( true)));
71
+ }
72
+ function getLogger() {
73
+ return _nullishCoalesce(_optionalChain([getRequestContext, 'call', _8 => _8(), 'optionalAccess', _9 => _9.log]), () => ( rootLogger));
74
+ }
75
+ var logger = new Proxy({}, {
76
+ get(_t, prop) {
77
+ const target = getLogger();
78
+ const value = target[prop];
79
+ return typeof value === "function" ? value.bind(target) : value;
80
+ }
81
+ });
82
+ var SAFE_REQUEST_ID = /^[\w.:-]{1,128}$/;
83
+ function requestLogger() {
84
+ return (req, res, next) => {
85
+ const incoming = req.get("x-request-id");
86
+ const id = incoming && SAFE_REQUEST_ID.test(incoming) ? incoming : _crypto.randomUUID.call(void 0, );
87
+ const log = rootLogger.child({ reqId: id });
88
+ req.id = id;
89
+ req.log = log;
90
+ res.setHeader("X-Request-Id", id);
91
+ const ctx = getRequestContext();
92
+ if (ctx) {
93
+ ctx.requestId = id;
94
+ ctx.log = log;
95
+ }
96
+ if (logRequests) {
97
+ const start = process.hrtime.bigint();
98
+ res.on("finish", () => {
99
+ const durationMs = Number(process.hrtime.bigint() - start) / 1e6;
100
+ const status = res.statusCode;
101
+ const line = {
102
+ method: req.method,
103
+ url: req.originalUrl,
104
+ status,
105
+ durationMs: Math.round(durationMs * 10) / 10
106
+ };
107
+ const msg = `${req.method} ${req.originalUrl} ${status}`;
108
+ if (status >= 500) log.error(line, msg);
109
+ else if (status >= 400) log.warn(line, msg);
110
+ else log.info(line, msg);
111
+ });
112
+ }
113
+ next();
114
+ };
115
+ }
116
+
117
+ // src/db/query-log.ts
118
+
119
+ var DEFAULTS = { slowMs: 500, nPlusOne: 10 };
120
+ var config;
121
+ var listeners = /* @__PURE__ */ new Set();
122
+ var enableHooks = [];
123
+ function configureQueryLog(logging) {
124
+ const q = logging === false ? void 0 : _optionalChain([logging, 'optionalAccess', _10 => _10.queries]);
125
+ config = !q ? void 0 : q === true ? { all: true, ...DEFAULTS } : {
126
+ all: _nullishCoalesce(q.all, () => ( false)),
127
+ slowMs: _nullishCoalesce(q.slowMs, () => ( DEFAULTS.slowMs)),
128
+ nPlusOne: _nullishCoalesce(q.nPlusOne, () => ( DEFAULTS.nPlusOne))
129
+ };
130
+ if (config) for (const hook of enableHooks) hook();
131
+ }
132
+ function active() {
133
+ return config !== void 0 || listeners.size > 0;
134
+ }
135
+ function whenQueryTracking(install) {
136
+ enableHooks.push(install);
137
+ if (active()) install();
138
+ }
139
+ var frames = new (0, _async_hooks.AsyncLocalStorage)();
140
+ function countStatement() {
141
+ for (let f = frames.getStore(); f; f = f.parent) f.statements++;
142
+ }
143
+ function untracked(fn) {
144
+ return frames.run(void 0, fn);
145
+ }
146
+ function callSite(callee) {
147
+ const holder = {};
148
+ Error.captureStackTrace(holder, callee);
149
+ const line = _optionalChain([holder, 'access', _11 => _11.stack, 'optionalAccess', _12 => _12.split, 'call', _13 => _13("\n"), 'access', _14 => _14[1]]);
150
+ return _optionalChain([line, 'optionalAccess', _15 => _15.trim, 'call', _16 => _16(), 'access', _17 => _17.replace, 'call', _18 => _18(/^at /, "")]);
151
+ }
152
+ function emit(event, site, top) {
153
+ for (const listener of listeners) listener(event);
154
+ if (!config) return;
155
+ const log = getLogger();
156
+ const msg = `${event.model}.${event.op} ${event.durationMs}ms`;
157
+ const fields = { ...event };
158
+ delete fields.reqId;
159
+ if (event.durationMs >= config.slowMs) {
160
+ log.warn({ ...fields, slow: true }, `Slow query: ${msg}`);
161
+ } else if (config.all) {
162
+ log.info(fields, msg);
163
+ }
164
+ if (top && config.nPlusOne !== false) detectNPlusOne(event, site, config.nPlusOne);
165
+ }
166
+ function detectNPlusOne(event, site, threshold) {
167
+ const ctx = getRequestContext();
168
+ if (!ctx) return;
169
+ const key = `${event.model}.${event.op}`;
170
+ const counts = ctx.queryCounts ??= /* @__PURE__ */ new Map();
171
+ const n = (_nullishCoalesce(counts.get(key), () => ( 0))) + 1;
172
+ counts.set(key, n);
173
+ if (n !== threshold) return;
174
+ getLogger().warn(
175
+ { model: event.model, op: event.op, count: n, ...site !== void 0 && { site } },
176
+ `Possible N+1: ${key} ran ${n} times in one request \u2014 load them in one query instead`
177
+ );
178
+ }
179
+ function traceOps(model, target, ops) {
180
+ const t = target;
181
+ for (const op of ops) {
182
+ const fn = t[op];
183
+ const traced = function(...args) {
184
+ if (!active()) return fn.apply(this, args);
185
+ const parent = frames.getStore();
186
+ const frame = { statements: 0, parent };
187
+ const site = !parent && config && config.nPlusOne !== false ? callSite(traced) : void 0;
188
+ const start = process.hrtime.bigint();
189
+ const finish = (error) => {
190
+ const durationMs = Math.round(Number(process.hrtime.bigint() - start) / 1e5) / 10;
191
+ const reqId = _optionalChain([getRequestContext, 'call', _19 => _19(), 'optionalAccess', _20 => _20.requestId]);
192
+ emit(
193
+ {
194
+ model,
195
+ op,
196
+ durationMs,
197
+ statements: frame.statements,
198
+ ...reqId !== void 0 && { reqId },
199
+ ...error !== void 0 && { error: _nullishCoalesce(_optionalChain([error, 'optionalAccess', _21 => _21.message]), () => ( String(error))) }
200
+ },
201
+ site,
202
+ !parent
203
+ );
204
+ };
205
+ return frames.run(frame, () => fn.apply(this, args)).then(
206
+ (result) => {
207
+ finish();
208
+ return result;
209
+ },
210
+ (err) => {
211
+ finish(err);
212
+ throw err;
213
+ }
214
+ );
215
+ };
216
+ t[op] = traced;
217
+ }
218
+ return target;
219
+ }
220
+
221
+ // src/db/postgres.ts
222
+ var pool;
223
+ function notInstalled(err, pkg, install) {
224
+ const code = err.code;
225
+ return code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND" ? new Error(`[EFC] ${pkg} is not installed. Run: ${install}`) : err;
226
+ }
227
+ var orm;
228
+ async function connectPostgres(url, poolConfig = {}) {
229
+ let PoolCtor;
230
+ try {
231
+ const pg = await Promise.resolve().then(() => _interopRequireWildcard(require("pg")));
232
+ PoolCtor = _nullishCoalesce(_optionalChain([pg, 'access', _22 => _22.default, 'optionalAccess', _23 => _23.Pool]), () => ( pg.Pool));
233
+ } catch (err) {
234
+ throw notInstalled(err, "pg", "npm install pg drizzle-orm");
235
+ }
236
+ let drizzle;
237
+ try {
238
+ ({ drizzle } = await Promise.resolve().then(() => _interopRequireWildcard(require("drizzle-orm/node-postgres"))));
239
+ } catch (err) {
240
+ throw notInstalled(err, "drizzle-orm", "npm install drizzle-orm");
241
+ }
242
+ const next = new PoolCtor({
243
+ connectionString: url,
244
+ ...poolConfig.max !== void 0 && { max: poolConfig.max },
245
+ ...poolConfig.idleTimeoutMs !== void 0 && { idleTimeoutMillis: poolConfig.idleTimeoutMs },
246
+ ...poolConfig.connectionTimeoutMs !== void 0 && {
247
+ connectionTimeoutMillis: poolConfig.connectionTimeoutMs
248
+ }
249
+ });
250
+ next.on("error", (err) => getLogger().error({ err }, "PostgreSQL pool error"));
251
+ try {
252
+ await next.query("select 1");
253
+ } catch (err) {
254
+ await next.end().catch(() => {
255
+ });
256
+ throw explainPostgresError(err, url);
257
+ }
258
+ pool = next;
259
+ orm = drizzle(next, { logger: { logQuery: countStatement } });
260
+ getLogger().info("PostgreSQL connected");
261
+ return next;
262
+ }
263
+ function describeUrl(url) {
264
+ try {
265
+ const u = new URL(url);
266
+ const database = decodeURIComponent(u.pathname.slice(1)) || "(default)";
267
+ return {
268
+ where: `${u.hostname || "localhost"}:${u.port || "5432"}`,
269
+ user: decodeURIComponent(u.username) || "(none)",
270
+ database
271
+ };
272
+ } catch (e3) {
273
+ return { where: "(unparsable DATABASE_URL)", user: "?", database: "?" };
274
+ }
275
+ }
276
+ function explainPostgresError(err, url) {
277
+ const e = err;
278
+ const msg = _nullishCoalesce(e.message, () => ( ""));
279
+ const { where, user, database } = describeUrl(url);
280
+ const hosted = "For Neon, Supabase or RDS, copy the full connection string from the dashboard.";
281
+ let text;
282
+ if (/client password must be a string/.test(msg)) {
283
+ text = `PostgreSQL asked for a password and DATABASE_URL has none (user "${user}" at ${where}). Put it in the URL: postgres://${user === "(none)" ? "user" : user}:<password>@${where}/${database === "(default)" ? "db" : database}. ${hosted}`;
284
+ } else if (e.code === "28P01") {
285
+ text = `PostgreSQL rejected the password for user "${user}" at ${where}. Check DATABASE_URL (special characters in the password must be URL-encoded). ${hosted}`;
286
+ } else if (e.code === "28000" && /role .* does not exist/.test(msg)) {
287
+ text = `PostgreSQL has no user "${user}" at ${where}. Create it (CREATE ROLE ${user} LOGIN PASSWORD '\u2026';) or fix the user in DATABASE_URL.`;
288
+ } else if (/no pg_hba\.conf entry.*no encryption/.test(msg)) {
289
+ text = `PostgreSQL at ${where} only accepts encrypted connections. Add ?sslmode=require to DATABASE_URL.`;
290
+ } else if (e.code === "28000") {
291
+ text = `PostgreSQL at ${where} refused user "${user}": ${msg}`;
292
+ } else if (e.code === "3D000") {
293
+ text = `Database "${database}" does not exist at ${where}. Create it first: createdb ${database} (or CREATE DATABASE "${database}";).`;
294
+ } else if (/does not support SSL/.test(msg)) {
295
+ text = `PostgreSQL at ${where} doesn't support SSL. Remove sslmode / ssl from DATABASE_URL (local servers usually run without it).`;
296
+ } else if (e.code === "ECONNREFUSED") {
297
+ text = `Nothing is accepting connections at ${where}. Is PostgreSQL running, and is the host/port in DATABASE_URL right?`;
298
+ } else if (e.code === "ENOTFOUND" || e.code === "EAI_AGAIN") {
299
+ text = `Can't resolve the PostgreSQL host in DATABASE_URL (${where}). Check the hostname.`;
300
+ } else if (e.code === "ETIMEDOUT" || /timeout/i.test(msg)) {
301
+ text = `Timed out connecting to PostgreSQL at ${where}. Check the host, and that a firewall / the provider's IP allow-list lets this machine in.`;
302
+ }
303
+ return text ? new Error(`[EFC] ${text}`, { cause: err }) : err;
304
+ }
305
+ async function checkConnectionBudget(perMachine, breakdown) {
306
+ const log = getLogger();
307
+ try {
308
+ const { rows } = await getPool().query(
309
+ `select current_setting('max_connections')::int as max,
310
+ current_setting('superuser_reserved_connections')::int as reserved`
311
+ );
312
+ const { max, reserved } = rows[0];
313
+ const usable = max - reserved;
314
+ if (perMachine > usable) {
315
+ log.warn(
316
+ `[EFC] PostgreSQL connections: up to ${perMachine} from this machine (${breakdown}), but the server allows ${usable} (max_connections ${max} \u2212 ${reserved} reserved). Under load, queries will fail with "too many clients". Lower databasePool.max or workers, or put PgBouncer in front.`
317
+ );
318
+ } else {
319
+ log.info(
320
+ `PostgreSQL connections: up to ${perMachine} from this machine (${breakdown}) of ${usable} allowed \u2014 multiply by your instance count if you run several`
321
+ );
322
+ }
323
+ } catch (e4) {
324
+ }
325
+ }
326
+ function getOrm() {
327
+ if (!orm) {
328
+ throw new Error(
329
+ "[EFC] PostgreSQL not connected \u2014 set database/databaseUrl in ignite() (or call connectPostgres)"
330
+ );
331
+ }
332
+ return orm;
333
+ }
334
+ function getPool() {
335
+ if (!pool) throw new Error("[EFC] PostgreSQL not connected");
336
+ return pool;
337
+ }
338
+ async function closePostgres() {
339
+ const p = pool;
340
+ pool = void 0;
341
+ orm = void 0;
342
+ await _optionalChain([p, 'optionalAccess', _24 => _24.end, 'call', _25 => _25()]);
343
+ }
344
+
345
+
346
+
347
+
348
+
349
+
350
+
351
+
352
+
353
+
354
+
355
+
356
+
357
+
358
+
359
+
360
+
361
+
362
+
363
+
364
+
365
+ exports.runWithContext = runWithContext; exports.setCurrentUser = setCurrentUser; exports.getCurrentUser = getCurrentUser; exports.configureLogger = configureLogger; exports.getLogger = getLogger; exports.logger = logger; exports.requestLogger = requestLogger; exports.configureQueryLog = configureQueryLog; exports.whenQueryTracking = whenQueryTracking; exports.countStatement = countStatement; exports.untracked = untracked; exports.traceOps = traceOps; exports.notInstalled = notInstalled; exports.connectPostgres = connectPostgres; exports.explainPostgresError = explainPostgresError; exports.checkConnectionBudget = checkConnectionBudget; exports.getOrm = getOrm; exports.getPool = getPool; exports.closePostgres = closePostgres;
366
+ //# sourceMappingURL=chunk-DUADUR6R.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-DUADUR6R.cjs","../src/context.ts","../src/logger.ts","../src/db/query-log.ts","../src/db/postgres.ts"],"names":[],"mappings":"AAAA;ACAA,0CAAkC;AAWlC,IAAM,QAAA,EAAU,IAAI,mCAAA,CAAkC,CAAA;AAM/C,SAAS,cAAA,CAAkB,GAAA,EAAqB,EAAA,EAAgB;AACrE,EAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,GAAA,EAAK,EAAE,CAAA;AAC5B;AAEO,SAAS,iBAAA,CAAA,EAAgD;AAC9D,EAAA,OAAO,OAAA,CAAQ,QAAA,CAAS,CAAA;AAC1B;AAEO,SAAS,cAAA,CAAe,IAAA,EAAiD;AAC9E,EAAA,MAAM,MAAA,EAAQ,OAAA,CAAQ,QAAA,CAAS,CAAA;AAC/B,EAAA,GAAA,CAAI,KAAA,EAAO,KAAA,CAAM,KAAA,EAAO,IAAA;AAC1B;AAEO,SAAS,cAAA,CAAA,EAAsD;AACpE,EAAA,uBAAO,OAAA,mBAAQ,QAAA,mBAAS,CAAA,6BAAG,MAAA;AAC7B;ADhBA;AACA;AEjBA,oFAAoB;AACpB,gCAA2B;AAE3B,gGAAe;AACf,4BAA0D;AAM1D,IAAM,aAAA,EAAuC;AAAA,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AA;AACF,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAEgC;AAC6B,EAAA;AACpD,EAAA;AACT;AAEqD;AACzC,EAAA;AACH,EAAA;AACD,EAAA;AACO,EAAA;AACf;AJgLyE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-DUADUR6R.cjs","sourcesContent":[null,"import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Logger } from 'pino';\n\nexport interface RequestContext {\n user?: Record<string, unknown> | undefined;\n requestId?: string;\n log?: Logger;\n /** Model operations run so far in this request, by `Model.op` (N+1 detection). */\n queryCounts?: Map<string, number>;\n}\n\nconst storage = new AsyncLocalStorage<RequestContext>();\n\n// Wraps one request's lifecycle in an AsyncLocalStorage context. Node propagates\n// the store through the async chain the callback initiates (awaits, .then, etc.),\n// so anything running as part of the same request — including a `$currentUser`\n// default resolved deep inside a mongoose `.create()` call — can read it back.\nexport function runWithContext<T>(ctx: RequestContext, fn: () => T): T {\n return storage.run(ctx, fn);\n}\n\nexport function getRequestContext(): RequestContext | undefined {\n return storage.getStore();\n}\n\nexport function setCurrentUser(user: Record<string, unknown> | undefined): void {\n const store = storage.getStore();\n if (store) store.user = user;\n}\n\nexport function getCurrentUser(): Record<string, unknown> | undefined {\n return storage.getStore()?.user;\n}\n","import cluster from 'node:cluster';\nimport { randomUUID } from 'node:crypto';\nimport type { RequestHandler } from 'express';\nimport pc from 'picocolors';\nimport { pino, type Logger, type DestinationStream } from 'pino';\nimport type { LoggingConfig } from './types.js';\nimport { getRequestContext } from './context.js';\n\nexport type { Logger };\n\nconst LEVEL_LABELS: Record<number, string> = {\n 10: pc.gray('TRACE'),\n 20: pc.blue('DEBUG'),\n 30: pc.green('INFO '),\n 40: pc.yellow('WARN '),\n 50: pc.red('ERROR'),\n 60: pc.bgRed('FATAL'),\n};\n\nconst OMIT = new Set(['level', 'time', 'msg', 'pid', 'hostname', 'worker', 'reqId']);\n\n// Dev-friendly one-line renderer, so readable output doesn't need pino-pretty or a\n// transport worker thread: `12:00:01 INFO [w2] a1b2c3d4 GET /users 200 (3ms)`.\nfunction prettyStream(out: NodeJS.WritableStream = process.stdout): DestinationStream {\n return {\n write(line: string) {\n let rec: Record<string, unknown>;\n try {\n rec = JSON.parse(line) as Record<string, unknown>;\n } catch {\n out.write(line);\n return;\n }\n const time = new Date(rec['time'] as number).toTimeString().slice(0, 8);\n const level = LEVEL_LABELS[rec['level'] as number] ?? String(rec['level']);\n const worker = rec['worker'] !== undefined ? pc.dim(`[${String(rec['worker'])}] `) : '';\n const reqId = rec['reqId'] ? pc.magenta(String(rec['reqId']).slice(0, 8)) + ' ' : '';\n const extra = Object.entries(rec).filter(([k]) => !OMIT.has(k));\n const err = rec['err'] as { stack?: string } | undefined;\n const fields = extra\n .filter(([k]) => k !== 'err')\n .map(([k, v]) => `${k}=${typeof v === 'string' ? v : JSON.stringify(v)}`)\n .join(' ');\n out.write(\n `${pc.dim(time)} ${level} ${worker}${reqId}${String(rec['msg'] ?? '')}` +\n (fields ? ' ' + pc.dim(fields) : '') +\n (err?.stack ? '\\n' + pc.red(err.stack) : '') +\n '\\n',\n );\n },\n };\n}\n\nfunction workerLabel(): string {\n return cluster.isWorker ? `w${cluster.worker?.id ?? '?'}` : 'primary';\n}\n\nfunction build(config: LoggingConfig | false | undefined): Logger {\n if (config === false) return pino({ level: 'silent' });\n const opts = config ?? {};\n const pretty =\n opts.pretty ?? (process.env['NODE_ENV'] !== 'production' && process.stdout.isTTY === true);\n const base = { worker: workerLabel() };\n const level = opts.level ?? 'info';\n return pretty\n ? pino({ level, base, errorKey: 'err' }, prettyStream())\n : pino({ level, base, errorKey: 'err', timestamp: pino.stdTimeFunctions.isoTime });\n}\n\nlet rootLogger: Logger = build(undefined);\nlet logRequests = true;\n\n/** Called by ignite() during Pre-Flight; before that the defaults apply. */\nexport function configureLogger(config: LoggingConfig | false | undefined): void {\n rootLogger = build(config);\n logRequests = config !== false && (config?.requests ?? true);\n}\n\n/**\n * The logger for the current scope: inside a request it is a child carrying that\n * request's `reqId`, so everything logged while handling it can be correlated;\n * elsewhere (startup, task handlers, timers) it is the root logger.\n */\nexport function getLogger(): Logger {\n return getRequestContext()?.log ?? rootLogger;\n}\n\n/** Root logger proxy — always reflects the latest configureLogger() call. */\nexport const logger: Logger = new Proxy({} as Logger, {\n get(_t, prop) {\n const target = getLogger() as unknown as Record<PropertyKey, unknown>;\n const value = target[prop];\n return typeof value === 'function'\n ? (value as (...a: unknown[]) => unknown).bind(target)\n : value;\n },\n});\n\nconst SAFE_REQUEST_ID = /^[\\w.:-]{1,128}$/;\n\n/**\n * Assigns the request ID (trusting a well-formed incoming `X-Request-Id`, e.g. from\n * a load balancer), echoes it back, attaches `req.id` / `req.log`, and logs one\n * line per completed request. Must run inside the request's context.\n */\nexport function requestLogger(): RequestHandler {\n return (req, res, next) => {\n const incoming = req.get('x-request-id');\n const id = incoming && SAFE_REQUEST_ID.test(incoming) ? incoming : randomUUID();\n const log = rootLogger.child({ reqId: id });\n\n req.id = id;\n req.log = log;\n res.setHeader('X-Request-Id', id);\n const ctx = getRequestContext();\n if (ctx) {\n ctx.requestId = id;\n ctx.log = log;\n }\n\n if (logRequests) {\n const start = process.hrtime.bigint();\n res.on('finish', () => {\n const durationMs = Number(process.hrtime.bigint() - start) / 1e6;\n const status = res.statusCode;\n const line = {\n method: req.method,\n url: req.originalUrl,\n status,\n durationMs: Math.round(durationMs * 10) / 10,\n };\n const msg = `${req.method} ${req.originalUrl} ${status}`;\n if (status >= 500) log.error(line, msg);\n else if (status >= 400) log.warn(line, msg);\n else log.info(line, msg);\n });\n }\n next();\n };\n}\n\ndeclare module 'express-serve-static-core' {\n interface Request {\n /** Request ID — the incoming `X-Request-Id` if well-formed, else a UUID. */\n id: string;\n /** Logger bound to this request's ID. */\n log: Logger;\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { LoggingConfig } from '../types.js';\nimport { getRequestContext } from '../context.js';\nimport { getLogger } from '../logger.js';\n\n// Query logging (`logging.queries`): one event per model operation — model, operation,\n// duration, how many database statements it issued, and the request ID — plus slow-query\n// warnings and an N+1 detector. Statements are counted at the driver: Drizzle's logger on\n// PostgreSQL, mongoose's debug hook on MongoDB.\n\n/** One finished model operation. */\nexport interface QueryEvent {\n model: string;\n op: string;\n durationMs: number;\n /** Database statements (SQL statements / MongoDB commands) issued, nested calls included. */\n statements: number;\n /** The request it ran in, if any. */\n reqId?: string;\n /** Set when it threw. */\n error?: string;\n}\n\ninterface Resolved {\n all: boolean;\n slowMs: number;\n nPlusOne: number | false;\n}\n\nconst DEFAULTS = { slowMs: 500, nPlusOne: 10 } as const;\n\nlet config: Resolved | undefined;\nconst listeners = new Set<(event: QueryEvent) => void>();\nconst enableHooks: (() => void)[] = [];\n\n/** Called by ignite() during Pre-Flight, next to configureLogger(). */\nexport function configureQueryLog(logging: LoggingConfig | false | undefined): void {\n const q = logging === false ? undefined : logging?.queries;\n config = !q\n ? undefined\n : q === true\n ? { all: true, ...DEFAULTS }\n : {\n all: q.all ?? false,\n slowMs: q.slowMs ?? DEFAULTS.slowMs,\n nPlusOne: q.nPlusOne ?? DEFAULTS.nPlusOne,\n };\n if (config) for (const hook of enableHooks) hook();\n}\n\nfunction active(): boolean {\n return config !== undefined || listeners.size > 0;\n}\n\n/**\n * Receives every model operation while subscribed (whether or not `logging.queries` is\n * on). Returns the unsubscribe function. Internal — tests use it to count statements.\n */\nexport function onQuery(listener: (event: QueryEvent) => void): () => void {\n listeners.add(listener);\n for (const hook of enableHooks) hook();\n return () => listeners.delete(listener);\n}\n\n/** Registers a driver hook to install once query tracking is first needed. */\nexport function whenQueryTracking(install: () => void): void {\n enableHooks.push(install);\n if (active()) install();\n}\n\ninterface Frame {\n statements: number;\n parent: Frame | undefined;\n}\n\nconst frames = new AsyncLocalStorage<Frame | undefined>();\n\n/** Called by the driver hooks for each statement sent to the database. */\nexport function countStatement(): void {\n for (let f = frames.getStore(); f; f = f.parent) f.statements++;\n}\n\n/** Runs `fn` outside any operation, so its statements (e.g. auto-sync) are not counted. */\nexport function untracked<R>(fn: () => R): R {\n return frames.run(undefined, fn);\n}\n\n// The first stack frame outside EFC: the line in the app that made the call.\nfunction callSite(callee: (...args: never[]) => unknown): string | undefined {\n const holder: { stack?: string } = {};\n Error.captureStackTrace(holder, callee);\n const line = holder.stack?.split('\\n')[1];\n return line?.trim().replace(/^at /, '');\n}\n\nfunction emit(event: QueryEvent, site: string | undefined, top: boolean): void {\n for (const listener of listeners) listener(event);\n if (!config) return;\n const log = getLogger();\n const msg = `${event.model}.${event.op} ${event.durationMs}ms`;\n // The request's logger already carries reqId.\n const fields: Partial<QueryEvent> = { ...event };\n delete fields.reqId;\n if (event.durationMs >= config.slowMs) {\n log.warn({ ...fields, slow: true }, `Slow query: ${msg}`);\n } else if (config.all) {\n log.info(fields, msg);\n }\n if (top && config.nPlusOne !== false) detectNPlusOne(event, site, config.nPlusOne);\n}\n\nfunction detectNPlusOne(event: QueryEvent, site: string | undefined, threshold: number): void {\n const ctx = getRequestContext();\n if (!ctx) return;\n const key = `${event.model}.${event.op}`;\n const counts = (ctx.queryCounts ??= new Map());\n const n = (counts.get(key) ?? 0) + 1;\n counts.set(key, n);\n if (n !== threshold) return;\n getLogger().warn(\n { model: event.model, op: event.op, count: n, ...(site !== undefined && { site }) },\n `Possible N+1: ${key} ran ${n} times in one request — load them in one query instead`,\n );\n}\n\n/**\n * Wraps a model's public operations so each call is timed, its statements counted and\n * the result reported. A no-op wrapper while query logging is off.\n */\nexport function traceOps<M extends object>(model: string, target: M, ops: readonly string[]): M {\n const t = target as Record<string, unknown>;\n for (const op of ops) {\n const fn = t[op] as (...args: unknown[]) => Promise<unknown>;\n const traced = function (this: unknown, ...args: unknown[]): Promise<unknown> {\n if (!active()) return fn.apply(this, args);\n const parent = frames.getStore();\n const frame: Frame = { statements: 0, parent };\n // Only N+1 checks need the call site; capture it while the caller is on the stack.\n const site = !parent && config && config.nPlusOne !== false ? callSite(traced) : undefined;\n const start = process.hrtime.bigint();\n const finish = (error?: unknown) => {\n const durationMs = Math.round(Number(process.hrtime.bigint() - start) / 1e5) / 10;\n const reqId = getRequestContext()?.requestId;\n emit(\n {\n model,\n op,\n durationMs,\n statements: frame.statements,\n ...(reqId !== undefined && { reqId }),\n ...(error !== undefined && { error: (error as Error)?.message ?? String(error) }),\n },\n site,\n !parent,\n );\n };\n return frames\n .run(frame, () => fn.apply(this, args))\n .then(\n (result) => {\n finish();\n return result;\n },\n (err: unknown) => {\n finish(err);\n throw err;\n },\n );\n };\n t[op] = traced;\n }\n return target;\n}\n","import type { Pool } from 'pg';\nimport { getLogger } from '../logger.js';\nimport { countStatement } from './query-log.js';\nimport type { DatabasePoolConfig } from '../types.js';\n\n// Pre-Flight's PostgreSQL connection: a node-postgres Pool (exposed as `db`) plus a\n// Drizzle instance over it that the model adapter queries through.\n\n/* eslint-disable @typescript-eslint/no-explicit-any -- drizzle is an optional peer, loaded dynamically */\nlet pool: Pool | undefined;\n\n/** Only a genuinely missing package becomes \"not installed\"; other load errors surface as-is. */\nexport function notInstalled(err: unknown, pkg: string, install: string): Error {\n const code = (err as { code?: string }).code;\n return code === 'ERR_MODULE_NOT_FOUND' || code === 'MODULE_NOT_FOUND'\n ? new Error(`[EFC] ${pkg} is not installed. Run: ${install}`)\n : (err as Error);\n}\nlet orm: any;\n\nexport async function connectPostgres(\n url: string,\n poolConfig: DatabasePoolConfig = {},\n): Promise<Pool> {\n let PoolCtor: typeof Pool;\n try {\n const pg = (await import('pg')) as unknown as {\n default?: { Pool: typeof Pool };\n Pool?: typeof Pool;\n };\n PoolCtor = (pg.default?.Pool ?? pg.Pool)!;\n } catch (err) {\n throw notInstalled(err, 'pg', 'npm install pg drizzle-orm');\n }\n let drizzle: (client: Pool, config: object) => unknown;\n try {\n ({ drizzle } = (await import('drizzle-orm/node-postgres')) as unknown as {\n drizzle: (client: Pool, config: object) => unknown;\n });\n } catch (err) {\n throw notInstalled(err, 'drizzle-orm', 'npm install drizzle-orm');\n }\n\n const next = new PoolCtor({\n connectionString: url,\n ...(poolConfig.max !== undefined && { max: poolConfig.max }),\n ...(poolConfig.idleTimeoutMs !== undefined && { idleTimeoutMillis: poolConfig.idleTimeoutMs }),\n ...(poolConfig.connectionTimeoutMs !== undefined && {\n connectionTimeoutMillis: poolConfig.connectionTimeoutMs,\n }),\n });\n // Idle-client errors (e.g. the server restarting) are emitted on the pool; unhandled\n // they would crash the process.\n next.on('error', (err) => getLogger().error({ err }, 'PostgreSQL pool error'));\n try {\n await next.query('select 1');\n } catch (err) {\n await next.end().catch(() => {});\n throw explainPostgresError(err, url);\n }\n pool = next;\n // Every model statement goes through Drizzle, in or out of a transaction: count it.\n orm = drizzle(next, { logger: { logQuery: countStatement } });\n getLogger().info('PostgreSQL connected');\n return next;\n}\n\n/** Where a connection string points, without the password (for error messages). */\nfunction describeUrl(url: string): { where: string; user: string; database: string } {\n try {\n const u = new URL(url);\n const database = decodeURIComponent(u.pathname.slice(1)) || '(default)';\n return {\n where: `${u.hostname || 'localhost'}:${u.port || '5432'}`,\n user: decodeURIComponent(u.username) || '(none)',\n database,\n };\n } catch {\n return { where: '(unparsable DATABASE_URL)', user: '?', database: '?' };\n }\n}\n\n/**\n * node-postgres' connection errors, said in terms of DATABASE_URL — e.g. a URL with no password\n * surfaces from pg as \"SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string\".\n * Unrecognised errors come back unchanged. The original is kept as `cause`.\n */\nexport function explainPostgresError(err: unknown, url: string): Error {\n const e = err as { code?: string; message?: string };\n const msg = e.message ?? '';\n const { where, user, database } = describeUrl(url);\n const hosted = 'For Neon, Supabase or RDS, copy the full connection string from the dashboard.';\n let text: string | undefined;\n if (/client password must be a string/.test(msg)) {\n text = `PostgreSQL asked for a password and DATABASE_URL has none (user \"${user}\" at ${where}). Put it in the URL: postgres://${user === '(none)' ? 'user' : user}:<password>@${where}/${database === '(default)' ? 'db' : database}. ${hosted}`;\n } else if (e.code === '28P01') {\n text = `PostgreSQL rejected the password for user \"${user}\" at ${where}. Check DATABASE_URL (special characters in the password must be URL-encoded). ${hosted}`;\n } else if (e.code === '28000' && /role .* does not exist/.test(msg)) {\n text = `PostgreSQL has no user \"${user}\" at ${where}. Create it (CREATE ROLE ${user} LOGIN PASSWORD '…';) or fix the user in DATABASE_URL.`;\n } else if (/no pg_hba\\.conf entry.*no encryption/.test(msg)) {\n text = `PostgreSQL at ${where} only accepts encrypted connections. Add ?sslmode=require to DATABASE_URL.`;\n } else if (e.code === '28000') {\n text = `PostgreSQL at ${where} refused user \"${user}\": ${msg}`;\n } else if (e.code === '3D000') {\n text = `Database \"${database}\" does not exist at ${where}. Create it first: createdb ${database} (or CREATE DATABASE \"${database}\";).`;\n } else if (/does not support SSL/.test(msg)) {\n text = `PostgreSQL at ${where} doesn't support SSL. Remove sslmode / ssl from DATABASE_URL (local servers usually run without it).`;\n } else if (e.code === 'ECONNREFUSED') {\n text = `Nothing is accepting connections at ${where}. Is PostgreSQL running, and is the host/port in DATABASE_URL right?`;\n } else if (e.code === 'ENOTFOUND' || e.code === 'EAI_AGAIN') {\n text = `Can't resolve the PostgreSQL host in DATABASE_URL (${where}). Check the hostname.`;\n } else if (e.code === 'ETIMEDOUT' || /timeout/i.test(msg)) {\n text = `Timed out connecting to PostgreSQL at ${where}. Check the host, and that a firewall / the provider's IP allow-list lets this machine in.`;\n }\n return text ? new Error(`[EFC] ${text}`, { cause: err }) : (err as Error);\n}\n\n/**\n * Every cluster worker opens its own pools, so a machine's total is `workers × (pool + …)`.\n * Logs that total against the server's limit, warning when this machine alone can exhaust it.\n * Best effort: a failure to read the limit is ignored.\n */\nexport async function checkConnectionBudget(\n perMachine: number,\n breakdown: string,\n): Promise<void> {\n const log = getLogger();\n try {\n const { rows } = await getPool().query<{ max: number; reserved: number }>(\n `select current_setting('max_connections')::int as max,\n current_setting('superuser_reserved_connections')::int as reserved`,\n );\n const { max, reserved } = rows[0]!;\n const usable = max - reserved;\n if (perMachine > usable) {\n log.warn(\n `[EFC] PostgreSQL connections: up to ${perMachine} from this machine (${breakdown}), but the server allows ${usable} (max_connections ${max} − ${reserved} reserved). Under load, queries will fail with \"too many clients\". Lower databasePool.max or workers, or put PgBouncer in front.`,\n );\n } else {\n log.info(\n `PostgreSQL connections: up to ${perMachine} from this machine (${breakdown}) of ${usable} allowed — multiply by your instance count if you run several`,\n );\n }\n } catch {\n /* can't read the limit (permissions, pooler) — nothing to compare against */\n }\n}\n\nexport function getOrm(): any {\n if (!orm) {\n throw new Error(\n '[EFC] PostgreSQL not connected — set database/databaseUrl in ignite() (or call connectPostgres)',\n );\n }\n return orm;\n}\n\nexport function getPool(): Pool {\n if (!pool) throw new Error('[EFC] PostgreSQL not connected');\n return pool;\n}\n\nexport async function closePostgres(): Promise<void> {\n const p = pool;\n pool = undefined;\n orm = undefined;\n await p?.end();\n}\n"]}
@@ -7,7 +7,7 @@ var _chunk7YEX4MQVcjs = require('./chunk-7YEX4MQV.cjs');
7
7
  var _chunkTI24L4XEcjs = require('./chunk-TI24L4XE.cjs');
8
8
 
9
9
 
10
- var _chunkYL37D6KMcjs = require('./chunk-YL37D6KM.cjs');
10
+ var _chunkDUADUR6Rcjs = require('./chunk-DUADUR6R.cjs');
11
11
 
12
12
  // src/tasks/bullmq-backend.ts
13
13
  var closeImpl = null;
@@ -40,7 +40,7 @@ async function syncSchedules(queue) {
40
40
  await queue.removeJobScheduler(s.key);
41
41
  }
42
42
  }
43
- if (wanted.size > 0) _chunkYL37D6KMcjs.getLogger.call(void 0, ).info(`Scheduled ${wanted.size} cron task(s)`);
43
+ if (wanted.size > 0) _chunkDUADUR6Rcjs.getLogger.call(void 0, ).info(`Scheduled ${wanted.size} cron task(s)`);
44
44
  }
45
45
  async function closeBullMQ() {
46
46
  const close = closeImpl;
@@ -76,16 +76,16 @@ async function initBullMQ(opts) {
76
76
  { connection, concurrency: opts.concurrency }
77
77
  );
78
78
  worker.on("failed", (job, err) => {
79
- _chunkYL37D6KMcjs.getLogger.call(void 0, ).error(
79
+ _chunkDUADUR6Rcjs.getLogger.call(void 0, ).error(
80
80
  { task: _optionalChain([job, 'optionalAccess', _3 => _3.name]), jobId: _optionalChain([job, 'optionalAccess', _4 => _4.id]), attempt: _optionalChain([job, 'optionalAccess', _5 => _5.attemptsMade]), err },
81
81
  `Task ${_nullishCoalesce(_optionalChain([job, 'optionalAccess', _6 => _6.name]), () => ( "unknown"))} failed`
82
82
  );
83
83
  });
84
84
  worker.on("error", (err) => {
85
- _chunkYL37D6KMcjs.getLogger.call(void 0, ).error(`Task worker error: ${err.message}`);
85
+ _chunkDUADUR6Rcjs.getLogger.call(void 0, ).error(`Task worker error: ${err.message}`);
86
86
  });
87
87
  worker.on("completed", (job) => {
88
- _chunkYL37D6KMcjs.getLogger.call(void 0, ).info({ task: job.name, jobId: job.id }, `Task ${job.name} completed`);
88
+ _chunkDUADUR6Rcjs.getLogger.call(void 0, ).info({ task: job.name, jobId: job.id }, `Task ${job.name} completed`);
89
89
  });
90
90
  _chunkTI24L4XEcjs.setEnqueueImpl.call(void 0, async (name, payload) => {
91
91
  const def = _chunkTI24L4XEcjs.taskRegistry.get(name);
@@ -119,14 +119,14 @@ async function initBullMQ(opts) {
119
119
  });
120
120
  let closing = false;
121
121
  schedulesSynced = queue.waitUntilReady().then(() => syncSchedules(queue)).catch((err) => {
122
- if (!closing) _chunkYL37D6KMcjs.getLogger.call(void 0, ).error({ err }, "Failed to sync cron task schedules");
122
+ if (!closing) _chunkDUADUR6Rcjs.getLogger.call(void 0, ).error({ err }, "Failed to sync cron task schedules");
123
123
  });
124
124
  closeImpl = async () => {
125
125
  closing = true;
126
126
  await worker.close();
127
127
  await queue.close();
128
128
  };
129
- _chunkYL37D6KMcjs.getLogger.call(void 0, ).info("BullMQ backend initialised");
129
+ _chunkDUADUR6Rcjs.getLogger.call(void 0, ).info("BullMQ backend initialised");
130
130
  }
131
131
  function parseRedisUrl(url) {
132
132
  try {
@@ -151,4 +151,4 @@ function parseRedisUrl(url) {
151
151
 
152
152
 
153
153
  exports.closeBullMQ = closeBullMQ; exports.initBullMQ = initBullMQ; exports.parseRedisUrl = parseRedisUrl;
154
- //# sourceMappingURL=chunk-T4OHFU5T.cjs.map
154
+ //# sourceMappingURL=chunk-FMA76PRH.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-T4OHFU5T.cjs","../src/tasks/bullmq-backend.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACGA,IAAI,UAAA,EAA0C,IAAA;AAC9C,IAAI,gBAAA,EAAiC,OAAA,CAAQ,OAAA,CAAQ,CAAA;AAO9C,IAAM,iBAAA,EAAmB,WAAA;AAEhC,SAAS,UAAA,CAAW,GAAA,EAAqB;AACvC,EAAA,OAAO;AAAA;AAAA,IAEL,QAAA,EAAA,kBAAW,GAAA,CAAI,OAAA,CAAQ,OAAA,UAAW,GAAA,EAAA,EAAK,CAAA;AAAA,IACvC,OAAA,EAAS,EAAE,IAAA,mBAAM,GAAA,CAAI,OAAA,CAAQ,OAAA,UAAW,eAAA,EAAe,KAAA,EAAO,IAAK;AAAA,EACrE,CAAA;AACF;AAKA,MAAA,SAAe,aAAA,CAAc,KAAA,EAAsC;AACjE,EAAA,MAAM,OAAA,kBAAS,IAAI,GAAA,CAAY,CAAA;AAC/B,EAAA,IAAA,CAAA,MAAW,IAAA,GAAO,8BAAA,CAAa,MAAA,CAAO,CAAA,EAAG;AACvC,IAAA,GAAA,CAAI,CAAC,GAAA,CAAI,OAAA,CAAQ,QAAA,EAAU,QAAA;AAC3B,IAAA,MAAM,GAAA,EAAK,iBAAA,EAAmB,GAAA,CAAI,IAAA;AAClC,IAAA,MAAA,CAAO,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ACD,IAAA;AAEG,IAAA;AAC+B,MAAA;AACrB,IAAA;AACiD,MAAA;AACnD,MAAA;AACuD,QAAA;AACjE,MAAA;AACA,IAAA;AACkB,MAAA;AACpB,IAAA;AACD,EAAA;AAEa,EAAA;AAIc,EAAA;AAGiB,IAAA;AAC1C,EAAA;AAEqB,EAAA;AACZ,IAAA;AACS,IAAA;AACD,IAAA;AACpB,EAAA;AAE6C,EAAA;AAC/C;AAW4D;AACtD,EAAA;AACmB,IAAA;AACW,IAAA;AACV,MAAA;AACe,MAAA;AACrC,IAAA;AAC+D,IAAA;AACA,IAAA;AACpB,IAAA;AACR,IAAA;AACS,IAAA;AACrC,IAAA;AACD,EAAA;AACiC,IAAA;AACzC,EAAA;AACF;AD/CuE;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-T4OHFU5T.cjs","sourcesContent":[null,"import type { Job } from 'bullmq';\nimport type * as BullMQNS from 'bullmq';\nimport { taskRegistry, setEnqueueImpl } from './index.js';\nimport type { TaskDefinition } from '../types.js';\nimport { runInThread } from './thread-runner.js';\nimport { getLogger } from '../logger.js';\n\ninterface BullMQOpts {\n redisUrl: string;\n concurrency: number;\n enqueueTimeout: number;\n queue: string;\n}\n\nlet closeImpl: (() => Promise<void>) | null = null;\nlet schedulesSynced: Promise<void> = Promise.resolve();\n\n/** Resolves once cron schedulers have been reconciled with the registry (tests, CLI). */\nexport function whenSchedulesSynced(): Promise<void> {\n return schedulesSynced;\n}\n\nexport const SCHEDULER_PREFIX = 'efc-cron:';\n\nfunction jobOptions(def: TaskDefinition) {\n return {\n // BullMQ's `attempts` counts the first run; `retries` counts only the re-runs.\n attempts: (def.options.retries ?? 3) + 1,\n backoff: { type: def.options.backoff ?? 'exponential', delay: 1000 },\n };\n}\n\n// One job scheduler per task with a `schedule`, keyed by task name. upsert is\n// idempotent, so every cluster worker can run this without creating duplicates;\n// schedulers whose task lost its `schedule` (or was deleted) are removed.\nasync function syncSchedules(queue: BullMQNS.Queue): Promise<void> {\n const wanted = new Set<string>();\n for (const def of taskRegistry.values()) {\n if (!def.options.schedule) continue;\n const id = SCHEDULER_PREFIX + def.name;\n wanted.add(id);\n await queue.upsertJobScheduler(\n id,\n {\n pattern: def.options.schedule,\n ...(def.options.timezone !== undefined && { tz: def.options.timezone }),\n },\n { name: def.name, data: {}, opts: jobOptions(def) },\n );\n }\n for (const s of await queue.getJobSchedulers(0, -1)) {\n if (s.key.startsWith(SCHEDULER_PREFIX) && !wanted.has(s.key)) {\n await queue.removeJobScheduler(s.key);\n }\n }\n if (wanted.size > 0) getLogger().info(`Scheduled ${wanted.size} cron task(s)`);\n}\n\n/** Drains the BullMQ worker and closes both Redis connections. No-op if never initialised. */\nexport async function closeBullMQ(): Promise<void> {\n const close = closeImpl;\n closeImpl = null;\n await close?.();\n}\n\nexport async function initBullMQ(opts: BullMQOpts): Promise<void> {\n let bullmq: typeof BullMQNS;\n try {\n bullmq = await import('bullmq');\n } catch {\n throw new Error('[EFC] bullmq is not installed. Run: npm install bullmq');\n }\n\n const connection = parseRedisUrl(opts.redisUrl);\n // With the offline queue on (ioredis default) queue.add() buffers forever while Redis is\n // down, so enqueue() never settles. Off, commands reject once the connection drops; the\n // initial connect is bounded by the enqueueTimeout race below.\n const queue = new bullmq.Queue(opts.queue, {\n connection: { ...connection, enableOfflineQueue: false },\n });\n // Without a listener, ioredis connection errors surface as unhandled 'error' events.\n queue.on('error', () => {});\n\n const worker = new bullmq.Worker(\n opts.queue,\n async (job: Job) => {\n const def = taskRegistry.get(job.name);\n if (!def) {\n throw new Error(`[EFC] No task registered for name: ${job.name}`);\n }\n\n if (def.options.thread && def.filePath) {\n await runInThread(def.filePath, job.data);\n } else {\n await def.handler(job.data);\n }\n },\n { connection, concurrency: opts.concurrency },\n );\n\n worker.on('failed', (job: Job | undefined, err: Error) => {\n getLogger().error(\n { task: job?.name, jobId: job?.id, attempt: job?.attemptsMade, err },\n `Task ${job?.name ?? 'unknown'} failed`,\n );\n });\n\n worker.on('error', (err: Error) => {\n getLogger().error(`Task worker error: ${err.message}`);\n });\n\n worker.on('completed', (job: Job) => {\n getLogger().info({ task: job.name, jobId: job.id }, `Task ${job.name} completed`);\n });\n\n setEnqueueImpl(async (name, payload) => {\n const def = taskRegistry.get(name);\n if (!def) {\n throw new Error(\n `[EFC] Cannot enqueue unknown task: \"${name}\". Is the task file in tasksDir?`,\n );\n }\n\n const add = queue.waitUntilReady().then(() => queue.add(name, payload, jobOptions(def)));\n\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () =>\n reject(\n new Error(\n `[EFC] Cannot enqueue task \"${name}\": Redis at ${connection.host}:${connection.port} did not respond within ${opts.enqueueTimeout}ms`,\n ),\n ),\n opts.enqueueTimeout,\n );\n });\n\n try {\n await Promise.race([add, timeout]);\n } catch (err) {\n if (err instanceof Error && err.message.startsWith('[EFC]')) throw err;\n throw new Error(\n `[EFC] Cannot enqueue task \"${name}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n } finally {\n clearTimeout(timer);\n }\n });\n\n let closing = false;\n // Not awaited: a Redis outage at boot must not block the HTTP server from starting.\n schedulesSynced = queue\n .waitUntilReady()\n .then(() => syncSchedules(queue))\n .catch((err: unknown) => {\n // Shutting down before Redis ever answered aborts the wait — not a real failure.\n if (!closing) getLogger().error({ err }, 'Failed to sync cron task schedules');\n });\n\n closeImpl = async () => {\n closing = true;\n await worker.close();\n await queue.close();\n };\n\n getLogger().info('BullMQ backend initialised');\n}\n\ninterface RedisConnection {\n host: string;\n port: number;\n username?: string;\n password?: string;\n db?: number;\n tls?: Record<string, never>;\n}\n\nexport function parseRedisUrl(url: string): RedisConnection {\n try {\n const u = new URL(url);\n const result: RedisConnection = {\n host: u.hostname || 'localhost',\n port: parseInt(u.port || '6379', 10),\n };\n if (u.username) result.username = decodeURIComponent(u.username);\n if (u.password) result.password = decodeURIComponent(u.password);\n const db = parseInt(u.pathname.slice(1), 10);\n if (!Number.isNaN(db)) result.db = db;\n if (u.protocol === 'rediss:') result.tls = {};\n return result;\n } catch {\n return { host: 'localhost', port: 6379 };\n }\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-FMA76PRH.cjs","../src/tasks/bullmq-backend.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACGA,IAAI,UAAA,EAA0C,IAAA;AAC9C,IAAI,gBAAA,EAAiC,OAAA,CAAQ,OAAA,CAAQ,CAAA;AAO9C,IAAM,iBAAA,EAAmB,WAAA;AAEhC,SAAS,UAAA,CAAW,GAAA,EAAqB;AACvC,EAAA,OAAO;AAAA;AAAA,IAEL,QAAA,EAAA,kBAAW,GAAA,CAAI,OAAA,CAAQ,OAAA,UAAW,GAAA,EAAA,EAAK,CAAA;AAAA,IACvC,OAAA,EAAS,EAAE,IAAA,mBAAM,GAAA,CAAI,OAAA,CAAQ,OAAA,UAAW,eAAA,EAAe,KAAA,EAAO,IAAK;AAAA,EACrE,CAAA;AACF;AAKA,MAAA,SAAe,aAAA,CAAc,KAAA,EAAsC;AACjE,EAAA,MAAM,OAAA,kBAAS,IAAI,GAAA,CAAY,CAAA;AAC/B,EAAA,IAAA,CAAA,MAAW,IAAA,GAAO,8BAAA,CAAa,MAAA,CAAO,CAAA,EAAG;AACvC,IAAA,GAAA,CAAI,CAAC,GAAA,CAAI,OAAA,CAAQ,QAAA,EAAU,QAAA;AAC3B,IAAA,MAAM,GAAA,EAAK,iBAAA,EAAmB,GAAA,CAAI,IAAA;AAClC,IAAA,MAAA,CAAO,GAAA,CAAI,EAAE,CAAA;AACb,IAAA,MAAM,KAAA,CAAM,kBAAA;AAAA,MACV,EAAA;AAAA,MACA;AAAA,QACE,OAAA,EAAS,GAAA,CAAI,OAAA,CAAQ,QAAA;AAAA,QACrB,GAAI,GA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A;AAGiB,IAAA;AAC1C,EAAA;AAEqB,EAAA;AACZ,IAAA;AACS,IAAA;AACD,IAAA;AACpB,EAAA;AAE6C,EAAA;AAC/C;AAW4D;AACtD,EAAA;AACmB,IAAA;AACW,IAAA;AACV,MAAA;AACe,MAAA;AACrC,IAAA;AAC+D,IAAA;AACA,IAAA;AACpB,IAAA;AACR,IAAA;AACS,IAAA;AACrC,IAAA;AACD,EAAA;AACiC,IAAA;AACzC,EAAA;AACF;AD/CuE;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-FMA76PRH.cjs","sourcesContent":[null,"import type { Job } from 'bullmq';\nimport type * as BullMQNS from 'bullmq';\nimport { taskRegistry, setEnqueueImpl } from './index.js';\nimport type { TaskDefinition } from '../types.js';\nimport { runInThread } from './thread-runner.js';\nimport { getLogger } from '../logger.js';\n\ninterface BullMQOpts {\n redisUrl: string;\n concurrency: number;\n enqueueTimeout: number;\n queue: string;\n}\n\nlet closeImpl: (() => Promise<void>) | null = null;\nlet schedulesSynced: Promise<void> = Promise.resolve();\n\n/** Resolves once cron schedulers have been reconciled with the registry (tests, CLI). */\nexport function whenSchedulesSynced(): Promise<void> {\n return schedulesSynced;\n}\n\nexport const SCHEDULER_PREFIX = 'efc-cron:';\n\nfunction jobOptions(def: TaskDefinition) {\n return {\n // BullMQ's `attempts` counts the first run; `retries` counts only the re-runs.\n attempts: (def.options.retries ?? 3) + 1,\n backoff: { type: def.options.backoff ?? 'exponential', delay: 1000 },\n };\n}\n\n// One job scheduler per task with a `schedule`, keyed by task name. upsert is\n// idempotent, so every cluster worker can run this without creating duplicates;\n// schedulers whose task lost its `schedule` (or was deleted) are removed.\nasync function syncSchedules(queue: BullMQNS.Queue): Promise<void> {\n const wanted = new Set<string>();\n for (const def of taskRegistry.values()) {\n if (!def.options.schedule) continue;\n const id = SCHEDULER_PREFIX + def.name;\n wanted.add(id);\n await queue.upsertJobScheduler(\n id,\n {\n pattern: def.options.schedule,\n ...(def.options.timezone !== undefined && { tz: def.options.timezone }),\n },\n { name: def.name, data: {}, opts: jobOptions(def) },\n );\n }\n for (const s of await queue.getJobSchedulers(0, -1)) {\n if (s.key.startsWith(SCHEDULER_PREFIX) && !wanted.has(s.key)) {\n await queue.removeJobScheduler(s.key);\n }\n }\n if (wanted.size > 0) getLogger().info(`Scheduled ${wanted.size} cron task(s)`);\n}\n\n/** Drains the BullMQ worker and closes both Redis connections. No-op if never initialised. */\nexport async function closeBullMQ(): Promise<void> {\n const close = closeImpl;\n closeImpl = null;\n await close?.();\n}\n\nexport async function initBullMQ(opts: BullMQOpts): Promise<void> {\n let bullmq: typeof BullMQNS;\n try {\n bullmq = await import('bullmq');\n } catch {\n throw new Error('[EFC] bullmq is not installed. Run: npm install bullmq');\n }\n\n const connection = parseRedisUrl(opts.redisUrl);\n // With the offline queue on (ioredis default) queue.add() buffers forever while Redis is\n // down, so enqueue() never settles. Off, commands reject once the connection drops; the\n // initial connect is bounded by the enqueueTimeout race below.\n const queue = new bullmq.Queue(opts.queue, {\n connection: { ...connection, enableOfflineQueue: false },\n });\n // Without a listener, ioredis connection errors surface as unhandled 'error' events.\n queue.on('error', () => {});\n\n const worker = new bullmq.Worker(\n opts.queue,\n async (job: Job) => {\n const def = taskRegistry.get(job.name);\n if (!def) {\n throw new Error(`[EFC] No task registered for name: ${job.name}`);\n }\n\n if (def.options.thread && def.filePath) {\n await runInThread(def.filePath, job.data);\n } else {\n await def.handler(job.data);\n }\n },\n { connection, concurrency: opts.concurrency },\n );\n\n worker.on('failed', (job: Job | undefined, err: Error) => {\n getLogger().error(\n { task: job?.name, jobId: job?.id, attempt: job?.attemptsMade, err },\n `Task ${job?.name ?? 'unknown'} failed`,\n );\n });\n\n worker.on('error', (err: Error) => {\n getLogger().error(`Task worker error: ${err.message}`);\n });\n\n worker.on('completed', (job: Job) => {\n getLogger().info({ task: job.name, jobId: job.id }, `Task ${job.name} completed`);\n });\n\n setEnqueueImpl(async (name, payload) => {\n const def = taskRegistry.get(name);\n if (!def) {\n throw new Error(\n `[EFC] Cannot enqueue unknown task: \"${name}\". Is the task file in tasksDir?`,\n );\n }\n\n const add = queue.waitUntilReady().then(() => queue.add(name, payload, jobOptions(def)));\n\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () =>\n reject(\n new Error(\n `[EFC] Cannot enqueue task \"${name}\": Redis at ${connection.host}:${connection.port} did not respond within ${opts.enqueueTimeout}ms`,\n ),\n ),\n opts.enqueueTimeout,\n );\n });\n\n try {\n await Promise.race([add, timeout]);\n } catch (err) {\n if (err instanceof Error && err.message.startsWith('[EFC]')) throw err;\n throw new Error(\n `[EFC] Cannot enqueue task \"${name}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n } finally {\n clearTimeout(timer);\n }\n });\n\n let closing = false;\n // Not awaited: a Redis outage at boot must not block the HTTP server from starting.\n schedulesSynced = queue\n .waitUntilReady()\n .then(() => syncSchedules(queue))\n .catch((err: unknown) => {\n // Shutting down before Redis ever answered aborts the wait — not a real failure.\n if (!closing) getLogger().error({ err }, 'Failed to sync cron task schedules');\n });\n\n closeImpl = async () => {\n closing = true;\n await worker.close();\n await queue.close();\n };\n\n getLogger().info('BullMQ backend initialised');\n}\n\ninterface RedisConnection {\n host: string;\n port: number;\n username?: string;\n password?: string;\n db?: number;\n tls?: Record<string, never>;\n}\n\nexport function parseRedisUrl(url: string): RedisConnection {\n try {\n const u = new URL(url);\n const result: RedisConnection = {\n host: u.hostname || 'localhost',\n port: parseInt(u.port || '6379', 10),\n };\n if (u.username) result.username = decodeURIComponent(u.username);\n if (u.password) result.password = decodeURIComponent(u.password);\n const db = parseInt(u.pathname.slice(1), 10);\n if (!Number.isNaN(db)) result.db = db;\n if (u.protocol === 'rediss:') result.tls = {};\n return result;\n } catch {\n return { host: 'localhost', port: 6379 };\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getLogger
3
- } from "./chunk-277BSYVH.js";
3
+ } from "./chunk-73XJUT2S.js";
4
4
 
5
5
  // src/router/scan.ts
6
6
  import fs from "fs";
@@ -113,4 +113,4 @@ function scanDir(dir, base = dir, maxDepth = DEFAULT_MAX_DEPTH, _depth = 0) {
113
113
  export {
114
114
  scanDir
115
115
  };
116
- //# sourceMappingURL=chunk-RS4MXCPW.js.map
116
+ //# sourceMappingURL=chunk-NI2BNGGV.js.map
@@ -18,18 +18,16 @@ import {
18
18
  tableNameFor,
19
19
  timestampFields,
20
20
  validateAtPath
21
- } from "./chunk-QKQZF573.js";
21
+ } from "./chunk-ULWNHN6P.js";
22
22
  import {
23
23
  countStatement,
24
+ getLogger,
24
25
  getOrm,
25
26
  notInstalled,
26
27
  traceOps,
27
28
  untracked,
28
29
  whenQueryTracking
29
- } from "./chunk-HXV543HZ.js";
30
- import {
31
- getLogger
32
- } from "./chunk-277BSYVH.js";
30
+ } from "./chunk-73XJUT2S.js";
33
31
 
34
32
  // src/db/mongo-model.ts
35
33
  var mongoosePromise;
@@ -479,10 +477,32 @@ async function connectMongo(url, pool = {}) {
479
477
  serverSelectionTimeoutMS: pool.connectionTimeoutMs,
480
478
  waitQueueTimeoutMS: pool.connectionTimeoutMs
481
479
  }
480
+ }).catch((err) => {
481
+ throw explainMongoError(err, url);
482
482
  });
483
483
  getLogger().info("MongoDB connected");
484
484
  return mg.connection;
485
485
  }
486
+ function explainMongoError(err, url) {
487
+ const e = err;
488
+ let where = "(unparsable DATABASE_URL)";
489
+ let user = "(none)";
490
+ try {
491
+ const u = new URL(url);
492
+ where = u.host || "localhost";
493
+ user = decodeURIComponent(u.username) || "(none)";
494
+ } catch {
495
+ }
496
+ let text;
497
+ if (e.code === 18 || e.codeName === "AuthenticationFailed") {
498
+ text = `MongoDB rejected the login for user "${user}" at ${where}. Check the username and password in DATABASE_URL (special characters must be URL-encoded), and authSource if the user lives in another database.`;
499
+ } else if (e.name === "MongooseServerSelectionError" || e.name === "MongoServerSelectionError") {
500
+ text = `Could not reach MongoDB at ${where}. Is it running? On Atlas, add this machine's IP under Network Access.`;
501
+ } else if (e.name === "MongoParseError") {
502
+ text = `DATABASE_URL isn't a valid MongoDB connection string: ${e.message ?? ""}`;
503
+ }
504
+ return text ? new Error(`[EFC] ${text}`, { cause: err }) : err;
505
+ }
486
506
 
487
507
  // src/db/pg-model.ts
488
508
  function pgModel(name, tree, options) {
@@ -3046,4 +3066,4 @@ export {
3046
3066
  getDbClient,
3047
3067
  db
3048
3068
  };
3049
- //# sourceMappingURL=chunk-RRQ2RK5M.js.map
3069
+ //# sourceMappingURL=chunk-OFA7OGN5.js.map