@open-mercato/scheduler 0.10.1-develop.7961.1.d65694a8e6 → 0.10.1-develop.7973.1.2d07035b6f
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/dist/modules/scheduler/lib/activeScheduleLimits.js +1 -0
- package/dist/modules/scheduler/lib/activeScheduleLimits.js.map +2 -2
- package/dist/modules/scheduler/services/schedulerService.js +6 -4
- package/dist/modules/scheduler/services/schedulerService.js.map +2 -2
- package/package.json +5 -5
- package/src/modules/scheduler/commands/__tests__/jobs.active-limit.test.ts +2 -0
- package/src/modules/scheduler/lib/activeScheduleLimits.ts +1 -0
- package/src/modules/scheduler/services/__tests__/schedulerService.test.ts +82 -0
- package/src/modules/scheduler/services/schedulerService.ts +6 -4
|
@@ -22,6 +22,7 @@ async function enforceTenantActiveScheduleLimit(em, tenantId) {
|
|
|
22
22
|
const maxActiveSchedules = getMaxActiveSchedulesPerTenant();
|
|
23
23
|
const activeScheduleCount = await em.count(ScheduledJob, {
|
|
24
24
|
tenantId,
|
|
25
|
+
sourceType: "user",
|
|
25
26
|
isEnabled: true,
|
|
26
27
|
deletedAt: null
|
|
27
28
|
});
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/scheduler/lib/activeScheduleLimits.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { createFallbackTranslator, type TranslateWithFallbackFn } from '@open-mercato/shared/lib/i18n/translate'\nimport { ScheduledJob } from '../data/entities.js'\n\nexport const DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT = 100\nconst ACTIVE_SCHEDULE_LIMIT_ENV = 'OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT'\n\nexport function getMaxActiveSchedulesPerTenant(): number {\n const parsed = Number.parseInt(process.env[ACTIVE_SCHEDULE_LIMIT_ENV] ?? '', 10)\n if (Number.isFinite(parsed) && parsed > 0) return parsed\n return DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT\n}\n\nasync function resolveActiveScheduleLimitTranslator(): Promise<TranslateWithFallbackFn> {\n try {\n const { translate } = await resolveTranslations()\n return translate\n } catch {\n return createFallbackTranslator({})\n }\n}\n\nexport async function enforceTenantActiveScheduleLimit(\n em: EntityManager,\n tenantId: string | null | undefined,\n): Promise<void> {\n if (!tenantId) return\n\n const maxActiveSchedules = getMaxActiveSchedulesPerTenant()\n const activeScheduleCount = await em.count(ScheduledJob, {\n tenantId,\n isEnabled: true,\n deletedAt: null,\n })\n\n if (activeScheduleCount >= maxActiveSchedules) {\n const translate = await resolveActiveScheduleLimitTranslator()\n throw new CrudHttpError(422, {\n error: translate(\n 'scheduler.error.active_schedule_limit',\n 'Active scheduled job limit reached for this tenant ({max}).',\n { max: maxActiveSchedules },\n ),\n })\n }\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,gCAA8D;AACvE,SAAS,oBAAoB;AAEtB,MAAM,0CAA0C;AACvD,MAAM,4BAA4B;AAE3B,SAAS,iCAAyC;AACvD,QAAM,SAAS,OAAO,SAAS,QAAQ,IAAI,yBAAyB,KAAK,IAAI,EAAE;AAC/E,MAAI,OAAO,SAAS,MAAM,KAAK,SAAS,EAAG,QAAO;AAClD,SAAO;AACT;AAEA,eAAe,uCAAyE;AACtF,MAAI;AACF,UAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,WAAO;AAAA,EACT,QAAQ;AACN,WAAO,yBAAyB,CAAC,CAAC;AAAA,EACpC;AACF;AAEA,eAAsB,iCACpB,IACA,UACe;AACf,MAAI,CAAC,SAAU;AAEf,QAAM,qBAAqB,+BAA+B;AAC1D,QAAM,sBAAsB,MAAM,GAAG,MAAM,cAAc;AAAA,IACvD;AAAA,IACA,WAAW;AAAA,IACX,WAAW;AAAA,EACb,CAAC;AAED,MAAI,uBAAuB,oBAAoB;AAC7C,UAAM,YAAY,MAAM,qCAAqC;AAC7D,UAAM,IAAI,cAAc,KAAK;AAAA,MAC3B,OAAO;AAAA,QACL;AAAA,QACA;AAAA,QACA,EAAE,KAAK,mBAAmB;AAAA,MAC5B;AAAA,IACF,CAAC;AAAA,EACH;AACF;",
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { createFallbackTranslator, type TranslateWithFallbackFn } from '@open-mercato/shared/lib/i18n/translate'\nimport { ScheduledJob } from '../data/entities.js'\n\nexport const DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT = 100\nconst ACTIVE_SCHEDULE_LIMIT_ENV = 'OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT'\n\nexport function getMaxActiveSchedulesPerTenant(): number {\n const parsed = Number.parseInt(process.env[ACTIVE_SCHEDULE_LIMIT_ENV] ?? '', 10)\n if (Number.isFinite(parsed) && parsed > 0) return parsed\n return DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT\n}\n\nasync function resolveActiveScheduleLimitTranslator(): Promise<TranslateWithFallbackFn> {\n try {\n const { translate } = await resolveTranslations()\n return translate\n } catch {\n return createFallbackTranslator({})\n }\n}\n\nexport async function enforceTenantActiveScheduleLimit(\n em: EntityManager,\n tenantId: string | null | undefined,\n): Promise<void> {\n if (!tenantId) return\n\n const maxActiveSchedules = getMaxActiveSchedulesPerTenant()\n const activeScheduleCount = await em.count(ScheduledJob, {\n tenantId,\n sourceType: 'user',\n isEnabled: true,\n deletedAt: null,\n })\n\n if (activeScheduleCount >= maxActiveSchedules) {\n const translate = await resolveActiveScheduleLimitTranslator()\n throw new CrudHttpError(422, {\n error: translate(\n 'scheduler.error.active_schedule_limit',\n 'Active scheduled job limit reached for this tenant ({max}).',\n { max: maxActiveSchedules },\n ),\n })\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,gCAA8D;AACvE,SAAS,oBAAoB;AAEtB,MAAM,0CAA0C;AACvD,MAAM,4BAA4B;AAE3B,SAAS,iCAAyC;AACvD,QAAM,SAAS,OAAO,SAAS,QAAQ,IAAI,yBAAyB,KAAK,IAAI,EAAE;AAC/E,MAAI,OAAO,SAAS,MAAM,KAAK,SAAS,EAAG,QAAO;AAClD,SAAO;AACT;AAEA,eAAe,uCAAyE;AACtF,MAAI;AACF,UAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,WAAO;AAAA,EACT,QAAQ;AACN,WAAO,yBAAyB,CAAC,CAAC;AAAA,EACpC;AACF;AAEA,eAAsB,iCACpB,IACA,UACe;AACf,MAAI,CAAC,SAAU;AAEf,QAAM,qBAAqB,+BAA+B;AAC1D,QAAM,sBAAsB,MAAM,GAAG,MAAM,cAAc;AAAA,IACvD;AAAA,IACA,YAAY;AAAA,IACZ,WAAW;AAAA,IACX,WAAW;AAAA,EACb,CAAC;AAED,MAAI,uBAAuB,oBAAoB;AAC7C,UAAM,YAAY,MAAM,qCAAqC;AAC7D,UAAM,IAAI,cAAc,KAAK;AAAA,MAC3B,OAAO;AAAA,QACL;AAAA,QACA;AAAA,QACA,EAAE,KAAK,mBAAmB;AAAA,MAC5B;AAAA,IACF,CAAC;AAAA,EACH;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -30,9 +30,11 @@ class SchedulerService {
|
|
|
30
30
|
}
|
|
31
31
|
let schedule = await em.findOne(ScheduledJob, { id: registration.id });
|
|
32
32
|
const nextTenantId = registration.tenantId || null;
|
|
33
|
+
const nextSourceType = registration.sourceType ?? "module";
|
|
33
34
|
const nextIsEnabled = registration.isEnabled !== void 0 ? registration.isEnabled : schedule?.isEnabled ?? true;
|
|
34
35
|
const tenantChanged = schedule ? (schedule.tenantId || null) !== nextTenantId : false;
|
|
35
|
-
|
|
36
|
+
const changedToUserSource = schedule?.sourceType !== "user" && nextSourceType === "user";
|
|
37
|
+
if (nextSourceType === "user" && nextIsEnabled && (schedule?.isEnabled !== true || tenantChanged || changedToUserSource)) {
|
|
36
38
|
await enforceTenantActiveScheduleLimit(em, nextTenantId);
|
|
37
39
|
}
|
|
38
40
|
if (schedule) {
|
|
@@ -49,7 +51,7 @@ class SchedulerService {
|
|
|
49
51
|
schedule.targetCommand = registration.targetCommand || null;
|
|
50
52
|
schedule.targetPayload = registration.targetPayload || null;
|
|
51
53
|
schedule.requireFeature = registration.requireFeature || null;
|
|
52
|
-
schedule.sourceType =
|
|
54
|
+
schedule.sourceType = nextSourceType;
|
|
53
55
|
schedule.sourceModule = registration.sourceModule || null;
|
|
54
56
|
schedule.isEnabled = registration.isEnabled !== void 0 ? registration.isEnabled : schedule.isEnabled;
|
|
55
57
|
schedule.nextRunAt = nextRunAt;
|
|
@@ -70,7 +72,7 @@ class SchedulerService {
|
|
|
70
72
|
targetCommand: registration.targetCommand || null,
|
|
71
73
|
targetPayload: registration.targetPayload || null,
|
|
72
74
|
requireFeature: registration.requireFeature || null,
|
|
73
|
-
sourceType:
|
|
75
|
+
sourceType: nextSourceType,
|
|
74
76
|
sourceModule: registration.sourceModule || null,
|
|
75
77
|
isEnabled: registration.isEnabled !== void 0 ? registration.isEnabled : true,
|
|
76
78
|
nextRunAt,
|
|
@@ -126,7 +128,7 @@ class SchedulerService {
|
|
|
126
128
|
if (!schedule) {
|
|
127
129
|
throw new Error(`Schedule not found: ${scheduleId}`);
|
|
128
130
|
}
|
|
129
|
-
if (changes.isEnabled === true && schedule.isEnabled !== true) {
|
|
131
|
+
if (schedule.sourceType === "user" && changes.isEnabled === true && schedule.isEnabled !== true) {
|
|
130
132
|
await enforceTenantActiveScheduleLimit(em, schedule.tenantId);
|
|
131
133
|
}
|
|
132
134
|
const scheduleChanged = changes.scheduleType !== void 0 || changes.scheduleValue !== void 0 || changes.timezone !== void 0;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/scheduler/services/schedulerService.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from '../data/entities.js'\nimport { calculateNextRunForWrite } from '../lib/nextRunCalculator.js'\nimport { enforceTenantActiveScheduleLimit } from '../lib/activeScheduleLimits.js'\nimport type { BullMQSchedulerService } from './bullmqSchedulerService.js'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { createInvalidScheduleValueError } from '@open-mercato/shared/lib/schedule/invalidScheduleValue'\n\nconst logger = createLogger('scheduler')\n\nexport interface ScheduleRegistration {\n id: string\n name: string\n scopeType: 'system' | 'organization' | 'tenant'\n organizationId?: string\n tenantId?: string\n scheduleType: 'cron' | 'interval'\n scheduleValue: string\n timezone?: string\n targetType: 'queue' | 'command'\n targetQueue?: string\n targetCommand?: string\n targetPayload?: unknown\n requireFeature?: string\n sourceType?: 'user' | 'module'\n sourceModule?: string\n isEnabled?: boolean\n description?: string\n}\n\nexport class SchedulerService {\n constructor(\n private em: () => EntityManager,\n private bullmqService?: BullMQSchedulerService,\n ) {}\n\n /**\n * Register a new schedule (upsert)\n */\n async register(registration: ScheduleRegistration): Promise<void> {\n const em = this.em().fork()\n \n // Validate scope consistency\n this.validateScope(registration)\n \n // Validate target consistency\n this.validateTarget(registration)\n \n // Calculate next run time\n const nextRunAt = calculateNextRunForWrite(\n registration.scheduleType,\n registration.scheduleValue,\n registration.timezone || 'UTC'\n )\n \n if (!nextRunAt) {\n throw createInvalidScheduleValueError(\n registration.scheduleType,\n registration.scheduleValue,\n `Failed to calculate next run time for schedule: ${registration.id}`,\n )\n }\n \n // Check if schedule already exists\n let schedule = await em.findOne(ScheduledJob, { id: registration.id })\n const nextTenantId = registration.tenantId || null\n const nextIsEnabled = registration.isEnabled !== undefined ? registration.isEnabled : (schedule?.isEnabled ?? true)\n const tenantChanged = schedule ? (schedule.tenantId || null) !== nextTenantId : false\n if (nextIsEnabled && (schedule?.isEnabled !== true || tenantChanged)) {\n await enforceTenantActiveScheduleLimit(em, nextTenantId)\n }\n \n if (schedule) {\n // Update existing\n schedule.name = registration.name\n schedule.description = registration.description || null\n schedule.scopeType = registration.scopeType\n schedule.organizationId = registration.organizationId || null\n schedule.tenantId = registration.tenantId || null\n schedule.scheduleType = registration.scheduleType\n schedule.scheduleValue = registration.scheduleValue\n schedule.timezone = registration.timezone || 'UTC'\n schedule.targetType = registration.targetType\n schedule.targetQueue = registration.targetQueue || null\n schedule.targetCommand = registration.targetCommand || null\n schedule.targetPayload = registration.targetPayload as Record<string, unknown> || null\n schedule.requireFeature = registration.requireFeature || null\n schedule.sourceType = registration.sourceType || 'user'\n schedule.sourceModule = registration.sourceModule || null\n schedule.isEnabled = registration.isEnabled !== undefined ? registration.isEnabled : schedule.isEnabled\n schedule.nextRunAt = nextRunAt\n schedule.updatedAt = new Date()\n } else {\n // Create new\n schedule = em.create(ScheduledJob, {\n id: registration.id,\n name: registration.name,\n description: registration.description || null,\n scopeType: registration.scopeType,\n organizationId: registration.organizationId || null,\n tenantId: registration.tenantId || null,\n scheduleType: registration.scheduleType,\n scheduleValue: registration.scheduleValue,\n timezone: registration.timezone || 'UTC',\n targetType: registration.targetType,\n targetQueue: registration.targetQueue || null,\n targetCommand: registration.targetCommand || null,\n targetPayload: registration.targetPayload as Record<string, unknown> || null,\n requireFeature: registration.requireFeature || null,\n sourceType: registration.sourceType || 'module',\n sourceModule: registration.sourceModule || null,\n isEnabled: registration.isEnabled !== undefined ? registration.isEnabled : true,\n nextRunAt,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(schedule)\n }\n \n await em.flush()\n\n // Sync with BullMQ if available\n if (this.bullmqService && schedule) {\n try {\n if (schedule.isEnabled) {\n await this.bullmqService.register(schedule)\n } else {\n await this.bullmqService.unregister(schedule.id)\n }\n } catch (error: unknown) {\n logger.error('Failed to sync with BullMQ', { scheduleId: schedule.id, err: error })\n // Don't throw - DB is source of truth, BullMQ sync is best-effort\n }\n }\n }\n\n /**\n * Unregister a schedule\n */\n async unregister(scheduleId: string): Promise<void> {\n const em = this.em().fork()\n const schedule = await em.findOne(ScheduledJob, { id: scheduleId })\n \n if (schedule) {\n await em.remove(schedule).flush()\n \n // Unregister from BullMQ if available\n if (this.bullmqService) {\n try {\n await this.bullmqService.unregister(scheduleId)\n } catch (error: unknown) {\n logger.error('Failed to unregister from BullMQ', { scheduleId, err: error })\n }\n }\n }\n }\n\n /**\n * Check if a schedule exists\n */\n async exists(scheduleId: string): Promise<boolean> {\n const em = this.em()\n const count = await em.count(ScheduledJob, { id: scheduleId })\n return count > 0\n }\n\n /**\n * Update an existing schedule\n */\n async update(\n scheduleId: string,\n changes: Partial<Omit<ScheduleRegistration, 'id'>>\n ): Promise<void> {\n const em = this.em().fork()\n const schedule = await em.findOne(ScheduledJob, { id: scheduleId })\n \n if (!schedule) {\n throw new Error(`Schedule not found: ${scheduleId}`)\n }\n\n if (changes.isEnabled === true && schedule.isEnabled !== true) {\n await enforceTenantActiveScheduleLimit(em, schedule.tenantId)\n }\n\n const scheduleChanged = changes.scheduleType !== undefined || changes.scheduleValue !== undefined || changes.timezone !== undefined\n const nextRunAt = scheduleChanged\n ? calculateNextRunForWrite(\n changes.scheduleType ?? schedule.scheduleType,\n changes.scheduleValue ?? schedule.scheduleValue,\n changes.timezone ?? schedule.timezone,\n )\n : null\n if (scheduleChanged && !nextRunAt) {\n throw createInvalidScheduleValueError(\n changes.scheduleType ?? schedule.scheduleType,\n changes.scheduleValue ?? schedule.scheduleValue,\n `Failed to calculate next run time for schedule: ${scheduleId}`,\n )\n }\n \n // Apply changes\n if (changes.name !== undefined) schedule.name = changes.name\n if (changes.description !== undefined) schedule.description = changes.description || null\n if (changes.scheduleType !== undefined) schedule.scheduleType = changes.scheduleType\n if (changes.scheduleValue !== undefined) schedule.scheduleValue = changes.scheduleValue\n if (changes.timezone !== undefined) schedule.timezone = changes.timezone\n if (changes.targetPayload !== undefined) {\n schedule.targetPayload = changes.targetPayload as Record<string, unknown> || null\n }\n if (changes.requireFeature !== undefined) schedule.requireFeature = changes.requireFeature || null\n if (changes.isEnabled !== undefined) schedule.isEnabled = changes.isEnabled\n \n // Handle target type changes - clear stale values when switching between queue and command\n if (changes.targetType !== undefined) {\n schedule.targetType = changes.targetType\n \n if (changes.targetType === 'queue') {\n // Switching to queue: set new queue and clear command\n if (changes.targetQueue !== undefined) schedule.targetQueue = changes.targetQueue || null\n schedule.targetCommand = null\n } else if (changes.targetType === 'command') {\n // Switching to command: set new command and clear queue\n if (changes.targetCommand !== undefined) schedule.targetCommand = changes.targetCommand || null\n schedule.targetQueue = null\n }\n } else {\n // targetType not changing, but allow updating individual target fields\n if (changes.targetQueue !== undefined) schedule.targetQueue = changes.targetQueue || null\n if (changes.targetCommand !== undefined) schedule.targetCommand = changes.targetCommand || null\n }\n \n if (nextRunAt) {\n schedule.nextRunAt = nextRunAt\n }\n \n schedule.updatedAt = new Date()\n await em.flush()\n\n // Sync with BullMQ if available\n if (this.bullmqService) {\n try {\n if (schedule.isEnabled) {\n await this.bullmqService.register(schedule)\n } else {\n await this.bullmqService.unregister(scheduleId)\n }\n } catch (error: unknown) {\n logger.error('Failed to sync update with BullMQ', { scheduleId, err: error })\n }\n }\n }\n\n /**\n * Find schedules by module\n */\n async findByModule(moduleId: string, limit = 100): Promise<ScheduledJob[]> {\n const em = this.em()\n return em.find(ScheduledJob, { sourceModule: moduleId, deletedAt: null }, { limit })\n }\n\n /**\n * Enable a schedule\n */\n async enable(scheduleId: string): Promise<void> {\n await this.update(scheduleId, { isEnabled: true })\n }\n\n /**\n * Disable a schedule\n */\n async disable(scheduleId: string): Promise<void> {\n await this.update(scheduleId, { isEnabled: false })\n }\n\n private validateScope(registration: ScheduleRegistration): void {\n const { scopeType, organizationId, tenantId } = registration\n \n if (scopeType === 'system') {\n if (organizationId || tenantId) {\n throw new Error('System-scoped schedules cannot have organizationId or tenantId')\n }\n } else if (scopeType === 'organization') {\n if (!organizationId || !tenantId) {\n throw new Error('Organization-scoped schedules must have both organizationId and tenantId')\n }\n } else if (scopeType === 'tenant') {\n if (organizationId || !tenantId) {\n throw new Error('Tenant-scoped schedules must have tenantId and no organizationId')\n }\n }\n }\n\n private validateTarget(registration: ScheduleRegistration): void {\n const { targetType, targetQueue, targetCommand } = registration\n \n if (targetType === 'queue') {\n if (!targetQueue) {\n throw new Error('Queue target must have targetQueue')\n }\n } else if (targetType === 'command') {\n if (!targetCommand) {\n throw new Error('Command target must have targetCommand')\n }\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,gCAAgC;AACzC,SAAS,wCAAwC;AAEjD,SAAS,oBAAoB;AAC7B,SAAS,uCAAuC;AAEhD,MAAM,SAAS,aAAa,WAAW;AAsBhC,MAAM,iBAAiB;AAAA,EAC5B,YACU,IACA,eACR;AAFQ;AACA;AAAA,EACP;AAAA;AAAA;AAAA;AAAA,EAKH,MAAM,SAAS,cAAmD;AAChE,UAAM,KAAK,KAAK,GAAG,EAAE,KAAK;AAG1B,SAAK,cAAc,YAAY;AAG/B,SAAK,eAAe,YAAY;AAGhC,UAAM,YAAY;AAAA,MAChB,aAAa;AAAA,MACb,aAAa;AAAA,MACb,aAAa,YAAY;AAAA,IAC3B;AAEA,QAAI,CAAC,WAAW;AACd,YAAM;AAAA,QACJ,aAAa;AAAA,QACb,aAAa;AAAA,QACb,mDAAmD,aAAa,EAAE;AAAA,MACpE;AAAA,IACF;AAGA,QAAI,WAAW,MAAM,GAAG,QAAQ,cAAc,EAAE,IAAI,aAAa,GAAG,CAAC;AACrE,UAAM,eAAe,aAAa,YAAY;AAC9C,UAAM,gBAAgB,aAAa,cAAc,SAAY,aAAa,YAAa,UAAU,aAAa;AAC9G,UAAM,gBAAgB,YAAY,SAAS,YAAY,UAAU,eAAe;AAChF,QAAI,kBAAkB,UAAU,cAAc,QAAQ,
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from '../data/entities.js'\nimport { calculateNextRunForWrite } from '../lib/nextRunCalculator.js'\nimport { enforceTenantActiveScheduleLimit } from '../lib/activeScheduleLimits.js'\nimport type { BullMQSchedulerService } from './bullmqSchedulerService.js'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { createInvalidScheduleValueError } from '@open-mercato/shared/lib/schedule/invalidScheduleValue'\n\nconst logger = createLogger('scheduler')\n\nexport interface ScheduleRegistration {\n id: string\n name: string\n scopeType: 'system' | 'organization' | 'tenant'\n organizationId?: string\n tenantId?: string\n scheduleType: 'cron' | 'interval'\n scheduleValue: string\n timezone?: string\n targetType: 'queue' | 'command'\n targetQueue?: string\n targetCommand?: string\n targetPayload?: unknown\n requireFeature?: string\n sourceType?: 'user' | 'module'\n sourceModule?: string\n isEnabled?: boolean\n description?: string\n}\n\nexport class SchedulerService {\n constructor(\n private em: () => EntityManager,\n private bullmqService?: BullMQSchedulerService,\n ) {}\n\n /**\n * Register a new schedule (upsert)\n */\n async register(registration: ScheduleRegistration): Promise<void> {\n const em = this.em().fork()\n \n // Validate scope consistency\n this.validateScope(registration)\n \n // Validate target consistency\n this.validateTarget(registration)\n \n // Calculate next run time\n const nextRunAt = calculateNextRunForWrite(\n registration.scheduleType,\n registration.scheduleValue,\n registration.timezone || 'UTC'\n )\n \n if (!nextRunAt) {\n throw createInvalidScheduleValueError(\n registration.scheduleType,\n registration.scheduleValue,\n `Failed to calculate next run time for schedule: ${registration.id}`,\n )\n }\n \n // Check if schedule already exists\n let schedule = await em.findOne(ScheduledJob, { id: registration.id })\n const nextTenantId = registration.tenantId || null\n const nextSourceType = registration.sourceType ?? 'module'\n const nextIsEnabled = registration.isEnabled !== undefined ? registration.isEnabled : (schedule?.isEnabled ?? true)\n const tenantChanged = schedule ? (schedule.tenantId || null) !== nextTenantId : false\n const changedToUserSource = schedule?.sourceType !== 'user' && nextSourceType === 'user'\n if (nextSourceType === 'user' && nextIsEnabled && (schedule?.isEnabled !== true || tenantChanged || changedToUserSource)) {\n await enforceTenantActiveScheduleLimit(em, nextTenantId)\n }\n \n if (schedule) {\n // Update existing\n schedule.name = registration.name\n schedule.description = registration.description || null\n schedule.scopeType = registration.scopeType\n schedule.organizationId = registration.organizationId || null\n schedule.tenantId = registration.tenantId || null\n schedule.scheduleType = registration.scheduleType\n schedule.scheduleValue = registration.scheduleValue\n schedule.timezone = registration.timezone || 'UTC'\n schedule.targetType = registration.targetType\n schedule.targetQueue = registration.targetQueue || null\n schedule.targetCommand = registration.targetCommand || null\n schedule.targetPayload = registration.targetPayload as Record<string, unknown> || null\n schedule.requireFeature = registration.requireFeature || null\n schedule.sourceType = nextSourceType\n schedule.sourceModule = registration.sourceModule || null\n schedule.isEnabled = registration.isEnabled !== undefined ? registration.isEnabled : schedule.isEnabled\n schedule.nextRunAt = nextRunAt\n schedule.updatedAt = new Date()\n } else {\n // Create new\n schedule = em.create(ScheduledJob, {\n id: registration.id,\n name: registration.name,\n description: registration.description || null,\n scopeType: registration.scopeType,\n organizationId: registration.organizationId || null,\n tenantId: registration.tenantId || null,\n scheduleType: registration.scheduleType,\n scheduleValue: registration.scheduleValue,\n timezone: registration.timezone || 'UTC',\n targetType: registration.targetType,\n targetQueue: registration.targetQueue || null,\n targetCommand: registration.targetCommand || null,\n targetPayload: registration.targetPayload as Record<string, unknown> || null,\n requireFeature: registration.requireFeature || null,\n sourceType: nextSourceType,\n sourceModule: registration.sourceModule || null,\n isEnabled: registration.isEnabled !== undefined ? registration.isEnabled : true,\n nextRunAt,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(schedule)\n }\n \n await em.flush()\n\n // Sync with BullMQ if available\n if (this.bullmqService && schedule) {\n try {\n if (schedule.isEnabled) {\n await this.bullmqService.register(schedule)\n } else {\n await this.bullmqService.unregister(schedule.id)\n }\n } catch (error: unknown) {\n logger.error('Failed to sync with BullMQ', { scheduleId: schedule.id, err: error })\n // Don't throw - DB is source of truth, BullMQ sync is best-effort\n }\n }\n }\n\n /**\n * Unregister a schedule\n */\n async unregister(scheduleId: string): Promise<void> {\n const em = this.em().fork()\n const schedule = await em.findOne(ScheduledJob, { id: scheduleId })\n \n if (schedule) {\n await em.remove(schedule).flush()\n \n // Unregister from BullMQ if available\n if (this.bullmqService) {\n try {\n await this.bullmqService.unregister(scheduleId)\n } catch (error: unknown) {\n logger.error('Failed to unregister from BullMQ', { scheduleId, err: error })\n }\n }\n }\n }\n\n /**\n * Check if a schedule exists\n */\n async exists(scheduleId: string): Promise<boolean> {\n const em = this.em()\n const count = await em.count(ScheduledJob, { id: scheduleId })\n return count > 0\n }\n\n /**\n * Update an existing schedule\n */\n async update(\n scheduleId: string,\n changes: Partial<Omit<ScheduleRegistration, 'id'>>\n ): Promise<void> {\n const em = this.em().fork()\n const schedule = await em.findOne(ScheduledJob, { id: scheduleId })\n \n if (!schedule) {\n throw new Error(`Schedule not found: ${scheduleId}`)\n }\n\n if (schedule.sourceType === 'user' && changes.isEnabled === true && schedule.isEnabled !== true) {\n await enforceTenantActiveScheduleLimit(em, schedule.tenantId)\n }\n\n const scheduleChanged = changes.scheduleType !== undefined || changes.scheduleValue !== undefined || changes.timezone !== undefined\n const nextRunAt = scheduleChanged\n ? calculateNextRunForWrite(\n changes.scheduleType ?? schedule.scheduleType,\n changes.scheduleValue ?? schedule.scheduleValue,\n changes.timezone ?? schedule.timezone,\n )\n : null\n if (scheduleChanged && !nextRunAt) {\n throw createInvalidScheduleValueError(\n changes.scheduleType ?? schedule.scheduleType,\n changes.scheduleValue ?? schedule.scheduleValue,\n `Failed to calculate next run time for schedule: ${scheduleId}`,\n )\n }\n \n // Apply changes\n if (changes.name !== undefined) schedule.name = changes.name\n if (changes.description !== undefined) schedule.description = changes.description || null\n if (changes.scheduleType !== undefined) schedule.scheduleType = changes.scheduleType\n if (changes.scheduleValue !== undefined) schedule.scheduleValue = changes.scheduleValue\n if (changes.timezone !== undefined) schedule.timezone = changes.timezone\n if (changes.targetPayload !== undefined) {\n schedule.targetPayload = changes.targetPayload as Record<string, unknown> || null\n }\n if (changes.requireFeature !== undefined) schedule.requireFeature = changes.requireFeature || null\n if (changes.isEnabled !== undefined) schedule.isEnabled = changes.isEnabled\n \n // Handle target type changes - clear stale values when switching between queue and command\n if (changes.targetType !== undefined) {\n schedule.targetType = changes.targetType\n \n if (changes.targetType === 'queue') {\n // Switching to queue: set new queue and clear command\n if (changes.targetQueue !== undefined) schedule.targetQueue = changes.targetQueue || null\n schedule.targetCommand = null\n } else if (changes.targetType === 'command') {\n // Switching to command: set new command and clear queue\n if (changes.targetCommand !== undefined) schedule.targetCommand = changes.targetCommand || null\n schedule.targetQueue = null\n }\n } else {\n // targetType not changing, but allow updating individual target fields\n if (changes.targetQueue !== undefined) schedule.targetQueue = changes.targetQueue || null\n if (changes.targetCommand !== undefined) schedule.targetCommand = changes.targetCommand || null\n }\n \n if (nextRunAt) {\n schedule.nextRunAt = nextRunAt\n }\n \n schedule.updatedAt = new Date()\n await em.flush()\n\n // Sync with BullMQ if available\n if (this.bullmqService) {\n try {\n if (schedule.isEnabled) {\n await this.bullmqService.register(schedule)\n } else {\n await this.bullmqService.unregister(scheduleId)\n }\n } catch (error: unknown) {\n logger.error('Failed to sync update with BullMQ', { scheduleId, err: error })\n }\n }\n }\n\n /**\n * Find schedules by module\n */\n async findByModule(moduleId: string, limit = 100): Promise<ScheduledJob[]> {\n const em = this.em()\n return em.find(ScheduledJob, { sourceModule: moduleId, deletedAt: null }, { limit })\n }\n\n /**\n * Enable a schedule\n */\n async enable(scheduleId: string): Promise<void> {\n await this.update(scheduleId, { isEnabled: true })\n }\n\n /**\n * Disable a schedule\n */\n async disable(scheduleId: string): Promise<void> {\n await this.update(scheduleId, { isEnabled: false })\n }\n\n private validateScope(registration: ScheduleRegistration): void {\n const { scopeType, organizationId, tenantId } = registration\n \n if (scopeType === 'system') {\n if (organizationId || tenantId) {\n throw new Error('System-scoped schedules cannot have organizationId or tenantId')\n }\n } else if (scopeType === 'organization') {\n if (!organizationId || !tenantId) {\n throw new Error('Organization-scoped schedules must have both organizationId and tenantId')\n }\n } else if (scopeType === 'tenant') {\n if (organizationId || !tenantId) {\n throw new Error('Tenant-scoped schedules must have tenantId and no organizationId')\n }\n }\n }\n\n private validateTarget(registration: ScheduleRegistration): void {\n const { targetType, targetQueue, targetCommand } = registration\n \n if (targetType === 'queue') {\n if (!targetQueue) {\n throw new Error('Queue target must have targetQueue')\n }\n } else if (targetType === 'command') {\n if (!targetCommand) {\n throw new Error('Command target must have targetCommand')\n }\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,gCAAgC;AACzC,SAAS,wCAAwC;AAEjD,SAAS,oBAAoB;AAC7B,SAAS,uCAAuC;AAEhD,MAAM,SAAS,aAAa,WAAW;AAsBhC,MAAM,iBAAiB;AAAA,EAC5B,YACU,IACA,eACR;AAFQ;AACA;AAAA,EACP;AAAA;AAAA;AAAA;AAAA,EAKH,MAAM,SAAS,cAAmD;AAChE,UAAM,KAAK,KAAK,GAAG,EAAE,KAAK;AAG1B,SAAK,cAAc,YAAY;AAG/B,SAAK,eAAe,YAAY;AAGhC,UAAM,YAAY;AAAA,MAChB,aAAa;AAAA,MACb,aAAa;AAAA,MACb,aAAa,YAAY;AAAA,IAC3B;AAEA,QAAI,CAAC,WAAW;AACd,YAAM;AAAA,QACJ,aAAa;AAAA,QACb,aAAa;AAAA,QACb,mDAAmD,aAAa,EAAE;AAAA,MACpE;AAAA,IACF;AAGA,QAAI,WAAW,MAAM,GAAG,QAAQ,cAAc,EAAE,IAAI,aAAa,GAAG,CAAC;AACrE,UAAM,eAAe,aAAa,YAAY;AAC9C,UAAM,iBAAiB,aAAa,cAAc;AAClD,UAAM,gBAAgB,aAAa,cAAc,SAAY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D,UAAM,EAAE,WAAW,gBAAgB,SAAS,IAAI;AAEhD,QAAI,cAAc,UAAU;AAC1B,UAAI,kBAAkB,UAAU;AAC9B,cAAM,IAAI,MAAM,gEAAgE;AAAA,MAClF;AAAA,IACF,WAAW,cAAc,gBAAgB;AACvC,UAAI,CAAC,kBAAkB,CAAC,UAAU;AAChC,cAAM,IAAI,MAAM,0EAA0E;AAAA,MAC5F;AAAA,IACF,WAAW,cAAc,UAAU;AACjC,UAAI,kBAAkB,CAAC,UAAU;AAC/B,cAAM,IAAI,MAAM,kEAAkE;AAAA,MACpF;AAAA,IACF;AAAA,EACF;AAAA,EAEQ,eAAe,cAA0C;AAC/D,UAAM,EAAE,YAAY,aAAa,cAAc,IAAI;AAEnD,QAAI,eAAe,SAAS;AAC1B,UAAI,CAAC,aAAa;AAChB,cAAM,IAAI,MAAM,oCAAoC;AAAA,MACtD;AAAA,IACF,WAAW,eAAe,WAAW;AACnC,UAAI,CAAC,eAAe;AAClB,cAAM,IAAI,MAAM,wCAAwC;AAAA,MAC1D;AAAA,IACF;AAAA,EACF;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.10.1-develop.
|
|
3
|
+
"version": "0.10.1-develop.7973.1.2d07035b6f",
|
|
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.10.1-develop.
|
|
63
|
-
"@open-mercato/queue": "0.10.1-develop.
|
|
62
|
+
"@open-mercato/events": "0.10.1-develop.7973.1.2d07035b6f",
|
|
63
|
+
"@open-mercato/queue": "0.10.1-develop.7973.1.2d07035b6f",
|
|
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.10.1-develop.
|
|
68
|
+
"@open-mercato/shared": "0.10.1-develop.7973.1.2d07035b6f",
|
|
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.10.1-develop.
|
|
82
|
+
"@open-mercato/shared": "0.10.1-develop.7973.1.2d07035b6f",
|
|
83
83
|
"@types/jest": "^30.0.0",
|
|
84
84
|
"@types/node": "^26.4.0",
|
|
85
85
|
"jest": "^30.4.2",
|
|
@@ -85,6 +85,7 @@ describe('scheduler.jobs active schedule tenant limit', () => {
|
|
|
85
85
|
|
|
86
86
|
expect(em.count).toHaveBeenCalledWith(expect.any(Function), {
|
|
87
87
|
tenantId: 'tenant-a',
|
|
88
|
+
sourceType: 'user',
|
|
88
89
|
isEnabled: true,
|
|
89
90
|
deletedAt: null,
|
|
90
91
|
})
|
|
@@ -127,6 +128,7 @@ describe('scheduler.jobs active schedule tenant limit', () => {
|
|
|
127
128
|
|
|
128
129
|
expect(em.count).toHaveBeenCalledWith(expect.any(Function), {
|
|
129
130
|
tenantId: 'tenant-a',
|
|
131
|
+
sourceType: 'user',
|
|
130
132
|
isEnabled: true,
|
|
131
133
|
deletedAt: null,
|
|
132
134
|
})
|
|
@@ -31,6 +31,7 @@ export async function enforceTenantActiveScheduleLimit(
|
|
|
31
31
|
const maxActiveSchedules = getMaxActiveSchedulesPerTenant()
|
|
32
32
|
const activeScheduleCount = await em.count(ScheduledJob, {
|
|
33
33
|
tenantId,
|
|
34
|
+
sourceType: 'user',
|
|
34
35
|
isEnabled: true,
|
|
35
36
|
deletedAt: null,
|
|
36
37
|
})
|
|
@@ -101,6 +101,7 @@ describe('SchedulerService', () => {
|
|
|
101
101
|
const existingSchedule = {
|
|
102
102
|
id: 'test-schedule-1',
|
|
103
103
|
name: 'Old Name',
|
|
104
|
+
sourceType: 'module',
|
|
104
105
|
isEnabled: true,
|
|
105
106
|
} as ScheduledJob
|
|
106
107
|
|
|
@@ -113,6 +114,7 @@ describe('SchedulerService', () => {
|
|
|
113
114
|
})
|
|
114
115
|
|
|
115
116
|
expect(existingSchedule.name).toBe('Updated Name')
|
|
117
|
+
expect(existingSchedule.sourceType).toBe('module')
|
|
116
118
|
expect(mockForkedEm.flush).toHaveBeenCalled()
|
|
117
119
|
expect(mockForkedEm.create).not.toHaveBeenCalled()
|
|
118
120
|
})
|
|
@@ -204,6 +206,7 @@ describe('SchedulerService', () => {
|
|
|
204
206
|
...baseRegistration,
|
|
205
207
|
scopeType: 'tenant',
|
|
206
208
|
tenantId: 'tenant-1',
|
|
209
|
+
sourceType: 'user',
|
|
207
210
|
scheduleType: 'interval',
|
|
208
211
|
scheduleValue: '15m',
|
|
209
212
|
})).rejects.toMatchObject({
|
|
@@ -213,6 +216,7 @@ describe('SchedulerService', () => {
|
|
|
213
216
|
|
|
214
217
|
expect(mockForkedEm.count).toHaveBeenCalledWith(ScheduledJob, {
|
|
215
218
|
tenantId: 'tenant-1',
|
|
219
|
+
sourceType: 'user',
|
|
216
220
|
isEnabled: true,
|
|
217
221
|
deletedAt: null,
|
|
218
222
|
})
|
|
@@ -223,6 +227,58 @@ describe('SchedulerService', () => {
|
|
|
223
227
|
else process.env.OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT = originalLimit
|
|
224
228
|
}
|
|
225
229
|
})
|
|
230
|
+
|
|
231
|
+
it('does not apply the user schedule cap to module registrations', async () => {
|
|
232
|
+
mockForkedEm.findOne.mockResolvedValue(null)
|
|
233
|
+
mockForkedEm.count.mockResolvedValue(100)
|
|
234
|
+
mockForkedEm.flush.mockResolvedValue()
|
|
235
|
+
|
|
236
|
+
await service.register({
|
|
237
|
+
...baseRegistration,
|
|
238
|
+
scopeType: 'organization',
|
|
239
|
+
organizationId: 'organization-1',
|
|
240
|
+
tenantId: 'tenant-1',
|
|
241
|
+
scheduleType: 'interval',
|
|
242
|
+
scheduleValue: '15m',
|
|
243
|
+
})
|
|
244
|
+
|
|
245
|
+
expect(mockForkedEm.count).not.toHaveBeenCalled()
|
|
246
|
+
expect(mockForkedEm.create).toHaveBeenCalledWith(ScheduledJob, expect.objectContaining({
|
|
247
|
+
sourceType: 'module',
|
|
248
|
+
}))
|
|
249
|
+
expect(mockForkedEm.flush).toHaveBeenCalled()
|
|
250
|
+
})
|
|
251
|
+
|
|
252
|
+
it('applies the user schedule cap when reclassifying an enabled module schedule', async () => {
|
|
253
|
+
const existingSchedule = {
|
|
254
|
+
id: 'test-schedule-1',
|
|
255
|
+
sourceType: 'module',
|
|
256
|
+
isEnabled: true,
|
|
257
|
+
tenantId: 'tenant-1',
|
|
258
|
+
} as ScheduledJob
|
|
259
|
+
mockForkedEm.findOne.mockResolvedValue(existingSchedule)
|
|
260
|
+
mockForkedEm.count.mockResolvedValue(100)
|
|
261
|
+
|
|
262
|
+
await expect(service.register({
|
|
263
|
+
...baseRegistration,
|
|
264
|
+
scopeType: 'tenant',
|
|
265
|
+
tenantId: 'tenant-1',
|
|
266
|
+
sourceType: 'user',
|
|
267
|
+
scheduleType: 'interval',
|
|
268
|
+
scheduleValue: '15m',
|
|
269
|
+
})).rejects.toMatchObject({
|
|
270
|
+
status: 422,
|
|
271
|
+
body: { error: 'translated:scheduler.error.active_schedule_limit:max=100' },
|
|
272
|
+
})
|
|
273
|
+
|
|
274
|
+
expect(mockForkedEm.count).toHaveBeenCalledWith(ScheduledJob, {
|
|
275
|
+
tenantId: 'tenant-1',
|
|
276
|
+
sourceType: 'user',
|
|
277
|
+
isEnabled: true,
|
|
278
|
+
deletedAt: null,
|
|
279
|
+
})
|
|
280
|
+
expect(mockForkedEm.flush).not.toHaveBeenCalled()
|
|
281
|
+
})
|
|
226
282
|
})
|
|
227
283
|
|
|
228
284
|
describe('unregister', () => {
|
|
@@ -429,6 +485,7 @@ describe('SchedulerService', () => {
|
|
|
429
485
|
tenantId: 'tenant-1',
|
|
430
486
|
organizationId: null,
|
|
431
487
|
scopeType: 'tenant',
|
|
488
|
+
sourceType: 'user',
|
|
432
489
|
isEnabled: false,
|
|
433
490
|
scheduleType: 'interval',
|
|
434
491
|
scheduleValue: '15m',
|
|
@@ -445,6 +502,7 @@ describe('SchedulerService', () => {
|
|
|
445
502
|
|
|
446
503
|
expect(mockForkedEm.count).toHaveBeenCalledWith(ScheduledJob, {
|
|
447
504
|
tenantId: 'tenant-1',
|
|
505
|
+
sourceType: 'user',
|
|
448
506
|
isEnabled: true,
|
|
449
507
|
deletedAt: null,
|
|
450
508
|
})
|
|
@@ -456,6 +514,30 @@ describe('SchedulerService', () => {
|
|
|
456
514
|
}
|
|
457
515
|
})
|
|
458
516
|
|
|
517
|
+
it('does not apply the user schedule cap when enabling a module schedule', async () => {
|
|
518
|
+
const schedule = {
|
|
519
|
+
id: 'test-1',
|
|
520
|
+
tenantId: 'tenant-1',
|
|
521
|
+
organizationId: 'organization-1',
|
|
522
|
+
scopeType: 'organization',
|
|
523
|
+
sourceType: 'module',
|
|
524
|
+
isEnabled: false,
|
|
525
|
+
scheduleType: 'interval',
|
|
526
|
+
scheduleValue: '15m',
|
|
527
|
+
timezone: 'UTC',
|
|
528
|
+
} as ScheduledJob
|
|
529
|
+
|
|
530
|
+
mockForkedEm.findOne.mockResolvedValue(schedule)
|
|
531
|
+
mockForkedEm.count.mockResolvedValue(100)
|
|
532
|
+
mockForkedEm.flush.mockResolvedValue()
|
|
533
|
+
|
|
534
|
+
await service.update('test-1', { isEnabled: true })
|
|
535
|
+
|
|
536
|
+
expect(mockForkedEm.count).not.toHaveBeenCalled()
|
|
537
|
+
expect(schedule.isEnabled).toBe(true)
|
|
538
|
+
expect(mockForkedEm.flush).toHaveBeenCalled()
|
|
539
|
+
})
|
|
540
|
+
|
|
459
541
|
it('should reject interval updates below one minute', async () => {
|
|
460
542
|
const nextRunAt = new Date('2026-01-01T00:15:00.000Z')
|
|
461
543
|
const schedule = {
|
|
@@ -64,9 +64,11 @@ export class SchedulerService {
|
|
|
64
64
|
// Check if schedule already exists
|
|
65
65
|
let schedule = await em.findOne(ScheduledJob, { id: registration.id })
|
|
66
66
|
const nextTenantId = registration.tenantId || null
|
|
67
|
+
const nextSourceType = registration.sourceType ?? 'module'
|
|
67
68
|
const nextIsEnabled = registration.isEnabled !== undefined ? registration.isEnabled : (schedule?.isEnabled ?? true)
|
|
68
69
|
const tenantChanged = schedule ? (schedule.tenantId || null) !== nextTenantId : false
|
|
69
|
-
|
|
70
|
+
const changedToUserSource = schedule?.sourceType !== 'user' && nextSourceType === 'user'
|
|
71
|
+
if (nextSourceType === 'user' && nextIsEnabled && (schedule?.isEnabled !== true || tenantChanged || changedToUserSource)) {
|
|
70
72
|
await enforceTenantActiveScheduleLimit(em, nextTenantId)
|
|
71
73
|
}
|
|
72
74
|
|
|
@@ -85,7 +87,7 @@ export class SchedulerService {
|
|
|
85
87
|
schedule.targetCommand = registration.targetCommand || null
|
|
86
88
|
schedule.targetPayload = registration.targetPayload as Record<string, unknown> || null
|
|
87
89
|
schedule.requireFeature = registration.requireFeature || null
|
|
88
|
-
schedule.sourceType =
|
|
90
|
+
schedule.sourceType = nextSourceType
|
|
89
91
|
schedule.sourceModule = registration.sourceModule || null
|
|
90
92
|
schedule.isEnabled = registration.isEnabled !== undefined ? registration.isEnabled : schedule.isEnabled
|
|
91
93
|
schedule.nextRunAt = nextRunAt
|
|
@@ -107,7 +109,7 @@ export class SchedulerService {
|
|
|
107
109
|
targetCommand: registration.targetCommand || null,
|
|
108
110
|
targetPayload: registration.targetPayload as Record<string, unknown> || null,
|
|
109
111
|
requireFeature: registration.requireFeature || null,
|
|
110
|
-
sourceType:
|
|
112
|
+
sourceType: nextSourceType,
|
|
111
113
|
sourceModule: registration.sourceModule || null,
|
|
112
114
|
isEnabled: registration.isEnabled !== undefined ? registration.isEnabled : true,
|
|
113
115
|
nextRunAt,
|
|
@@ -178,7 +180,7 @@ export class SchedulerService {
|
|
|
178
180
|
throw new Error(`Schedule not found: ${scheduleId}`)
|
|
179
181
|
}
|
|
180
182
|
|
|
181
|
-
if (changes.isEnabled === true && schedule.isEnabled !== true) {
|
|
183
|
+
if (schedule.sourceType === 'user' && changes.isEnabled === true && schedule.isEnabled !== true) {
|
|
182
184
|
await enforceTenantActiveScheduleLimit(em, schedule.tenantId)
|
|
183
185
|
}
|
|
184
186
|
|