@open-mercato/scheduler 0.8.1-develop.7297.1.67605e74f9 → 0.8.1-develop.7442.1.4c1dbf1f0e

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.
@@ -1,2 +1,2 @@
1
- [build:scheduler] found 62 entry points
1
+ [build:scheduler] found 64 entry points
2
2
  [build:scheduler] built successfully
@@ -7,6 +7,10 @@ async function buildSchedulerJobsFilters(query, ctx) {
7
7
  return filters;
8
8
  }
9
9
  const isSuperAdmin = ctx.auth?.isSuperAdmin === true;
10
+ if (Array.isArray(ctx.organizationIds) && ctx.organizationIds.length === 0) {
11
+ filters.id = { $eq: "00000000-0000-0000-0000-000000000000" };
12
+ return filters;
13
+ }
10
14
  const rawOrgIds = Array.isArray(ctx.organizationIds) ? ctx.organizationIds.filter((id) => typeof id === "string" && id.trim().length > 0) : [];
11
15
  const orgIdsForVisibility = rawOrgIds.length > 0 ? rawOrgIds : ctx.auth?.orgId ? [ctx.auth.orgId] : [];
12
16
  const visibilityBranches = [];
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/scheduler/api/jobs/buildFilters.ts"],
4
- "sourcesContent": ["import { escapeLikePattern } from '@open-mercato/shared/lib/db/escapeLikePattern'\n\nexport type SchedulerJobsFilterContext = {\n auth?: {\n tenantId?: string | null\n orgId?: string | null\n isSuperAdmin?: boolean\n } | null\n organizationIds?: string[] | null\n}\n\nexport type SchedulerJobsFilterQuery = {\n id?: string\n scopeType?: string\n isEnabled?: boolean\n sourceType?: string\n sourceModule?: string\n search?: string\n}\n\nexport async function buildSchedulerJobsFilters(\n query: SchedulerJobsFilterQuery,\n ctx: SchedulerJobsFilterContext,\n): Promise<Record<string, unknown>> {\n const filters: Record<string, unknown> = {}\n const tenantId = ctx.auth?.tenantId\n if (!tenantId) {\n filters.id = { $eq: '00000000-0000-0000-0000-000000000000' }\n return filters\n }\n\n const isSuperAdmin = ctx.auth?.isSuperAdmin === true\n\n const rawOrgIds = Array.isArray(ctx.organizationIds)\n ? ctx.organizationIds.filter((id): id is string => typeof id === 'string' && id.trim().length > 0)\n : []\n const orgIdsForVisibility =\n rawOrgIds.length > 0 ? rawOrgIds : ctx.auth?.orgId ? [ctx.auth.orgId] : []\n\n const visibilityBranches: Record<string, unknown>[] = []\n if (orgIdsForVisibility.length === 1) {\n visibilityBranches.push({\n organization_id: { $eq: orgIdsForVisibility[0] },\n tenant_id: { $eq: tenantId },\n })\n } else if (orgIdsForVisibility.length > 1) {\n visibilityBranches.push({\n organization_id: { $in: orgIdsForVisibility },\n tenant_id: { $eq: tenantId },\n })\n }\n visibilityBranches.push({\n organization_id: { $eq: null },\n tenant_id: { $eq: tenantId },\n scope_type: { $eq: 'tenant' },\n })\n if (isSuperAdmin) {\n visibilityBranches.push({\n organization_id: { $eq: null },\n tenant_id: { $eq: null },\n scope_type: { $eq: 'system' },\n })\n }\n\n const searchNeedle = query.search?.trim()\n ? `%${escapeLikePattern(query.search.trim())}%`\n : null\n\n const visibilityOr: Record<string, unknown>[] = searchNeedle\n ? visibilityBranches.flatMap((branch) => [\n { ...branch, name: { $ilike: searchNeedle } },\n { ...branch, description: { $ilike: searchNeedle } },\n ])\n : visibilityBranches\n\n filters.$or = visibilityOr\n\n if (query.id) {\n filters.id = { $eq: query.id }\n }\n\n if (query.scopeType) {\n filters.scope_type = { $eq: query.scopeType }\n }\n\n if (query.isEnabled !== undefined) {\n filters.is_enabled = { $eq: query.isEnabled }\n }\n\n if (query.sourceType) {\n filters.source_type = { $eq: query.sourceType }\n }\n\n if (query.sourceModule) {\n filters.source_module = { $eq: query.sourceModule }\n }\n\n return filters\n}\n"],
5
- "mappings": "AAAA,SAAS,yBAAyB;AAoBlC,eAAsB,0BACpB,OACA,KACkC;AAClC,QAAM,UAAmC,CAAC;AAC1C,QAAM,WAAW,IAAI,MAAM;AAC3B,MAAI,CAAC,UAAU;AACb,YAAQ,KAAK,EAAE,KAAK,uC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GAAG,QAAQ,aAAa,EAAE,QAAQ,aAAa,EAAE;AAAA,EACrD,CAAC,IACD;AAEJ,UAAQ,MAAM;AAEd,MAAI,MAAM,IAAI;AACZ,YAAQ,KAAK,EAAE,KAAK,MAAM,GAAG;AAAA,EAC/B;AAEA,MAAI,MAAM,WAAW;AACnB,YAAQ,aAAa,EAAE,KAAK,MAAM,UAAU;AAAA,EAC9C;AAEA,MAAI,MAAM,cAAc,QAAW;AACjC,YAAQ,aAAa,EAAE,KAAK,MAAM,UAAU;AAAA,EAC9C;AAEA,MAAI,MAAM,YAAY;AACpB,YAAQ,cAAc,EAAE,KAAK,MAAM,WAAW;AAAA,EAChD;AAEA,MAAI,MAAM,cAAc;AACtB,YAAQ,gBAAgB,EAAE,KAAK,MAAM,aAAa;AAAA,EACpD;AAEA,SAAO;AACT;",
4
+ "sourcesContent": ["import { escapeLikePattern } from '@open-mercato/shared/lib/db/escapeLikePattern'\n\nexport type SchedulerJobsFilterContext = {\n auth?: {\n tenantId?: string | null\n orgId?: string | null\n isSuperAdmin?: boolean\n } | null\n organizationIds?: string[] | null\n}\n\nexport type SchedulerJobsFilterQuery = {\n id?: string\n scopeType?: string\n isEnabled?: boolean\n sourceType?: string\n sourceModule?: string\n search?: string\n}\n\nexport async function buildSchedulerJobsFilters(\n query: SchedulerJobsFilterQuery,\n ctx: SchedulerJobsFilterContext,\n): Promise<Record<string, unknown>> {\n const filters: Record<string, unknown> = {}\n const tenantId = ctx.auth?.tenantId\n if (!tenantId) {\n filters.id = { $eq: '00000000-0000-0000-0000-000000000000' }\n return filters\n }\n\n const isSuperAdmin = ctx.auth?.isSuperAdmin === true\n\n if (Array.isArray(ctx.organizationIds) && ctx.organizationIds.length === 0) {\n filters.id = { $eq: '00000000-0000-0000-0000-000000000000' }\n return filters\n }\n\n const rawOrgIds = Array.isArray(ctx.organizationIds)\n ? ctx.organizationIds.filter((id): id is string => typeof id === 'string' && id.trim().length > 0)\n : []\n const orgIdsForVisibility =\n rawOrgIds.length > 0 ? rawOrgIds : ctx.auth?.orgId ? [ctx.auth.orgId] : []\n\n const visibilityBranches: Record<string, unknown>[] = []\n if (orgIdsForVisibility.length === 1) {\n visibilityBranches.push({\n organization_id: { $eq: orgIdsForVisibility[0] },\n tenant_id: { $eq: tenantId },\n })\n } else if (orgIdsForVisibility.length > 1) {\n visibilityBranches.push({\n organization_id: { $in: orgIdsForVisibility },\n tenant_id: { $eq: tenantId },\n })\n }\n visibilityBranches.push({\n organization_id: { $eq: null },\n tenant_id: { $eq: tenantId },\n scope_type: { $eq: 'tenant' },\n })\n if (isSuperAdmin) {\n visibilityBranches.push({\n organization_id: { $eq: null },\n tenant_id: { $eq: null },\n scope_type: { $eq: 'system' },\n })\n }\n\n const searchNeedle = query.search?.trim()\n ? `%${escapeLikePattern(query.search.trim())}%`\n : null\n\n const visibilityOr: Record<string, unknown>[] = searchNeedle\n ? visibilityBranches.flatMap((branch) => [\n { ...branch, name: { $ilike: searchNeedle } },\n { ...branch, description: { $ilike: searchNeedle } },\n ])\n : visibilityBranches\n\n filters.$or = visibilityOr\n\n if (query.id) {\n filters.id = { $eq: query.id }\n }\n\n if (query.scopeType) {\n filters.scope_type = { $eq: query.scopeType }\n }\n\n if (query.isEnabled !== undefined) {\n filters.is_enabled = { $eq: query.isEnabled }\n }\n\n if (query.sourceType) {\n filters.source_type = { $eq: query.sourceType }\n }\n\n if (query.sourceModule) {\n filters.source_module = { $eq: query.sourceModule }\n }\n\n return filters\n}\n"],
5
+ "mappings": "AAAA,SAAS,yBAAyB;AAoBlC,eAAsB,0BACpB,OACA,KACkC;AAClC,QAAM,UAAmC,CAAC;AAC1C,QAAM,WAAW,IAAI,MAAM;AAC3B,MAAI,CAAC,UAAU;AACb,YAAQ,KAAK,EAAE,KAAK,uCAAuC;AAC3D,WAAO;AAAA,EACT;AAEA,QAAM,eAAe,IAAI,MAAM,iBAAiB;AAEhD,MAAI,MAAM,QAAQ,IAAI,eAAe,KAAK,IAAI,gBAAgB,WAAW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E,GAAG,QAAQ,aAAa,EAAE,QAAQ,aAAa,EAAE;AAAA,EACrD,CAAC,IACD;AAEJ,UAAQ,MAAM;AAEd,MAAI,MAAM,IAAI;AACZ,YAAQ,KAAK,EAAE,KAAK,MAAM,GAAG;AAAA,EAC/B;AAEA,MAAI,MAAM,WAAW;AACnB,YAAQ,aAAa,EAAE,KAAK,MAAM,UAAU;AAAA,EAC9C;AAEA,MAAI,MAAM,cAAc,QAAW;AACjC,YAAQ,aAAa,EAAE,KAAK,MAAM,UAAU;AAAA,EAC9C;AAEA,MAAI,MAAM,YAAY;AACpB,YAAQ,cAAc,EAAE,KAAK,MAAM,WAAW;AAAA,EAChD;AAEA,MAAI,MAAM,cAAc;AACtB,YAAQ,gBAAgB,EAAE,KAAK,MAAM,aAAa;AAAA,EACpD;AAEA,SAAO;AACT;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,61 @@
1
+ import { getRedisUrlOrThrow, parseRedisUrl } from "@open-mercato/shared/lib/redis/connection";
2
+ import { createLogger } from "@open-mercato/shared/lib/logger";
3
+ const logger = createLogger("scheduler").child({ component: "next-run-sync" });
4
+ const BULLMQ_NEXT_RUN_READ_TIMEOUT_MS = 2e3;
5
+ function toBullmqNextRun(state) {
6
+ if (!state || typeof state.next !== "number" || !Number.isFinite(state.next)) return null;
7
+ return {
8
+ nextRunAt: new Date(state.next),
9
+ ...typeof state.pattern === "string" ? { pattern: state.pattern } : {},
10
+ ...typeof state.every === "number" ? { every: state.every } : {},
11
+ ...typeof state.tz === "string" ? { timezone: state.tz } : {}
12
+ };
13
+ }
14
+ async function readAndClose(queue, scheduleId) {
15
+ try {
16
+ if (typeof queue.getJobScheduler !== "function") return null;
17
+ return toBullmqNextRun(await queue.getJobScheduler(`schedule-${scheduleId}`));
18
+ } finally {
19
+ await queue.close().catch((error) => {
20
+ logger.debug("Failed to close the BullMQ queue after reading the job scheduler", { scheduleId, err: error });
21
+ });
22
+ }
23
+ }
24
+ async function readBullmqNextRun(scheduleId, timeoutMs = BULLMQ_NEXT_RUN_READ_TIMEOUT_MS) {
25
+ const { Queue } = await import("bullmq");
26
+ const queue = new Queue("scheduler-execution", {
27
+ connection: parseRedisUrl(getRedisUrlOrThrow("QUEUE"))
28
+ });
29
+ let lastConnectionError;
30
+ queue.on("error", (error) => {
31
+ lastConnectionError = error;
32
+ });
33
+ let timer;
34
+ let timedOut = false;
35
+ const deadline = new Promise((_resolve, reject) => {
36
+ timer = setTimeout(() => {
37
+ timedOut = true;
38
+ reject(new Error(
39
+ `[internal] Timed out after ${timeoutMs}ms reading the BullMQ job scheduler`,
40
+ lastConnectionError ? { cause: lastConnectionError } : void 0
41
+ ));
42
+ }, timeoutMs);
43
+ });
44
+ const read = readAndClose(queue, scheduleId);
45
+ try {
46
+ return await Promise.race([read, deadline]);
47
+ } catch (error) {
48
+ if (timedOut) {
49
+ queue.close().catch(() => void 0);
50
+ queue.disconnect().catch(() => void 0);
51
+ }
52
+ throw error;
53
+ } finally {
54
+ if (timer) clearTimeout(timer);
55
+ }
56
+ }
57
+ export {
58
+ BULLMQ_NEXT_RUN_READ_TIMEOUT_MS,
59
+ readBullmqNextRun
60
+ };
61
+ //# sourceMappingURL=bullmqNextRun.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/scheduler/lib/bullmqNextRun.ts"],
4
+ "sourcesContent": ["import { getRedisUrlOrThrow, parseRedisUrl } from '@open-mercato/shared/lib/redis/connection'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler').child({ component: 'next-run-sync' })\n\nexport const BULLMQ_NEXT_RUN_READ_TIMEOUT_MS = 2000\n\nexport type BullmqNextRun = {\n nextRunAt: Date\n pattern?: string\n every?: number\n timezone?: string\n}\n\ninterface BullJobSchedulerState {\n next?: number | null\n pattern?: string | null\n every?: number | null\n tz?: string | null\n}\n\ninterface BullNextRunQueue {\n getJobScheduler?(id: string): Promise<BullJobSchedulerState | undefined>\n on(event: 'error', listener: (error: Error) => void): unknown\n close(): Promise<void>\n disconnect(): Promise<void>\n}\n\nfunction toBullmqNextRun(state: BullJobSchedulerState | undefined): BullmqNextRun | null {\n if (!state || typeof state.next !== 'number' || !Number.isFinite(state.next)) return null\n return {\n nextRunAt: new Date(state.next),\n ...(typeof state.pattern === 'string' ? { pattern: state.pattern } : {}),\n ...(typeof state.every === 'number' ? { every: state.every } : {}),\n ...(typeof state.tz === 'string' ? { timezone: state.tz } : {}),\n }\n}\n\nasync function readAndClose(queue: BullNextRunQueue, scheduleId: string): Promise<BullmqNextRun | null> {\n try {\n if (typeof queue.getJobScheduler !== 'function') return null\n return toBullmqNextRun(await queue.getJobScheduler(`schedule-${scheduleId}`))\n } finally {\n await queue.close().catch((error: unknown) => {\n logger.debug('Failed to close the BullMQ queue after reading the job scheduler', { scheduleId, err: error })\n })\n }\n}\n\n/**\n * Reads the instant BullMQ will fire a schedule next, straight from its Job Scheduler.\n *\n * BullMQ moves a scheduler to its following slot before it hands the current\n * slot's job to the processor, so from inside a running execution this is the\n * upcoming fire, not the one being executed.\n *\n * The queue handle is opened and closed per call on purpose. Workers build a\n * fresh DI container for every job and never dispose it, so the DI-registered\n * `BullMQSchedulerService` \u2014 which caches its queue on the instance \u2014 would\n * leave one Redis connection behind per execution.\n *\n * Open, read and close share one deadline: during a Redis outage commands queue\n * up instead of failing, and a caller awaiting this from a `finally` must not\n * hold its worker slot open. Past the deadline the handle is torn down both\n * ways, because each covers a state the other waits on: `close()` drops a\n * connection that never became ready, `disconnect()` drops one that is ready\n * but not answering. The timeout error carries the last connection error\n * BullMQ emitted as its `cause`; the listener also keeps BullMQ from printing\n * those errors to the console itself. A close that fails after a completed read\n * is only logged, so it can neither discard the value nor replace the read's\n * own error. Returns `null` when the installed BullMQ has no\n * `getJobScheduler`, when the scheduler does not exist, or when it has no next\n * slot.\n */\nexport async function readBullmqNextRun(\n scheduleId: string,\n timeoutMs: number = BULLMQ_NEXT_RUN_READ_TIMEOUT_MS,\n): Promise<BullmqNextRun | null> {\n const { Queue } = await import('bullmq')\n const queue = new Queue('scheduler-execution', {\n connection: parseRedisUrl(getRedisUrlOrThrow('QUEUE')),\n }) as unknown as BullNextRunQueue\n let lastConnectionError: Error | undefined\n queue.on('error', (error) => {\n lastConnectionError = error\n })\n\n let timer: NodeJS.Timeout | undefined\n let timedOut = false\n const deadline = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n timedOut = true\n reject(new Error(\n `[internal] Timed out after ${timeoutMs}ms reading the BullMQ job scheduler`,\n lastConnectionError ? { cause: lastConnectionError } : undefined,\n ))\n }, timeoutMs)\n })\n const read = readAndClose(queue, scheduleId)\n\n try {\n return await Promise.race([read, deadline])\n } catch (error) {\n if (timedOut) {\n queue.close().catch(() => undefined)\n queue.disconnect().catch(() => undefined)\n }\n throw error\n } finally {\n if (timer) clearTimeout(timer)\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB,qBAAqB;AAClD,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,gBAAgB,CAAC;AAEtE,MAAM,kCAAkC;AAuB/C,SAAS,gBAAgB,OAAgE;AACvF,MAAI,CAAC,SAAS,OAAO,MAAM,SAAS,YAAY,CAAC,OAAO,SAAS,MAAM,IAAI,EAAG,QAAO;AACrF,SAAO;AAAA,IACL,WAAW,IAAI,KAAK,MAAM,IAAI;AAAA,IAC9B,GAAI,OAAO,MAAM,YAAY,WAAW,EAAE,SAAS,MAAM,QAAQ,IAAI,CAAC;AAAA,IACtE,GAAI,OAAO,MAAM,UAAU,WAAW,EAAE,OAAO,MAAM,MAAM,IAAI,CAAC;AAAA,IAChE,GAAI,OAAO,MAAM,OAAO,WAAW,EAAE,UAAU,MAAM,GAAG,IAAI,CAAC;AAAA,EAC/D;AACF;AAEA,eAAe,aAAa,OAAyB,YAAmD;AACtG,MAAI;AACF,QAAI,OAAO,MAAM,oBAAoB,WAAY,QAAO;AACxD,WAAO,gBAAgB,MAAM,MAAM,gBAAgB,YAAY,UAAU,EAAE,CAAC;AAAA,EAC9E,UAAE;AACA,UAAM,MAAM,MAAM,EAAE,MAAM,CAAC,UAAmB;AAC5C,aAAO,MAAM,oEAAoE,EAAE,YAAY,KAAK,MAAM,CAAC;AAAA,IAC7G,CAAC;AAAA,EACH;AACF;AA2BA,eAAsB,kBACpB,YACA,YAAoB,iCACW;AAC/B,QAAM,EAAE,MAAM,IAAI,MAAM,OAAO,QAAQ;AACvC,QAAM,QAAQ,IAAI,MAAM,uBAAuB;AAAA,IAC7C,YAAY,cAAc,mBAAmB,OAAO,CAAC;AAAA,EACvD,CAAC;AACD,MAAI;AACJ,QAAM,GAAG,SAAS,CAAC,UAAU;AAC3B,0BAAsB;AAAA,EACxB,CAAC;AAED,MAAI;AACJ,MAAI,WAAW;AACf,QAAM,WAAW,IAAI,QAAe,CAAC,UAAU,WAAW;AACxD,YAAQ,WAAW,MAAM;AACvB,iBAAW;AACX,aAAO,IAAI;AAAA,QACT,8BAA8B,SAAS;AAAA,QACvC,sBAAsB,EAAE,OAAO,oBAAoB,IAAI;AAAA,MACzD,CAAC;AAAA,IACH,GAAG,SAAS;AAAA,EACd,CAAC;AACD,QAAM,OAAO,aAAa,OAAO,UAAU;AAE3C,MAAI;AACF,WAAO,MAAM,QAAQ,KAAK,CAAC,MAAM,QAAQ,CAAC;AAAA,EAC5C,SAAS,OAAO;AACd,QAAI,UAAU;AACZ,YAAM,MAAM,EAAE,MAAM,MAAM,MAAS;AACnC,YAAM,WAAW,EAAE,MAAM,MAAM,MAAS;AAAA,IAC1C;AACA,UAAM;AAAA,EACR,UAAE;AACA,QAAI,MAAO,cAAa,KAAK;AAAA,EAC/B;AACF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,80 @@
1
+ import { createLogger } from "@open-mercato/shared/lib/logger";
2
+ import { getTelemetryRuntime } from "@open-mercato/shared/lib/telemetry/runtime";
3
+ import { readBullmqNextRun } from "./bullmqNextRun.js";
4
+ import { parseInterval, resolveScheduleIntervalMs } from "./intervalParser.js";
5
+ const logger = createLogger("scheduler").child({ component: "next-run-sync" });
6
+ const UPDATE_NEXT_RUN_AT_SQL = `update scheduled_jobs
7
+ set next_run_at = ?
8
+ where id = ?
9
+ and tenant_id is not distinct from ?
10
+ and organization_id is not distinct from ?
11
+ and deleted_at is null
12
+ and is_enabled = true
13
+ and schedule_type = ?
14
+ and schedule_value = ?
15
+ and timezone = ?
16
+ and ? > now()
17
+ and next_run_at is distinct from ?`;
18
+ function intervalCandidates(scheduleValue) {
19
+ try {
20
+ return [resolveScheduleIntervalMs(scheduleValue), parseInterval(scheduleValue)];
21
+ } catch {
22
+ return [];
23
+ }
24
+ }
25
+ function bullmqNextRunMatchesTiming(next, timing) {
26
+ if (timing.scheduleType === "cron") {
27
+ return next.pattern === timing.scheduleValue && (next.timezone ?? "UTC") === (timing.timezone || "UTC");
28
+ }
29
+ return typeof next.every === "number" && intervalCandidates(timing.scheduleValue).includes(next.every);
30
+ }
31
+ async function syncScheduleNextRunAt(resolveEm, timing) {
32
+ if (process.env.QUEUE_STRATEGY !== "async") return;
33
+ try {
34
+ const next = await readBullmqNextRun(timing.scheduleId);
35
+ if (!next) return;
36
+ if (!bullmqNextRunMatchesTiming(next, timing)) {
37
+ logger.debug("Skipping nextRunAt sync: BullMQ scheduler does not match the loaded schedule timing", {
38
+ scheduleId: timing.scheduleId,
39
+ scheduleType: timing.scheduleType,
40
+ scheduleValue: timing.scheduleValue,
41
+ timezone: timing.timezone,
42
+ bullmqPattern: next.pattern,
43
+ bullmqEvery: next.every,
44
+ bullmqTimezone: next.timezone
45
+ });
46
+ return;
47
+ }
48
+ await resolveEm().getConnection().execute(
49
+ UPDATE_NEXT_RUN_AT_SQL,
50
+ [
51
+ next.nextRunAt,
52
+ timing.scheduleId,
53
+ timing.tenantId,
54
+ timing.organizationId,
55
+ timing.scheduleType,
56
+ timing.scheduleValue,
57
+ timing.timezone,
58
+ next.nextRunAt,
59
+ next.nextRunAt
60
+ ],
61
+ "run"
62
+ );
63
+ } catch (error) {
64
+ logger.warn("Failed to sync nextRunAt from BullMQ", { scheduleId: timing.scheduleId, err: error });
65
+ try {
66
+ getTelemetryRuntime()?.reportError(error, {
67
+ module: "scheduler",
68
+ code: "scheduler.next_run_sync_failed",
69
+ attributes: { scheduleId: timing.scheduleId }
70
+ });
71
+ } catch (telemetryError) {
72
+ logger.warn("Failed to report a nextRunAt sync error to telemetry", { err: telemetryError });
73
+ }
74
+ }
75
+ }
76
+ export {
77
+ bullmqNextRunMatchesTiming,
78
+ syncScheduleNextRunAt
79
+ };
80
+ //# sourceMappingURL=nextRunSync.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/scheduler/lib/nextRunSync.ts"],
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport { readBullmqNextRun, type BullmqNextRun } from './bullmqNextRun.js'\nimport { parseInterval, resolveScheduleIntervalMs } from './intervalParser.js'\n\nconst logger = createLogger('scheduler').child({ component: 'next-run-sync' })\n\n/**\n * The schedule's timing configuration as an execution loaded it, captured\n * before the target runs.\n */\nexport type ScheduleTimingSnapshot = {\n scheduleId: string\n tenantId: string | null\n organizationId: string | null\n scheduleType: 'cron' | 'interval'\n scheduleValue: string\n timezone: string\n}\n\nconst UPDATE_NEXT_RUN_AT_SQL = `update scheduled_jobs\n set next_run_at = ?\n where id = ?\n and tenant_id is not distinct from ?\n and organization_id is not distinct from ?\n and deleted_at is null\n and is_enabled = true\n and schedule_type = ?\n and schedule_value = ?\n and timezone = ?\n and ? > now()\n and next_run_at is distinct from ?`\n\nfunction intervalCandidates(scheduleValue: string): number[] {\n try {\n return [resolveScheduleIntervalMs(scheduleValue), parseInterval(scheduleValue)]\n } catch {\n return []\n }\n}\n\n/**\n * True when the BullMQ scheduler was registered from the same timing\n * configuration the execution loaded. A scheduler registered before the\n * minimum-interval clamp keeps the unclamped `every`, so both forms match.\n */\nexport function bullmqNextRunMatchesTiming(next: BullmqNextRun, timing: ScheduleTimingSnapshot): boolean {\n if (timing.scheduleType === 'cron') {\n return next.pattern === timing.scheduleValue\n && (next.timezone ?? 'UTC') === (timing.timezone || 'UTC')\n }\n return typeof next.every === 'number' && intervalCandidates(timing.scheduleValue).includes(next.every)\n}\n\n/**\n * Mirrors BullMQ's next fire time into `scheduled_jobs.next_run_at` after an\n * execution under the async strategy, where BullMQ \u2014 not this row \u2014 decides\n * when a schedule fires.\n *\n * The row is matched by id and by the tenant and organization the execution\n * verified against its job payload, so a write can only land on that scope.\n *\n * The value is written only while it is still true: the BullMQ scheduler and\n * the row must both still carry the timing configuration this execution\n * loaded (an edit in flight writes its own `nextRunAt`), and the instant must\n * still be ahead of the database clock (an execution holding an older slot,\n * or a slot that is due but not picked up, writes nothing). When BullMQ has no\n * usable value nothing is written: a locally computed time would show a run\n * BullMQ is not going to perform.\n *\n * The statement is raw so that `updated_at` stays untouched \u2014 skipped and\n * failed executions must not invalidate an editor's optimistic-lock version \u2014\n * and it runs on a pooled connection, outside the per-job unit of work, which\n * may hold whatever a failed target left behind.\n *\n * Never throws: this is bookkeeping awaited from the worker's `finally`, so a\n * failure here must neither fail a successful execution nor replace the\n * target's own error.\n */\nexport async function syncScheduleNextRunAt(\n resolveEm: () => EntityManager,\n timing: ScheduleTimingSnapshot,\n): Promise<void> {\n if (process.env.QUEUE_STRATEGY !== 'async') return\n\n try {\n const next = await readBullmqNextRun(timing.scheduleId)\n if (!next) return\n\n if (!bullmqNextRunMatchesTiming(next, timing)) {\n logger.debug('Skipping nextRunAt sync: BullMQ scheduler does not match the loaded schedule timing', {\n scheduleId: timing.scheduleId,\n scheduleType: timing.scheduleType,\n scheduleValue: timing.scheduleValue,\n timezone: timing.timezone,\n bullmqPattern: next.pattern,\n bullmqEvery: next.every,\n bullmqTimezone: next.timezone,\n })\n return\n }\n\n await resolveEm().getConnection().execute(\n UPDATE_NEXT_RUN_AT_SQL,\n [\n next.nextRunAt,\n timing.scheduleId,\n timing.tenantId,\n timing.organizationId,\n timing.scheduleType,\n timing.scheduleValue,\n timing.timezone,\n next.nextRunAt,\n next.nextRunAt,\n ],\n 'run',\n )\n } catch (error) {\n logger.warn('Failed to sync nextRunAt from BullMQ', { scheduleId: timing.scheduleId, err: error })\n try {\n getTelemetryRuntime()?.reportError(error, {\n module: 'scheduler',\n code: 'scheduler.next_run_sync_failed',\n attributes: { scheduleId: timing.scheduleId },\n })\n } catch (telemetryError) {\n logger.warn('Failed to report a nextRunAt sync error to telemetry', { err: telemetryError })\n }\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC,SAAS,yBAA6C;AACtD,SAAS,eAAe,iCAAiC;AAEzD,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,gBAAgB,CAAC;AAe7E,MAAM,yBAAyB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAa/B,SAAS,mBAAmB,eAAiC;AAC3D,MAAI;AACF,WAAO,CAAC,0BAA0B,aAAa,GAAG,cAAc,aAAa,CAAC;AAAA,EAChF,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;AAOO,SAAS,2BAA2B,MAAqB,QAAyC;AACvG,MAAI,OAAO,iBAAiB,QAAQ;AAClC,WAAO,KAAK,YAAY,OAAO,kBACzB,KAAK,YAAY,YAAY,OAAO,YAAY;AAAA,EACxD;AACA,SAAO,OAAO,KAAK,UAAU,YAAY,mBAAmB,OAAO,aAAa,EAAE,SAAS,KAAK,KAAK;AACvG;AA2BA,eAAsB,sBACpB,WACA,QACe;AACf,MAAI,QAAQ,IAAI,mBAAmB,QAAS;AAE5C,MAAI;AACF,UAAM,OAAO,MAAM,kBAAkB,OAAO,UAAU;AACtD,QAAI,CAAC,KAAM;AAEX,QAAI,CAAC,2BAA2B,MAAM,MAAM,GAAG;AAC7C,aAAO,MAAM,uFAAuF;AAAA,QAClG,YAAY,OAAO;AAAA,QACnB,cAAc,OAAO;AAAA,QACrB,eAAe,OAAO;AAAA,QACtB,UAAU,OAAO;AAAA,QACjB,eAAe,KAAK;AAAA,QACpB,aAAa,KAAK;AAAA,QAClB,gBAAgB,KAAK;AAAA,MACvB,CAAC;AACD;AAAA,IACF;AAEA,UAAM,UAAU,EAAE,cAAc,EAAE;AAAA,MAChC;AAAA,MACA;AAAA,QACE,KAAK;AAAA,QACL,OAAO;AAAA,QACP,OAAO;AAAA,QACP,OAAO;AAAA,QACP,OAAO;AAAA,QACP,OAAO;AAAA,QACP,OAAO;AAAA,QACP,KAAK;AAAA,QACL,KAAK;AAAA,MACP;AAAA,MACA;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AACd,WAAO,KAAK,wCAAwC,EAAE,YAAY,OAAO,YAAY,KAAK,MAAM,CAAC;AACjG,QAAI;AACF,0BAAoB,GAAG,YAAY,OAAO;AAAA,QACxC,QAAQ;AAAA,QACR,MAAM;AAAA,QACN,YAAY,EAAE,YAAY,OAAO,WAAW;AAAA,MAC9C,CAAC;AAAA,IACH,SAAS,gBAAgB;AACvB,aAAO,KAAK,wDAAwD,EAAE,KAAK,eAAe,CAAC;AAAA,IAC7F;AAAA,EACF;AACF;",
6
+ "names": []
7
+ }
@@ -16,6 +16,7 @@ import {
16
16
  sanitizeSchedulerTargetPayload,
17
17
  validateSchedulerTargetPayload
18
18
  } from "../lib/safeQueueTargets.js";
19
+ import { syncScheduleNextRunAt } from "../lib/nextRunSync.js";
19
20
  const logger = createLogger("scheduler").child({ component: "worker" });
20
21
  const metadata = {
21
22
  queue: "scheduler-execution",
@@ -23,6 +24,17 @@ const metadata = {
23
24
  // Process up to 5 schedules concurrently
24
25
  };
25
26
  async function executeScheduleWorker(job, ctx) {
27
+ const execution = { timing: null };
28
+ try {
29
+ await executeSchedule(job, ctx, execution);
30
+ } finally {
31
+ const { timing } = execution;
32
+ if (timing) {
33
+ await syncScheduleNextRunAt(() => ctx.resolve("em"), timing);
34
+ }
35
+ }
36
+ }
37
+ async function executeSchedule(job, ctx, execution) {
26
38
  logger.debug("Processing job", {
27
39
  jobId: ctx.jobId,
28
40
  attemptNumber: ctx.attemptNumber
@@ -77,6 +89,14 @@ async function executeScheduleWorker(job, ctx) {
77
89
  });
78
90
  return;
79
91
  }
92
+ execution.timing = {
93
+ scheduleId: schedule.id,
94
+ tenantId: schedule.tenantId ?? null,
95
+ organizationId: schedule.organizationId ?? null,
96
+ scheduleType: schedule.scheduleType,
97
+ scheduleValue: schedule.scheduleValue,
98
+ timezone: schedule.timezone
99
+ };
80
100
  await emitSchedulerEvent("scheduler.job.started", {
81
101
  id: schedule.id,
82
102
  tenantId: schedule.tenantId,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/scheduler/workers/execute-schedule.worker.ts"],
4
- "sourcesContent": ["import type { QueuedJob, JobContext, WorkerMeta } from '@open-mercato/queue'\nimport { createQueue } from '@open-mercato/queue'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\nimport type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from '../data/entities.js'\nimport { CommandBus } from '@open-mercato/shared/lib/commands'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { emitSchedulerEvent } from '../events.js'\nimport {\n assertSchedulerSafeCommandAuthorized,\n SchedulerCommandAuthorizationError,\n} from '../lib/scheduler-safe-commands.js'\nimport { buildScheduledCommandContext, resolveScheduledCommandActorUserId } from '../lib/commandContext.js'\nimport { buildQueueTargetPayload, buildSchedulerIdempotencyKey } from '../lib/queueTargetPayload.js'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport {\n canDispatchScheduleQueueTarget,\n getSchedulerQueueRequiredFeatures,\n sanitizeSchedulerTargetPayload,\n validateSchedulerTargetPayload,\n} from '../lib/safeQueueTargets'\n\nconst logger = createLogger('scheduler').child({ component: 'worker' })\n\n// Worker metadata for auto-discovery\nexport const metadata: WorkerMeta = {\n queue: 'scheduler-execution',\n concurrency: 5, // Process up to 5 schedules concurrently\n}\n\nexport type ExecuteSchedulePayload = {\n scheduleId: string\n tenantId?: string | null\n organizationId?: string | null\n scopeType: 'system' | 'organization' | 'tenant'\n triggerType?: 'scheduled' | 'manual'\n triggeredByUserId?: string | null\n}\n\ntype HandlerContext = { resolve: <T = unknown>(name: string) => T }\ntype RbacServiceLike = {\n tenantHasFeature(\n tenantId: string | null | undefined,\n feature: string,\n opts?: { organizationId?: string | null },\n ): Promise<boolean>\n userHasAllFeatures(\n userId: string,\n required: readonly string[],\n scope: { tenantId: string | null; organizationId: string | null },\n ): Promise<boolean>\n}\n\n/**\n * Worker that executes scheduled jobs.\n * \n * This worker is triggered by BullMQ repeatable jobs at the scheduled times.\n * It loads the fresh schedule configuration from the database, validates\n * conditions, and enqueues the target job or executes the command.\n * \n * BullMQ handles:\n * - Timing (exact cron/interval execution)\n * - Distributed locking (prevents duplicate execution)\n * - Retries (if worker fails)\n * - Execution history (via job state, logs, timestamps)\n * \n * This worker handles:\n * - Loading fresh schedule config\n * - Checking feature flags and conditions\n * - Enqueuing target job or executing command\n * - Updating last run time\n */\nexport default async function executeScheduleWorker(\n job: QueuedJob<ExecuteSchedulePayload>,\n ctx: JobContext & HandlerContext,\n): Promise<void> {\n logger.debug('Processing job', {\n jobId: ctx.jobId,\n attemptNumber: ctx.attemptNumber,\n })\n \n // Defensive: handle both data and payload for BullMQ compatibility\n const payload = (job.payload || (job as unknown as { data?: ExecuteSchedulePayload }).data) as ExecuteSchedulePayload | undefined\n \n if (!payload || !payload.scheduleId) {\n logger.error('Invalid job payload: scheduleId missing', { jobId: ctx.jobId })\n throw new Error('scheduleId is required in job payload')\n }\n\n const { scheduleId } = payload\n\n const em = ctx.resolve<EntityManager>('em')\n const rbacService = ctx.resolve<RbacServiceLike>('rbacService')\n\n // Load fresh schedule from database\n const schedule = await em.findOne(ScheduledJob, { \n id: scheduleId,\n deletedAt: null,\n })\n\n if (!schedule) {\n logger.info('Schedule not found or deleted', { scheduleId })\n return\n }\n\n // CRITICAL: Verify scope integrity - ensure payload scope matches database\n // This prevents scope tampering and ensures proper multi-tenant isolation\n if (payload.scopeType !== schedule.scopeType) {\n logger.error('Scope type mismatch for schedule', {\n scheduleId,\n payloadScope: payload.scopeType,\n dbScope: schedule.scopeType,\n })\n throw new Error('Schedule scope type mismatch - potential security issue')\n }\n\n if (payload.tenantId !== schedule.tenantId) {\n logger.error('Tenant ID mismatch for schedule', {\n scheduleId,\n payloadTenant: payload.tenantId,\n dbTenant: schedule.tenantId,\n })\n throw new Error('Schedule tenant ID mismatch - potential security issue')\n }\n\n if (payload.organizationId !== schedule.organizationId) {\n logger.error('Organization ID mismatch for schedule', {\n scheduleId,\n payloadOrg: payload.organizationId,\n dbOrg: schedule.organizationId,\n })\n throw new Error('Schedule organization ID mismatch - potential security issue')\n }\n\n // Check if schedule is still enabled\n if (!schedule.isEnabled) {\n logger.debug('Schedule is disabled', { scheduleId })\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: 'Schedule is disabled',\n })\n return\n }\n\n // Emit started event\n await emitSchedulerEvent('scheduler.job.started', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n attemptNumber: ctx.attemptNumber || 1,\n })\n\n // Check feature flag if required\n if (schedule.requireFeature) {\n const hasFeature = await rbacService.tenantHasFeature(\n schedule.tenantId,\n schedule.requireFeature,\n { organizationId: schedule.organizationId },\n )\n \n if (!hasFeature) {\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: `Feature not enabled: ${schedule.requireFeature}`,\n })\n\n logger.debug('Schedule skipped: feature not enabled', { scheduleId, requireFeature: schedule.requireFeature })\n return\n }\n }\n\n // Enqueue target job or execute command\n if (schedule.targetType === 'queue' && schedule.targetQueue) {\n // Dispatch-time reauthorization (#5213): provenance is verified, never\n // trusted \u2014 module-authored rows must still be owned by their recorded\n // sourceModule and carry no acting-user stamp; API-authored rows may only\n // target workers that opted into scheduling.\n if (!canDispatchScheduleQueueTarget(schedule)) {\n logger.error('Refusing non-safe queue target for schedule', {\n scheduleId,\n targetQueue: schedule.targetQueue,\n sourceType: schedule.sourceType,\n sourceModule: schedule.sourceType === 'module' ? schedule.sourceModule : undefined,\n })\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: `Queue is not an approved scheduler target: ${schedule.targetQueue}`,\n })\n return\n }\n\n // Re-validate the stored payload against the target's registered schema and\n // the tenant-level features the target requires (#5213, defense in depth).\n const payloadIssue = validateSchedulerTargetPayload(schedule.targetQueue, schedule.targetPayload)\n if (payloadIssue) {\n logger.error('Refusing schedule with invalid payload for queue target', {\n scheduleId,\n targetQueue: schedule.targetQueue,\n issue: payloadIssue,\n })\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: `Invalid payload for scheduler queue ${schedule.targetQueue}`,\n })\n return\n }\n\n const requiredQueueFeatures = getSchedulerQueueRequiredFeatures(schedule.targetQueue)\n if (schedule.scopeType !== 'system' && requiredQueueFeatures.length > 0) {\n for (const feature of requiredQueueFeatures) {\n if (await rbacService.tenantHasFeature(schedule.tenantId, feature, { organizationId: schedule.organizationId })) continue\n logger.error('Refusing schedule whose tenant lacks a required feature of the queue target', {\n scheduleId,\n targetQueue: schedule.targetQueue,\n feature,\n })\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: `Tenant lacks feature required by scheduler queue ${schedule.targetQueue}: ${feature}`,\n })\n return\n }\n }\n\n // Determine queue strategy from environment\n const queueStrategy = (process.env.QUEUE_STRATEGY || 'local') as 'local' | 'async'\n const targetQueue = createQueue(schedule.targetQueue, queueStrategy, {\n connection: { url: getRedisUrlOrThrow('QUEUE') },\n })\n\n let targetJobId: string | undefined\n try {\n // The execute-schedule job id is stable across BullMQ retries, so if\n // this worker crashes between enqueue and DB flush the retried attempt\n // reuses the same idempotency key and downstream workers can dedupe.\n const idempotencyKey = buildSchedulerIdempotencyKey(schedule.id, ctx.jobId ?? Date.now())\n\n // Rebuild tenant/org authority context and the trusted dispatch origin\n // server-side; author-supplied scope/envelope keys never survive (#5213).\n const sanitizedPayload = sanitizeSchedulerTargetPayload(schedule.targetPayload, schedule)\n targetJobId = await targetQueue.enqueue({\n ...buildQueueTargetPayload({\n targetPayload: sanitizedPayload,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n idempotencyKey,\n }),\n _jobOrigin: 'scheduler' as const,\n })\n } finally {\n // Always close the queue instance to free Redis connections\n await targetQueue.close()\n }\n \n // Update schedule's last run time\n schedule.lastRunAt = new Date()\n await em.flush()\n\n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n queueJobId: targetJobId,\n queueName: schedule.targetQueue,\n })\n\n logger.debug('Successfully enqueued job', {\n scheduleId: schedule.id,\n targetQueue: schedule.targetQueue,\n queueJobId: targetJobId,\n })\n\n } else if (schedule.targetType === 'command' && schedule.targetCommand) {\n const commandBus = new CommandBus()\n // A manual run acts as whoever pressed the button; an unattended run keeps\n // acting as the schedule's creator. The gate below and the context built\n // afterwards must agree on that identity, so it is resolved once, by the same\n // helper the context itself uses.\n const triggeredByUserId = payload.triggerType === 'manual' ? payload.triggeredByUserId ?? null : null\n const actorUserId = resolveScheduledCommandActorUserId(schedule, { triggeredByUserId })\n try {\n await assertSchedulerSafeCommandAuthorized({\n commandId: schedule.targetCommand,\n actorUserId,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n rbacService,\n })\n } catch (error) {\n // A refusal is permanent, so it must not be thrown: throwing hands BullMQ an\n // error it cannot tell from an outage and it retries a decision that no\n // attempt can change, while the run leaves no trace beyond a log line. The\n // queue branch above already ends its equivalent conditions with an event and\n // a return; this does the same, and records the refusal as a failure rather\n // than a skip because a schedule whose actor may no longer run its command is\n // a state an operator has to act on.\n //\n // Only the authorization decision is swallowed. Anything else \u2014 an RBAC\n // lookup that fails because its store is down \u2014 is genuinely transient and\n // still propagates so BullMQ retries it.\n if (!(error instanceof SchedulerCommandAuthorizationError)) throw error\n\n const reason = error.message\n await emitSchedulerEvent('scheduler.job.failed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n error: reason,\n failedAt: new Date(),\n })\n\n logger.warn('Schedule refused: scheduled command is not authorized', {\n scheduleId: schedule.id,\n commandId: schedule.targetCommand,\n triggerType: payload.triggerType ?? 'scheduled',\n reason,\n })\n return\n }\n\n const commandInput = {\n ...((schedule.targetPayload as Record<string, unknown>) || {}),\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n }\n\n // Build the schedule-scoped command context after the allowlist/RBAC gate.\n // The gate authorized `actorUserId`; this must execute as that same identity.\n const commandCtx = buildScheduledCommandContext(schedule, ctx as unknown as AppContainer, {\n triggeredByUserId,\n })\n \n const commandResult = await commandBus.execute(schedule.targetCommand, {\n input: commandInput,\n ctx: commandCtx,\n })\n \n // Update schedule's last run time\n schedule.lastRunAt = new Date()\n await em.flush()\n \n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n commandId: schedule.targetCommand,\n commandResult: commandResult.result,\n })\n \n logger.debug('Successfully executed command', {\n scheduleId: schedule.id,\n commandId: schedule.targetCommand,\n })\n\n } else {\n throw new Error('Invalid target configuration')\n }\n}\n"],
5
-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AAM;AAElE,YAAM,SAAS,MAAM;AACrB,YAAM,mBAAmB,wBAAwB;AAAA,QAC/C,IAAI,SAAS;AAAA,QACb,UAAU,SAAS;AAAA,QACnB,gBAAgB,SAAS;AAAA,QACzB,cAAc,SAAS;AAAA,QACvB,WAAW,SAAS;AAAA,QACpB,OAAO;AAAA,QACP,UAAU,oBAAI,KAAK;AAAA,MACrB,CAAC;AAED,aAAO,KAAK,yDAAyD;AAAA,QACnE,YAAY,SAAS;AAAA,QACrB,WAAW,SAAS;AAAA,QACpB,aAAa,QAAQ,eAAe;AAAA,QACpC;AAAA,MACF,CAAC;AACD;AAAA,IACF;AAEA,UAAM,eAAe;AAAA,MACnB,GAAK,SAAS,iBAA6C,CAAC;AAAA,MAC5D,UAAU,SAAS;AAAA,MACnB,gBAAgB,SAAS;AAAA,IAC3B;AAIA,UAAM,aAAa,6BAA6B,UAAU,KAAgC;AAAA,MACxF;AAAA,IACF,CAAC;AAED,UAAM,gBAAgB,MAAM,WAAW,QAAQ,SAAS,eAAe;AAAA,MACrE,OAAO;AAAA,MACP,KAAK;AAAA,IACP,CAAC;AAGD,aAAS,YAAY,oBAAI,KAAK;AAC9B,UAAM,GAAG,MAAM;AAEf,UAAM,mBAAmB,2BAA2B;AAAA,MAClD,IAAI,SAAS;AAAA,MACb,UAAU,SAAS;AAAA,MACnB,gBAAgB,SAAS;AAAA,MACzB,WAAW,SAAS;AAAA,MACpB,eAAe,cAAc;AAAA,IAC/B,CAAC;AAED,WAAO,MAAM,iCAAiC;AAAA,MAC5C,YAAY,SAAS;AAAA,MACrB,WAAW,SAAS;AAAA,IACtB,CAAC;AAAA,EAEH,OAAO;AACL,UAAM,IAAI,MAAM,8BAA8B;AAAA,EAChD;AACF;",
4
+ "sourcesContent": ["import type { QueuedJob, JobContext, WorkerMeta } from '@open-mercato/queue'\nimport { createQueue } from '@open-mercato/queue'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\nimport type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from '../data/entities.js'\nimport { CommandBus } from '@open-mercato/shared/lib/commands'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { emitSchedulerEvent } from '../events.js'\nimport {\n assertSchedulerSafeCommandAuthorized,\n SchedulerCommandAuthorizationError,\n} from '../lib/scheduler-safe-commands.js'\nimport { buildScheduledCommandContext, resolveScheduledCommandActorUserId } from '../lib/commandContext.js'\nimport { buildQueueTargetPayload, buildSchedulerIdempotencyKey } from '../lib/queueTargetPayload.js'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport {\n canDispatchScheduleQueueTarget,\n getSchedulerQueueRequiredFeatures,\n sanitizeSchedulerTargetPayload,\n validateSchedulerTargetPayload,\n} from '../lib/safeQueueTargets'\nimport { syncScheduleNextRunAt, type ScheduleTimingSnapshot } from '../lib/nextRunSync.js'\n\nconst logger = createLogger('scheduler').child({ component: 'worker' })\n\n// Worker metadata for auto-discovery\nexport const metadata: WorkerMeta = {\n queue: 'scheduler-execution',\n concurrency: 5, // Process up to 5 schedules concurrently\n}\n\nexport type ExecuteSchedulePayload = {\n scheduleId: string\n tenantId?: string | null\n organizationId?: string | null\n scopeType: 'system' | 'organization' | 'tenant'\n triggerType?: 'scheduled' | 'manual'\n triggeredByUserId?: string | null\n}\n\ntype HandlerContext = { resolve: <T = unknown>(name: string) => T }\ntype RbacServiceLike = {\n tenantHasFeature(\n tenantId: string | null | undefined,\n feature: string,\n opts?: { organizationId?: string | null },\n ): Promise<boolean>\n userHasAllFeatures(\n userId: string,\n required: readonly string[],\n scope: { tenantId: string | null; organizationId: string | null },\n ): Promise<boolean>\n}\n\n/**\n * Worker that executes scheduled jobs.\n * \n * This worker is triggered by BullMQ repeatable jobs at the scheduled times.\n * It loads the fresh schedule configuration from the database, validates\n * conditions, and enqueues the target job or executes the command.\n * \n * BullMQ handles:\n * - Timing (exact cron/interval execution)\n * - Distributed locking (prevents duplicate execution)\n * - Retries (if worker fails)\n * - Execution history (via job state, logs, timestamps)\n * \n * This worker handles:\n * - Loading fresh schedule config\n * - Checking feature flags and conditions\n * - Enqueuing target job or executing command\n * - Updating last run time\n * - Mirroring BullMQ's next fire time into nextRunAt once the run is over\n */\nexport default async function executeScheduleWorker(\n job: QueuedJob<ExecuteSchedulePayload>,\n ctx: JobContext & HandlerContext,\n): Promise<void> {\n const execution: ScheduleExecution = { timing: null }\n try {\n await executeSchedule(job, ctx, execution)\n } finally {\n // Runs on every outcome of a started execution \u2014 completed, skipped,\n // refused or thrown \u2014 because BullMQ has consumed the slot either way.\n // A job rejected before it started (unknown, mismatched or disabled\n // schedule) never sets the timing and is left alone.\n const { timing } = execution\n if (timing) {\n await syncScheduleNextRunAt(() => ctx.resolve<EntityManager>('em'), timing)\n }\n }\n}\n\ntype ScheduleExecution = { timing: ScheduleTimingSnapshot | null }\n\nasync function executeSchedule(\n job: QueuedJob<ExecuteSchedulePayload>,\n ctx: JobContext & HandlerContext,\n execution: ScheduleExecution,\n): Promise<void> {\n logger.debug('Processing job', {\n jobId: ctx.jobId,\n attemptNumber: ctx.attemptNumber,\n })\n \n // Defensive: handle both data and payload for BullMQ compatibility\n const payload = (job.payload || (job as unknown as { data?: ExecuteSchedulePayload }).data) as ExecuteSchedulePayload | undefined\n \n if (!payload || !payload.scheduleId) {\n logger.error('Invalid job payload: scheduleId missing', { jobId: ctx.jobId })\n throw new Error('scheduleId is required in job payload')\n }\n\n const { scheduleId } = payload\n\n const em = ctx.resolve<EntityManager>('em')\n const rbacService = ctx.resolve<RbacServiceLike>('rbacService')\n\n // Load fresh schedule from database\n const schedule = await em.findOne(ScheduledJob, { \n id: scheduleId,\n deletedAt: null,\n })\n\n if (!schedule) {\n logger.info('Schedule not found or deleted', { scheduleId })\n return\n }\n\n // CRITICAL: Verify scope integrity - ensure payload scope matches database\n // This prevents scope tampering and ensures proper multi-tenant isolation\n if (payload.scopeType !== schedule.scopeType) {\n logger.error('Scope type mismatch for schedule', {\n scheduleId,\n payloadScope: payload.scopeType,\n dbScope: schedule.scopeType,\n })\n throw new Error('Schedule scope type mismatch - potential security issue')\n }\n\n if (payload.tenantId !== schedule.tenantId) {\n logger.error('Tenant ID mismatch for schedule', {\n scheduleId,\n payloadTenant: payload.tenantId,\n dbTenant: schedule.tenantId,\n })\n throw new Error('Schedule tenant ID mismatch - potential security issue')\n }\n\n if (payload.organizationId !== schedule.organizationId) {\n logger.error('Organization ID mismatch for schedule', {\n scheduleId,\n payloadOrg: payload.organizationId,\n dbOrg: schedule.organizationId,\n })\n throw new Error('Schedule organization ID mismatch - potential security issue')\n }\n\n // Check if schedule is still enabled\n if (!schedule.isEnabled) {\n logger.debug('Schedule is disabled', { scheduleId })\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: 'Schedule is disabled',\n })\n return\n }\n\n // Captured before the target runs: the sync that follows the run must compare\n // against the timing this execution loaded, not whatever the entity holds later.\n execution.timing = {\n scheduleId: schedule.id,\n tenantId: schedule.tenantId ?? null,\n organizationId: schedule.organizationId ?? null,\n scheduleType: schedule.scheduleType,\n scheduleValue: schedule.scheduleValue,\n timezone: schedule.timezone,\n }\n\n // Emit started event\n await emitSchedulerEvent('scheduler.job.started', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n attemptNumber: ctx.attemptNumber || 1,\n })\n\n // Check feature flag if required\n if (schedule.requireFeature) {\n const hasFeature = await rbacService.tenantHasFeature(\n schedule.tenantId,\n schedule.requireFeature,\n { organizationId: schedule.organizationId },\n )\n \n if (!hasFeature) {\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: `Feature not enabled: ${schedule.requireFeature}`,\n })\n\n logger.debug('Schedule skipped: feature not enabled', { scheduleId, requireFeature: schedule.requireFeature })\n return\n }\n }\n\n // Enqueue target job or execute command\n if (schedule.targetType === 'queue' && schedule.targetQueue) {\n // Dispatch-time reauthorization (#5213): provenance is verified, never\n // trusted \u2014 module-authored rows must still be owned by their recorded\n // sourceModule and carry no acting-user stamp; API-authored rows may only\n // target workers that opted into scheduling.\n if (!canDispatchScheduleQueueTarget(schedule)) {\n logger.error('Refusing non-safe queue target for schedule', {\n scheduleId,\n targetQueue: schedule.targetQueue,\n sourceType: schedule.sourceType,\n sourceModule: schedule.sourceType === 'module' ? schedule.sourceModule : undefined,\n })\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: `Queue is not an approved scheduler target: ${schedule.targetQueue}`,\n })\n return\n }\n\n // Re-validate the stored payload against the target's registered schema and\n // the tenant-level features the target requires (#5213, defense in depth).\n const payloadIssue = validateSchedulerTargetPayload(schedule.targetQueue, schedule.targetPayload)\n if (payloadIssue) {\n logger.error('Refusing schedule with invalid payload for queue target', {\n scheduleId,\n targetQueue: schedule.targetQueue,\n issue: payloadIssue,\n })\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: `Invalid payload for scheduler queue ${schedule.targetQueue}`,\n })\n return\n }\n\n const requiredQueueFeatures = getSchedulerQueueRequiredFeatures(schedule.targetQueue)\n if (schedule.scopeType !== 'system' && requiredQueueFeatures.length > 0) {\n for (const feature of requiredQueueFeatures) {\n if (await rbacService.tenantHasFeature(schedule.tenantId, feature, { organizationId: schedule.organizationId })) continue\n logger.error('Refusing schedule whose tenant lacks a required feature of the queue target', {\n scheduleId,\n targetQueue: schedule.targetQueue,\n feature,\n })\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: `Tenant lacks feature required by scheduler queue ${schedule.targetQueue}: ${feature}`,\n })\n return\n }\n }\n\n // Determine queue strategy from environment\n const queueStrategy = (process.env.QUEUE_STRATEGY || 'local') as 'local' | 'async'\n const targetQueue = createQueue(schedule.targetQueue, queueStrategy, {\n connection: { url: getRedisUrlOrThrow('QUEUE') },\n })\n\n let targetJobId: string | undefined\n try {\n // The execute-schedule job id is stable across BullMQ retries, so if\n // this worker crashes between enqueue and DB flush the retried attempt\n // reuses the same idempotency key and downstream workers can dedupe.\n const idempotencyKey = buildSchedulerIdempotencyKey(schedule.id, ctx.jobId ?? Date.now())\n\n // Rebuild tenant/org authority context and the trusted dispatch origin\n // server-side; author-supplied scope/envelope keys never survive (#5213).\n const sanitizedPayload = sanitizeSchedulerTargetPayload(schedule.targetPayload, schedule)\n targetJobId = await targetQueue.enqueue({\n ...buildQueueTargetPayload({\n targetPayload: sanitizedPayload,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n idempotencyKey,\n }),\n _jobOrigin: 'scheduler' as const,\n })\n } finally {\n // Always close the queue instance to free Redis connections\n await targetQueue.close()\n }\n \n // Update schedule's last run time\n schedule.lastRunAt = new Date()\n await em.flush()\n\n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n queueJobId: targetJobId,\n queueName: schedule.targetQueue,\n })\n\n logger.debug('Successfully enqueued job', {\n scheduleId: schedule.id,\n targetQueue: schedule.targetQueue,\n queueJobId: targetJobId,\n })\n\n } else if (schedule.targetType === 'command' && schedule.targetCommand) {\n const commandBus = new CommandBus()\n // A manual run acts as whoever pressed the button; an unattended run keeps\n // acting as the schedule's creator. The gate below and the context built\n // afterwards must agree on that identity, so it is resolved once, by the same\n // helper the context itself uses.\n const triggeredByUserId = payload.triggerType === 'manual' ? payload.triggeredByUserId ?? null : null\n const actorUserId = resolveScheduledCommandActorUserId(schedule, { triggeredByUserId })\n try {\n await assertSchedulerSafeCommandAuthorized({\n commandId: schedule.targetCommand,\n actorUserId,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n rbacService,\n })\n } catch (error) {\n // A refusal is permanent, so it must not be thrown: throwing hands BullMQ an\n // error it cannot tell from an outage and it retries a decision that no\n // attempt can change, while the run leaves no trace beyond a log line. The\n // queue branch above already ends its equivalent conditions with an event and\n // a return; this does the same, and records the refusal as a failure rather\n // than a skip because a schedule whose actor may no longer run its command is\n // a state an operator has to act on.\n //\n // Only the authorization decision is swallowed. Anything else \u2014 an RBAC\n // lookup that fails because its store is down \u2014 is genuinely transient and\n // still propagates so BullMQ retries it.\n if (!(error instanceof SchedulerCommandAuthorizationError)) throw error\n\n const reason = error.message\n await emitSchedulerEvent('scheduler.job.failed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n scopeType: schedule.scopeType,\n error: reason,\n failedAt: new Date(),\n })\n\n logger.warn('Schedule refused: scheduled command is not authorized', {\n scheduleId: schedule.id,\n commandId: schedule.targetCommand,\n triggerType: payload.triggerType ?? 'scheduled',\n reason,\n })\n return\n }\n\n const commandInput = {\n ...((schedule.targetPayload as Record<string, unknown>) || {}),\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n }\n\n // Build the schedule-scoped command context after the allowlist/RBAC gate.\n // The gate authorized `actorUserId`; this must execute as that same identity.\n const commandCtx = buildScheduledCommandContext(schedule, ctx as unknown as AppContainer, {\n triggeredByUserId,\n })\n \n const commandResult = await commandBus.execute(schedule.targetCommand, {\n input: commandInput,\n ctx: commandCtx,\n })\n \n // Update schedule's last run time\n schedule.lastRunAt = new Date()\n await em.flush()\n \n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n commandId: schedule.targetCommand,\n commandResult: commandResult.result,\n })\n \n logger.debug('Successfully executed command', {\n scheduleId: schedule.id,\n commandId: schedule.targetCommand,\n })\n\n } else {\n throw new Error('Invalid target configuration')\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,mBAAmB;AAC5B,SAAS,0BAA0B;AAEnC,SAAS,oBAAoB;AAC7B,SA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A,MACnB,gBAAgB,SAAS;AAAA,MACzB,WAAW,SAAS;AAAA,MACpB,eAAe,cAAc;AAAA,IAC/B,CAAC;AAED,WAAO,MAAM,iCAAiC;AAAA,MAC5C,YAAY,SAAS;AAAA,MACrB,WAAW,SAAS;AAAA,IACtB,CAAC;AAAA,EAEH,OAAO;AACL,UAAM,IAAI,MAAM,8BAA8B;AAAA,EAChD;AACF;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/scheduler",
3
- "version": "0.8.1-develop.7297.1.67605e74f9",
3
+ "version": "0.8.1-develop.7442.1.4c1dbf1f0e",
4
4
  "license": "MIT",
5
5
  "description": "Database-managed scheduled jobs with admin UI",
6
6
  "type": "module",
@@ -59,13 +59,13 @@
59
59
  "./*/*/*/*/*/*.json": "./src/*/*/*/*/*/*.json"
60
60
  },
61
61
  "dependencies": {
62
- "@open-mercato/events": "0.8.1-develop.7297.1.67605e74f9",
63
- "@open-mercato/queue": "0.8.1-develop.7297.1.67605e74f9",
62
+ "@open-mercato/events": "0.8.1-develop.7442.1.4c1dbf1f0e",
63
+ "@open-mercato/queue": "0.8.1-develop.7442.1.4c1dbf1f0e",
64
64
  "cron-parser": "^5.6.2"
65
65
  },
66
66
  "peerDependencies": {
67
67
  "@mikro-orm/core": "^7.0.14",
68
- "@open-mercato/shared": "0.8.1-develop.7297.1.67605e74f9",
68
+ "@open-mercato/shared": "0.8.1-develop.7442.1.4c1dbf1f0e",
69
69
  "bullmq": "^5.0.0 || ^6.0.0",
70
70
  "ioredis": "^5.0.0 || ^6.0.0",
71
71
  "zod": ">=3.23.0"
@@ -79,7 +79,7 @@
79
79
  }
80
80
  },
81
81
  "devDependencies": {
82
- "@open-mercato/shared": "0.8.1-develop.7297.1.67605e74f9",
82
+ "@open-mercato/shared": "0.8.1-develop.7442.1.4c1dbf1f0e",
83
83
  "@types/jest": "^30.0.0",
84
84
  "@types/node": "^26.4.0",
85
85
  "jest": "^30.4.2",
@@ -0,0 +1,54 @@
1
+ /** @jest-environment node */
2
+
3
+ jest.mock('@open-mercato/cache', () => ({
4
+ runWithCacheTenant: async (_tenantId: string | null, fn: () => Promise<unknown>) => fn(),
5
+ }), { virtual: true })
6
+
7
+ const resolveContainerValue = jest.fn()
8
+ const tenantId = '11111111-1111-4111-8111-111111111111'
9
+ const organizationId = '22222222-2222-4222-8222-222222222222'
10
+
11
+ jest.mock('@open-mercato/shared/lib/di/container', () => ({
12
+ createRequestContainer: async () => ({ resolve: resolveContainerValue }),
13
+ }))
14
+
15
+ jest.mock('@open-mercato/shared/lib/auth/server', () => ({
16
+ getAuthFromRequest: async () => ({
17
+ sub: 'user-1',
18
+ tenantId,
19
+ orgId: organizationId,
20
+ roles: ['admin'],
21
+ }),
22
+ getAuthFromCookies: async () => null,
23
+ }))
24
+
25
+ jest.mock('@open-mercato/core/modules/directory/utils/organizationScope', () => ({
26
+ resolveOrganizationScopeForRequest: async () => ({
27
+ tenantId,
28
+ selectedId: organizationId,
29
+ filterIds: [],
30
+ allowedIds: [],
31
+ }),
32
+ }))
33
+
34
+ import { GET } from '../route'
35
+
36
+ describe('scheduler jobs route organization scope', () => {
37
+ beforeEach(() => {
38
+ jest.clearAllMocks()
39
+ })
40
+
41
+ it('denies the opt-out list before cache, query-engine, or entity-manager access', async () => {
42
+ const response = await GET(new Request('http://localhost/api/scheduler/jobs?page=3&pageSize=20'))
43
+
44
+ expect(response.status).toBe(200)
45
+ await expect(response.json()).resolves.toEqual({
46
+ items: [],
47
+ total: 0,
48
+ page: 3,
49
+ pageSize: 20,
50
+ totalPages: 0,
51
+ })
52
+ expect(resolveContainerValue).not.toHaveBeenCalled()
53
+ })
54
+ })
@@ -22,7 +22,9 @@ const makeCtx = (overrides: Partial<{
22
22
  orgId: overrides.orgId === undefined ? 'o1' : overrides.orgId,
23
23
  isSuperAdmin: overrides.isSuperAdmin === undefined ? false : overrides.isSuperAdmin,
24
24
  },
25
- organizationIds: overrides.organizationIds === undefined ? ['o1'] : overrides.organizationIds,
25
+ organizationIds: Object.prototype.hasOwnProperty.call(overrides, 'organizationIds')
26
+ ? overrides.organizationIds
27
+ : ['o1'],
26
28
  })
27
29
 
28
30
  describe('buildSchedulerJobsFilters — scope visibility (#815, #1587)', () => {
@@ -91,6 +93,27 @@ describe('buildSchedulerJobsFilters — scope visibility (#815, #1587)', () => {
91
93
  expect(or[0]).toEqual({ organization_id: { $in: ['o1', 'o2'] }, tenant_id: { $eq: 't1' } })
92
94
  })
93
95
 
96
+ it('returns an unmatchable filter for an explicit empty organization scope', async () => {
97
+ const filters = await buildSchedulerJobsFilters(
98
+ {},
99
+ makeCtx({ organizationIds: [] }),
100
+ )
101
+
102
+ expect(filters).toEqual({ id: { $eq: '00000000-0000-0000-0000-000000000000' } })
103
+ })
104
+
105
+ it.each([null, undefined])('preserves the home-organization fallback for %s scope', async (organizationIds) => {
106
+ const filters = await buildSchedulerJobsFilters(
107
+ {},
108
+ makeCtx({ organizationIds: organizationIds as null | undefined }),
109
+ )
110
+
111
+ expect(filters.$or).toEqual([
112
+ { organization_id: { $eq: 'o1' }, tenant_id: { $eq: 't1' } },
113
+ { organization_id: { $eq: null }, tenant_id: { $eq: 't1' }, scope_type: { $eq: 'tenant' } },
114
+ ])
115
+ })
116
+
94
117
  it('distributes search across every visibility branch (name + description)', async () => {
95
118
  const filters = await buildSchedulerJobsFilters(
96
119
  { search: 'nightly' },
@@ -31,6 +31,11 @@ export async function buildSchedulerJobsFilters(
31
31
 
32
32
  const isSuperAdmin = ctx.auth?.isSuperAdmin === true
33
33
 
34
+ if (Array.isArray(ctx.organizationIds) && ctx.organizationIds.length === 0) {
35
+ filters.id = { $eq: '00000000-0000-0000-0000-000000000000' }
36
+ return filters
37
+ }
38
+
34
39
  const rawOrgIds = Array.isArray(ctx.organizationIds)
35
40
  ? ctx.organizationIds.filter((id): id is string => typeof id === 'string' && id.trim().length > 0)
36
41
  : []