@open-mercato/cli 0.11.1-develop.8920.1.d3c2cc4681 → 0.11.1-develop.8929.1.493f6c653c
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/.turbo/turbo-build.log +6 -2
- package/dist/agentic/guides/module-facts.json +356 -385
- package/dist/agentic/guides/module-facts.v2.json +356 -385
- package/dist/agentic/guides/modules/agent_orchestrator/active-extension-bindings.md +1 -1
- package/dist/agentic/guides/modules/agent_orchestrator/exact-override-targets.md +1 -1
- package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
- package/dist/agentic/guides/modules/agent_orchestrator/workers.md +1 -1
- package/dist/agentic/guides/modules/ai_assistant/exact-override-targets.md +2 -2
- package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
- package/dist/agentic/guides/modules/ai_assistant/workers.md +2 -2
- package/dist/agentic/guides/modules/api_docs/index.md +1 -1
- package/dist/agentic/guides/modules/api_keys/index.md +1 -1
- package/dist/agentic/guides/modules/assisted_selling/index.md +1 -1
- package/dist/agentic/guides/modules/attachments/index.md +1 -1
- package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
- package/dist/agentic/guides/modules/auth/entities.md +1 -0
- package/dist/agentic/guides/modules/auth/index.md +2 -2
- package/dist/agentic/guides/modules/auth/umes-hosts.md +1 -0
- package/dist/agentic/guides/modules/availability/index.md +1 -1
- package/dist/agentic/guides/modules/backups/index.md +1 -1
- package/dist/agentic/guides/modules/business_rules/index.md +1 -1
- package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
- package/dist/agentic/guides/modules/cart/index.md +1 -1
- package/dist/agentic/guides/modules/catalog/index.md +1 -1
- package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
- package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
- package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
- package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
- package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
- package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
- package/dist/agentic/guides/modules/channel_ms365/index.md +1 -1
- package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
- package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
- package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
- package/dist/agentic/guides/modules/checkout/index.md +1 -1
- package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
- package/dist/agentic/guides/modules/configs/index.md +1 -1
- package/dist/agentic/guides/modules/content/index.md +1 -1
- package/dist/agentic/guides/modules/currencies/index.md +1 -1
- package/dist/agentic/guides/modules/customer_accounts/exact-override-targets.md +4 -4
- package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
- package/dist/agentic/guides/modules/customer_accounts/workers.md +4 -4
- package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
- package/dist/agentic/guides/modules/customers/index.md +1 -1
- package/dist/agentic/guides/modules/dashboards/index.md +1 -1
- package/dist/agentic/guides/modules/data_sync/index.md +1 -1
- package/dist/agentic/guides/modules/design_system/index.md +1 -1
- package/dist/agentic/guides/modules/devices/index.md +1 -1
- package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
- package/dist/agentic/guides/modules/directory/index.md +1 -1
- package/dist/agentic/guides/modules/documents/index.md +1 -1
- package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
- package/dist/agentic/guides/modules/entities/index.md +1 -1
- package/dist/agentic/guides/modules/eudr/index.md +1 -1
- package/dist/agentic/guides/modules/events/index.md +1 -1
- package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
- package/dist/agentic/guides/modules/forms/index.md +1 -1
- package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
- package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
- package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
- package/dist/agentic/guides/modules/generators/index.md +1 -1
- package/dist/agentic/guides/modules/gus_regon/index.md +1 -1
- package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
- package/dist/agentic/guides/modules/integrations/index.md +1 -1
- package/dist/agentic/guides/modules/ledger/index.md +1 -1
- package/dist/agentic/guides/modules/maintenance/index.md +1 -1
- package/dist/agentic/guides/modules/messages/index.md +1 -1
- package/dist/agentic/guides/modules/notifications/index.md +1 -1
- package/dist/agentic/guides/modules/onboarding/index.md +1 -1
- package/dist/agentic/guides/modules/payment_gateways/exact-override-targets.md +1 -1
- package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
- package/dist/agentic/guides/modules/payment_gateways/workers.md +1 -1
- package/dist/agentic/guides/modules/perspectives/index.md +1 -1
- package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
- package/dist/agentic/guides/modules/planner/index.md +1 -1
- package/dist/agentic/guides/modules/portal/index.md +1 -1
- package/dist/agentic/guides/modules/progress/index.md +1 -1
- package/dist/agentic/guides/modules/promotions/index.md +1 -1
- package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
- package/dist/agentic/guides/modules/query_index/index.md +1 -1
- package/dist/agentic/guides/modules/record_locks/index.md +1 -1
- package/dist/agentic/guides/modules/resources/index.md +1 -1
- package/dist/agentic/guides/modules/sales/exact-override-targets.md +4 -4
- package/dist/agentic/guides/modules/sales/index.md +1 -1
- package/dist/agentic/guides/modules/sales/setup.md +1 -1
- package/dist/agentic/guides/modules/sales_invoices_gl_posting/index.md +1 -1
- package/dist/agentic/guides/modules/scheduler/di-registrations-rich.md +3 -3
- package/dist/agentic/guides/modules/scheduler/di-service-tokens.md +3 -3
- package/dist/agentic/guides/modules/scheduler/exact-override-targets.md +4 -9
- package/dist/agentic/guides/modules/scheduler/index.md +3 -4
- package/dist/agentic/guides/modules/scheduler/workers.md +1 -1
- package/dist/agentic/guides/modules/search/di-registrations-rich.md +4 -4
- package/dist/agentic/guides/modules/search/di-service-tokens.md +13 -0
- package/dist/agentic/guides/modules/search/exact-override-targets.md +4 -4
- package/dist/agentic/guides/modules/search/index.md +3 -2
- package/dist/agentic/guides/modules/security/index.md +1 -1
- package/dist/agentic/guides/modules/seeds/index.md +1 -1
- package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
- package/dist/agentic/guides/modules/sso/index.md +1 -1
- package/dist/agentic/guides/modules/staff/index.md +1 -1
- package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
- package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
- package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
- package/dist/agentic/guides/modules/sync_shopify/index.md +1 -1
- package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
- package/dist/agentic/guides/modules/telemetry/index.md +1 -1
- package/dist/agentic/guides/modules/tenant_boundaries/generator-plugins.md +11 -0
- package/dist/agentic/guides/modules/tenant_boundaries/index.md +13 -0
- package/dist/agentic/guides/modules/tenant_boundaries/owned-contract-module-metadata.md +11 -0
- package/dist/agentic/guides/modules/tillio/index.md +1 -1
- package/dist/agentic/guides/modules/translations/index.md +1 -1
- package/dist/agentic/guides/modules/upgrade_actions/index.md +1 -1
- package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
- package/dist/agentic/guides/modules/webhooks/index.md +1 -1
- package/dist/agentic/guides/modules/wms/index.md +1 -1
- package/dist/agentic/guides/modules/workflows/index.md +1 -1
- package/dist/agentic/guides/reference-module-facts.json +2 -2
- package/dist/agentic/guides/reference-modules/example/index.md +1 -1
- package/dist/agentic/guides/upstream/manifest.json +1 -1
- package/dist/agentic/shared/AGENTS.md.template +3 -3
- package/dist/agentic/shared/ai/harness/cases.json +4 -4
- package/dist/bin.js +6 -3
- package/dist/bin.js.map +2 -2
- package/dist/i18n/de.json +5 -1
- package/dist/i18n/en.json +5 -1
- package/dist/i18n/es.json +5 -1
- package/dist/i18n/ko.json +5 -1
- package/dist/i18n/pl.json +5 -1
- package/dist/lib/cli-bootstrap-mode.js +10 -1
- package/dist/lib/cli-bootstrap-mode.js.map +2 -2
- package/dist/lib/db/commands.js +18 -3
- package/dist/lib/db/commands.js.map +2 -2
- package/dist/lib/db/maintenance-client.js +72 -0
- package/dist/lib/db/maintenance-client.js.map +7 -0
- package/dist/lib/generate-watch-structure.js +2 -1
- package/dist/lib/generate-watch-structure.js.map +2 -2
- package/dist/lib/generators/database-declarations.js +21 -0
- package/dist/lib/generators/database-declarations.js.map +7 -0
- package/dist/lib/generators/module-registry.js +19 -3
- package/dist/lib/generators/module-registry.js.map +2 -2
- package/dist/lib/init-existing-database.js +91 -1
- package/dist/lib/init-existing-database.js.map +2 -2
- package/dist/lib/init-i18n.js +13 -0
- package/dist/lib/init-i18n.js.map +7 -0
- package/dist/lib/init-secrets.js +2 -10
- package/dist/lib/init-secrets.js.map +2 -2
- package/dist/lib/scheduler-supervisor.js +47 -7
- package/dist/lib/scheduler-supervisor.js.map +2 -2
- package/dist/lib/worker-job-handler.js +36 -26
- package/dist/lib/worker-job-handler.js.map +2 -2
- package/dist/mercato.js +93 -54
- package/dist/mercato.js.map +3 -3
- package/package.json +7 -7
- package/src/__tests__/mercato.test.ts +166 -9
- package/src/bin.ts +10 -4
- package/src/i18n/de.json +5 -1
- package/src/i18n/en.json +5 -1
- package/src/i18n/es.json +5 -1
- package/src/i18n/ko.json +5 -1
- package/src/i18n/pl.json +5 -1
- package/src/lib/__tests__/cli-bootstrap-mode.test.ts +76 -1
- package/src/lib/__tests__/generate-watch-structure.test.ts +26 -0
- package/src/lib/__tests__/rotation-kms-warning-presentation.test.ts +1 -1
- package/src/lib/__tests__/scheduler-supervisor.test.ts +107 -0
- package/src/lib/__tests__/worker-job-handler.database.test.ts +76 -0
- package/src/lib/cli-bootstrap-mode.ts +12 -2
- package/src/lib/db/__tests__/commands.migrate-reindex.test.ts +72 -1
- package/src/lib/db/__tests__/maintenance-client.test.ts +70 -0
- package/src/lib/db/commands.ts +20 -6
- package/src/lib/db/maintenance-client.ts +54 -0
- package/src/lib/generate-watch-structure.ts +2 -1
- package/src/lib/generators/__tests__/database-declarations.test.ts +69 -0
- package/src/lib/generators/__tests__/incremental-registry.test.ts +1 -1
- package/src/lib/generators/__tests__/module-subset.test.ts +17 -1
- package/src/lib/generators/database-declarations.ts +19 -0
- package/src/lib/generators/module-registry.ts +23 -4
- package/src/lib/init-existing-database.ts +107 -0
- package/src/lib/init-i18n.ts +11 -0
- package/src/lib/init-secrets.ts +2 -12
- package/src/lib/scheduler-supervisor.ts +40 -7
- package/src/lib/worker-job-handler.ts +39 -28
- package/src/mercato.ts +92 -53
- package/dist/agentic/guides/modules/scheduler/cli-commands.md +0 -15
|
@@ -1,7 +1,85 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { createCliMaintenanceClient } from "./db/maintenance-client.js";
|
|
3
|
+
import { createInitTranslator } from "./init-i18n.js";
|
|
4
|
+
const INITIALIZATION_NAME = "mercato-init";
|
|
1
5
|
function decideExistingDatabase(existingUsersCount, skipIfInitialized) {
|
|
2
6
|
if (!Number.isFinite(existingUsersCount) || existingUsersCount <= 0) return "proceed";
|
|
3
7
|
return skipIfInitialized ? "skip" : "abort";
|
|
4
8
|
}
|
|
9
|
+
async function withInitializationClient(databaseUrl, action) {
|
|
10
|
+
const client = await createCliMaintenanceClient(databaseUrl);
|
|
11
|
+
try {
|
|
12
|
+
await client.connect();
|
|
13
|
+
return await action(client);
|
|
14
|
+
} finally {
|
|
15
|
+
await client.end();
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
async function hasIncompleteInitialization(client) {
|
|
19
|
+
const table = await client.query(
|
|
20
|
+
"SELECT to_regclass('app_initializations') AS regclass"
|
|
21
|
+
);
|
|
22
|
+
if (!table.rows[0]?.regclass) return false;
|
|
23
|
+
const result = await client.query(
|
|
24
|
+
"SELECT completed_at IS NULL AS pending FROM app_initializations WHERE name = $1",
|
|
25
|
+
[INITIALIZATION_NAME]
|
|
26
|
+
);
|
|
27
|
+
return result.rows[0]?.pending === true;
|
|
28
|
+
}
|
|
29
|
+
async function startInitialization(client) {
|
|
30
|
+
const translate = createInitTranslator(process.env);
|
|
31
|
+
const lock = await client.query(
|
|
32
|
+
"SELECT pg_try_advisory_lock(hashtext($1)) AS locked",
|
|
33
|
+
[INITIALIZATION_NAME]
|
|
34
|
+
);
|
|
35
|
+
if (lock.rows[0]?.locked !== true) {
|
|
36
|
+
throw new Error(translate("cli.init.errors.concurrentInitialization"));
|
|
37
|
+
}
|
|
38
|
+
const cleared = await client.query(
|
|
39
|
+
"DELETE FROM app_initializations WHERE name = $1 AND completed_at IS NULL AND NOT EXISTS (SELECT 1 FROM users)",
|
|
40
|
+
[INITIALIZATION_NAME]
|
|
41
|
+
);
|
|
42
|
+
const initializationId = randomUUID();
|
|
43
|
+
const result = await client.query(
|
|
44
|
+
"INSERT INTO app_initializations (id, name) VALUES ($1, $2) ON CONFLICT (name) DO NOTHING",
|
|
45
|
+
[initializationId, INITIALIZATION_NAME]
|
|
46
|
+
);
|
|
47
|
+
if (result.rowCount !== 1) {
|
|
48
|
+
throw new Error(translate("cli.init.errors.concurrentInitialization"));
|
|
49
|
+
}
|
|
50
|
+
return { initializationId, clearedInterruptedAttempt: cleared.rowCount === 1 };
|
|
51
|
+
}
|
|
52
|
+
async function openInitializationSession(databaseUrl) {
|
|
53
|
+
const client = await createCliMaintenanceClient(databaseUrl, { pinned: true });
|
|
54
|
+
try {
|
|
55
|
+
await client.connect();
|
|
56
|
+
const { initializationId, clearedInterruptedAttempt } = await startInitialization(client);
|
|
57
|
+
return {
|
|
58
|
+
clearedInterruptedAttempt,
|
|
59
|
+
cancelWithoutUsers: () => cancelInitializationWithoutUsers(client, initializationId),
|
|
60
|
+
complete: () => completeInitialization(client, initializationId),
|
|
61
|
+
close: () => client.end()
|
|
62
|
+
};
|
|
63
|
+
} catch (error) {
|
|
64
|
+
await client.end();
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
async function cancelInitializationWithoutUsers(client, initializationId) {
|
|
69
|
+
await client.query(
|
|
70
|
+
"DELETE FROM app_initializations WHERE id = $1 AND completed_at IS NULL AND NOT EXISTS (SELECT 1 FROM users)",
|
|
71
|
+
[initializationId]
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
async function completeInitialization(client, initializationId) {
|
|
75
|
+
const result = await client.query(
|
|
76
|
+
"UPDATE app_initializations SET completed_at = now() WHERE id = $1 AND completed_at IS NULL",
|
|
77
|
+
[initializationId]
|
|
78
|
+
);
|
|
79
|
+
if (result.rowCount !== 1) {
|
|
80
|
+
throw new Error(createInitTranslator(process.env)("cli.init.errors.initializationStateMissing"));
|
|
81
|
+
}
|
|
82
|
+
}
|
|
5
83
|
function describeDatabaseTarget(databaseUrl) {
|
|
6
84
|
try {
|
|
7
85
|
const url = new URL(databaseUrl);
|
|
@@ -18,9 +96,21 @@ function formatSkipIfInitializedMessage(existingUsersCount, databaseUrl) {
|
|
|
18
96
|
" Not the database you expected? Check DATABASE_URL in .env. To wipe it and seed from scratch: yarn mercato init --reinstall"
|
|
19
97
|
];
|
|
20
98
|
}
|
|
99
|
+
function formatIncompleteInitializationMessage(databaseUrl) {
|
|
100
|
+
return createInitTranslator(process.env)("cli.init.errors.incompleteInitialization", {
|
|
101
|
+
database: describeDatabaseTarget(databaseUrl)
|
|
102
|
+
});
|
|
103
|
+
}
|
|
21
104
|
export {
|
|
105
|
+
cancelInitializationWithoutUsers,
|
|
106
|
+
completeInitialization,
|
|
22
107
|
decideExistingDatabase,
|
|
23
108
|
describeDatabaseTarget,
|
|
24
|
-
|
|
109
|
+
formatIncompleteInitializationMessage,
|
|
110
|
+
formatSkipIfInitializedMessage,
|
|
111
|
+
hasIncompleteInitialization,
|
|
112
|
+
openInitializationSession,
|
|
113
|
+
startInitialization,
|
|
114
|
+
withInitializationClient
|
|
25
115
|
};
|
|
26
116
|
//# sourceMappingURL=init-existing-database.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/lib/init-existing-database.ts"],
|
|
4
|
-
"sourcesContent": ["
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import type { Client } from 'pg'\nimport { randomUUID } from 'node:crypto'\nimport { createCliMaintenanceClient } from './db/maintenance-client'\nimport { createInitTranslator } from './init-i18n'\n\nconst INITIALIZATION_NAME = 'mercato-init'\n\nexport type ExistingDatabaseDecision = 'proceed' | 'skip' | 'abort'\ntype InitializationClient = Pick<Client, 'query'>\n\nexport function decideExistingDatabase(existingUsersCount: number, skipIfInitialized: boolean): ExistingDatabaseDecision {\n if (!Number.isFinite(existingUsersCount) || existingUsersCount <= 0) return 'proceed'\n return skipIfInitialized ? 'skip' : 'abort'\n}\n\nexport async function withInitializationClient<T>(\n databaseUrl: string,\n action: (client: InitializationClient) => Promise<T>,\n): Promise<T> {\n const client = await createCliMaintenanceClient(databaseUrl)\n try {\n await client.connect()\n return await action(client)\n } finally {\n await client.end()\n }\n}\n\nexport async function hasIncompleteInitialization(client: InitializationClient): Promise<boolean> {\n const table = await client.query<{ regclass: string | null }>(\n \"SELECT to_regclass('app_initializations') AS regclass\",\n )\n if (!table.rows[0]?.regclass) return false\n\n const result = await client.query<{ pending: boolean }>(\n 'SELECT completed_at IS NULL AS pending FROM app_initializations WHERE name = $1',\n [INITIALIZATION_NAME],\n )\n return result.rows[0]?.pending === true\n}\n\nexport type InitializationStart = { initializationId: string; clearedInterruptedAttempt: boolean }\n\nexport async function startInitialization(client: InitializationClient): Promise<InitializationStart> {\n const translate = createInitTranslator(process.env)\n const lock = await client.query<{ locked: boolean }>(\n 'SELECT pg_try_advisory_lock(hashtext($1)) AS locked',\n [INITIALIZATION_NAME],\n )\n if (lock.rows[0]?.locked !== true) {\n throw new Error(translate('cli.init.errors.concurrentInitialization'))\n }\n const cleared = await client.query(\n 'DELETE FROM app_initializations WHERE name = $1 AND completed_at IS NULL AND NOT EXISTS (SELECT 1 FROM users)',\n [INITIALIZATION_NAME],\n )\n const initializationId = randomUUID()\n const result = await client.query(\n 'INSERT INTO app_initializations (id, name) VALUES ($1, $2) ON CONFLICT (name) DO NOTHING',\n [initializationId, INITIALIZATION_NAME],\n )\n if (result.rowCount !== 1) {\n throw new Error(translate('cli.init.errors.concurrentInitialization'))\n }\n return { initializationId, clearedInterruptedAttempt: cleared.rowCount === 1 }\n}\n\nexport type InitializationSession = {\n clearedInterruptedAttempt: boolean\n cancelWithoutUsers: () => Promise<void>\n complete: () => Promise<void>\n close: () => Promise<void>\n}\n\nexport async function openInitializationSession(databaseUrl: string): Promise<InitializationSession> {\n const client = await createCliMaintenanceClient(databaseUrl, { pinned: true })\n try {\n await client.connect()\n const { initializationId, clearedInterruptedAttempt } = await startInitialization(client)\n return {\n clearedInterruptedAttempt,\n cancelWithoutUsers: () => cancelInitializationWithoutUsers(client, initializationId),\n complete: () => completeInitialization(client, initializationId),\n close: () => client.end(),\n }\n } catch (error) {\n await client.end()\n throw error\n }\n}\n\nexport async function cancelInitializationWithoutUsers(client: InitializationClient, initializationId: string): Promise<void> {\n await client.query(\n 'DELETE FROM app_initializations WHERE id = $1 AND completed_at IS NULL AND NOT EXISTS (SELECT 1 FROM users)',\n [initializationId],\n )\n}\n\nexport async function completeInitialization(client: InitializationClient, initializationId: string): Promise<void> {\n const result = await client.query(\n 'UPDATE app_initializations SET completed_at = now() WHERE id = $1 AND completed_at IS NULL',\n [initializationId],\n )\n if (result.rowCount !== 1) {\n throw new Error(createInitTranslator(process.env)('cli.init.errors.initializationStateMissing'))\n }\n}\n\nexport function describeDatabaseTarget(databaseUrl: string): string {\n try {\n const url = new URL(databaseUrl)\n const database = decodeURIComponent(url.pathname.replace(/^\\/+/, '')) || '(default database)'\n const host = url.hostname || 'localhost'\n return `${host}${url.port ? `:${url.port}` : ''}/${database}`\n } catch {\n return 'the database from DATABASE_URL'\n }\n}\n\nexport function formatSkipIfInitializedMessage(existingUsersCount: number, databaseUrl: string): string[] {\n return [\n `\u2705 Database already initialized (${existingUsersCount} user(s) in ${describeDatabaseTarget(databaseUrl)}) \u2014 keeping the existing data and skipping the first-run seed.`,\n ' Not the database you expected? Check DATABASE_URL in .env. To wipe it and seed from scratch: yarn mercato init --reinstall',\n ]\n}\n\nexport function formatIncompleteInitializationMessage(databaseUrl: string): string {\n return createInitTranslator(process.env)('cli.init.errors.incompleteInitialization', {\n database: describeDatabaseTarget(databaseUrl),\n })\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,kBAAkB;AAC3B,SAAS,kCAAkC;AAC3C,SAAS,4BAA4B;AAErC,MAAM,sBAAsB;AAKrB,SAAS,uBAAuB,oBAA4B,mBAAsD;AACvH,MAAI,CAAC,OAAO,SAAS,kBAAkB,KAAK,sBAAsB,EAAG,QAAO;AAC5E,SAAO,oBAAoB,SAAS;AACtC;AAEA,eAAsB,yBACpB,aACA,QACY;AACZ,QAAM,SAAS,MAAM,2BAA2B,WAAW;AAC3D,MAAI;AACF,UAAM,OAAO,QAAQ;AACrB,WAAO,MAAM,OAAO,MAAM;AAAA,EAC5B,UAAE;AACA,UAAM,OAAO,IAAI;AAAA,EACnB;AACF;AAEA,eAAsB,4BAA4B,QAAgD;AAChG,QAAM,QAAQ,MAAM,OAAO;AAAA,IACzB;AAAA,EACF;AACA,MAAI,CAAC,MAAM,KAAK,CAAC,GAAG,SAAU,QAAO;AAErC,QAAM,SAAS,MAAM,OAAO;AAAA,IAC1B;AAAA,IACA,CAAC,mBAAmB;AAAA,EACtB;AACA,SAAO,OAAO,KAAK,CAAC,GAAG,YAAY;AACrC;AAIA,eAAsB,oBAAoB,QAA4D;AACpG,QAAM,YAAY,qBAAqB,QAAQ,GAAG;AAClD,QAAM,OAAO,MAAM,OAAO;AAAA,IACxB;AAAA,IACA,CAAC,mBAAmB;AAAA,EACtB;AACA,MAAI,KAAK,KAAK,CAAC,GAAG,WAAW,MAAM;AACjC,UAAM,IAAI,MAAM,UAAU,0CAA0C,CAAC;AAAA,EACvE;AACA,QAAM,UAAU,MAAM,OAAO;AAAA,IAC3B;AAAA,IACA,CAAC,mBAAmB;AAAA,EACtB;AACA,QAAM,mBA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,OAAO,IAAI,IAAI,IAAI,KAAK,EAAE,IAAI,QAAQ;AAAA,EAC7D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,+BAA+B,oBAA4B,aAA+B;AACxG,SAAO;AAAA,IACL,wCAAmC,kBAAkB,eAAe,uBAAuB,WAAW,CAAC;AAAA,IACvG;AAAA,EACF;AACF;AAEO,SAAS,sCAAsC,aAA6B;AACjF,SAAO,qBAAqB,QAAQ,GAAG,EAAE,4CAA4C;AAAA,IACnF,UAAU,uBAAuB,WAAW;AAAA,EAC9C,CAAC;AACH;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createTranslator } from "@open-mercato/shared/lib/i18n/translate";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
const requireLocale = createRequire(import.meta.url);
|
|
4
|
+
function createInitTranslator(env) {
|
|
5
|
+
const locale = (env.LC_ALL || env.LC_MESSAGES || env.LANG || "en").split(/[_.-]/)[0].toLowerCase();
|
|
6
|
+
const supportedLocale = ["en", "pl", "es", "de", "ko"].includes(locale) ? locale : "en";
|
|
7
|
+
const dictionary = requireLocale(`../i18n/${supportedLocale}.json`);
|
|
8
|
+
return createTranslator(dictionary);
|
|
9
|
+
}
|
|
10
|
+
export {
|
|
11
|
+
createInitTranslator
|
|
12
|
+
};
|
|
13
|
+
//# sourceMappingURL=init-i18n.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/lib/init-i18n.ts"],
|
|
4
|
+
"sourcesContent": ["import { createTranslator } from '@open-mercato/shared/lib/i18n/translate'\nimport { createRequire } from 'node:module'\n\nconst requireLocale = createRequire(import.meta.url)\n\nexport function createInitTranslator(env: NodeJS.ProcessEnv) {\n const locale = (env.LC_ALL || env.LC_MESSAGES || env.LANG || 'en').split(/[_.-]/)[0].toLowerCase()\n const supportedLocale = ['en', 'pl', 'es', 'de', 'ko'].includes(locale) ? locale : 'en'\n const dictionary: Record<string, string> = requireLocale(`../i18n/${supportedLocale}.json`)\n return createTranslator(dictionary)\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,wBAAwB;AACjC,SAAS,qBAAqB;AAE9B,MAAM,gBAAgB,cAAc,YAAY,GAAG;AAE5C,SAAS,qBAAqB,KAAwB;AAC3D,QAAM,UAAU,IAAI,UAAU,IAAI,eAAe,IAAI,QAAQ,MAAM,MAAM,OAAO,EAAE,CAAC,EAAE,YAAY;AACjG,QAAM,kBAAkB,CAAC,MAAM,MAAM,MAAM,MAAM,IAAI,EAAE,SAAS,MAAM,IAAI,SAAS;AACnF,QAAM,aAAqC,cAAc,WAAW,eAAe,OAAO;AAC1F,SAAO,iBAAiB,UAAU;AACpC;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/lib/init-secrets.js
CHANGED
|
@@ -1,15 +1,7 @@
|
|
|
1
1
|
import { parseBooleanToken } from "@open-mercato/shared/lib/boolean";
|
|
2
2
|
import { getPasswordPolicy, validatePassword } from "@open-mercato/shared/lib/auth/passwordPolicy";
|
|
3
3
|
import { randomBytes } from "node:crypto";
|
|
4
|
-
import {
|
|
5
|
-
import { createRequire } from "node:module";
|
|
6
|
-
const requireLocale = createRequire(import.meta.url);
|
|
7
|
-
function initTranslator(env) {
|
|
8
|
-
const locale = (env.LC_ALL || env.LC_MESSAGES || env.LANG || "en").split(/[_.-]/)[0].toLowerCase();
|
|
9
|
-
const supportedLocale = ["en", "pl", "es", "de", "ko"].includes(locale) ? locale : "en";
|
|
10
|
-
const dictionary = requireLocale(`../i18n/${supportedLocale}.json`);
|
|
11
|
-
return createTranslator(dictionary);
|
|
12
|
-
}
|
|
4
|
+
import { createInitTranslator } from "./init-i18n.js";
|
|
13
5
|
function readEnvValue(env, key) {
|
|
14
6
|
const value = env[key];
|
|
15
7
|
if (typeof value !== "string") return void 0;
|
|
@@ -60,7 +52,7 @@ function resolveInitSuperadminCredentials(args, env = process.env) {
|
|
|
60
52
|
);
|
|
61
53
|
const skipPasswordPolicy = !isProduction && (skipPolicyArg ? parseBooleanToken(skipPolicyArg.split("=")[1] ?? "true") ?? true : true);
|
|
62
54
|
if (isProduction) {
|
|
63
|
-
const t =
|
|
55
|
+
const t = createInitTranslator(env);
|
|
64
56
|
const placeholder = suppliedPassword?.trim().toLowerCase();
|
|
65
57
|
if (!suppliedPassword || !placeholder || ["secret", "password", "changeme", "change-me", "change_me", "replace-me", "replace_me"].includes(placeholder)) {
|
|
66
58
|
throw new Error(t("cli.init.errors.superadminPasswordRequired"));
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/lib/init-secrets.ts"],
|
|
4
|
-
"sourcesContent": ["import { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { getPasswordPolicy, validatePassword } from '@open-mercato/shared/lib/auth/passwordPolicy'\nimport { randomBytes } from 'node:crypto'\nimport {
|
|
5
|
-
"mappings": "AAAA,SAAS,yBAAyB;AAClC,SAAS,mBAAmB,wBAAwB;AACpD,SAAS,mBAAmB;AAC5B,SAAS,
|
|
4
|
+
"sourcesContent": ["import { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { getPasswordPolicy, validatePassword } from '@open-mercato/shared/lib/auth/passwordPolicy'\nimport { randomBytes } from 'node:crypto'\nimport { createInitTranslator } from './init-i18n'\n\ntype EnvReader = (key: string) => string | undefined\n\nfunction readEnvValue(env: NodeJS.ProcessEnv, key: string): string | undefined {\n const value = env[key]\n if (typeof value !== 'string') return undefined\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : undefined\n}\n\nfunction resolveEmailFromDomain(domain: string | undefined, prefix: string): string | null {\n if (!domain) return null\n return `${prefix}@${domain}`\n}\n\nexport type InitDerivedSecrets = {\n adminEmail: string | null\n employeeEmail: string | null\n adminPassword: string | null\n employeePassword: string | null\n}\n\n// Well-known dev/demo password baked into local bootstrap flows so developers\n// keep the documented \"log in as admin@<domain> with password 'secret'\" UX.\n// Only used when NODE_ENV !== 'production' and the OM_INIT_*_PASSWORD env vars\n// are unset \u2014 production paths always use a random 96-bit secret.\nconst DEMO_DERIVED_PASSWORD = 'secret'\n\nlet warnedAboutDeprecatedRandomToggle = false\n\nexport function resolveInitDerivedSecrets(options: {\n email: string\n env?: NodeJS.ProcessEnv\n randomSource?: (size: number) => Buffer\n}): InitDerivedSecrets {\n const env = options.env ?? process.env\n const envRead: EnvReader = (key) => readEnvValue(env, key)\n const [, domain] = String(options.email ?? '').split('@')\n const adminEmail = envRead('OM_INIT_ADMIN_EMAIL') ?? resolveEmailFromDomain(domain, 'admin')\n const employeeEmail = envRead('OM_INIT_EMPLOYEE_EMAIL') ?? resolveEmailFromDomain(domain, 'employee')\n // OM_INIT_GENERATE_RANDOM_PASSWORD used to be an opt-in toggle for random\n // derived secrets; in production it is now the unconditional behaviour when\n // no override is set. Surface a one-time deprecation warning so existing\n // operators notice their config is no longer required.\n if (parseBooleanToken(envRead('OM_INIT_GENERATE_RANDOM_PASSWORD') ?? '') === true && !warnedAboutDeprecatedRandomToggle) {\n warnedAboutDeprecatedRandomToggle = true\n console.warn(\n '\u26A0\uFE0F OM_INIT_GENERATE_RANDOM_PASSWORD is deprecated and no longer required: derived admin/employee passwords are always randomized in production when overrides are unset.',\n )\n }\n const isProduction = (env.NODE_ENV ?? '').trim().toLowerCase() === 'production'\n const randomize = options.randomSource ?? randomBytes\n const randomSecret = () => `Aa1!${randomize(Math.max(12, getPasswordPolicy(env).minLength)).toString('base64url')}`\n const resolvePassword = (key: string, emailValue: string | null) => {\n if (!emailValue) return null\n const envValue = envRead(key)\n if (envValue) return envValue\n // Non-production (dev/test/staging defaults): seed the documented demo\n // password so `yarn dev` / `mercato init` workflows stay predictable.\n // Production: generate a fresh random secret so credentials are never\n // hardcoded and the operator-facing CLI prints the value once.\n return isProduction ? randomSecret() : DEMO_DERIVED_PASSWORD\n }\n\n return {\n adminEmail,\n employeeEmail,\n adminPassword: resolvePassword('OM_INIT_ADMIN_PASSWORD', adminEmail),\n employeePassword: resolvePassword('OM_INIT_EMPLOYEE_PASSWORD', employeeEmail),\n }\n}\n\nexport function resolveInitSuperadminCredentials(args: string[], env: NodeJS.ProcessEnv = process.env) {\n const argValue = (name: string) => args.find((arg) => arg.startsWith(`${name}=`))?.slice(name.length + 1) || undefined\n const email = argValue('--email') ?? readEnvValue(env, 'OM_INIT_SUPERADMIN_EMAIL') ?? 'superadmin@acme.com'\n const suppliedPassword = argValue('--password') ?? readEnvValue(env, 'OM_INIT_SUPERADMIN_PASSWORD')\n const isProduction = (env.NODE_ENV ?? '').trim().toLowerCase() === 'production'\n const skipPolicyArg = args.find((arg) =>\n arg === '--skip-password-policy' || arg.startsWith('--skip-password-policy=') ||\n arg === '--allow-weak-password' || arg.startsWith('--allow-weak-password='),\n )\n const skipPasswordPolicy = !isProduction && (skipPolicyArg\n ? parseBooleanToken(skipPolicyArg.split('=')[1] ?? 'true') ?? true\n : true)\n if (isProduction) {\n const t = createInitTranslator(env)\n const placeholder = suppliedPassword?.trim().toLowerCase()\n if (!suppliedPassword || !placeholder || ['secret', 'password', 'changeme', 'change-me', 'change_me', 'replace-me', 'replace_me'].includes(placeholder)) {\n throw new Error(t('cli.init.errors.superadminPasswordRequired'))\n }\n if (!validatePassword(suppliedPassword, getPasswordPolicy(env)).ok) {\n throw new Error(t('cli.init.errors.superadminPasswordPolicy'))\n }\n }\n return { email, password: suppliedPassword ?? 'secret', skipPasswordPolicy }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,yBAAyB;AAClC,SAAS,mBAAmB,wBAAwB;AACpD,SAAS,mBAAmB;AAC5B,SAAS,4BAA4B;AAIrC,SAAS,aAAa,KAAwB,KAAiC;AAC7E,QAAM,QAAQ,IAAI,GAAG;AACrB,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAK;AAC3B,SAAO,QAAQ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,KAAK,CAAC,QAAQ,IAAI,WAAW,GAAG,IAAI,GAAG,CAAC,GAAG,MAAM,KAAK,SAAS,CAAC,KAAK;AAC7G,QAAM,QAAQ,SAAS,SAAS,KAAK,aAAa,KAAK,0BAA0B,KAAK;AACtF,QAAM,mBAAmB,SAAS,YAAY,KAAK,aAAa,KAAK,6BAA6B;AAClG,QAAM,gBAAgB,IAAI,YAAY,IAAI,KAAK,EAAE,YAAY,MAAM;AACnE,QAAM,gBAAgB,KAAK;AAAA,IAAK,CAAC,QAC/B,QAAQ,4BAA4B,IAAI,WAAW,yBAAyB,KAC5E,QAAQ,2BAA2B,IAAI,WAAW,wBAAwB;AAAA,EAC5E;AACA,QAAM,qBAAqB,CAAC,iBAAiB,gBACzC,kBAAkB,cAAc,MAAM,GAAG,EAAE,CAAC,KAAK,MAAM,KAAK,OAC5D;AACJ,MAAI,cAAc;AAChB,UAAM,IAAI,qBAAqB,GAAG;AAClC,UAAM,cAAc,kBAAkB,KAAK,EAAE,YAAY;AACzD,QAAI,CAAC,oBAAoB,CAAC,eAAe,CAAC,UAAU,YAAY,YAAY,aAAa,aAAa,cAAc,YAAY,EAAE,SAAS,WAAW,GAAG;AACvJ,YAAM,IAAI,MAAM,EAAE,4CAA4C,CAAC;AAAA,IACjE;AACA,QAAI,CAAC,iBAAiB,kBAAkB,kBAAkB,GAAG,CAAC,EAAE,IAAI;AAClE,YAAM,IAAI,MAAM,EAAE,0CAA0C,CAAC;AAAA,IAC/D;AAAA,EACF;AACA,SAAO,EAAE,OAAO,UAAU,oBAAoB,UAAU,mBAAmB;AAC7E;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { spawn as nodeSpawn } from "node:child_process";
|
|
2
2
|
import { getSslConfig } from "@open-mercato/shared/lib/db/ssl";
|
|
3
|
+
import { configureDatabasePool, isDatabaseRuntimeEnabled, resolveDatabaseConnectionUrl, runWithFreshDatabaseExecutionContext } from "@open-mercato/shared/lib/db/runtime";
|
|
3
4
|
const PROBE_ERROR_LOG_THROTTLE_MS = 6e4;
|
|
4
5
|
function coerceCount(value) {
|
|
5
6
|
if (typeof value === "number" && Number.isFinite(value)) return Math.max(0, Math.floor(value));
|
|
@@ -25,14 +26,42 @@ async function probeEnabledSchedules(env = process.env) {
|
|
|
25
26
|
errorMessage: "DATABASE_URL is not set"
|
|
26
27
|
};
|
|
27
28
|
}
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
29
|
+
if (isDatabaseRuntimeEnabled()) {
|
|
30
|
+
return runWithFreshDatabaseExecutionContext({
|
|
31
|
+
kind: "maintenance",
|
|
32
|
+
tenantId: null,
|
|
33
|
+
source: "scheduler",
|
|
34
|
+
operation: "scheduler.lazy-probe"
|
|
35
|
+
}, () => probeScheduleConnection(databaseUrl, true));
|
|
36
|
+
}
|
|
37
|
+
return probeScheduleConnection(databaseUrl, false);
|
|
38
|
+
}
|
|
39
|
+
async function probeScheduleConnection(databaseUrl, maintenance) {
|
|
40
|
+
let clientEnded = false;
|
|
41
|
+
let lifecycle;
|
|
42
|
+
let release;
|
|
43
|
+
let client;
|
|
33
44
|
try {
|
|
45
|
+
const { Client } = await import("pg");
|
|
46
|
+
client = new Client({
|
|
47
|
+
connectionString: maintenance ? resolveDatabaseConnectionUrl("maintenance", databaseUrl) : databaseUrl,
|
|
48
|
+
ssl: getSslConfig(),
|
|
49
|
+
...maintenance ? { connectionTimeoutMillis: 5e3, query_timeout: 5e3 } : {}
|
|
50
|
+
});
|
|
34
51
|
await client.connect();
|
|
35
|
-
|
|
52
|
+
let connection = client;
|
|
53
|
+
if (maintenance) {
|
|
54
|
+
const physical = { query: client.query.bind(client), release: () => void 0 };
|
|
55
|
+
const pool = { connect: async () => physical, get ended() {
|
|
56
|
+
return clientEnded;
|
|
57
|
+
} };
|
|
58
|
+
lifecycle = configureDatabasePool(pool, { id: "scheduler-lazy-probe", purpose: "maintenance", tables: ["scheduled_jobs"] });
|
|
59
|
+
await lifecycle.ready();
|
|
60
|
+
const guarded = await pool.connect();
|
|
61
|
+
connection = guarded;
|
|
62
|
+
release = guarded.release;
|
|
63
|
+
}
|
|
64
|
+
const result = await connection.query(`
|
|
36
65
|
select
|
|
37
66
|
count(*)::int as enabled_schedules,
|
|
38
67
|
count(*) filter (where next_run_at <= now())::int as due_schedules
|
|
@@ -61,7 +90,18 @@ async function probeEnabledSchedules(env = process.env) {
|
|
|
61
90
|
errorMessage: error instanceof Error ? error.message : String(error)
|
|
62
91
|
};
|
|
63
92
|
} finally {
|
|
64
|
-
|
|
93
|
+
try {
|
|
94
|
+
release?.();
|
|
95
|
+
} finally {
|
|
96
|
+
try {
|
|
97
|
+
if (client) {
|
|
98
|
+
await client.end();
|
|
99
|
+
clientEnded = true;
|
|
100
|
+
}
|
|
101
|
+
} finally {
|
|
102
|
+
lifecycle?.dispose();
|
|
103
|
+
}
|
|
104
|
+
}
|
|
65
105
|
}
|
|
66
106
|
}
|
|
67
107
|
function startLazySchedulerSupervisor(options) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/lib/scheduler-supervisor.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Lazy local scheduler supervisor.\n *\n * Keeps the server runtime from spawning the local scheduler polling engine\n * until at least one enabled schedule exists. The scheduler process itself is\n * still the existing `mercato scheduler start` command, so schedule execution,\n * locking, RBAC checks, and queue/command targets remain unchanged.\n */\n\nimport { spawn as nodeSpawn } from 'node:child_process'\nimport type { ChildProcess, SpawnOptions } from 'node:child_process'\nimport { getSslConfig } from '@open-mercato/shared/lib/db/ssl'\n\nexport type SchedulerScheduleProbeResult = {\n enabledSchedules: number\n dueSchedules: number\n error?: boolean\n errorMessage?: string\n}\n\nexport type LazySchedulerSupervisorProbeFn = (\n env: NodeJS.ProcessEnv,\n) => Promise<SchedulerScheduleProbeResult>\n\nexport type LazySchedulerSupervisorSpawnFn = (\n command: string,\n args: readonly string[],\n options: SpawnOptions,\n) => ChildProcess\n\nexport type LazySchedulerSupervisorOptions = {\n mercatoBin: string\n appDir: string\n runtimeEnv: NodeJS.ProcessEnv\n pollMs: number\n restartOnUnexpectedExit: boolean\n spawnFn?: LazySchedulerSupervisorSpawnFn\n probeFn?: LazySchedulerSupervisorProbeFn\n logger?: Pick<Console, 'log' | 'warn' | 'error'>\n onSpawn?: (child: ChildProcess) => void\n onChildExit?: (code: number | null, signal: NodeJS.Signals | null) => void\n}\n\nexport type LazySchedulerSupervisorHandle = {\n readonly started: boolean\n getActiveChild(): ChildProcess | undefined\n close(): Promise<void>\n done: Promise<void>\n}\n\nconst PROBE_ERROR_LOG_THROTTLE_MS = 60_000\n\nfunction coerceCount(value: unknown): number {\n if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.floor(value))\n if (typeof value === 'bigint') return Number(value)\n if (typeof value === 'string') {\n const parsed = Number(value)\n return Number.isFinite(parsed) ? Math.max(0, Math.floor(parsed)) : 0\n }\n return 0\n}\n\nfunction isMissingScheduledJobsTableError(error: unknown): boolean {\n return Boolean(\n error\n && typeof error === 'object'\n && 'code' in error\n && (error as { code?: unknown }).code === '42P01',\n )\n}\n\nexport async function probeEnabledSchedules(env: NodeJS.ProcessEnv = process.env): Promise<SchedulerScheduleProbeResult> {\n const databaseUrl = env.DATABASE_URL?.trim()\n if (!databaseUrl) {\n return {\n enabledSchedules: 0,\n dueSchedules: 0,\n error: true,\n errorMessage: 'DATABASE_URL is not set',\n }\n }\n\n const { Client } = await import('pg')\n const client = new Client({\n connectionString: databaseUrl,\n ssl: getSslConfig(),\n })\n\n try {\n await client.connect()\n const result = await client.query(`\n select\n count(*)::int as enabled_schedules,\n count(*) filter (where next_run_at <= now())::int as due_schedules\n from scheduled_jobs\n where is_enabled = true\n and deleted_at is null\n `)\n const row = result.rows[0] ?? {}\n return {\n enabledSchedules: coerceCount(row.enabled_schedules),\n dueSchedules: coerceCount(row.due_schedules),\n error: false,\n }\n } catch (error) {\n if (isMissingScheduledJobsTableError(error)) {\n return {\n enabledSchedules: 0,\n dueSchedules: 0,\n error: false,\n }\n }\n return {\n enabledSchedules: 0,\n dueSchedules: 0,\n error: true,\n errorMessage: error instanceof Error ? error.message : String(error),\n }\n } finally {\n await client.end().catch(() => undefined)\n }\n}\n\nexport function startLazySchedulerSupervisor(\n options: LazySchedulerSupervisorOptions,\n): LazySchedulerSupervisorHandle {\n const logger = options.logger ?? console\n const probe = options.probeFn ?? probeEnabledSchedules\n const spawnFn: LazySchedulerSupervisorSpawnFn =\n options.spawnFn ?? ((command, args, opts) => nodeSpawn(command, args as string[], opts))\n\n let stopping = false\n let started = false\n let starting = false\n let activeChild: ChildProcess | undefined\n let pollTimer: ReturnType<typeof setTimeout> | null = null\n let lastProbeErrorLoggedAt = 0\n let doneResolve: (() => void) | null = null\n const done = new Promise<void>((resolve) => {\n doneResolve = resolve\n })\n\n logger.log('[lazy-scheduler] Watching for enabled schedules before starting the polling engine.')\n\n function logProbeError(message: string): void {\n const now = Date.now()\n if (now - lastProbeErrorLoggedAt < PROBE_ERROR_LOG_THROTTLE_MS) return\n lastProbeErrorLoggedAt = now\n logger.warn(`[lazy-scheduler] Schedule probe failed: ${message}`)\n }\n\n function spawnScheduler(): void {\n if (stopping || activeChild || starting) return\n starting = true\n logger.log('[lazy-scheduler] Enabled schedule detected - starting scheduler polling engine.')\n\n let child: ChildProcess\n try {\n child = spawnFn('node', [options.mercatoBin, 'scheduler', 'start'], {\n stdio: 'inherit',\n env: options.runtimeEnv,\n cwd: options.appDir,\n })\n } catch (error) {\n starting = false\n const message = error instanceof Error ? error.message : String(error)\n logger.error(`[lazy-scheduler] Failed to spawn scheduler: ${message}`)\n return\n }\n\n activeChild = child\n started = true\n starting = false\n options.onSpawn?.(child)\n\n child.on('exit', (code, signal) => {\n activeChild = undefined\n options.onChildExit?.(code, signal)\n if (stopping) return\n const expected = signal === 'SIGTERM' || signal === 'SIGINT'\n if (expected) return\n const reason = code !== null ? `code ${code}` : `signal ${signal ?? 'unknown'}`\n logger.warn(`[lazy-scheduler] Scheduler polling engine exited (${reason}).`)\n if (!options.restartOnUnexpectedExit) return\n void (async () => {\n const result = await safeProbe()\n if (!result || result.error) return\n if (result.enabledSchedules > 0) {\n logger.warn('[lazy-scheduler] Restarting scheduler because enabled schedules still exist.')\n spawnScheduler()\n }\n })()\n })\n }\n\n async function safeProbe(): Promise<SchedulerScheduleProbeResult | null> {\n try {\n return await probe(options.runtimeEnv)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logProbeError(message)\n return null\n }\n }\n\n async function tickOnce(): Promise<void> {\n if (stopping || activeChild || starting) return\n const result = await safeProbe()\n if (!result) return\n if (result.error) {\n if (result.errorMessage) logProbeError(result.errorMessage)\n return\n }\n if (result.enabledSchedules > 0) {\n spawnScheduler()\n }\n }\n\n function scheduleNext(): void {\n if (stopping || activeChild) return\n pollTimer = setTimeout(() => {\n void (async () => {\n try {\n await tickOnce()\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.warn(`[lazy-scheduler] Poll cycle failed: ${message}`)\n } finally {\n scheduleNext()\n }\n })()\n }, options.pollMs)\n pollTimer.unref?.()\n }\n\n void (async () => {\n try {\n await tickOnce()\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.warn(`[lazy-scheduler] Initial poll failed: ${message}`)\n } finally {\n scheduleNext()\n }\n })()\n\n async function close(): Promise<void> {\n if (stopping) {\n await done\n return\n }\n stopping = true\n if (pollTimer) {\n clearTimeout(pollTimer)\n pollTimer = null\n }\n\n const child = activeChild\n if (child) {\n await new Promise<void>((resolve) => {\n if (child.exitCode !== null || child.signalCode !== null) return resolve()\n child.once('exit', () => resolve())\n try {\n if (!child.killed) child.kill('SIGTERM')\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.warn(`[lazy-scheduler] Failed to send SIGTERM to scheduler: ${message}`)\n resolve()\n }\n })\n activeChild = undefined\n }\n\n doneResolve?.()\n doneResolve = null\n }\n\n return {\n get started() {\n return started\n },\n getActiveChild: () => activeChild,\n close,\n done,\n }\n}\n"],
|
|
5
|
-
"mappings": "AASA,SAAS,SAAS,iBAAiB;AAEnC,SAAS,oBAAoB;
|
|
4
|
+
"sourcesContent": ["/**\n * Lazy local scheduler supervisor.\n *\n * Keeps the server runtime from spawning the local scheduler polling engine\n * until at least one enabled schedule exists. The scheduler process itself is\n * still the existing `mercato scheduler start` command, so schedule execution,\n * locking, RBAC checks, and queue/command targets remain unchanged.\n */\n\nimport { spawn as nodeSpawn } from 'node:child_process'\nimport type { ChildProcess, SpawnOptions } from 'node:child_process'\nimport { getSslConfig } from '@open-mercato/shared/lib/db/ssl'\nimport { configureDatabasePool, isDatabaseRuntimeEnabled, resolveDatabaseConnectionUrl, runWithFreshDatabaseExecutionContext } from '@open-mercato/shared/lib/db/runtime'\nimport type { DatabasePoolLifecycle } from '@open-mercato/shared/lib/db/runtime'\n\nexport type SchedulerScheduleProbeResult = {\n enabledSchedules: number\n dueSchedules: number\n error?: boolean\n errorMessage?: string\n}\n\nexport type LazySchedulerSupervisorProbeFn = (\n env: NodeJS.ProcessEnv,\n) => Promise<SchedulerScheduleProbeResult>\n\nexport type LazySchedulerSupervisorSpawnFn = (\n command: string,\n args: readonly string[],\n options: SpawnOptions,\n) => ChildProcess\n\nexport type LazySchedulerSupervisorOptions = {\n mercatoBin: string\n appDir: string\n runtimeEnv: NodeJS.ProcessEnv\n pollMs: number\n restartOnUnexpectedExit: boolean\n spawnFn?: LazySchedulerSupervisorSpawnFn\n probeFn?: LazySchedulerSupervisorProbeFn\n logger?: Pick<Console, 'log' | 'warn' | 'error'>\n onSpawn?: (child: ChildProcess) => void\n onChildExit?: (code: number | null, signal: NodeJS.Signals | null) => void\n}\n\nexport type LazySchedulerSupervisorHandle = {\n readonly started: boolean\n getActiveChild(): ChildProcess | undefined\n close(): Promise<void>\n done: Promise<void>\n}\n\nconst PROBE_ERROR_LOG_THROTTLE_MS = 60_000\n\nfunction coerceCount(value: unknown): number {\n if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.floor(value))\n if (typeof value === 'bigint') return Number(value)\n if (typeof value === 'string') {\n const parsed = Number(value)\n return Number.isFinite(parsed) ? Math.max(0, Math.floor(parsed)) : 0\n }\n return 0\n}\n\nfunction isMissingScheduledJobsTableError(error: unknown): boolean {\n return Boolean(\n error\n && typeof error === 'object'\n && 'code' in error\n && (error as { code?: unknown }).code === '42P01',\n )\n}\n\nexport async function probeEnabledSchedules(env: NodeJS.ProcessEnv = process.env): Promise<SchedulerScheduleProbeResult> {\n const databaseUrl = env.DATABASE_URL?.trim()\n if (!databaseUrl) {\n return {\n enabledSchedules: 0,\n dueSchedules: 0,\n error: true,\n errorMessage: 'DATABASE_URL is not set',\n }\n }\n\n if (isDatabaseRuntimeEnabled()) {\n return runWithFreshDatabaseExecutionContext({\n kind: 'maintenance', tenantId: null, source: 'scheduler', operation: 'scheduler.lazy-probe',\n }, () => probeScheduleConnection(databaseUrl, true))\n }\n return probeScheduleConnection(databaseUrl, false)\n}\n\nasync function probeScheduleConnection(databaseUrl: string, maintenance: boolean): Promise<SchedulerScheduleProbeResult> {\n let clientEnded = false\n let lifecycle: DatabasePoolLifecycle | undefined\n let release: (() => void) | undefined\n let client: InstanceType<typeof import('pg').Client> | undefined\n try {\n const { Client } = await import('pg')\n client = new Client({\n connectionString: maintenance ? resolveDatabaseConnectionUrl('maintenance', databaseUrl) : databaseUrl,\n ssl: getSslConfig(),\n ...(maintenance ? { connectionTimeoutMillis: 5000, query_timeout: 5000 } : {}),\n })\n\n await client.connect()\n let connection: Pick<InstanceType<typeof Client>, 'query'> = client\n if (maintenance) {\n const physical = { query: client.query.bind(client), release: () => undefined }\n const pool = { connect: async () => physical, get ended() { return clientEnded } }\n lifecycle = configureDatabasePool(pool, { id: 'scheduler-lazy-probe', purpose: 'maintenance', tables: ['scheduled_jobs'] })\n await lifecycle.ready()\n const guarded = await pool.connect()\n connection = guarded\n release = guarded.release\n }\n const result = await connection.query(`\n select\n count(*)::int as enabled_schedules,\n count(*) filter (where next_run_at <= now())::int as due_schedules\n from scheduled_jobs\n where is_enabled = true\n and deleted_at is null\n `)\n const row = result.rows[0] ?? {}\n return {\n enabledSchedules: coerceCount(row.enabled_schedules),\n dueSchedules: coerceCount(row.due_schedules),\n error: false,\n }\n } catch (error) {\n if (isMissingScheduledJobsTableError(error)) {\n return {\n enabledSchedules: 0,\n dueSchedules: 0,\n error: false,\n }\n }\n return {\n enabledSchedules: 0,\n dueSchedules: 0,\n error: true,\n errorMessage: error instanceof Error ? error.message : String(error),\n }\n } finally {\n try { release?.() } finally {\n try {\n if (client) {\n await client.end()\n clientEnded = true\n }\n } finally { lifecycle?.dispose() }\n }\n }\n}\n\nexport function startLazySchedulerSupervisor(\n options: LazySchedulerSupervisorOptions,\n): LazySchedulerSupervisorHandle {\n const logger = options.logger ?? console\n const probe = options.probeFn ?? probeEnabledSchedules\n const spawnFn: LazySchedulerSupervisorSpawnFn =\n options.spawnFn ?? ((command, args, opts) => nodeSpawn(command, args as string[], opts))\n\n let stopping = false\n let started = false\n let starting = false\n let activeChild: ChildProcess | undefined\n let pollTimer: ReturnType<typeof setTimeout> | null = null\n let lastProbeErrorLoggedAt = 0\n let doneResolve: (() => void) | null = null\n const done = new Promise<void>((resolve) => {\n doneResolve = resolve\n })\n\n logger.log('[lazy-scheduler] Watching for enabled schedules before starting the polling engine.')\n\n function logProbeError(message: string): void {\n const now = Date.now()\n if (now - lastProbeErrorLoggedAt < PROBE_ERROR_LOG_THROTTLE_MS) return\n lastProbeErrorLoggedAt = now\n logger.warn(`[lazy-scheduler] Schedule probe failed: ${message}`)\n }\n\n function spawnScheduler(): void {\n if (stopping || activeChild || starting) return\n starting = true\n logger.log('[lazy-scheduler] Enabled schedule detected - starting scheduler polling engine.')\n\n let child: ChildProcess\n try {\n child = spawnFn('node', [options.mercatoBin, 'scheduler', 'start'], {\n stdio: 'inherit',\n env: options.runtimeEnv,\n cwd: options.appDir,\n })\n } catch (error) {\n starting = false\n const message = error instanceof Error ? error.message : String(error)\n logger.error(`[lazy-scheduler] Failed to spawn scheduler: ${message}`)\n return\n }\n\n activeChild = child\n started = true\n starting = false\n options.onSpawn?.(child)\n\n child.on('exit', (code, signal) => {\n activeChild = undefined\n options.onChildExit?.(code, signal)\n if (stopping) return\n const expected = signal === 'SIGTERM' || signal === 'SIGINT'\n if (expected) return\n const reason = code !== null ? `code ${code}` : `signal ${signal ?? 'unknown'}`\n logger.warn(`[lazy-scheduler] Scheduler polling engine exited (${reason}).`)\n if (!options.restartOnUnexpectedExit) return\n void (async () => {\n const result = await safeProbe()\n if (!result || result.error) return\n if (result.enabledSchedules > 0) {\n logger.warn('[lazy-scheduler] Restarting scheduler because enabled schedules still exist.')\n spawnScheduler()\n }\n })()\n })\n }\n\n async function safeProbe(): Promise<SchedulerScheduleProbeResult | null> {\n try {\n return await probe(options.runtimeEnv)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logProbeError(message)\n return null\n }\n }\n\n async function tickOnce(): Promise<void> {\n if (stopping || activeChild || starting) return\n const result = await safeProbe()\n if (!result) return\n if (result.error) {\n if (result.errorMessage) logProbeError(result.errorMessage)\n return\n }\n if (result.enabledSchedules > 0) {\n spawnScheduler()\n }\n }\n\n function scheduleNext(): void {\n if (stopping || activeChild) return\n pollTimer = setTimeout(() => {\n void (async () => {\n try {\n await tickOnce()\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.warn(`[lazy-scheduler] Poll cycle failed: ${message}`)\n } finally {\n scheduleNext()\n }\n })()\n }, options.pollMs)\n pollTimer.unref?.()\n }\n\n void (async () => {\n try {\n await tickOnce()\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.warn(`[lazy-scheduler] Initial poll failed: ${message}`)\n } finally {\n scheduleNext()\n }\n })()\n\n async function close(): Promise<void> {\n if (stopping) {\n await done\n return\n }\n stopping = true\n if (pollTimer) {\n clearTimeout(pollTimer)\n pollTimer = null\n }\n\n const child = activeChild\n if (child) {\n await new Promise<void>((resolve) => {\n if (child.exitCode !== null || child.signalCode !== null) return resolve()\n child.once('exit', () => resolve())\n try {\n if (!child.killed) child.kill('SIGTERM')\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.warn(`[lazy-scheduler] Failed to send SIGTERM to scheduler: ${message}`)\n resolve()\n }\n })\n activeChild = undefined\n }\n\n doneResolve?.()\n doneResolve = null\n }\n\n return {\n get started() {\n return started\n },\n getActiveChild: () => activeChild,\n close,\n done,\n }\n}\n"],
|
|
5
|
+
"mappings": "AASA,SAAS,SAAS,iBAAiB;AAEnC,SAAS,oBAAoB;AAC7B,SAAS,uBAAuB,0BAA0B,8BAA8B,4CAA4C;AAwCpI,MAAM,8BAA8B;AAEpC,SAAS,YAAY,OAAwB;AAC3C,MAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,EAAG,QAAO,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,CAAC;AAC7F,MAAI,OAAO,UAAU,SAAU,QAAO,OAAO,KAAK;AAClD,MAAI,OAAO,UAAU,UAAU;AAC7B,UAAM,SAAS,OAAO,KAAK;AAC3B,WAAO,OAAO,SAAS,MAAM,IAAI,KAAK,IAAI,GAAG,KAAK,MAAM,MAAM,CAAC,IAAI;AAAA,EACrE;AACA,SAAO;AACT;AAEA,SAAS,iCAAiC,OAAyB;AACjE,SAAO;AAAA,IACL,SACK,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS;AAAA,EAC9C;AACF;AAEA,eAAsB,sBAAsB,MAAyB,QAAQ,KAA4C;AACvH,QAAM,cAAc,IAAI,cAAc,KAAK;AAC3C,MAAI,CAAC,aAAa;AAChB,WAAO;AAAA,MACL,kBAAkB;AAAA,MAClB,cAAc;AAAA,MACd,OAAO;AAAA,MACP,cAAc;AAAA,IAChB;AAAA,EACF;AAEA,MAAI,yBAAyB,GAAG;AAC9B,WAAO,qC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;AAAA,IACA,gBAAgB,MAAM;AAAA,IACtB;AAAA,IACA;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,38 +1,48 @@
|
|
|
1
|
+
import { isDatabaseRuntimeEnabled, runWithFreshDatabaseExecutionContext } from "@open-mercato/shared/lib/db/runtime";
|
|
2
|
+
import { resolveDeclaredDatabaseJobContext, validateDeclaredDatabaseBinding } from "@open-mercato/shared/lib/db/declarations";
|
|
1
3
|
import {
|
|
2
4
|
inferModuleIdFromResourceId,
|
|
3
5
|
withModuleResourceUsage
|
|
4
6
|
} from "@open-mercato/shared/lib/modules/resource-usage";
|
|
5
7
|
import { bindRequestScopeContainer, runInOwnedRequestScope, runWithRequestScopeContainer } from "@open-mercato/shared/lib/di/request-scope";
|
|
6
8
|
function createPerJobWorkerHandler(workers, createContainer) {
|
|
7
|
-
return (job, ctx) =>
|
|
8
|
-
const
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
for (const worker of workers) {
|
|
12
|
-
await withModuleResourceUsage(
|
|
13
|
-
{
|
|
14
|
-
moduleId: worker.moduleId ?? inferModuleIdFromResourceId(worker.id),
|
|
15
|
-
surface: "worker",
|
|
16
|
-
operation: worker.id,
|
|
17
|
-
resourceId: worker.id
|
|
18
|
-
},
|
|
19
|
-
() => runWithRequestScopeContainer(container, () => worker.handler(job, {
|
|
20
|
-
...ctx,
|
|
21
|
-
resolve: container.resolve.bind(container),
|
|
22
|
-
// See `WorkerJobContainer.register`'s own doc — present only when the
|
|
23
|
-
// factory handed back a real container, never a `{ resolve }`-only one.
|
|
24
|
-
container: typeof container.register === "function" ? container : void 0
|
|
25
|
-
}))
|
|
26
|
-
);
|
|
27
|
-
}
|
|
28
|
-
} finally {
|
|
9
|
+
return async (job, ctx) => {
|
|
10
|
+
const execute = () => runInOwnedRequestScope(async () => {
|
|
11
|
+
const container = await createContainer();
|
|
12
|
+
bindRequestScopeContainer(container);
|
|
29
13
|
try {
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
|
|
14
|
+
for (const worker of workers) {
|
|
15
|
+
await withModuleResourceUsage(
|
|
16
|
+
{
|
|
17
|
+
moduleId: worker.moduleId ?? inferModuleIdFromResourceId(worker.id),
|
|
18
|
+
surface: "worker",
|
|
19
|
+
operation: worker.id,
|
|
20
|
+
resourceId: worker.id
|
|
21
|
+
},
|
|
22
|
+
() => runWithRequestScopeContainer(container, () => worker.handler(job, {
|
|
23
|
+
...ctx,
|
|
24
|
+
resolve: container.resolve.bind(container),
|
|
25
|
+
container: typeof container.register === "function" ? container : void 0
|
|
26
|
+
}))
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
} finally {
|
|
30
|
+
try {
|
|
31
|
+
const em = container.resolve("em");
|
|
32
|
+
em?.clear?.();
|
|
33
|
+
} catch {
|
|
34
|
+
}
|
|
35
|
+
await container.dispose?.();
|
|
33
36
|
}
|
|
37
|
+
});
|
|
38
|
+
if (!isDatabaseRuntimeEnabled()) return execute();
|
|
39
|
+
const context = await resolveDeclaredDatabaseJobContext({ queue: ctx.queueName, workerIds: workers.map((worker) => worker.id), payload: job.payload, metadata: job.metadata });
|
|
40
|
+
if (context.kind === "tenant") {
|
|
41
|
+
const valid = await runWithFreshDatabaseExecutionContext({ kind: "identity", tenantId: context.tenantId, source: "identity", operation: "worker-tenant-binding" }, () => validateDeclaredDatabaseBinding({ context }, { requireValidator: true }));
|
|
42
|
+
if (!valid) throw new Error("[internal] Worker requires a persisted active tenant");
|
|
34
43
|
}
|
|
35
|
-
|
|
44
|
+
return runWithFreshDatabaseExecutionContext(context, execute);
|
|
45
|
+
};
|
|
36
46
|
}
|
|
37
47
|
export {
|
|
38
48
|
createPerJobWorkerHandler
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/lib/worker-job-handler.ts"],
|
|
4
|
-
"sourcesContent": ["import type { JobContext, JobHandler } from '@open-mercato/queue'\nimport type { ModuleWorker } from '@open-mercato/shared/modules/registry'\nimport {\n inferModuleIdFromResourceId,\n withModuleResourceUsage,\n} from '@open-mercato/shared/lib/modules/resource-usage'\nimport { bindRequestScopeContainer, runInOwnedRequestScope, runWithRequestScopeContainer } from '@open-mercato/shared/lib/di/request-scope'\n\nexport type WorkerJobContainer = {\n resolve: <T = unknown>(name: string) => T\n /**\n * #8268 review Major 1 (re-review): optional \u2014 the factory's real container,\n * when it has one, so a worker that needs `.register()` (several command\n * phases override the trusted `auth` scope for nested resolution, e.g. before\n * resolving `promotionsService`) can use the SAME container a module's\n * `register(container)` call closed over, rather than a `{ resolve }`-only\n * shim whose overrides are invisible to an already-constructed dependent\n * service holding its own reference to the original container.\n */\n register?: (registrations: Record<string, unknown>) => void\n}\n\nexport type WorkerJobContainerFactory = () => Promise<WorkerJobContainer>\n\ntype ClearableEntityManager = {\n clear?: () => void\n}\n\n/**\n * Builds a queue job handler that isolates every job in its own request\n * container, instead of sharing a single process-wide `EntityManager` fork\n * across all concurrent jobs.\n *\n * Under the async (BullMQ) strategy jobs run with real concurrency, so a\n * shared EM would interleave unit-of-work flushes between unrelated jobs and\n * never release its identity map. Creating one container per job removes both\n * the cross-job flush race and the unbounded identity-map growth, while\n * keeping the `ctx.resolve` contract and DI keys unchanged. See issue #2970.\n */\nexport function createPerJobWorkerHandler(\n workers: ModuleWorker[],\n createContainer: WorkerJobContainerFactory,\n): JobHandler {\n return (job, ctx: JobContext) => runInOwnedRequestScope(async ()
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import { isDatabaseRuntimeEnabled, runWithFreshDatabaseExecutionContext } from '@open-mercato/shared/lib/db/runtime'\nimport { resolveDeclaredDatabaseJobContext, validateDeclaredDatabaseBinding } from '@open-mercato/shared/lib/db/declarations'\nimport type { JobContext, JobHandler } from '@open-mercato/queue'\nimport type { ModuleWorker } from '@open-mercato/shared/modules/registry'\nimport {\n inferModuleIdFromResourceId,\n withModuleResourceUsage,\n} from '@open-mercato/shared/lib/modules/resource-usage'\nimport { bindRequestScopeContainer, runInOwnedRequestScope, runWithRequestScopeContainer } from '@open-mercato/shared/lib/di/request-scope'\n\nexport type WorkerJobContainer = {\n resolve: <T = unknown>(name: string) => T\n dispose?: () => void | Promise<void>\n /**\n * #8268 review Major 1 (re-review): optional \u2014 the factory's real container,\n * when it has one, so a worker that needs `.register()` (several command\n * phases override the trusted `auth` scope for nested resolution, e.g. before\n * resolving `promotionsService`) can use the SAME container a module's\n * `register(container)` call closed over, rather than a `{ resolve }`-only\n * shim whose overrides are invisible to an already-constructed dependent\n * service holding its own reference to the original container.\n */\n register?: (registrations: Record<string, unknown>) => void\n}\n\nexport type WorkerJobContainerFactory = () => Promise<WorkerJobContainer>\n\ntype ClearableEntityManager = {\n clear?: () => void\n}\n\n/**\n * Builds a queue job handler that isolates every job in its own request\n * container, instead of sharing a single process-wide `EntityManager` fork\n * across all concurrent jobs.\n *\n * Under the async (BullMQ) strategy jobs run with real concurrency, so a\n * shared EM would interleave unit-of-work flushes between unrelated jobs and\n * never release its identity map. Creating one container per job removes both\n * the cross-job flush race and the unbounded identity-map growth, while\n * keeping the `ctx.resolve` contract and DI keys unchanged. See issue #2970.\n */\nexport function createPerJobWorkerHandler(\n workers: ModuleWorker[],\n createContainer: WorkerJobContainerFactory,\n): JobHandler {\n return async (job, ctx: JobContext) => {\n const execute = () => runInOwnedRequestScope(async () => {\n const container = await createContainer()\n bindRequestScopeContainer(container)\n try {\n for (const worker of workers) {\n await withModuleResourceUsage(\n {\n moduleId: worker.moduleId ?? inferModuleIdFromResourceId(worker.id),\n surface: 'worker',\n operation: worker.id,\n resourceId: worker.id,\n },\n () => runWithRequestScopeContainer(container, () => worker.handler(job, {\n ...ctx,\n resolve: container.resolve.bind(container),\n container: typeof container.register === 'function' ? container : undefined,\n })),\n )\n }\n } finally {\n try {\n const em = container.resolve('em') as ClearableEntityManager | null\n em?.clear?.()\n } catch {\n // Best-effort: clearing the identity map is a memory optimization and\n // must never mask a job's own outcome.\n }\n await container.dispose?.()\n }\n })\n if (!isDatabaseRuntimeEnabled()) return execute()\n const context = await resolveDeclaredDatabaseJobContext({ queue: ctx.queueName, workerIds: workers.map((worker) => worker.id), payload: job.payload, metadata: job.metadata })\n if (context.kind === 'tenant') {\n const valid = await runWithFreshDatabaseExecutionContext({ kind: 'identity', tenantId: context.tenantId, source: 'identity', operation: 'worker-tenant-binding' }, () => validateDeclaredDatabaseBinding({ context }, { requireValidator: true }))\n if (!valid) throw new Error('[internal] Worker requires a persisted active tenant')\n }\n return runWithFreshDatabaseExecutionContext(context, execute)\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,0BAA0B,4CAA4C;AAC/E,SAAS,mCAAmC,uCAAuC;AAGnF;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B,wBAAwB,oCAAoC;AAkCzF,SAAS,0BACd,SACA,iBACY;AACZ,SAAO,OAAO,KAAK,QAAoB;AACrC,UAAM,UAAU,MAAM,uBAAuB,YAAY;AACvD,YAAM,YAAY,MAAM,gBAAgB;AACxC,gCAA0B,SAAS;AACnC,UAAI;AACF,mBAAW,UAAU,SAAS;AAC5B,gBAAM;AAAA,YACJ;AAAA,cACE,UAAU,OAAO,YAAY,4BAA4B,OAAO,EAAE;AAAA,cAClE,SAAS;AAAA,cACT,WAAW,OAAO;AAAA,cAClB,YAAY,OAAO;AAAA,YACrB;AAAA,YACA,MAAM,6BAA6B,WAAW,MAAM,OAAO,QAAQ,KAAK;AAAA,cACtE,GAAG;AAAA,cACH,SAAS,UAAU,QAAQ,KAAK,SAAS;AAAA,cACzC,WAAW,OAAO,UAAU,aAAa,aAAa,YAAY;AAAA,YACpE,CAAC,CAAC;AAAA,UACJ;AAAA,QACF;AAAA,MACF,UAAE;AACA,YAAI;AACF,gBAAM,KAAK,UAAU,QAAQ,IAAI;AACjC,cAAI,QAAQ;AAAA,QACd,QAAQ;AAAA,QAGR;AACA,cAAM,UAAU,UAAU;AAAA,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