express-file-cluster 0.3.14 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +204 -52
- package/dist/auth/index.cjs +12 -2
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +13 -2
- package/dist/auth/index.d.ts +13 -2
- package/dist/auth/index.js +12 -2
- package/dist/chunk-3VWD2ZED.js +60 -0
- package/dist/chunk-3VWD2ZED.js.map +1 -0
- package/dist/chunk-47K2532L.cjs +196 -0
- package/dist/chunk-47K2532L.cjs.map +1 -0
- package/dist/chunk-5PDAWMGF.js +438 -0
- package/dist/chunk-5PDAWMGF.js.map +1 -0
- package/dist/chunk-7YEX4MQV.cjs +38 -0
- package/dist/chunk-7YEX4MQV.cjs.map +1 -0
- package/dist/chunk-ALBDM5R3.cjs +60 -0
- package/dist/chunk-ALBDM5R3.cjs.map +1 -0
- package/dist/chunk-JJJJTACK.js +196 -0
- package/dist/chunk-JJJJTACK.js.map +1 -0
- package/dist/chunk-LJNSJFOL.js +38 -0
- package/dist/chunk-LJNSJFOL.js.map +1 -0
- package/dist/chunk-M7MUPWCE.js +116 -0
- package/dist/chunk-M7MUPWCE.js.map +1 -0
- package/dist/chunk-PMF4GMHD.js +154 -0
- package/dist/chunk-PMF4GMHD.js.map +1 -0
- package/dist/chunk-QTRGJ2EN.cjs +2635 -0
- package/dist/chunk-QTRGJ2EN.cjs.map +1 -0
- package/dist/chunk-RSBW2B3D.cjs +126 -0
- package/dist/chunk-RSBW2B3D.cjs.map +1 -0
- package/dist/chunk-RTFJ32T5.js +2635 -0
- package/dist/chunk-RTFJ32T5.js.map +1 -0
- package/dist/chunk-SFVEQ2T5.cjs +438 -0
- package/dist/chunk-SFVEQ2T5.cjs.map +1 -0
- package/dist/chunk-SZT36SGB.cjs +154 -0
- package/dist/chunk-SZT36SGB.cjs.map +1 -0
- package/dist/chunk-TI24L4XE.cjs.map +1 -1
- package/dist/chunk-ULQXD4YZ.cjs +116 -0
- package/dist/chunk-ULQXD4YZ.cjs.map +1 -0
- package/dist/chunk-VYHJX54R.js +126 -0
- package/dist/chunk-VYHJX54R.js.map +1 -0
- package/dist/cli/db-runner.cjs +497 -0
- package/dist/cli/db-runner.cjs.map +1 -0
- package/dist/cli/db-runner.d.cts +2 -0
- package/dist/cli/db-runner.d.ts +2 -0
- package/dist/cli/db-runner.js +497 -0
- package/dist/cli/db-runner.js.map +1 -0
- package/dist/cli/index.cjs +447 -69
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +473 -95
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/auth.md +232 -0
- package/dist/docs/api-reference/compose.md +78 -0
- package/dist/docs/api-reference/db.md +351 -0
- package/dist/docs/api-reference/http-error.md +109 -0
- package/dist/docs/api-reference/ignite.md +323 -0
- package/dist/docs/api-reference/table.md +250 -0
- package/dist/docs/api-reference/tasks.md +140 -0
- package/dist/docs/cli/db.md +38 -0
- package/dist/docs/cli/diagnostics.md +145 -0
- package/dist/docs/cli/generate.md +120 -0
- package/dist/docs/cli/index.md +48 -0
- package/dist/docs/cli/start.md +112 -0
- package/dist/docs/contributing/index.md +139 -0
- package/dist/docs/core-concepts/background-tasks.md +228 -0
- package/dist/docs/core-concepts/clustering.md +114 -0
- package/dist/docs/core-concepts/file-based-routing.md +235 -0
- package/dist/docs/core-concepts/index.md +79 -0
- package/dist/docs/core-concepts/middleware.md +144 -0
- package/dist/docs/getting-started/index.md +91 -0
- package/dist/docs/getting-started/project-structure.md +154 -0
- package/dist/docs/guides/ai-agents.md +48 -0
- package/dist/docs/guides/authentication.md +196 -0
- package/dist/docs/guides/caching.md +124 -0
- package/dist/docs/guides/database.md +217 -0
- package/dist/docs/guides/deployment.md +171 -0
- package/dist/docs/guides/environment-variables.md +106 -0
- package/dist/docs/guides/error-handling.md +172 -0
- package/dist/docs/guides/generated-portals.md +115 -0
- package/dist/docs/guides/logging.md +70 -0
- package/dist/docs/guides/mailer.md +166 -0
- package/dist/docs/guides/migrations.md +106 -0
- package/dist/docs/guides/rbac.md +89 -0
- package/dist/docs/guides/validation.md +95 -0
- package/dist/docs/index.md +93 -0
- package/dist/docs/skills/SKILL.md +44 -0
- package/dist/docs/skills/api-surface.md +308 -0
- package/dist/docs/skills/auth-internals.md +141 -0
- package/dist/docs/skills/pre-flight.md +142 -0
- package/dist/docs/skills/routing-rules.md +114 -0
- package/dist/docs/skills/tasks-internals.md +172 -0
- package/dist/docs/skills/what-not-to-invent.md +251 -0
- package/dist/index.cjs +289 -391
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +472 -7
- package/dist/index.d.ts +472 -7
- package/dist/index.js +283 -385
- package/dist/index.js.map +1 -1
- package/dist/pgboss-backend-3E6ATY42.cjs +14 -0
- package/dist/pgboss-backend-3E6ATY42.cjs.map +1 -0
- package/dist/pgboss-backend-UUJOVEYK.js +14 -0
- package/dist/pgboss-backend-UUJOVEYK.js.map +1 -0
- package/dist/tasks/index.cjs.map +1 -1
- package/dist/tasks/index.d.cts +1 -1
- package/dist/tasks/index.d.ts +1 -1
- package/dist/types-DJCPAsM4.d.cts +541 -0
- package/dist/types-DJCPAsM4.d.ts +541 -0
- package/package.json +28 -5
- package/dist/chunk-6522HS2J.cjs +0 -99
- package/dist/chunk-6522HS2J.cjs.map +0 -1
- package/dist/chunk-DGVOJNR6.cjs +0 -55
- package/dist/chunk-DGVOJNR6.cjs.map +0 -1
- package/dist/chunk-KOHLLUN7.js +0 -55
- package/dist/chunk-KOHLLUN7.js.map +0 -1
- package/dist/chunk-VIP3PFWZ.js +0 -99
- package/dist/chunk-VIP3PFWZ.js.map +0 -1
- package/dist/types-BusbSenn.d.cts +0 -162
- package/dist/types-BusbSenn.d.ts +0 -162
package/dist/index.js
CHANGED
|
@@ -1,17 +1,55 @@
|
|
|
1
1
|
import {
|
|
2
|
+
cache,
|
|
3
|
+
closeCache,
|
|
2
4
|
configureAuth,
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
configureCache,
|
|
6
|
+
servePrimaryCache
|
|
7
|
+
} from "./chunk-5PDAWMGF.js";
|
|
8
|
+
import {
|
|
9
|
+
scanDir
|
|
10
|
+
} from "./chunk-M7MUPWCE.js";
|
|
11
|
+
import {
|
|
12
|
+
closeBullMQ,
|
|
13
|
+
initBullMQ
|
|
14
|
+
} from "./chunk-PMF4GMHD.js";
|
|
15
|
+
import {
|
|
16
|
+
HttpError,
|
|
17
|
+
ModelValidationError,
|
|
18
|
+
connectMongo,
|
|
19
|
+
currentTx,
|
|
20
|
+
db,
|
|
21
|
+
defineModel,
|
|
22
|
+
defineTable,
|
|
23
|
+
getDbClient,
|
|
24
|
+
getDbEngine,
|
|
25
|
+
isHttpError,
|
|
26
|
+
loadMongoose,
|
|
27
|
+
runInTx,
|
|
28
|
+
setAutoSync,
|
|
29
|
+
setDbClient,
|
|
30
|
+
setDbEngine
|
|
31
|
+
} from "./chunk-RTFJ32T5.js";
|
|
32
|
+
import {
|
|
33
|
+
connectPostgres,
|
|
34
|
+
getOrm
|
|
35
|
+
} from "./chunk-3VWD2ZED.js";
|
|
36
|
+
import {
|
|
37
|
+
closePgBoss,
|
|
38
|
+
initPgBoss
|
|
39
|
+
} from "./chunk-JJJJTACK.js";
|
|
40
|
+
import "./chunk-LJNSJFOL.js";
|
|
6
41
|
import {
|
|
7
42
|
listTasks,
|
|
8
|
-
registerTask
|
|
9
|
-
setEnqueueImpl,
|
|
10
|
-
taskRegistry
|
|
43
|
+
registerTask
|
|
11
44
|
} from "./chunk-HBYSKULC.js";
|
|
12
45
|
import {
|
|
13
|
-
|
|
14
|
-
|
|
46
|
+
configureLogger,
|
|
47
|
+
getCurrentUser,
|
|
48
|
+
getLogger,
|
|
49
|
+
logger,
|
|
50
|
+
requestLogger,
|
|
51
|
+
runWithContext
|
|
52
|
+
} from "./chunk-VYHJX54R.js";
|
|
15
53
|
|
|
16
54
|
// src/index.ts
|
|
17
55
|
import fs2 from "fs";
|
|
@@ -22,6 +60,70 @@ import cluster2 from "cluster";
|
|
|
22
60
|
import os from "os";
|
|
23
61
|
import path2 from "path";
|
|
24
62
|
|
|
63
|
+
// src/router/validate.ts
|
|
64
|
+
var LOCATIONS = ["params", "query", "body"];
|
|
65
|
+
function isRequestSchema(value) {
|
|
66
|
+
return value != null && typeof value === "object" && LOCATIONS.some((loc) => loc in value);
|
|
67
|
+
}
|
|
68
|
+
function schemaFor(schema, method) {
|
|
69
|
+
if (!schema) return void 0;
|
|
70
|
+
const byMethod = schema[method];
|
|
71
|
+
if (isRequestSchema(byMethod)) return byMethod;
|
|
72
|
+
return isRequestSchema(schema) ? schema : void 0;
|
|
73
|
+
}
|
|
74
|
+
function pathToString(path3) {
|
|
75
|
+
if (!path3) return "";
|
|
76
|
+
return path3.map((p) => typeof p === "object" && p !== null && "key" in p ? p.key : p).map(String).join(".");
|
|
77
|
+
}
|
|
78
|
+
async function run(validator, input) {
|
|
79
|
+
const std = validator["~standard"];
|
|
80
|
+
if (std && typeof std.validate === "function") {
|
|
81
|
+
return await std.validate(input);
|
|
82
|
+
}
|
|
83
|
+
const v = validator;
|
|
84
|
+
const parse = v.safeParseAsync ?? v.safeParse;
|
|
85
|
+
if (typeof parse !== "function") {
|
|
86
|
+
throw new Error("[EFC] Route schema entries must be Standard Schema validators (e.g. zod)");
|
|
87
|
+
}
|
|
88
|
+
const r = await parse.call(validator, input);
|
|
89
|
+
return r.success ? { value: r.data } : { issues: r.error?.issues ?? [{ message: "Invalid" }] };
|
|
90
|
+
}
|
|
91
|
+
function validateRequest(schema) {
|
|
92
|
+
return (req, res, next) => {
|
|
93
|
+
void (async () => {
|
|
94
|
+
const issues = [];
|
|
95
|
+
const parsed = {};
|
|
96
|
+
for (const location of LOCATIONS) {
|
|
97
|
+
const validator = schema[location];
|
|
98
|
+
if (!validator) continue;
|
|
99
|
+
const result = await run(validator, req[location]);
|
|
100
|
+
if (result.issues) {
|
|
101
|
+
for (const issue of result.issues) {
|
|
102
|
+
issues.push({ location, path: pathToString(issue.path), message: issue.message });
|
|
103
|
+
}
|
|
104
|
+
} else {
|
|
105
|
+
parsed[location] = result.value;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (issues.length > 0) {
|
|
109
|
+
res.status(400).json({ error: "Validation failed", statusCode: 400, issues });
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
for (const location of LOCATIONS) {
|
|
113
|
+
if (location in parsed) {
|
|
114
|
+
Object.defineProperty(req, location, {
|
|
115
|
+
value: parsed[location],
|
|
116
|
+
writable: true,
|
|
117
|
+
configurable: true,
|
|
118
|
+
enumerable: true
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
next();
|
|
123
|
+
})().catch(next);
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
25
127
|
// src/router/mount.ts
|
|
26
128
|
var HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
|
|
27
129
|
function asyncWrap(handler) {
|
|
@@ -29,6 +131,25 @@ function asyncWrap(handler) {
|
|
|
29
131
|
Promise.resolve(handler(req, res, next)).catch(next);
|
|
30
132
|
};
|
|
31
133
|
}
|
|
134
|
+
function namedParams(route) {
|
|
135
|
+
const catchAlls = new Set([...route.urlPath.matchAll(/:([A-Za-z0-9_$]+)\*/g)].map((m) => m[1]));
|
|
136
|
+
return (req, _res, next) => {
|
|
137
|
+
const positional = req.params;
|
|
138
|
+
const named = {};
|
|
139
|
+
route.params.forEach((name, i) => {
|
|
140
|
+
const value = positional[String(i)];
|
|
141
|
+
if (value === void 0 || value === "") {
|
|
142
|
+
named[name] = catchAlls.has(name) ? [] : void 0;
|
|
143
|
+
} else if (catchAlls.has(name)) {
|
|
144
|
+
named[name] = value.split("/").filter(Boolean).map(decodeURIComponent);
|
|
145
|
+
} else {
|
|
146
|
+
named[name] = decodeURIComponent(value);
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
req.params = named;
|
|
150
|
+
next();
|
|
151
|
+
};
|
|
152
|
+
}
|
|
32
153
|
async function mountRoutes(app, routes) {
|
|
33
154
|
const mounted = [];
|
|
34
155
|
for (const route of routes) {
|
|
@@ -36,14 +157,21 @@ async function mountRoutes(app, routes) {
|
|
|
36
157
|
const routeMiddlewares = Array.isArray(mod["middlewares"]) ? mod["middlewares"] : [];
|
|
37
158
|
const raw = mod["meta"];
|
|
38
159
|
const meta = raw != null && typeof raw === "object" && !Array.isArray(raw) ? raw : void 0;
|
|
160
|
+
const schema = mod["schema"] != null && typeof mod["schema"] === "object" ? mod["schema"] : void 0;
|
|
161
|
+
const routePath = route.pattern ?? route.urlPath;
|
|
162
|
+
const paramMapper = route.pattern ? [namedParams(route)] : [];
|
|
39
163
|
const implemented = [];
|
|
40
164
|
const unimplemented = [];
|
|
41
165
|
for (const method of HTTP_METHODS) {
|
|
42
166
|
if (typeof mod[method] === "function") {
|
|
43
167
|
implemented.push(method);
|
|
168
|
+
const methodSchema = schemaFor(schema, method);
|
|
169
|
+
const validation = methodSchema ? [validateRequest(methodSchema)] : [];
|
|
44
170
|
app[method.toLowerCase()](
|
|
45
|
-
|
|
171
|
+
routePath,
|
|
172
|
+
...paramMapper,
|
|
46
173
|
...routeMiddlewares,
|
|
174
|
+
...validation,
|
|
47
175
|
asyncWrap(mod[method])
|
|
48
176
|
);
|
|
49
177
|
} else {
|
|
@@ -52,7 +180,7 @@ async function mountRoutes(app, routes) {
|
|
|
52
180
|
}
|
|
53
181
|
if (implemented.length > 0 && unimplemented.length > 0) {
|
|
54
182
|
const allowHeader = implemented.join(", ");
|
|
55
|
-
app.all(
|
|
183
|
+
app.all(routePath, (req, res, next) => {
|
|
56
184
|
if (unimplemented.includes(req.method)) {
|
|
57
185
|
res.set("Allow", allowHeader).status(405).json({ error: "Method Not Allowed" });
|
|
58
186
|
} else {
|
|
@@ -73,11 +201,15 @@ function workerCount() {
|
|
|
73
201
|
}
|
|
74
202
|
function shutdownMaster() {
|
|
75
203
|
isShuttingDown = true;
|
|
76
|
-
|
|
204
|
+
getLogger().info(`Cluster primary (pid=${process.pid}) shutting down, waiting for workers\u2026`);
|
|
205
|
+
if (workerCount() === 0) process.exit(0);
|
|
206
|
+
for (const worker of Object.values(cluster.workers ?? {})) {
|
|
207
|
+
worker?.process.kill("SIGTERM");
|
|
208
|
+
}
|
|
77
209
|
}
|
|
78
210
|
function runMaster(options = {}) {
|
|
79
211
|
const count = options.workers ?? 1;
|
|
80
|
-
|
|
212
|
+
getLogger().info(`Primary ${process.pid} starting ${count} workers`);
|
|
81
213
|
for (let i = 0; i < count; i++) {
|
|
82
214
|
cluster.fork();
|
|
83
215
|
}
|
|
@@ -87,280 +219,19 @@ function runMaster(options = {}) {
|
|
|
87
219
|
cluster.on("exit", (worker, code, signal) => {
|
|
88
220
|
const exitCode = code ?? (signal ? -1 : 0);
|
|
89
221
|
if (isShuttingDown) {
|
|
90
|
-
|
|
222
|
+
getLogger().info(`Worker ${worker.id} gracefully exited`);
|
|
91
223
|
if (workerCount() === 0) {
|
|
92
|
-
|
|
224
|
+
getLogger().info("All workers exited. Primary exiting.");
|
|
93
225
|
process.exit(0);
|
|
94
226
|
}
|
|
95
227
|
return;
|
|
96
228
|
}
|
|
97
|
-
|
|
229
|
+
getLogger().warn(`Worker ${worker.id} exited (code=${exitCode}), respawning\u2026`);
|
|
98
230
|
options.onWorkerCrash?.(worker.id, exitCode);
|
|
99
231
|
cluster.fork();
|
|
100
232
|
});
|
|
101
233
|
}
|
|
102
234
|
|
|
103
|
-
// src/errors.ts
|
|
104
|
-
var HttpError = class _HttpError extends Error {
|
|
105
|
-
statusCode;
|
|
106
|
-
constructor(statusCode, message) {
|
|
107
|
-
super(message);
|
|
108
|
-
this.name = "HttpError";
|
|
109
|
-
this.statusCode = statusCode;
|
|
110
|
-
Error.captureStackTrace(this, _HttpError);
|
|
111
|
-
}
|
|
112
|
-
/**
|
|
113
|
-
* Wraps an unknown caught value into an `HttpError`.
|
|
114
|
-
* If the value is already an `HttpError`, it is returned as-is.
|
|
115
|
-
* Otherwise the `message` from the caught `Error` (or a fallback) is used.
|
|
116
|
-
*
|
|
117
|
-
* @example
|
|
118
|
-
* } catch (err) {
|
|
119
|
-
* throw HttpError.from(err, 500, 'Something went wrong');
|
|
120
|
-
* }
|
|
121
|
-
*/
|
|
122
|
-
static from(err, statusCode = 500, fallback = "Internal Server Error") {
|
|
123
|
-
if (err instanceof _HttpError) return err;
|
|
124
|
-
const message = err instanceof Error ? err.message : fallback;
|
|
125
|
-
return new _HttpError(statusCode, message);
|
|
126
|
-
}
|
|
127
|
-
/** Returns a plain object representation suitable for JSON serialization. */
|
|
128
|
-
toJSON() {
|
|
129
|
-
return {
|
|
130
|
-
statusCode: this.statusCode,
|
|
131
|
-
error: this.name,
|
|
132
|
-
message: this.message
|
|
133
|
-
};
|
|
134
|
-
}
|
|
135
|
-
};
|
|
136
|
-
function isHttpError(value) {
|
|
137
|
-
return value instanceof HttpError;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
// src/db/mongo.ts
|
|
141
|
-
var mongoose;
|
|
142
|
-
async function loadMongoose() {
|
|
143
|
-
if (mongoose) return mongoose;
|
|
144
|
-
try {
|
|
145
|
-
mongoose = await import("mongoose");
|
|
146
|
-
return mongoose;
|
|
147
|
-
} catch {
|
|
148
|
-
throw new Error("[EFC] mongoose is not installed. Run: npm install mongoose");
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
async function connectMongo(url) {
|
|
152
|
-
const mg = await loadMongoose();
|
|
153
|
-
await mg.connect(url);
|
|
154
|
-
console.log("[EFC] MongoDB connected");
|
|
155
|
-
return mg.connection;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
// src/db/model.ts
|
|
159
|
-
import { randomUUID, randomBytes } from "crypto";
|
|
160
|
-
function normalise(doc) {
|
|
161
|
-
const id = doc["_id"] ? String(doc["_id"]) : "";
|
|
162
|
-
return { ...doc, id };
|
|
163
|
-
}
|
|
164
|
-
var STATIC_DEFAULT_OPERATORS = {
|
|
165
|
-
$now: () => /* @__PURE__ */ new Date(),
|
|
166
|
-
$uuid: () => randomUUID(),
|
|
167
|
-
$timestamp: () => Date.now(),
|
|
168
|
-
$shortId: () => randomBytes(12).toString("base64url")
|
|
169
|
-
};
|
|
170
|
-
var FIXED_DEFAULT_OPERATORS = /* @__PURE__ */ new Set(["$now", "$uuid", "$objectId", "$timestamp", "$shortId"]);
|
|
171
|
-
function isCurrentUserOperator(value) {
|
|
172
|
-
return typeof value === "string" && (value === "$currentUser" || value.startsWith("$currentUser."));
|
|
173
|
-
}
|
|
174
|
-
function isDefaultOperator(value) {
|
|
175
|
-
return typeof value === "string" && FIXED_DEFAULT_OPERATORS.has(value) || isCurrentUserOperator(value);
|
|
176
|
-
}
|
|
177
|
-
function resolveDefault(value, mg) {
|
|
178
|
-
if (!isDefaultOperator(value)) return value;
|
|
179
|
-
if (value === "$objectId") return () => new mg.Types.ObjectId();
|
|
180
|
-
if (value === "$currentUser") return () => getCurrentUser();
|
|
181
|
-
if (isCurrentUserOperator(value)) {
|
|
182
|
-
const key = value.slice("$currentUser.".length);
|
|
183
|
-
return () => getCurrentUser()?.[key];
|
|
184
|
-
}
|
|
185
|
-
return STATIC_DEFAULT_OPERATORS[value];
|
|
186
|
-
}
|
|
187
|
-
function isNestedArraySchema(def) {
|
|
188
|
-
return Array.isArray(def);
|
|
189
|
-
}
|
|
190
|
-
function primitiveCtor(type, mg) {
|
|
191
|
-
switch (type) {
|
|
192
|
-
case "string":
|
|
193
|
-
return String;
|
|
194
|
-
case "number":
|
|
195
|
-
return Number;
|
|
196
|
-
case "boolean":
|
|
197
|
-
return Boolean;
|
|
198
|
-
case "date":
|
|
199
|
-
return Date;
|
|
200
|
-
case "object":
|
|
201
|
-
return Object;
|
|
202
|
-
case "objectId":
|
|
203
|
-
return mg.Schema.Types.ObjectId;
|
|
204
|
-
case "array":
|
|
205
|
-
return Array;
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
function buildFieldEntry(def, mg) {
|
|
209
|
-
const entry = {};
|
|
210
|
-
if (def.type === "array") {
|
|
211
|
-
if (def.of === "objectId") {
|
|
212
|
-
const item = { type: mg.Schema.Types.ObjectId };
|
|
213
|
-
if (def.ref !== void 0) item["ref"] = def.ref;
|
|
214
|
-
entry["type"] = [item];
|
|
215
|
-
} else if (def.of) {
|
|
216
|
-
entry["type"] = [primitiveCtor(def.of, mg)];
|
|
217
|
-
} else {
|
|
218
|
-
entry["type"] = Array;
|
|
219
|
-
}
|
|
220
|
-
} else {
|
|
221
|
-
entry["type"] = primitiveCtor(def.type, mg);
|
|
222
|
-
if (def.type === "objectId" && def.ref !== void 0) entry["ref"] = def.ref;
|
|
223
|
-
}
|
|
224
|
-
if (def.required !== void 0) entry["required"] = def.required;
|
|
225
|
-
if (def.unique !== void 0) entry["unique"] = def.unique;
|
|
226
|
-
if (def.default !== void 0) entry["default"] = resolveDefault(def.default, mg);
|
|
227
|
-
if (def.enum !== void 0) entry["enum"] = def.enum;
|
|
228
|
-
return entry;
|
|
229
|
-
}
|
|
230
|
-
function buildMongooseSchema(schema, mg) {
|
|
231
|
-
const out = {};
|
|
232
|
-
for (const [key, def] of Object.entries(schema)) {
|
|
233
|
-
if (isNestedArraySchema(def)) {
|
|
234
|
-
out[key] = def[0] ? [buildMongooseSchema(def[0], mg)] : [];
|
|
235
|
-
} else {
|
|
236
|
-
out[key] = buildFieldEntry(def, mg);
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
return out;
|
|
240
|
-
}
|
|
241
|
-
function collectSequenceFields(name, schema) {
|
|
242
|
-
const fields = [];
|
|
243
|
-
for (const [path3, def] of Object.entries(schema)) {
|
|
244
|
-
if (isNestedArraySchema(def)) continue;
|
|
245
|
-
if (def.sequence) {
|
|
246
|
-
const key = typeof def.sequence === "string" ? def.sequence : `${name}.${path3}`;
|
|
247
|
-
fields.push({ path: path3, key });
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
return fields;
|
|
251
|
-
}
|
|
252
|
-
var COUNTER_MODEL_NAME = "__EFCCounter__";
|
|
253
|
-
function getCounterModel(mg) {
|
|
254
|
-
if (mg.models[COUNTER_MODEL_NAME]) {
|
|
255
|
-
return mg.models[COUNTER_MODEL_NAME];
|
|
256
|
-
}
|
|
257
|
-
const counterSchema = new mg.Schema(
|
|
258
|
-
{ _id: { type: String, required: true }, seq: { type: Number, default: 0 } },
|
|
259
|
-
{ collection: "efc_counters", versionKey: false }
|
|
260
|
-
);
|
|
261
|
-
return mg.model(COUNTER_MODEL_NAME, counterSchema);
|
|
262
|
-
}
|
|
263
|
-
async function nextSequence(mg, key) {
|
|
264
|
-
const Counter = getCounterModel(mg);
|
|
265
|
-
const doc = await Counter.findByIdAndUpdate(
|
|
266
|
-
key,
|
|
267
|
-
{ $inc: { seq: 1 } },
|
|
268
|
-
{ returnDocument: "after", upsert: true }
|
|
269
|
-
).lean();
|
|
270
|
-
return doc.seq;
|
|
271
|
-
}
|
|
272
|
-
async function getModel(name, schema, options = {}) {
|
|
273
|
-
let mg;
|
|
274
|
-
try {
|
|
275
|
-
const mod = await import("mongoose");
|
|
276
|
-
mg = mod.default || mod;
|
|
277
|
-
} catch {
|
|
278
|
-
throw new Error("[EFC] mongoose is not installed. Run: npm install mongoose");
|
|
279
|
-
}
|
|
280
|
-
if (mg.models[name]) return mg.models[name];
|
|
281
|
-
const schemaObj = buildMongooseSchema(schema, mg);
|
|
282
|
-
const mongooseSchema = new mg.Schema(schemaObj, { timestamps: options.timestamps ?? true });
|
|
283
|
-
const sequenceFields = collectSequenceFields(name, schema);
|
|
284
|
-
if (sequenceFields.length > 0) {
|
|
285
|
-
mongooseSchema.pre("validate", async function() {
|
|
286
|
-
if (!this.isNew) return;
|
|
287
|
-
for (const { path: path3, key } of sequenceFields) {
|
|
288
|
-
if (this.get(path3) == null) {
|
|
289
|
-
this.set(path3, await nextSequence(mg, key));
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
});
|
|
293
|
-
}
|
|
294
|
-
return mg.model(name, mongooseSchema);
|
|
295
|
-
}
|
|
296
|
-
function defineModel(name, schema, options) {
|
|
297
|
-
return {
|
|
298
|
-
async find(filter = {}, queryOptions) {
|
|
299
|
-
const M = await getModel(name, schema, options);
|
|
300
|
-
const query = M.find(filter);
|
|
301
|
-
if (queryOptions?.populate) query.populate(queryOptions.populate);
|
|
302
|
-
const docs = await query.lean();
|
|
303
|
-
return docs.map(normalise);
|
|
304
|
-
},
|
|
305
|
-
async findById(id, queryOptions) {
|
|
306
|
-
const M = await getModel(name, schema, options);
|
|
307
|
-
const query = M.findById(id);
|
|
308
|
-
if (queryOptions?.populate) query.populate(queryOptions.populate);
|
|
309
|
-
const doc = await query.lean();
|
|
310
|
-
if (!doc) return null;
|
|
311
|
-
return normalise(doc);
|
|
312
|
-
},
|
|
313
|
-
async findOne(filter, queryOptions) {
|
|
314
|
-
const M = await getModel(name, schema, options);
|
|
315
|
-
const query = M.findOne(filter);
|
|
316
|
-
if (queryOptions?.populate) query.populate(queryOptions.populate);
|
|
317
|
-
const doc = await query.lean();
|
|
318
|
-
if (!doc) return null;
|
|
319
|
-
return normalise(doc);
|
|
320
|
-
},
|
|
321
|
-
async create(data) {
|
|
322
|
-
const M = await getModel(name, schema, options);
|
|
323
|
-
const doc = await M.create(data);
|
|
324
|
-
return normalise(doc.toObject());
|
|
325
|
-
},
|
|
326
|
-
async update(id, data) {
|
|
327
|
-
const M = await getModel(name, schema, options);
|
|
328
|
-
const doc = await M.findByIdAndUpdate(id, data, { returnDocument: "after" }).lean();
|
|
329
|
-
if (!doc) return null;
|
|
330
|
-
return normalise(doc);
|
|
331
|
-
},
|
|
332
|
-
async delete(id) {
|
|
333
|
-
const M = await getModel(name, schema, options);
|
|
334
|
-
await M.findByIdAndDelete(id);
|
|
335
|
-
},
|
|
336
|
-
async count(filter = {}) {
|
|
337
|
-
const M = await getModel(name, schema, options);
|
|
338
|
-
return M.countDocuments(filter);
|
|
339
|
-
}
|
|
340
|
-
};
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
// src/db/index.ts
|
|
344
|
-
var _client = null;
|
|
345
|
-
function setDbClient(client) {
|
|
346
|
-
_client = client;
|
|
347
|
-
}
|
|
348
|
-
function getDbClient() {
|
|
349
|
-
if (!_client) {
|
|
350
|
-
throw new Error("[EFC] db not ready \u2014 accessed before Pre-Flight completed");
|
|
351
|
-
}
|
|
352
|
-
return _client;
|
|
353
|
-
}
|
|
354
|
-
var db = new Proxy({}, {
|
|
355
|
-
get(_target, prop) {
|
|
356
|
-
return getDbClient()[prop];
|
|
357
|
-
},
|
|
358
|
-
set(_target, prop, value) {
|
|
359
|
-
getDbClient()[prop] = value;
|
|
360
|
-
return true;
|
|
361
|
-
}
|
|
362
|
-
});
|
|
363
|
-
|
|
364
235
|
// src/tasks/scanner.ts
|
|
365
236
|
import fs from "fs";
|
|
366
237
|
import path from "path";
|
|
@@ -374,113 +245,17 @@ async function scanTasks(tasksDir) {
|
|
|
374
245
|
const mod = await import(filePath);
|
|
375
246
|
const def = mod["default"];
|
|
376
247
|
if (!def || typeof def.handler !== "function") {
|
|
377
|
-
|
|
248
|
+
getLogger().warn(`Task file ${file} has no valid default export \u2014 skipping`);
|
|
378
249
|
continue;
|
|
379
250
|
}
|
|
380
251
|
registerTask(taskName, { ...def, filePath });
|
|
381
|
-
|
|
252
|
+
getLogger().debug(`Registered task: ${taskName}`);
|
|
382
253
|
} catch (err) {
|
|
383
|
-
|
|
254
|
+
getLogger().warn({ err }, `Failed to load task ${file}`);
|
|
384
255
|
}
|
|
385
256
|
}
|
|
386
257
|
}
|
|
387
258
|
|
|
388
|
-
// src/tasks/thread-runner.ts
|
|
389
|
-
import { Worker, workerData, parentPort, isMainThread } from "worker_threads";
|
|
390
|
-
if (!isMainThread) {
|
|
391
|
-
const { handlerPath, payload } = workerData;
|
|
392
|
-
(async () => {
|
|
393
|
-
try {
|
|
394
|
-
const mod = await import(handlerPath);
|
|
395
|
-
const def = mod["default"];
|
|
396
|
-
if (!def || typeof def.handler !== "function") {
|
|
397
|
-
throw new Error(`[EFC] Thread runner: no valid task export in ${handlerPath}`);
|
|
398
|
-
}
|
|
399
|
-
await def.handler(payload);
|
|
400
|
-
parentPort?.postMessage({ ok: true });
|
|
401
|
-
} catch (err) {
|
|
402
|
-
parentPort?.postMessage({ ok: false, error: String(err) });
|
|
403
|
-
}
|
|
404
|
-
})();
|
|
405
|
-
}
|
|
406
|
-
function runInThread(handlerPath, payload) {
|
|
407
|
-
return new Promise((resolve, reject) => {
|
|
408
|
-
const worker = new Worker(new URL("./thread-runner.js", import.meta.url), {
|
|
409
|
-
workerData: { handlerPath, payload }
|
|
410
|
-
});
|
|
411
|
-
worker.on("message", (msg) => {
|
|
412
|
-
if (msg.ok) resolve();
|
|
413
|
-
else reject(new Error(msg.error ?? "Thread task failed"));
|
|
414
|
-
});
|
|
415
|
-
worker.on("error", reject);
|
|
416
|
-
worker.on("exit", (code) => {
|
|
417
|
-
if (code !== 0) reject(new Error(`Thread worker exited with code ${code}`));
|
|
418
|
-
});
|
|
419
|
-
});
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
// src/tasks/bullmq-backend.ts
|
|
423
|
-
async function initBullMQ(opts) {
|
|
424
|
-
let bullmq;
|
|
425
|
-
try {
|
|
426
|
-
bullmq = await import("bullmq");
|
|
427
|
-
} catch {
|
|
428
|
-
throw new Error("[EFC] bullmq is not installed. Run: npm install bullmq");
|
|
429
|
-
}
|
|
430
|
-
const connection = parseRedisUrl(opts.redisUrl);
|
|
431
|
-
const queue = new bullmq.Queue("efc", { connection });
|
|
432
|
-
const worker = new bullmq.Worker(
|
|
433
|
-
"efc",
|
|
434
|
-
async (job) => {
|
|
435
|
-
const def = taskRegistry.get(job.name);
|
|
436
|
-
if (!def) {
|
|
437
|
-
throw new Error(`[EFC] No task registered for name: ${job.name}`);
|
|
438
|
-
}
|
|
439
|
-
if (def.options.thread && def.filePath) {
|
|
440
|
-
await runInThread(def.filePath, job.data);
|
|
441
|
-
} else {
|
|
442
|
-
await def.handler(job.data);
|
|
443
|
-
}
|
|
444
|
-
},
|
|
445
|
-
{ connection, concurrency: opts.concurrency }
|
|
446
|
-
);
|
|
447
|
-
worker.on("failed", (job, err) => {
|
|
448
|
-
console.error(`[EFC] Task ${job?.name ?? "unknown"} failed:`, err.message);
|
|
449
|
-
});
|
|
450
|
-
worker.on("completed", (job) => {
|
|
451
|
-
console.log(`[EFC] Task ${job.name} completed (id=${job.id})`);
|
|
452
|
-
});
|
|
453
|
-
setEnqueueImpl(async (name, payload) => {
|
|
454
|
-
const def = taskRegistry.get(name);
|
|
455
|
-
if (!def) {
|
|
456
|
-
throw new Error(
|
|
457
|
-
`[EFC] Cannot enqueue unknown task: "${name}". Is the task file in tasksDir?`
|
|
458
|
-
);
|
|
459
|
-
}
|
|
460
|
-
await queue.add(name, payload, {
|
|
461
|
-
attempts: def.options.retries ?? 3,
|
|
462
|
-
backoff: {
|
|
463
|
-
type: def.options.backoff ?? "exponential",
|
|
464
|
-
delay: 1e3
|
|
465
|
-
}
|
|
466
|
-
});
|
|
467
|
-
});
|
|
468
|
-
console.log("[EFC] BullMQ backend initialised");
|
|
469
|
-
}
|
|
470
|
-
function parseRedisUrl(url) {
|
|
471
|
-
try {
|
|
472
|
-
const u = new URL(url);
|
|
473
|
-
const result = {
|
|
474
|
-
host: u.hostname || "localhost",
|
|
475
|
-
port: parseInt(u.port || "6379", 10)
|
|
476
|
-
};
|
|
477
|
-
if (u.password) result.password = u.password;
|
|
478
|
-
return result;
|
|
479
|
-
} catch {
|
|
480
|
-
return { host: "localhost", port: 6379 };
|
|
481
|
-
}
|
|
482
|
-
}
|
|
483
|
-
|
|
484
259
|
// src/dashboard.ts
|
|
485
260
|
var HTTP_STATUS = {
|
|
486
261
|
200: "OK",
|
|
@@ -1079,6 +854,38 @@ function generateDashboard(routes, basePath, port, projectName, projectVersion)
|
|
|
1079
854
|
</html>`;
|
|
1080
855
|
}
|
|
1081
856
|
|
|
857
|
+
// src/cache/response.ts
|
|
858
|
+
var RESPONSE_PREFIX = "res:";
|
|
859
|
+
function cacheResponse(options) {
|
|
860
|
+
const opts = typeof options === "number" ? { ttl: options } : options;
|
|
861
|
+
return (req, res, next) => {
|
|
862
|
+
if (req.method !== "GET" && req.method !== "HEAD") return next();
|
|
863
|
+
let scope = "";
|
|
864
|
+
if (opts.perUser) {
|
|
865
|
+
const user = getCurrentUser();
|
|
866
|
+
const id = user?.["sub"] ?? user?.["id"];
|
|
867
|
+
if (id === void 0) return next();
|
|
868
|
+
scope = `u:${String(id)}:`;
|
|
869
|
+
}
|
|
870
|
+
const key = RESPONSE_PREFIX + scope + (opts.key ? opts.key(req) : req.originalUrl);
|
|
871
|
+
void (async () => {
|
|
872
|
+
const hit = await cache.get(key);
|
|
873
|
+
if (hit) {
|
|
874
|
+
res.setHeader("X-Cache", "HIT");
|
|
875
|
+
res.status(hit.status).json(hit.body);
|
|
876
|
+
return;
|
|
877
|
+
}
|
|
878
|
+
res.setHeader("X-Cache", "MISS");
|
|
879
|
+
const json = res.json.bind(res);
|
|
880
|
+
res.json = (body) => {
|
|
881
|
+
if (res.statusCode === 200) void cache.set(key, { status: 200, body }, { ttl: opts.ttl });
|
|
882
|
+
return json(body);
|
|
883
|
+
};
|
|
884
|
+
next();
|
|
885
|
+
})().catch(next);
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
|
|
1082
889
|
// src/compose.ts
|
|
1083
890
|
function compose(...handlers) {
|
|
1084
891
|
return (req, res, next) => {
|
|
@@ -1102,6 +909,29 @@ function compose(...handlers) {
|
|
|
1102
909
|
};
|
|
1103
910
|
}
|
|
1104
911
|
|
|
912
|
+
// src/db/transaction.ts
|
|
913
|
+
async function transaction(fn) {
|
|
914
|
+
if (currentTx()) return fn();
|
|
915
|
+
if (getDbEngine() === "postgresql") {
|
|
916
|
+
let result;
|
|
917
|
+
await getOrm().transaction(async (tx) => {
|
|
918
|
+
result = await runInTx({ engine: "postgresql", tx }, fn);
|
|
919
|
+
});
|
|
920
|
+
return result;
|
|
921
|
+
}
|
|
922
|
+
const mg = await loadMongoose();
|
|
923
|
+
const session = await mg.connection.startSession();
|
|
924
|
+
try {
|
|
925
|
+
let result;
|
|
926
|
+
await session.withTransaction(async () => {
|
|
927
|
+
result = await runInTx({ engine: "mongodb", session }, fn);
|
|
928
|
+
});
|
|
929
|
+
return result;
|
|
930
|
+
} finally {
|
|
931
|
+
await session.endSession();
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
|
|
1105
935
|
// src/index.ts
|
|
1106
936
|
function detectDatabase(url) {
|
|
1107
937
|
if (!url) return void 0;
|
|
@@ -1145,7 +975,11 @@ async function ignite(config) {
|
|
|
1145
975
|
const jwtSecret = config.jwtSecret;
|
|
1146
976
|
const authStrategy = config.authStrategy ?? "http-only";
|
|
1147
977
|
const clusterEnabled = config.cluster ?? process.env["NODE_ENV"] === "production";
|
|
978
|
+
configureLogger(config.logging);
|
|
1148
979
|
if (clusterEnabled && cluster2.isPrimary) {
|
|
980
|
+
if (config.cache && config.cache.backend === "memory") {
|
|
981
|
+
servePrimaryCache(config.cache.maxEntries ?? 1e4);
|
|
982
|
+
}
|
|
1149
983
|
runMaster({
|
|
1150
984
|
workers: workers ?? os.cpus().length,
|
|
1151
985
|
...onWorkerReady !== void 0 && { onWorkerReady },
|
|
@@ -1154,9 +988,26 @@ async function ignite(config) {
|
|
|
1154
988
|
return;
|
|
1155
989
|
}
|
|
1156
990
|
const app = express();
|
|
991
|
+
app.set(
|
|
992
|
+
"json replacer",
|
|
993
|
+
(_key, value) => typeof value === "bigint" ? value.toString() : value
|
|
994
|
+
);
|
|
1157
995
|
app.use((_req, _res, next) => {
|
|
1158
996
|
runWithContext({}, next);
|
|
1159
997
|
});
|
|
998
|
+
app.use(requestLogger());
|
|
999
|
+
if (config.requestTimeout) {
|
|
1000
|
+
const ms = config.requestTimeout;
|
|
1001
|
+
app.use((_req, res, next) => {
|
|
1002
|
+
const timer = setTimeout(() => {
|
|
1003
|
+
if (!res.headersSent) res.status(408).json({ error: "Request Timeout", statusCode: 408 });
|
|
1004
|
+
}, ms);
|
|
1005
|
+
const clear = () => clearTimeout(timer);
|
|
1006
|
+
res.once("finish", clear);
|
|
1007
|
+
res.once("close", clear);
|
|
1008
|
+
next();
|
|
1009
|
+
});
|
|
1010
|
+
}
|
|
1160
1011
|
const corsOption = config.cors ?? true;
|
|
1161
1012
|
if (corsOption !== false) {
|
|
1162
1013
|
const origin = typeof corsOption === "object" && corsOption.origin !== void 0 ? corsOption.origin : true;
|
|
@@ -1169,9 +1020,17 @@ async function ignite(config) {
|
|
|
1169
1020
|
for (const mw of globalMiddlewares) {
|
|
1170
1021
|
app.use(mw);
|
|
1171
1022
|
}
|
|
1023
|
+
if (database) setDbEngine(database);
|
|
1024
|
+
setAutoSync(config.autoSync ?? true);
|
|
1172
1025
|
if (database === "mongodb" && databaseUrl) {
|
|
1173
1026
|
const conn = await connectMongo(databaseUrl);
|
|
1174
1027
|
setDbClient(conn);
|
|
1028
|
+
} else if (database === "postgresql" && databaseUrl) {
|
|
1029
|
+
const pool = await connectPostgres(databaseUrl);
|
|
1030
|
+
setDbClient(pool);
|
|
1031
|
+
}
|
|
1032
|
+
if (config.cache) {
|
|
1033
|
+
await configureCache(config.cache);
|
|
1175
1034
|
}
|
|
1176
1035
|
if (jwtSecret) {
|
|
1177
1036
|
configureAuth({
|
|
@@ -1188,7 +1047,23 @@ async function ignite(config) {
|
|
|
1188
1047
|
if (config.tasks.backend === "bullmq") {
|
|
1189
1048
|
await initBullMQ({
|
|
1190
1049
|
redisUrl: config.tasks.redisUrl ?? "redis://localhost:6379",
|
|
1191
|
-
concurrency: config.tasks.concurrency ?? 5
|
|
1050
|
+
concurrency: config.tasks.concurrency ?? 5,
|
|
1051
|
+
enqueueTimeout: config.tasks.enqueueTimeout ?? 5e3,
|
|
1052
|
+
queue: config.tasks.queue ?? "efc"
|
|
1053
|
+
});
|
|
1054
|
+
} else if (config.tasks.backend === "pg-boss") {
|
|
1055
|
+
const connectionString = config.tasks.connectionString ?? databaseUrl;
|
|
1056
|
+
if (!connectionString) {
|
|
1057
|
+
throw new Error(
|
|
1058
|
+
'[EFC] tasks.backend "pg-boss" needs tasks.connectionString or databaseUrl'
|
|
1059
|
+
);
|
|
1060
|
+
}
|
|
1061
|
+
await initPgBoss({
|
|
1062
|
+
connectionString,
|
|
1063
|
+
concurrency: config.tasks.concurrency ?? 5,
|
|
1064
|
+
enqueueTimeout: config.tasks.enqueueTimeout ?? 5e3,
|
|
1065
|
+
queue: config.tasks.queue ?? "efc",
|
|
1066
|
+
...config.tasks.schema !== void 0 && { schema: config.tasks.schema }
|
|
1192
1067
|
});
|
|
1193
1068
|
}
|
|
1194
1069
|
}
|
|
@@ -1208,13 +1083,22 @@ async function ignite(config) {
|
|
|
1208
1083
|
} else {
|
|
1209
1084
|
app.use(
|
|
1210
1085
|
(err, _req, res, _next) => {
|
|
1086
|
+
if (res.headersSent) {
|
|
1087
|
+
getLogger().warn({ err }, "Error after the response was sent");
|
|
1088
|
+
return;
|
|
1089
|
+
}
|
|
1211
1090
|
const duckTyped = err instanceof Error && typeof err.statusCode === "number" ? err : null;
|
|
1212
1091
|
if (isHttpError(err)) {
|
|
1213
|
-
|
|
1092
|
+
const issues = err.issues;
|
|
1093
|
+
res.status(err.statusCode).json({
|
|
1094
|
+
error: err.message,
|
|
1095
|
+
statusCode: err.statusCode,
|
|
1096
|
+
...issues !== void 0 && { issues }
|
|
1097
|
+
});
|
|
1214
1098
|
} else if (duckTyped) {
|
|
1215
1099
|
res.status(duckTyped.statusCode).json({ error: duckTyped.message, statusCode: duckTyped.statusCode });
|
|
1216
1100
|
} else {
|
|
1217
|
-
|
|
1101
|
+
getLogger().error({ err }, "Unhandled error");
|
|
1218
1102
|
res.status(500).json({ error: "Internal Server Error", statusCode: 500 });
|
|
1219
1103
|
}
|
|
1220
1104
|
}
|
|
@@ -1225,44 +1109,58 @@ async function ignite(config) {
|
|
|
1225
1109
|
server.once("listening", () => {
|
|
1226
1110
|
const wid = cluster2.worker?.id ?? "primary";
|
|
1227
1111
|
const addr = server.address();
|
|
1228
|
-
|
|
1112
|
+
getLogger().info(`Worker ${wid} listening on :${addr?.port ?? port}`);
|
|
1229
1113
|
resolve(server);
|
|
1230
1114
|
});
|
|
1231
1115
|
server.once("error", reject);
|
|
1232
1116
|
});
|
|
1233
1117
|
}
|
|
1234
1118
|
function gracefulShutdown(server, timeoutMs = 1e4) {
|
|
1119
|
+
let shuttingDown = false;
|
|
1235
1120
|
const shutdown = (signal) => {
|
|
1236
|
-
|
|
1121
|
+
if (shuttingDown) return;
|
|
1122
|
+
shuttingDown = true;
|
|
1123
|
+
getLogger().info(`${signal} received \u2014 closing server gracefully\u2026`);
|
|
1237
1124
|
if (server) {
|
|
1238
1125
|
server.closeIdleConnections();
|
|
1239
1126
|
server.close(() => {
|
|
1240
|
-
|
|
1241
|
-
process.exit(0);
|
|
1127
|
+
getLogger().info("Server closed");
|
|
1128
|
+
Promise.all([closeBullMQ(), closePgBoss(), closeCache()]).catch((err) => getLogger().error({ err }, "Task backend close failed")).finally(() => process.exit(0));
|
|
1242
1129
|
});
|
|
1243
1130
|
setTimeout(() => {
|
|
1244
|
-
|
|
1131
|
+
getLogger().error("Forced exit after timeout");
|
|
1245
1132
|
process.exit(1);
|
|
1246
1133
|
}, timeoutMs).unref();
|
|
1247
1134
|
} else {
|
|
1248
1135
|
shutdownMaster();
|
|
1136
|
+
setTimeout(() => {
|
|
1137
|
+
getLogger().error("Workers did not exit in time \u2014 forcing primary exit");
|
|
1138
|
+
process.exit(1);
|
|
1139
|
+
}, timeoutMs + 2e3).unref();
|
|
1249
1140
|
}
|
|
1250
1141
|
};
|
|
1251
|
-
process.
|
|
1252
|
-
process.
|
|
1142
|
+
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
|
1143
|
+
process.on("SIGINT", () => shutdown("SIGINT"));
|
|
1253
1144
|
}
|
|
1254
1145
|
export {
|
|
1255
1146
|
HttpError,
|
|
1147
|
+
ModelValidationError,
|
|
1148
|
+
cache,
|
|
1149
|
+
cacheResponse,
|
|
1256
1150
|
compose,
|
|
1257
1151
|
db,
|
|
1258
1152
|
defineModel,
|
|
1153
|
+
defineTable,
|
|
1259
1154
|
getDbClient,
|
|
1155
|
+
getLogger,
|
|
1260
1156
|
gracefulShutdown,
|
|
1261
1157
|
ignite,
|
|
1262
1158
|
isHttpError,
|
|
1263
1159
|
listTasks,
|
|
1160
|
+
logger,
|
|
1264
1161
|
scanDir,
|
|
1265
1162
|
setDbClient,
|
|
1163
|
+
transaction,
|
|
1266
1164
|
workerCount
|
|
1267
1165
|
};
|
|
1268
1166
|
//# sourceMappingURL=index.js.map
|