@open-mercato/scheduler 0.6.7-develop.6696.1.4236709f7e → 0.6.7-develop.6725.1.07a748cfc2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/scheduler/__integration__/TC-SCHED-007.spec.js +4 -1
  3. package/dist/modules/scheduler/__integration__/TC-SCHED-007.spec.js.map +2 -2
  4. package/dist/modules/scheduler/commands/jobs.js +20 -11
  5. package/dist/modules/scheduler/commands/jobs.js.map +2 -2
  6. package/dist/modules/scheduler/lib/activeScheduleLimits.js +29 -0
  7. package/dist/modules/scheduler/lib/activeScheduleLimits.js.map +7 -0
  8. package/dist/modules/scheduler/lib/intervalParser.js +8 -3
  9. package/dist/modules/scheduler/lib/intervalParser.js.map +2 -2
  10. package/dist/modules/scheduler/lib/nextRunCalculator.js +8 -1
  11. package/dist/modules/scheduler/lib/nextRunCalculator.js.map +2 -2
  12. package/dist/modules/scheduler/services/bullmqSchedulerService.js +2 -2
  13. package/dist/modules/scheduler/services/bullmqSchedulerService.js.map +2 -2
  14. package/dist/modules/scheduler/services/schedulerService.js +23 -11
  15. package/dist/modules/scheduler/services/schedulerService.js.map +2 -2
  16. package/package.json +5 -5
  17. package/src/modules/scheduler/__integration__/TC-SCHED-007.spec.ts +6 -4
  18. package/src/modules/scheduler/commands/__tests__/jobs.active-limit.test.ts +173 -0
  19. package/src/modules/scheduler/commands/jobs.ts +26 -12
  20. package/src/modules/scheduler/data/__tests__/validators.test.ts +29 -1
  21. package/src/modules/scheduler/lib/__tests__/intervalParser.test.ts +27 -9
  22. package/src/modules/scheduler/lib/__tests__/nextRunCalculator.test.ts +18 -7
  23. package/src/modules/scheduler/lib/activeScheduleLimits.ts +32 -0
  24. package/src/modules/scheduler/lib/intervalParser.ts +8 -3
  25. package/src/modules/scheduler/lib/nextRunCalculator.ts +14 -1
  26. package/src/modules/scheduler/services/__tests__/bullmqSchedulerService.test.ts +36 -0
  27. package/src/modules/scheduler/services/__tests__/schedulerService.test.ts +87 -0
  28. package/src/modules/scheduler/services/bullmqSchedulerService.ts +2 -2
  29. package/src/modules/scheduler/services/schedulerService.ts +27 -12
@@ -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 { calculateNextRun } from '../lib/nextRunCalculator.js'\nimport type { BullMQSchedulerService } from './bullmqSchedulerService.js'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\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 = calculateNextRun(\n registration.scheduleType,\n registration.scheduleValue,\n registration.timezone || 'UTC'\n )\n \n if (!nextRunAt) {\n throw new Error(`Failed to calculate next run time for schedule: ${registration.id}`)\n }\n \n // Check if schedule already exists\n let schedule = await em.findOne(ScheduledJob, { id: registration.id })\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 // 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 // Recalculate next run if schedule changed\n if (changes.scheduleType !== undefined || changes.scheduleValue !== undefined || changes.timezone !== undefined) {\n const nextRunAt = calculateNextRun(\n schedule.scheduleType,\n schedule.scheduleValue,\n schedule.timezone\n )\n if (nextRunAt) {\n schedule.nextRunAt = nextRunAt\n }\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,wBAAwB;AAEjC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAsBhC,MAAM,iBAAiB;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AI,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;",
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'\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 new Error(`Failed to calculate next run time for schedule: ${registration.id}`)\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 new Error(`Failed to calculate next run time for schedule: ${scheduleId}`)\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;AAE7B,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,IAAI,MAAM,mDAAmD,aAAa,EAAE,EAAE;AAAA,IACtF;AAGA,QAAI,WAAW,MAAM,GAAG,QAAQ,cAAc,EA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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.6.7-develop.6696.1.4236709f7e",
3
+ "version": "0.6.7-develop.6725.1.07a748cfc2",
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.6.7-develop.6696.1.4236709f7e",
63
- "@open-mercato/queue": "0.6.7-develop.6696.1.4236709f7e",
62
+ "@open-mercato/events": "0.6.7-develop.6725.1.07a748cfc2",
63
+ "@open-mercato/queue": "0.6.7-develop.6725.1.07a748cfc2",
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.6.7-develop.6696.1.4236709f7e",
68
+ "@open-mercato/shared": "0.6.7-develop.6725.1.07a748cfc2",
69
69
  "bullmq": "^5.0.0",
70
70
  "ioredis": "^5.0.0",
71
71
  "zod": ">=3.23.0"
@@ -79,7 +79,7 @@
79
79
  }
80
80
  },
81
81
  "devDependencies": {
82
- "@open-mercato/shared": "0.6.7-develop.6696.1.4236709f7e",
82
+ "@open-mercato/shared": "0.6.7-develop.6725.1.07a748cfc2",
83
83
  "@types/jest": "^30.0.0",
84
84
  "@types/node": "^26.0.1",
85
85
  "jest": "^30.4.2",
@@ -9,16 +9,18 @@ type ValidationError = { error?: string; details?: Array<{ path?: Array<string |
9
9
  * TC-SCHED-007: POST /api/scheduler/jobs rejects invalid cron and interval
10
10
  * `scheduleValue`s with 400 and an error scoped to the `scheduleValue` path.
11
11
  *
12
- * Interval format is `<number><unit>` with unit in s|m|h|d, so the inputs below
13
- * are genuinely malformed (the issue's "99h"/"0m" drafts are actually valid).
14
- * All cases are rejected at validation, so no records are created and no
15
- * teardown is required.
12
+ * Interval format is `<number><unit>` with unit in s|m|h|d and a minimum floor
13
+ * of one minute. All cases are rejected at validation, so no records are
14
+ * created and no teardown is required.
16
15
  */
17
16
  const invalidCases = [
18
17
  { label: 'cron: not a cron expression', scheduleType: 'cron' as const, scheduleValue: 'not-a-cron' },
19
18
  { label: 'cron: too few fields', scheduleType: 'cron' as const, scheduleValue: '* * *' },
20
19
  { label: 'interval: unsupported unit', scheduleType: 'interval' as const, scheduleValue: '15x' },
21
20
  { label: 'interval: missing unit', scheduleType: 'interval' as const, scheduleValue: '99' },
21
+ { label: 'interval: zero seconds', scheduleType: 'interval' as const, scheduleValue: '0s' },
22
+ { label: 'interval: one second', scheduleType: 'interval' as const, scheduleValue: '1s' },
23
+ { label: 'interval: below one minute', scheduleType: 'interval' as const, scheduleValue: '59s' },
22
24
  ]
23
25
 
24
26
  test.describe('TC-SCHED-007: POST /api/scheduler/jobs validates schedule value format', () => {
@@ -0,0 +1,173 @@
1
+ import type { CommandHandler, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'
2
+ import type { ScheduleCreateInput, ScheduleUpdateInput } from '../../data/validators.js'
3
+
4
+ const registerCommand = jest.fn()
5
+
6
+ jest.mock('@open-mercato/shared/lib/commands', () => ({
7
+ registerCommand,
8
+ }))
9
+
10
+ jest.mock('@open-mercato/shared/lib/i18n/server', () => ({
11
+ resolveTranslations: jest.fn().mockResolvedValue({
12
+ translate: (_key: string, fallback?: string) => fallback ?? _key,
13
+ }),
14
+ }))
15
+
16
+ function loadCommands() {
17
+ let create: CommandHandler<ScheduleCreateInput, { id: string }> | undefined
18
+ let update: CommandHandler<ScheduleUpdateInput, { ok: boolean }> | undefined
19
+ jest.isolateModules(() => {
20
+ require('../jobs')
21
+ create = registerCommand.mock.calls.find(([command]) => command.id === 'scheduler.jobs.create')?.[0]
22
+ update = registerCommand.mock.calls.find(([command]) => command.id === 'scheduler.jobs.update')?.[0]
23
+ })
24
+ if (!create || !update) throw new Error('[internal] Scheduler commands were not registered')
25
+ return { create, update }
26
+ }
27
+
28
+ function makeEm(schedule: Record<string, unknown> | null) {
29
+ return {
30
+ fork: jest.fn().mockReturnThis(),
31
+ findOne: jest.fn().mockResolvedValue(schedule),
32
+ count: jest.fn(),
33
+ create: jest.fn((_entity: unknown, data: Record<string, unknown>) => ({ id: 'new-job', ...data })),
34
+ persist: jest.fn(),
35
+ flush: jest.fn().mockResolvedValue(undefined),
36
+ }
37
+ }
38
+
39
+ function makeCtx(em: ReturnType<typeof makeEm>): CommandRuntimeContext {
40
+ return {
41
+ auth: { isSuperAdmin: false, tenantId: 'tenant-a', orgId: 'org-a' },
42
+ container: { resolve: jest.fn(() => em) },
43
+ } as unknown as CommandRuntimeContext
44
+ }
45
+
46
+ function createInput(overrides: Record<string, unknown> = {}) {
47
+ return {
48
+ name: 'Tenant schedule',
49
+ scopeType: 'tenant',
50
+ tenantId: 'tenant-a',
51
+ scheduleType: 'interval',
52
+ scheduleValue: '15m',
53
+ targetType: 'queue',
54
+ targetQueue: 'scheduler',
55
+ isEnabled: true,
56
+ ...overrides,
57
+ }
58
+ }
59
+
60
+ describe('scheduler.jobs active schedule tenant limit', () => {
61
+ const originalLimit = process.env.OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT
62
+
63
+ beforeEach(() => {
64
+ jest.clearAllMocks()
65
+ jest.resetModules()
66
+ process.env.OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT = '2'
67
+ })
68
+
69
+ afterEach(() => {
70
+ if (originalLimit === undefined) delete process.env.OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT
71
+ else process.env.OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT = originalLimit
72
+ })
73
+
74
+ it('rejects creating an enabled tenant-scoped schedule after the tenant reaches the active cap', async () => {
75
+ const { create } = loadCommands()
76
+ const em = makeEm(null)
77
+ em.count.mockResolvedValue(2)
78
+
79
+ await expect(create.execute(createInput(), makeCtx(em))).rejects.toMatchObject({ status: 422 })
80
+
81
+ expect(em.count).toHaveBeenCalledWith(expect.any(Function), {
82
+ tenantId: 'tenant-a',
83
+ isEnabled: true,
84
+ deletedAt: null,
85
+ })
86
+ expect(em.persist).not.toHaveBeenCalled()
87
+ expect(em.flush).not.toHaveBeenCalled()
88
+ })
89
+
90
+ it('rejects direct command creates below the interval floor', async () => {
91
+ const { create } = loadCommands()
92
+ const em = makeEm(null)
93
+ em.count.mockResolvedValue(0)
94
+
95
+ await expect(create.execute(createInput({ scheduleValue: '1s' }), makeCtx(em))).rejects.toThrow(
96
+ 'Failed to calculate next run time',
97
+ )
98
+
99
+ expect(em.persist).not.toHaveBeenCalled()
100
+ expect(em.flush).not.toHaveBeenCalled()
101
+ })
102
+
103
+ it('rejects enabling a disabled tenant-scoped schedule after the tenant reaches the active cap', async () => {
104
+ const { update } = loadCommands()
105
+ const schedule = {
106
+ id: 'job-1',
107
+ tenantId: 'tenant-a',
108
+ organizationId: null,
109
+ scopeType: 'tenant',
110
+ isEnabled: false,
111
+ scheduleType: 'interval',
112
+ scheduleValue: '15m',
113
+ timezone: 'UTC',
114
+ }
115
+ const em = makeEm(schedule)
116
+ em.count.mockResolvedValue(2)
117
+
118
+ await expect(update.execute({ id: 'job-1', isEnabled: true }, makeCtx(em))).rejects.toMatchObject({ status: 422 })
119
+
120
+ expect(em.count).toHaveBeenCalledWith(expect.any(Function), {
121
+ tenantId: 'tenant-a',
122
+ isEnabled: true,
123
+ deletedAt: null,
124
+ })
125
+ expect(schedule.isEnabled).toBe(false)
126
+ expect(em.flush).not.toHaveBeenCalled()
127
+ })
128
+
129
+ it('does not count an already-enabled schedule when updating other fields', async () => {
130
+ const { update } = loadCommands()
131
+ const schedule = {
132
+ id: 'job-1',
133
+ tenantId: 'tenant-a',
134
+ organizationId: null,
135
+ scopeType: 'tenant',
136
+ isEnabled: true,
137
+ scheduleType: 'interval',
138
+ scheduleValue: '15m',
139
+ timezone: 'UTC',
140
+ }
141
+ const em = makeEm(schedule)
142
+
143
+ await expect(update.execute({ id: 'job-1', name: 'Renamed' }, makeCtx(em))).resolves.toEqual({ ok: true })
144
+
145
+ expect(em.count).not.toHaveBeenCalled()
146
+ expect(schedule.name).toBe('Renamed')
147
+ expect(em.flush).toHaveBeenCalled()
148
+ })
149
+
150
+ it('rejects direct command interval updates below one minute', async () => {
151
+ const { update } = loadCommands()
152
+ const schedule = {
153
+ id: 'job-1',
154
+ tenantId: 'tenant-a',
155
+ organizationId: null,
156
+ scopeType: 'tenant',
157
+ isEnabled: true,
158
+ scheduleType: 'interval',
159
+ scheduleValue: '15m',
160
+ timezone: 'UTC',
161
+ nextRunAt: new Date('2026-01-01T00:15:00.000Z'),
162
+ }
163
+ const em = makeEm(schedule)
164
+
165
+ await expect(
166
+ update.execute({ id: 'job-1', scheduleType: 'interval', scheduleValue: '1s' }, makeCtx(em)),
167
+ ).rejects.toMatchObject({ status: 422 })
168
+
169
+ expect(schedule.scheduleValue).toBe('15m')
170
+ expect(schedule.nextRunAt).toEqual(new Date('2026-01-01T00:15:00.000Z'))
171
+ expect(em.flush).not.toHaveBeenCalled()
172
+ })
173
+ })
@@ -6,7 +6,8 @@ import { ensureOrganizationScope } from '@open-mercato/shared/lib/commands/scope
6
6
  import { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'
7
7
  import type { EntityManager } from '@mikro-orm/core'
8
8
  import { ScheduledJob } from '../data/entities.js'
9
- import { calculateNextRun } from '../lib/nextRunCalculator.js'
9
+ import { calculateNextRunForWrite } from '../lib/nextRunCalculator.js'
10
+ import { enforceTenantActiveScheduleLimit } from '../lib/activeScheduleLimits.js'
10
11
  import type {
11
12
  ScheduleCreateInput,
12
13
  ScheduleUpdateInput,
@@ -188,8 +189,12 @@ const createScheduleCommand: CommandHandler<ScheduleCreateInput, { id: string }>
188
189
 
189
190
  const em = ctx.container.resolve<EntityManager>('em').fork()
190
191
 
192
+ if (input.isEnabled ?? true) {
193
+ await enforceTenantActiveScheduleLimit(em, input.tenantId)
194
+ }
195
+
191
196
  // Calculate next run time
192
- const nextRunAt = calculateNextRun(
197
+ const nextRunAt = calculateNextRunForWrite(
193
198
  input.scheduleType,
194
199
  input.scheduleValue,
195
200
  input.timezone || 'UTC'
@@ -297,6 +302,23 @@ const updateScheduleCommand: CommandHandler<ScheduleUpdateInput, { ok: boolean }
297
302
  if (schedule.organizationId) ensureOrganizationScope(ctx, schedule.organizationId)
298
303
  ensureCanManageSystemScopedJob(ctx, schedule)
299
304
 
305
+ if (input.isEnabled === true && schedule.isEnabled !== true) {
306
+ await enforceTenantActiveScheduleLimit(em, schedule.tenantId)
307
+ }
308
+
309
+ const scheduleChanged = input.scheduleType !== undefined || input.scheduleValue !== undefined || input.timezone !== undefined
310
+ const nextRunAt = scheduleChanged
311
+ ? calculateNextRunForWrite(
312
+ input.scheduleType ?? schedule.scheduleType,
313
+ input.scheduleValue ?? schedule.scheduleValue,
314
+ input.timezone ?? schedule.timezone,
315
+ )
316
+ : null
317
+
318
+ if (scheduleChanged && !nextRunAt) {
319
+ throw new CrudHttpError(422, { error: 'Invalid schedule value.' })
320
+ }
321
+
300
322
  // Update fields
301
323
  if (input.name !== undefined) schedule.name = input.name
302
324
  if (input.description !== undefined) schedule.description = input.description ?? null
@@ -326,16 +348,8 @@ const updateScheduleCommand: CommandHandler<ScheduleUpdateInput, { ok: boolean }
326
348
  if (input.targetCommand !== undefined) schedule.targetCommand = input.targetCommand
327
349
  }
328
350
 
329
- // Recalculate next run if schedule changed
330
- if (input.scheduleType !== undefined || input.scheduleValue !== undefined || input.timezone !== undefined) {
331
- const nextRunAt = calculateNextRun(
332
- schedule.scheduleType,
333
- schedule.scheduleValue,
334
- schedule.timezone
335
- )
336
- if (nextRunAt) {
337
- schedule.nextRunAt = nextRunAt
338
- }
351
+ if (nextRunAt) {
352
+ schedule.nextRunAt = nextRunAt
339
353
  }
340
354
 
341
355
  schedule.updatedAt = new Date()
@@ -126,7 +126,8 @@ describe('scheduleCreateSchema', () => {
126
126
 
127
127
  it('should accept various interval formats', () => {
128
128
  const validIntervals = [
129
- '30s', // 30 seconds
129
+ '60s', // 60 seconds
130
+ '1m', // 1 minute
130
131
  '15m', // 15 minutes
131
132
  '2h', // 2 hours
132
133
  '1d', // 1 day
@@ -324,6 +325,23 @@ describe('scheduleCreateSchema', () => {
324
325
  })
325
326
  ).toThrow(/Invalid schedule value/)
326
327
  })
328
+
329
+ it('should reject interval values below one minute', () => {
330
+ const subMinuteIntervals = ['0s', '1s', '59s', '0m']
331
+
332
+ subMinuteIntervals.forEach(scheduleValue => {
333
+ expect(() =>
334
+ scheduleCreateSchema.parse({
335
+ name: 'Invalid',
336
+ scopeType: 'system',
337
+ scheduleType: 'interval',
338
+ scheduleValue,
339
+ targetType: 'queue',
340
+ targetQueue: 'test',
341
+ })
342
+ ).toThrow(/Invalid schedule value/)
343
+ })
344
+ })
327
345
  })
328
346
 
329
347
  describe('field constraints', () => {
@@ -436,6 +454,16 @@ describe('scheduleUpdateSchema', () => {
436
454
  ).toThrow(/Invalid schedule value/)
437
455
  })
438
456
 
457
+ it('should reject interval values below one minute when updating', () => {
458
+ expect(() =>
459
+ scheduleUpdateSchema.parse({
460
+ id: scheduleId,
461
+ scheduleType: 'interval',
462
+ scheduleValue: '1s',
463
+ })
464
+ ).toThrow(/Invalid schedule value/)
465
+ })
466
+
439
467
  it('should require targetQueue when changing to queue target', () => {
440
468
  expect(() =>
441
469
  scheduleUpdateSchema.parse({
@@ -1,6 +1,7 @@
1
1
  import { describe, it, expect } from '@jest/globals'
2
2
  import {
3
3
  parseInterval,
4
+ resolveScheduleIntervalMs,
4
5
  calculateNextRunFromInterval,
5
6
  validateInterval,
6
7
  intervalToHuman,
@@ -10,9 +11,8 @@ describe('intervalParser', () => {
10
11
  describe('parseInterval', () => {
11
12
  describe('seconds', () => {
12
13
  it('should parse seconds correctly', () => {
13
- expect(parseInterval('30s')).toBe(30 * 1000)
14
- expect(parseInterval('1s')).toBe(1000)
15
14
  expect(parseInterval('60s')).toBe(60 * 1000)
15
+ expect(parseInterval('90s')).toBe(90 * 1000)
16
16
  })
17
17
  })
18
18
 
@@ -86,8 +86,10 @@ describe('intervalParser', () => {
86
86
  })
87
87
 
88
88
  describe('edge cases', () => {
89
- it('should handle zero', () => {
89
+ it('should preserve parsing for legacy intervals below one minute', () => {
90
90
  expect(parseInterval('0s')).toBe(0)
91
+ expect(parseInterval('1s')).toBe(1000)
92
+ expect(parseInterval('59s')).toBe(59 * 1000)
91
93
  expect(parseInterval('0m')).toBe(0)
92
94
  expect(parseInterval('0h')).toBe(0)
93
95
  expect(parseInterval('0d')).toBe(0)
@@ -102,6 +104,16 @@ describe('intervalParser', () => {
102
104
  })
103
105
  })
104
106
 
107
+ describe('resolveScheduleIntervalMs', () => {
108
+ it('should clamp legacy sub-minute intervals to one minute', () => {
109
+ expect(resolveScheduleIntervalMs('0s')).toBe(60 * 1000)
110
+ expect(resolveScheduleIntervalMs('10s')).toBe(60 * 1000)
111
+ expect(resolveScheduleIntervalMs('59s')).toBe(60 * 1000)
112
+ expect(resolveScheduleIntervalMs('60s')).toBe(60 * 1000)
113
+ expect(resolveScheduleIntervalMs('15m')).toBe(15 * 60 * 1000)
114
+ })
115
+ })
116
+
105
117
  describe('calculateNextRunFromInterval', () => {
106
118
  it('should calculate next run from current time', () => {
107
119
  const before = new Date()
@@ -122,9 +134,9 @@ describe('intervalParser', () => {
122
134
 
123
135
  it('should handle seconds intervals', () => {
124
136
  const baseDate = new Date('2025-01-27T12:00:00Z')
125
- const nextRun = calculateNextRunFromInterval('30s', baseDate)
137
+ const nextRun = calculateNextRunFromInterval('60s', baseDate)
126
138
 
127
- expect(nextRun).toEqual(new Date('2025-01-27T12:00:30Z'))
139
+ expect(nextRun).toEqual(new Date('2025-01-27T12:01:00Z'))
128
140
  })
129
141
 
130
142
  it('should handle minute intervals', () => {
@@ -179,15 +191,19 @@ describe('intervalParser', () => {
179
191
 
180
192
  describe('validateInterval', () => {
181
193
  it('should return true for valid intervals', () => {
182
- expect(validateInterval('30s')).toBe(true)
194
+ expect(validateInterval('60s')).toBe(true)
195
+ expect(validateInterval('1m')).toBe(true)
183
196
  expect(validateInterval('15m')).toBe(true)
184
197
  expect(validateInterval('2h')).toBe(true)
185
198
  expect(validateInterval('1d')).toBe(true)
186
- expect(validateInterval('0s')).toBe(true)
187
199
  expect(validateInterval('999d')).toBe(true)
188
200
  })
189
201
 
190
202
  it('should return false for invalid intervals', () => {
203
+ expect(validateInterval('0s')).toBe(false)
204
+ expect(validateInterval('1s')).toBe(false)
205
+ expect(validateInterval('59s')).toBe(false)
206
+ expect(validateInterval('0m')).toBe(false)
191
207
  expect(validateInterval('invalid')).toBe(false)
192
208
  expect(validateInterval('')).toBe(false)
193
209
  expect(validateInterval('15')).toBe(false)
@@ -204,7 +220,8 @@ describe('intervalParser', () => {
204
220
  it('should convert seconds to human readable', () => {
205
221
  expect(intervalToHuman('1s')).toBe('1 second')
206
222
  expect(intervalToHuman('30s')).toBe('30 seconds')
207
- expect(intervalToHuman('59s')).toBe('59 seconds')
223
+ expect(intervalToHuman('60s')).toBe('60 seconds')
224
+ expect(intervalToHuman('90s')).toBe('90 seconds')
208
225
  })
209
226
  })
210
227
 
@@ -260,6 +277,7 @@ describe('intervalParser', () => {
260
277
  it('should use plural for other numbers', () => {
261
278
  expect(intervalToHuman('0s')).toBe('0 seconds')
262
279
  expect(intervalToHuman('2s')).toBe('2 seconds')
280
+ expect(intervalToHuman('60s')).toBe('60 seconds')
263
281
  expect(intervalToHuman('2m')).toBe('2 minutes')
264
282
  expect(intervalToHuman('2h')).toBe('2 hours')
265
283
  expect(intervalToHuman('2d')).toBe('2 days')
@@ -300,7 +318,7 @@ describe('intervalParser', () => {
300
318
 
301
319
  describe('integration', () => {
302
320
  it('should work end-to-end for various intervals', () => {
303
- const intervals = ['30s', '15m', '2h', '1d']
321
+ const intervals = ['60s', '15m', '2h', '1d']
304
322
 
305
323
  intervals.forEach(interval => {
306
324
  expect(validateInterval(interval)).toBe(true)
@@ -73,9 +73,9 @@ describe('nextRunCalculator', () => {
73
73
 
74
74
  it('should handle seconds', () => {
75
75
  const fromDate = new Date('2025-01-27T12:00:00Z')
76
- const result = calculateNextRun('interval', '30s', 'UTC', fromDate)
76
+ const result = calculateNextRun('interval', '60s', 'UTC', fromDate)
77
77
 
78
- expect(result).toEqual(new Date('2025-01-27T12:00:30Z'))
78
+ expect(result).toEqual(new Date('2025-01-27T12:01:00Z'))
79
79
  })
80
80
 
81
81
  it('should handle minutes', () => {
@@ -223,10 +223,10 @@ describe('nextRunCalculator', () => {
223
223
  it('should handle various intervals', () => {
224
224
  const before = Date.now()
225
225
 
226
- const result30s = recalculateNextRun('interval', '30s')
227
- const diff30s = result30s!.getTime() - before
228
- expect(diff30s).toBeGreaterThanOrEqual(30 * 1000 - 500)
229
- expect(diff30s).toBeLessThanOrEqual(30 * 1000 + 500)
226
+ const result60s = recalculateNextRun('interval', '60s')
227
+ const diff60s = result60s!.getTime() - before
228
+ expect(diff60s).toBeGreaterThanOrEqual(60 * 1000 - 500)
229
+ expect(diff60s).toBeLessThanOrEqual(60 * 1000 + 500)
230
230
 
231
231
  const result15m = recalculateNextRun('interval', '15m')
232
232
  const diff15m = result15m!.getTime() - before
@@ -310,6 +310,17 @@ describe('nextRunCalculator', () => {
310
310
 
311
311
  expect(result).toBeNull()
312
312
  })
313
+
314
+ it('should clamp legacy interval values below one minute', () => {
315
+ const before = Date.now()
316
+
317
+ for (const scheduleValue of ['0s', '1s', '59s']) {
318
+ const result = recalculateNextRun('interval', scheduleValue)
319
+ const intervalMs = result!.getTime() - before
320
+ expect(intervalMs).toBeGreaterThanOrEqual(60 * 1000 - 500)
321
+ expect(intervalMs).toBeLessThanOrEqual(60 * 1000 + 500)
322
+ }
323
+ })
313
324
  })
314
325
  })
315
326
 
@@ -341,7 +352,7 @@ describe('nextRunCalculator', () => {
341
352
  { type: 'cron' as const, value: '0 0 * * *' }, // Daily at midnight
342
353
  { type: 'cron' as const, value: '*/5 * * * *' }, // Every 5 minutes
343
354
  { type: 'cron' as const, value: '0 9-17 * * 1-5' }, // Weekdays 9am-5pm
344
- { type: 'interval' as const, value: '30s' },
355
+ { type: 'interval' as const, value: '60s' },
345
356
  { type: 'interval' as const, value: '15m' },
346
357
  { type: 'interval' as const, value: '2h' },
347
358
  { type: 'interval' as const, value: '1d' },
@@ -0,0 +1,32 @@
1
+ import type { EntityManager } from '@mikro-orm/core'
2
+ import { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'
3
+ import { ScheduledJob } from '../data/entities.js'
4
+
5
+ export const DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT = 100
6
+ const ACTIVE_SCHEDULE_LIMIT_ENV = 'OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT'
7
+
8
+ export function getMaxActiveSchedulesPerTenant(): number {
9
+ const parsed = Number.parseInt(process.env[ACTIVE_SCHEDULE_LIMIT_ENV] ?? '', 10)
10
+ if (Number.isFinite(parsed) && parsed > 0) return parsed
11
+ return DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT
12
+ }
13
+
14
+ export async function enforceTenantActiveScheduleLimit(
15
+ em: EntityManager,
16
+ tenantId: string | null | undefined,
17
+ ): Promise<void> {
18
+ if (!tenantId) return
19
+
20
+ const maxActiveSchedules = getMaxActiveSchedulesPerTenant()
21
+ const activeScheduleCount = await em.count(ScheduledJob, {
22
+ tenantId,
23
+ isEnabled: true,
24
+ deletedAt: null,
25
+ })
26
+
27
+ if (activeScheduleCount >= maxActiveSchedules) {
28
+ throw new CrudHttpError(422, {
29
+ error: `Active scheduled job limit reached for this tenant (${maxActiveSchedules}).`,
30
+ })
31
+ }
32
+ }
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * Parse simple interval strings like '15m', '2h', '1d' into milliseconds
3
3
  */
4
+ export const MIN_SCHEDULE_INTERVAL_MS = 60 * 1000
5
+
4
6
  export function parseInterval(interval: string): number {
5
7
  const regex = /^(\d+)(s|m|h|d)$/
6
8
  const match = interval.match(regex)
@@ -22,6 +24,10 @@ export function parseInterval(interval: string): number {
22
24
  return value * multipliers[unit]
23
25
  }
24
26
 
27
+ export function resolveScheduleIntervalMs(interval: string): number {
28
+ return Math.max(parseInterval(interval), MIN_SCHEDULE_INTERVAL_MS)
29
+ }
30
+
25
31
  /**
26
32
  * Calculate next run time based on interval
27
33
  */
@@ -29,7 +35,7 @@ export function calculateNextRunFromInterval(
29
35
  interval: string,
30
36
  fromDate: Date = new Date()
31
37
  ): Date {
32
- const ms = parseInterval(interval)
38
+ const ms = resolveScheduleIntervalMs(interval)
33
39
  return new Date(fromDate.getTime() + ms)
34
40
  }
35
41
 
@@ -38,8 +44,7 @@ export function calculateNextRunFromInterval(
38
44
  */
39
45
  export function validateInterval(interval: string): boolean {
40
46
  try {
41
- parseInterval(interval)
42
- return true
47
+ return parseInterval(interval) >= MIN_SCHEDULE_INTERVAL_MS
43
48
  } catch {
44
49
  return false
45
50
  }