@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,5 +1,5 @@
1
1
  import { parseCronExpression } from './cronParser.js'
2
- import { calculateNextRunFromInterval } from './intervalParser.js'
2
+ import { calculateNextRunFromInterval, validateInterval } from './intervalParser.js'
3
3
 
4
4
  /**
5
5
  * Calculate the next run time for a schedule
@@ -28,6 +28,19 @@ export function calculateNextRun(
28
28
  return null
29
29
  }
30
30
 
31
+ export function calculateNextRunForWrite(
32
+ scheduleType: 'cron' | 'interval',
33
+ scheduleValue: string,
34
+ timezone: string = 'UTC',
35
+ fromDate?: Date,
36
+ ): Date | null {
37
+ if (scheduleType === 'interval' && !validateInterval(scheduleValue)) {
38
+ return null
39
+ }
40
+
41
+ return calculateNextRun(scheduleType, scheduleValue, timezone, fromDate)
42
+ }
43
+
31
44
  /**
32
45
  * Recalculate next run for a schedule after execution
33
46
  */
@@ -413,6 +413,42 @@ describe('BullMQSchedulerService', () => {
413
413
  )
414
414
  })
415
415
 
416
+ it('should clamp a legacy sub-minute schedule and continue registering the batch', async () => {
417
+ const dbSchedules = [
418
+ { id: 'legacy', name: 'Legacy', isEnabled: true, scheduleType: 'interval', scheduleValue: '10s', timezone: 'UTC', scopeType: 'system' },
419
+ { id: 'current', name: 'Current', isEnabled: true, scheduleType: 'cron', scheduleValue: '0 0 * * *', timezone: 'UTC', scopeType: 'system' },
420
+ ] as ScheduledJob[]
421
+
422
+ mockForkedEm.find.mockResolvedValue(dbSchedules)
423
+ mockQueue.getRepeatableJobs.mockResolvedValue([])
424
+
425
+ await service.syncAll()
426
+
427
+ expect(mockQueue.add).toHaveBeenCalledTimes(2)
428
+ expect(mockQueue.add).toHaveBeenNthCalledWith(
429
+ 1,
430
+ 'schedule-legacy',
431
+ expect.any(Object),
432
+ expect.objectContaining({
433
+ repeat: {
434
+ every: 60 * 1000,
435
+ tz: 'UTC',
436
+ },
437
+ }),
438
+ )
439
+ expect(mockQueue.add).toHaveBeenNthCalledWith(
440
+ 2,
441
+ 'schedule-current',
442
+ expect.any(Object),
443
+ expect.objectContaining({
444
+ repeat: {
445
+ pattern: '0 0 * * *',
446
+ tz: 'UTC',
447
+ },
448
+ }),
449
+ )
450
+ })
451
+
416
452
  it('should remove orphaned BullMQ jobs', async () => {
417
453
  const dbSchedules = [
418
454
  { id: 'schedule-1', name: 'Schedule 1', isEnabled: true },
@@ -184,6 +184,34 @@ describe('SchedulerService', () => {
184
184
  timezone: 'America/New_York',
185
185
  }))
186
186
  })
187
+
188
+ it('should reject a new enabled tenant schedule when the tenant active cap is reached', async () => {
189
+ const originalLimit = process.env.OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT
190
+ process.env.OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT = '2'
191
+ try {
192
+ mockForkedEm.findOne.mockResolvedValue(null)
193
+ mockForkedEm.count.mockResolvedValue(2)
194
+
195
+ await expect(service.register({
196
+ ...baseRegistration,
197
+ scopeType: 'tenant',
198
+ tenantId: 'tenant-1',
199
+ scheduleType: 'interval',
200
+ scheduleValue: '15m',
201
+ })).rejects.toThrow('Active scheduled job limit reached')
202
+
203
+ expect(mockForkedEm.count).toHaveBeenCalledWith(ScheduledJob, {
204
+ tenantId: 'tenant-1',
205
+ isEnabled: true,
206
+ deletedAt: null,
207
+ })
208
+ expect(mockForkedEm.create).not.toHaveBeenCalled()
209
+ expect(mockForkedEm.flush).not.toHaveBeenCalled()
210
+ } finally {
211
+ if (originalLimit === undefined) delete process.env.OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT
212
+ else process.env.OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT = originalLimit
213
+ }
214
+ })
187
215
  })
188
216
 
189
217
  describe('unregister', () => {
@@ -380,6 +408,65 @@ describe('SchedulerService', () => {
380
408
 
381
409
  expect(mockBullMQService.unregister).toHaveBeenCalledWith('test-1')
382
410
  })
411
+
412
+ it('should reject enabling a tenant schedule when the tenant active cap is reached', async () => {
413
+ const originalLimit = process.env.OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT
414
+ process.env.OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT = '2'
415
+ try {
416
+ const schedule = {
417
+ id: 'test-1',
418
+ tenantId: 'tenant-1',
419
+ organizationId: null,
420
+ scopeType: 'tenant',
421
+ isEnabled: false,
422
+ scheduleType: 'interval',
423
+ scheduleValue: '15m',
424
+ timezone: 'UTC',
425
+ } as ScheduledJob
426
+
427
+ mockForkedEm.findOne.mockResolvedValue(schedule)
428
+ mockForkedEm.count.mockResolvedValue(2)
429
+
430
+ await expect(service.update('test-1', { isEnabled: true })).rejects.toThrow('Active scheduled job limit reached')
431
+
432
+ expect(mockForkedEm.count).toHaveBeenCalledWith(ScheduledJob, {
433
+ tenantId: 'tenant-1',
434
+ isEnabled: true,
435
+ deletedAt: null,
436
+ })
437
+ expect(schedule.isEnabled).toBe(false)
438
+ expect(mockForkedEm.flush).not.toHaveBeenCalled()
439
+ } finally {
440
+ if (originalLimit === undefined) delete process.env.OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT
441
+ else process.env.OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT = originalLimit
442
+ }
443
+ })
444
+
445
+ it('should reject interval updates below one minute', async () => {
446
+ const nextRunAt = new Date('2026-01-01T00:15:00.000Z')
447
+ const schedule = {
448
+ id: 'test-1',
449
+ tenantId: 'tenant-1',
450
+ organizationId: null,
451
+ scopeType: 'tenant',
452
+ isEnabled: true,
453
+ scheduleType: 'interval',
454
+ scheduleValue: '15m',
455
+ timezone: 'UTC',
456
+ nextRunAt,
457
+ } as ScheduledJob
458
+
459
+ mockForkedEm.findOne.mockResolvedValue(schedule)
460
+
461
+ await expect(service.update('test-1', {
462
+ scheduleType: 'interval',
463
+ scheduleValue: '1s',
464
+ })).rejects.toThrow('Failed to calculate next run time')
465
+
466
+ expect(schedule.scheduleValue).toBe('15m')
467
+ expect(schedule.nextRunAt).toBe(nextRunAt)
468
+ expect(mockForkedEm.flush).not.toHaveBeenCalled()
469
+ })
383
470
  })
384
471
 
385
472
  describe('findByModule', () => {
@@ -2,7 +2,7 @@ import type { EntityManager } from '@mikro-orm/core'
2
2
  import { ScheduledJob } from '../data/entities.js'
3
3
  import { recalculateNextRun } from '../lib/nextRunCalculator'
4
4
  import { parseCronExpression } from '../lib/cronParser'
5
- import { parseInterval } from '../lib/intervalParser'
5
+ import { resolveScheduleIntervalMs } from '../lib/intervalParser'
6
6
  import { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'
7
7
  import { createLogger } from '@open-mercato/shared/lib/logger'
8
8
 
@@ -288,7 +288,7 @@ export class BullMQSchedulerService {
288
288
  opts.pattern = schedule.scheduleValue
289
289
  } else if (schedule.scheduleType === 'interval') {
290
290
  // Parse interval (e.g., "15m", "2h", "1d")
291
- const intervalMs = parseInterval(schedule.scheduleValue)
291
+ const intervalMs = resolveScheduleIntervalMs(schedule.scheduleValue)
292
292
  opts.every = intervalMs
293
293
  } else {
294
294
  throw new Error(`Unsupported schedule type: ${schedule.scheduleType}`)
@@ -1,6 +1,7 @@
1
1
  import type { EntityManager } from '@mikro-orm/core'
2
2
  import { ScheduledJob } from '../data/entities.js'
3
- import { calculateNextRun } from '../lib/nextRunCalculator.js'
3
+ import { calculateNextRunForWrite } from '../lib/nextRunCalculator.js'
4
+ import { enforceTenantActiveScheduleLimit } from '../lib/activeScheduleLimits.js'
4
5
  import type { BullMQSchedulerService } from './bullmqSchedulerService.js'
5
6
  import { createLogger } from '@open-mercato/shared/lib/logger'
6
7
 
@@ -45,7 +46,7 @@ export class SchedulerService {
45
46
  this.validateTarget(registration)
46
47
 
47
48
  // Calculate next run time
48
- const nextRunAt = calculateNextRun(
49
+ const nextRunAt = calculateNextRunForWrite(
49
50
  registration.scheduleType,
50
51
  registration.scheduleValue,
51
52
  registration.timezone || 'UTC'
@@ -57,6 +58,12 @@ export class SchedulerService {
57
58
 
58
59
  // Check if schedule already exists
59
60
  let schedule = await em.findOne(ScheduledJob, { id: registration.id })
61
+ const nextTenantId = registration.tenantId || null
62
+ const nextIsEnabled = registration.isEnabled !== undefined ? registration.isEnabled : (schedule?.isEnabled ?? true)
63
+ const tenantChanged = schedule ? (schedule.tenantId || null) !== nextTenantId : false
64
+ if (nextIsEnabled && (schedule?.isEnabled !== true || tenantChanged)) {
65
+ await enforceTenantActiveScheduleLimit(em, nextTenantId)
66
+ }
60
67
 
61
68
  if (schedule) {
62
69
  // Update existing
@@ -165,6 +172,22 @@ export class SchedulerService {
165
172
  if (!schedule) {
166
173
  throw new Error(`Schedule not found: ${scheduleId}`)
167
174
  }
175
+
176
+ if (changes.isEnabled === true && schedule.isEnabled !== true) {
177
+ await enforceTenantActiveScheduleLimit(em, schedule.tenantId)
178
+ }
179
+
180
+ const scheduleChanged = changes.scheduleType !== undefined || changes.scheduleValue !== undefined || changes.timezone !== undefined
181
+ const nextRunAt = scheduleChanged
182
+ ? calculateNextRunForWrite(
183
+ changes.scheduleType ?? schedule.scheduleType,
184
+ changes.scheduleValue ?? schedule.scheduleValue,
185
+ changes.timezone ?? schedule.timezone,
186
+ )
187
+ : null
188
+ if (scheduleChanged && !nextRunAt) {
189
+ throw new Error(`Failed to calculate next run time for schedule: ${scheduleId}`)
190
+ }
168
191
 
169
192
  // Apply changes
170
193
  if (changes.name !== undefined) schedule.name = changes.name
@@ -197,16 +220,8 @@ export class SchedulerService {
197
220
  if (changes.targetCommand !== undefined) schedule.targetCommand = changes.targetCommand || null
198
221
  }
199
222
 
200
- // Recalculate next run if schedule changed
201
- if (changes.scheduleType !== undefined || changes.scheduleValue !== undefined || changes.timezone !== undefined) {
202
- const nextRunAt = calculateNextRun(
203
- schedule.scheduleType,
204
- schedule.scheduleValue,
205
- schedule.timezone
206
- )
207
- if (nextRunAt) {
208
- schedule.nextRunAt = nextRunAt
209
- }
223
+ if (nextRunAt) {
224
+ schedule.nextRunAt = nextRunAt
210
225
  }
211
226
 
212
227
  schedule.updatedAt = new Date()