@open-mercato/scheduler 0.6.7-develop.6862.1.c11a64ce0a → 0.6.7

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 (67) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/scheduler/__integration__/TC-SCHED-007.spec.js +1 -4
  3. package/dist/modules/scheduler/__integration__/TC-SCHED-007.spec.js.map +2 -2
  4. package/dist/modules/scheduler/api/jobs/[id]/executions/route.js +2 -4
  5. package/dist/modules/scheduler/api/jobs/[id]/executions/route.js.map +2 -2
  6. package/dist/modules/scheduler/api/queue-jobs/[jobId]/route.js +2 -4
  7. package/dist/modules/scheduler/api/queue-jobs/[jobId]/route.js.map +2 -2
  8. package/dist/modules/scheduler/api/targets/route.js +4 -5
  9. package/dist/modules/scheduler/api/targets/route.js.map +2 -2
  10. package/dist/modules/scheduler/commands/jobs.js +14 -33
  11. package/dist/modules/scheduler/commands/jobs.js.map +2 -2
  12. package/dist/modules/scheduler/data/validators.js +1 -27
  13. package/dist/modules/scheduler/data/validators.js.map +2 -2
  14. package/dist/modules/scheduler/i18n/de.json +0 -2
  15. package/dist/modules/scheduler/i18n/en.json +0 -2
  16. package/dist/modules/scheduler/i18n/es.json +0 -2
  17. package/dist/modules/scheduler/i18n/pl.json +0 -2
  18. package/dist/modules/scheduler/lib/intervalParser.js +3 -8
  19. package/dist/modules/scheduler/lib/intervalParser.js.map +2 -2
  20. package/dist/modules/scheduler/lib/localLockStrategy.js +45 -23
  21. package/dist/modules/scheduler/lib/localLockStrategy.js.map +2 -2
  22. package/dist/modules/scheduler/lib/nextRunCalculator.js +1 -8
  23. package/dist/modules/scheduler/lib/nextRunCalculator.js.map +2 -2
  24. package/dist/modules/scheduler/services/bullmqSchedulerService.js +43 -92
  25. package/dist/modules/scheduler/services/bullmqSchedulerService.js.map +2 -2
  26. package/dist/modules/scheduler/services/localSchedulerService.js +3 -9
  27. package/dist/modules/scheduler/services/localSchedulerService.js.map +2 -2
  28. package/dist/modules/scheduler/services/schedulerService.js +11 -23
  29. package/dist/modules/scheduler/services/schedulerService.js.map +2 -2
  30. package/dist/modules/scheduler/workers/execute-schedule.worker.js +0 -9
  31. package/dist/modules/scheduler/workers/execute-schedule.worker.js.map +2 -2
  32. package/package.json +9 -10
  33. package/src/modules/scheduler/__integration__/TC-SCHED-007.spec.ts +4 -6
  34. package/src/modules/scheduler/api/jobs/[id]/executions/route.ts +2 -4
  35. package/src/modules/scheduler/api/queue-jobs/[jobId]/route.ts +2 -4
  36. package/src/modules/scheduler/api/targets/route.ts +7 -7
  37. package/src/modules/scheduler/commands/jobs.ts +15 -40
  38. package/src/modules/scheduler/data/__tests__/validators.test.ts +9 -69
  39. package/src/modules/scheduler/data/validators.ts +1 -30
  40. package/src/modules/scheduler/i18n/de.json +0 -2
  41. package/src/modules/scheduler/i18n/en.json +0 -2
  42. package/src/modules/scheduler/i18n/es.json +0 -2
  43. package/src/modules/scheduler/i18n/pl.json +0 -2
  44. package/src/modules/scheduler/lib/__tests__/intervalParser.test.ts +9 -27
  45. package/src/modules/scheduler/lib/__tests__/localLockStrategy.test.ts +106 -0
  46. package/src/modules/scheduler/lib/__tests__/nextRunCalculator.test.ts +7 -18
  47. package/src/modules/scheduler/lib/intervalParser.ts +3 -8
  48. package/src/modules/scheduler/lib/localLockStrategy.ts +60 -26
  49. package/src/modules/scheduler/lib/nextRunCalculator.ts +1 -14
  50. package/src/modules/scheduler/services/__tests__/bullmqSchedulerService.test.ts +149 -246
  51. package/src/modules/scheduler/services/__tests__/localSchedulerService.test.ts +11 -97
  52. package/src/modules/scheduler/services/__tests__/schedulerService.test.ts +0 -101
  53. package/src/modules/scheduler/services/bullmqSchedulerService.ts +49 -135
  54. package/src/modules/scheduler/services/localSchedulerService.ts +11 -14
  55. package/src/modules/scheduler/services/schedulerService.ts +12 -27
  56. package/src/modules/scheduler/workers/__tests__/execute-schedule.worker.test.ts +0 -12
  57. package/src/modules/scheduler/workers/execute-schedule.worker.ts +0 -15
  58. package/dist/modules/scheduler/i18n/ko.json +0 -157
  59. package/dist/modules/scheduler/lib/activeScheduleLimits.js +0 -44
  60. package/dist/modules/scheduler/lib/activeScheduleLimits.js.map +0 -7
  61. package/dist/modules/scheduler/lib/scheduler-safe-commands.js +0 -73
  62. package/dist/modules/scheduler/lib/scheduler-safe-commands.js.map +0 -7
  63. package/src/modules/scheduler/api/targets/__tests__/route.test.ts +0 -76
  64. package/src/modules/scheduler/commands/__tests__/jobs.active-limit.test.ts +0 -184
  65. package/src/modules/scheduler/i18n/ko.json +0 -157
  66. package/src/modules/scheduler/lib/activeScheduleLimits.ts +0 -48
  67. package/src/modules/scheduler/lib/scheduler-safe-commands.ts +0 -98
@@ -2,9 +2,8 @@ import { NextRequest, NextResponse } from 'next/server'
2
2
  import { z } from 'zod'
3
3
  import { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'
4
4
  import { getModules } from '@open-mercato/shared/lib/modules/registry'
5
- import { commandRegistry } from '@open-mercato/shared/lib/commands/registry'
5
+ import { commandRegistry } from '@open-mercato/shared/lib/commands'
6
6
  import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'
7
- import { listSchedulerSafeCommands } from '../../lib/scheduler-safe-commands'
8
7
 
9
8
  export const metadata = {
10
9
  requireAuth: true,
@@ -36,9 +35,10 @@ export async function GET(req: NextRequest) {
36
35
  .sort((a, b) => a.localeCompare(b))
37
36
  .map((queue) => ({ value: queue, label: queue }))
38
37
 
39
- const commands = listSchedulerSafeCommands()
40
- .filter((command) => commandRegistry.has(command.commandId))
41
- .map((command) => ({ value: command.commandId, label: command.commandId }))
38
+ const commands = commandRegistry
39
+ .list()
40
+ .sort((a, b) => a.localeCompare(b))
41
+ .map((id) => ({ value: id, label: id }))
42
42
 
43
43
  return NextResponse.json({ queues, commands })
44
44
  }
@@ -61,12 +61,12 @@ const errorResponseSchema = z.object({
61
61
  export const openApi: OpenApiRouteDoc = {
62
62
  tag: 'Scheduler',
63
63
  summary: 'List available schedule targets',
64
- description: 'Returns available queue names and scheduler-safe command IDs for schedule target selection.',
64
+ description: 'Returns available queue names and registered command IDs for schedule target selection.',
65
65
  methods: {
66
66
  GET: {
67
67
  operationId: 'listScheduleTargets',
68
68
  summary: 'List available queues and commands',
69
- description: 'Returns all registered queue names (from module workers) and explicitly scheduler-safe command IDs that can be used as schedule targets.',
69
+ description: 'Returns all registered queue names (from module workers) and command IDs (from the command registry) that can be used as schedule targets.',
70
70
  responses: [
71
71
  {
72
72
  status: 200,
@@ -6,8 +6,7 @@ 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 { calculateNextRunForWrite } from '../lib/nextRunCalculator.js'
10
- import { enforceTenantActiveScheduleLimit } from '../lib/activeScheduleLimits.js'
9
+ import { calculateNextRun } from '../lib/nextRunCalculator.js'
11
10
  import type {
12
11
  ScheduleCreateInput,
13
12
  ScheduleUpdateInput,
@@ -83,14 +82,6 @@ function toDate(value: Date | string | null | undefined): Date | null {
83
82
  return value instanceof Date ? value : new Date(value)
84
83
  }
85
84
 
86
- function resolveCommandActorUserId(ctx: CommandRuntimeContext): string | null {
87
- const auth = ctx.auth
88
- if (!auth) return null
89
- if (typeof auth.userId === 'string' && auth.userId.trim().length > 0) return auth.userId.trim()
90
- if (auth.isApiKey) return null
91
- return typeof auth.sub === 'string' && auth.sub.trim().length > 0 ? auth.sub.trim() : null
92
- }
93
-
94
85
  /**
95
86
  * Build a full create seed (including the original id and Date-coerced timestamps)
96
87
  * from a snapshot. Shared by `materializeScheduleFromSnapshot` (delete-undo) and the
@@ -197,12 +188,8 @@ const createScheduleCommand: CommandHandler<ScheduleCreateInput, { id: string }>
197
188
 
198
189
  const em = ctx.container.resolve<EntityManager>('em').fork()
199
190
 
200
- if (input.isEnabled ?? true) {
201
- await enforceTenantActiveScheduleLimit(em, input.tenantId)
202
- }
203
-
204
191
  // Calculate next run time
205
- const nextRunAt = calculateNextRunForWrite(
192
+ const nextRunAt = calculateNextRun(
206
193
  input.scheduleType,
207
194
  input.scheduleValue,
208
195
  input.timezone || 'UTC'
@@ -231,7 +218,7 @@ const createScheduleCommand: CommandHandler<ScheduleCreateInput, { id: string }>
231
218
  sourceType: input.sourceType ?? 'user',
232
219
  sourceModule: input.sourceModule ?? null,
233
220
  nextRunAt,
234
- createdByUserId: resolveCommandActorUserId(ctx),
221
+ createdByUserId: (ctx.auth?.userId as string | undefined) ?? null,
235
222
  createdAt: new Date(),
236
223
  updatedAt: new Date(),
237
224
  })
@@ -310,26 +297,6 @@ const updateScheduleCommand: CommandHandler<ScheduleUpdateInput, { ok: boolean }
310
297
  if (schedule.organizationId) ensureOrganizationScope(ctx, schedule.organizationId)
311
298
  ensureCanManageSystemScopedJob(ctx, schedule)
312
299
 
313
- if (input.isEnabled === true && schedule.isEnabled !== true) {
314
- await enforceTenantActiveScheduleLimit(em, schedule.tenantId)
315
- }
316
-
317
- const scheduleChanged = input.scheduleType !== undefined || input.scheduleValue !== undefined || input.timezone !== undefined
318
- const nextRunAt = scheduleChanged
319
- ? calculateNextRunForWrite(
320
- input.scheduleType ?? schedule.scheduleType,
321
- input.scheduleValue ?? schedule.scheduleValue,
322
- input.timezone ?? schedule.timezone,
323
- )
324
- : null
325
-
326
- if (scheduleChanged && !nextRunAt) {
327
- const { translate } = await resolveTranslations()
328
- throw new CrudHttpError(422, {
329
- error: translate('scheduler.error.invalid_schedule_value', 'Invalid schedule value.'),
330
- })
331
- }
332
-
333
300
  // Update fields
334
301
  if (input.name !== undefined) schedule.name = input.name
335
302
  if (input.description !== undefined) schedule.description = input.description ?? null
@@ -359,12 +326,20 @@ const updateScheduleCommand: CommandHandler<ScheduleUpdateInput, { ok: boolean }
359
326
  if (input.targetCommand !== undefined) schedule.targetCommand = input.targetCommand
360
327
  }
361
328
 
362
- if (nextRunAt) {
363
- schedule.nextRunAt = nextRunAt
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
+ }
364
339
  }
365
340
 
366
341
  schedule.updatedAt = new Date()
367
- schedule.updatedByUserId = resolveCommandActorUserId(ctx)
342
+ schedule.updatedByUserId = (ctx.auth?.userId as string | undefined) ?? null
368
343
 
369
344
  await em.flush()
370
345
 
@@ -455,7 +430,7 @@ const deleteScheduleCommand: CommandHandler<{ id: string }, { ok: boolean }> = {
455
430
  // Soft delete
456
431
  schedule.deletedAt = new Date()
457
432
  schedule.updatedAt = new Date()
458
- schedule.updatedByUserId = resolveCommandActorUserId(ctx)
433
+ schedule.updatedByUserId = (ctx.auth?.userId as string | undefined) ?? null
459
434
 
460
435
  await em.flush()
461
436
 
@@ -7,38 +7,19 @@ import {
7
7
  scheduleTriggerSchema,
8
8
  scheduleRunsQuerySchema,
9
9
  } from '../validators'
10
- import { registerCommand } from '@open-mercato/shared/lib/commands/registry'
11
- import type { CommandHandler } from '@open-mercato/shared/lib/commands/types'
12
- import {
13
- clearSchedulerSafeCommandsForTests,
14
- registerSchedulerSafeCommands,
15
- } from '../../lib/scheduler-safe-commands'
10
+ import { registerCommand } from '@open-mercato/shared/lib/commands'
11
+ import type { CommandHandler } from '@open-mercato/shared/lib/commands'
16
12
 
17
- // Register test commands for validation tests
18
- const testCommand: CommandHandler<unknown, { ok: boolean }> = {
13
+ // Register a test command for validation tests
14
+ const testCommand: CommandHandler<any, any> = {
19
15
  id: 'test.command.for.validators',
20
16
  async execute() {
21
17
  return { ok: true }
22
18
  },
23
19
  }
24
20
 
25
- const schedulableTestCommand: CommandHandler<unknown, { ok: boolean }> = {
26
- id: 'test.command.schedulable',
27
- async execute() {
28
- return { ok: true }
29
- },
30
- }
31
-
32
21
  beforeAll(() => {
33
- clearSchedulerSafeCommandsForTests()
34
22
  registerCommand(testCommand)
35
- registerCommand(schedulableTestCommand)
36
- registerSchedulerSafeCommands([
37
- {
38
- commandId: 'test.command.schedulable',
39
- requiredFeatures: ['scheduler.jobs.manage'],
40
- },
41
- ])
42
23
  })
43
24
 
44
25
  const tenantId = '123e4567-e89b-12d3-a456-426614174000'
@@ -75,7 +56,7 @@ describe('scheduleCreateSchema', () => {
75
56
  scheduleValue: '1h',
76
57
  timezone: 'America/New_York',
77
58
  targetType: 'command',
78
- targetCommand: 'test.command.schedulable',
59
+ targetCommand: 'test.command.for.validators',
79
60
  targetPayload: { foo: 'bar' },
80
61
  isEnabled: true,
81
62
  })
@@ -87,7 +68,7 @@ describe('scheduleCreateSchema', () => {
87
68
  expect(result.scheduleType).toBe('interval')
88
69
  expect(result.scheduleValue).toBe('1h')
89
70
  expect(result.targetType).toBe('command')
90
- expect(result.targetCommand).toBe('test.command.schedulable')
71
+ expect(result.targetCommand).toBe('test.command.for.validators')
91
72
  })
92
73
 
93
74
  it('should accept valid tenant-scoped schedule', () => {
@@ -145,8 +126,7 @@ describe('scheduleCreateSchema', () => {
145
126
 
146
127
  it('should accept various interval formats', () => {
147
128
  const validIntervals = [
148
- '60s', // 60 seconds
149
- '1m', // 1 minute
129
+ '30s', // 30 seconds
150
130
  '15m', // 15 minutes
151
131
  '2h', // 2 hours
152
132
  '1d', // 1 day
@@ -290,19 +270,6 @@ describe('scheduleCreateSchema', () => {
290
270
  })
291
271
  ).toThrow(/Command does not exist/)
292
272
  })
293
-
294
- it('should reject a registered command that did not opt into scheduler execution', () => {
295
- expect(() =>
296
- scheduleCreateSchema.parse({
297
- name: 'Unsafe command',
298
- scopeType: 'system',
299
- scheduleType: 'cron',
300
- scheduleValue: '0 0 * * *',
301
- targetType: 'command',
302
- targetCommand: 'test.command.for.validators',
303
- })
304
- ).toThrow(/Command is not schedulable/)
305
- })
306
273
  })
307
274
 
308
275
  describe('schedule validation', () => {
@@ -357,23 +324,6 @@ describe('scheduleCreateSchema', () => {
357
324
  })
358
325
  ).toThrow(/Invalid schedule value/)
359
326
  })
360
-
361
- it('should reject interval values below one minute', () => {
362
- const subMinuteIntervals = ['0s', '1s', '59s', '0m']
363
-
364
- subMinuteIntervals.forEach(scheduleValue => {
365
- expect(() =>
366
- scheduleCreateSchema.parse({
367
- name: 'Invalid',
368
- scopeType: 'system',
369
- scheduleType: 'interval',
370
- scheduleValue,
371
- targetType: 'queue',
372
- targetQueue: 'test',
373
- })
374
- ).toThrow(/Invalid schedule value/)
375
- })
376
- })
377
327
  })
378
328
 
379
329
  describe('field constraints', () => {
@@ -486,16 +436,6 @@ describe('scheduleUpdateSchema', () => {
486
436
  ).toThrow(/Invalid schedule value/)
487
437
  })
488
438
 
489
- it('should reject interval values below one minute when updating', () => {
490
- expect(() =>
491
- scheduleUpdateSchema.parse({
492
- id: scheduleId,
493
- scheduleType: 'interval',
494
- scheduleValue: '1s',
495
- })
496
- ).toThrow(/Invalid schedule value/)
497
- })
498
-
499
439
  it('should require targetQueue when changing to queue target', () => {
500
440
  expect(() =>
501
441
  scheduleUpdateSchema.parse({
@@ -518,11 +458,11 @@ describe('scheduleUpdateSchema', () => {
518
458
  const result = scheduleUpdateSchema.parse({
519
459
  id: scheduleId,
520
460
  targetType: 'command',
521
- targetCommand: 'test.command.schedulable',
461
+ targetCommand: 'test.command.for.validators',
522
462
  })
523
463
 
524
464
  expect(result.targetType).toBe('command')
525
- expect(result.targetCommand).toBe('test.command.schedulable')
465
+ expect(result.targetCommand).toBe('test.command.for.validators')
526
466
  })
527
467
 
528
468
  it('should reject non-existent command on update', () => {
@@ -1,9 +1,8 @@
1
1
  import { z } from 'zod'
2
2
  import { validateCron } from '../lib/cronParser'
3
3
  import { validateInterval } from '../lib/intervalParser'
4
- import { commandRegistry } from '@open-mercato/shared/lib/commands/registry'
4
+ import { commandRegistry } from '@open-mercato/shared/lib/commands'
5
5
  import { parseBooleanToken } from '@open-mercato/shared/lib/boolean'
6
- import { isSchedulerSafeCommandId } from '../lib/scheduler-safe-commands'
7
6
 
8
7
  /**
9
8
  * Validate that a command exists in the command registry
@@ -12,10 +11,6 @@ function validateCommandExists(commandId: string): boolean {
12
11
  return commandRegistry.has(commandId)
13
12
  }
14
13
 
15
- function validateCommandIsSchedulable(commandId: string): boolean {
16
- return isSchedulerSafeCommandId(commandId)
17
- }
18
-
19
14
  /**
20
15
  * Base schedule fields
21
16
  */
@@ -108,18 +103,6 @@ export const scheduleCreateSchema = scheduleBaseSchema
108
103
  path: ['targetCommand'],
109
104
  }
110
105
  )
111
- .refine(
112
- (data) => {
113
- if (data.targetType === 'command' && data.targetCommand) {
114
- return validateCommandIsSchedulable(data.targetCommand)
115
- }
116
- return true
117
- },
118
- {
119
- message: 'Command is not schedulable. Only scheduler-safe commands can be used as schedule targets.',
120
- path: ['targetCommand'],
121
- }
122
- )
123
106
 
124
107
  /**
125
108
  * Update schedule schema (all fields optional except id)
@@ -202,18 +185,6 @@ export const scheduleUpdateSchema = z.object({
202
185
  path: ['targetCommand'],
203
186
  }
204
187
  )
205
- .refine(
206
- (data) => {
207
- if (data.targetCommand) {
208
- return validateCommandIsSchedulable(data.targetCommand)
209
- }
210
- return true
211
- },
212
- {
213
- message: 'Command is not schedulable. Only scheduler-safe commands can be used as schedule targets.',
214
- path: ['targetCommand'],
215
- }
216
- )
217
188
 
218
189
  /**
219
190
  * Delete schedule schema
@@ -26,7 +26,6 @@
26
26
  "scheduler.details.triggering": "Wird ausgeführt...",
27
27
  "scheduler.edit.title": "Zeitplan bearbeiten",
28
28
  "scheduler.error.access_denied": "Zugriff verweigert",
29
- "scheduler.error.active_schedule_limit": "Das Limit aktiver geplanter Aufgaben für diesen Mandanten wurde erreicht ({max}).",
30
29
  "scheduler.error.async_strategy_hint": "Bitte setzen Sie QUEUE_STRATEGY=async, um den Ausführungsverlauf einzusehen",
31
30
  "scheduler.error.async_strategy_required": "Ausführungsverlauf erfordert QUEUE_STRATEGY=async",
32
31
  "scheduler.error.bullmq_required": "BullMQ-Job-Logs sind nur mit QUEUE_STRATEGY=async verfügbar",
@@ -37,7 +36,6 @@
37
36
  "scheduler.error.forbidden": "Verboten",
38
37
  "scheduler.error.invalidPayload": "Ungültiges JSON-Payload",
39
38
  "scheduler.error.invalid_queue_name": "Ungültiger Queue-Name",
40
- "scheduler.error.invalid_schedule_value": "Ungültiger Zeitplanwert.",
41
39
  "scheduler.error.job_not_found": "Job in BullMQ nicht gefunden (möglicherweise entfernt)",
42
40
  "scheduler.error.load_failed": "Fehler beim Laden des Zeitplans",
43
41
  "scheduler.error.not_found": "Zeitplan nicht gefunden",
@@ -26,7 +26,6 @@
26
26
  "scheduler.details.triggering": "Triggering...",
27
27
  "scheduler.edit.title": "Edit Schedule",
28
28
  "scheduler.error.access_denied": "Access denied",
29
- "scheduler.error.active_schedule_limit": "Active scheduled job limit reached for this tenant ({max}).",
30
29
  "scheduler.error.async_strategy_hint": "Please set QUEUE_STRATEGY=async to view execution history",
31
30
  "scheduler.error.async_strategy_required": "Execution history requires QUEUE_STRATEGY=async",
32
31
  "scheduler.error.bullmq_required": "BullMQ job logs are only available with QUEUE_STRATEGY=async",
@@ -37,7 +36,6 @@
37
36
  "scheduler.error.forbidden": "Forbidden",
38
37
  "scheduler.error.invalidPayload": "Invalid JSON payload",
39
38
  "scheduler.error.invalid_queue_name": "Invalid queue name",
40
- "scheduler.error.invalid_schedule_value": "Invalid schedule value.",
41
39
  "scheduler.error.job_not_found": "Job not found in BullMQ (may have been removed)",
42
40
  "scheduler.error.load_failed": "Failed to load schedule",
43
41
  "scheduler.error.not_found": "Schedule not found",
@@ -26,7 +26,6 @@
26
26
  "scheduler.details.triggering": "Ejecutando...",
27
27
  "scheduler.edit.title": "Editar programación",
28
28
  "scheduler.error.access_denied": "Acceso denegado",
29
- "scheduler.error.active_schedule_limit": "Se alcanzó el límite de tareas programadas activas para este inquilino ({max}).",
30
29
  "scheduler.error.async_strategy_hint": "Configure QUEUE_STRATEGY=async para ver el historial de ejecución",
31
30
  "scheduler.error.async_strategy_required": "El historial de ejecución requiere QUEUE_STRATEGY=async",
32
31
  "scheduler.error.bullmq_required": "Los registros de trabajos de BullMQ solo están disponibles con QUEUE_STRATEGY=async",
@@ -37,7 +36,6 @@
37
36
  "scheduler.error.forbidden": "Prohibido",
38
37
  "scheduler.error.invalidPayload": "Carga JSON no válida",
39
38
  "scheduler.error.invalid_queue_name": "Nombre de cola inválido",
40
- "scheduler.error.invalid_schedule_value": "Valor de programación no válido.",
41
39
  "scheduler.error.job_not_found": "Trabajo no encontrado en BullMQ (puede haber sido eliminado)",
42
40
  "scheduler.error.load_failed": "Error al cargar la programación",
43
41
  "scheduler.error.not_found": "Programación no encontrada",
@@ -26,7 +26,6 @@
26
26
  "scheduler.details.triggering": "Uruchamianie...",
27
27
  "scheduler.edit.title": "Edytuj harmonogram",
28
28
  "scheduler.error.access_denied": "Odmowa dostępu",
29
- "scheduler.error.active_schedule_limit": "Osiągnięto limit aktywnych zaplanowanych zadań dla tego najemcy ({max}).",
30
29
  "scheduler.error.async_strategy_hint": "Ustaw QUEUE_STRATEGY=async, aby wyświetlić historię wykonań",
31
30
  "scheduler.error.async_strategy_required": "Historia wykonań wymaga QUEUE_STRATEGY=async",
32
31
  "scheduler.error.bullmq_required": "Logi zadań BullMQ są dostępne tylko z QUEUE_STRATEGY=async",
@@ -37,7 +36,6 @@
37
36
  "scheduler.error.forbidden": "Zabronione",
38
37
  "scheduler.error.invalidPayload": "Nieprawidłowy ładunek JSON",
39
38
  "scheduler.error.invalid_queue_name": "Nieprawidłowa nazwa kolejki",
40
- "scheduler.error.invalid_schedule_value": "Nieprawidłowa wartość harmonogramu.",
41
39
  "scheduler.error.job_not_found": "Zadanie nie zostało znalezione w BullMQ (mogło zostać usunięte)",
42
40
  "scheduler.error.load_failed": "Nie udało się załadować harmonogramu",
43
41
  "scheduler.error.not_found": "Harmonogram nie znaleziony",
@@ -1,7 +1,6 @@
1
1
  import { describe, it, expect } from '@jest/globals'
2
2
  import {
3
3
  parseInterval,
4
- resolveScheduleIntervalMs,
5
4
  calculateNextRunFromInterval,
6
5
  validateInterval,
7
6
  intervalToHuman,
@@ -11,8 +10,9 @@ describe('intervalParser', () => {
11
10
  describe('parseInterval', () => {
12
11
  describe('seconds', () => {
13
12
  it('should parse seconds correctly', () => {
13
+ expect(parseInterval('30s')).toBe(30 * 1000)
14
+ expect(parseInterval('1s')).toBe(1000)
14
15
  expect(parseInterval('60s')).toBe(60 * 1000)
15
- expect(parseInterval('90s')).toBe(90 * 1000)
16
16
  })
17
17
  })
18
18
 
@@ -86,10 +86,8 @@ describe('intervalParser', () => {
86
86
  })
87
87
 
88
88
  describe('edge cases', () => {
89
- it('should preserve parsing for legacy intervals below one minute', () => {
89
+ it('should handle zero', () => {
90
90
  expect(parseInterval('0s')).toBe(0)
91
- expect(parseInterval('1s')).toBe(1000)
92
- expect(parseInterval('59s')).toBe(59 * 1000)
93
91
  expect(parseInterval('0m')).toBe(0)
94
92
  expect(parseInterval('0h')).toBe(0)
95
93
  expect(parseInterval('0d')).toBe(0)
@@ -104,16 +102,6 @@ describe('intervalParser', () => {
104
102
  })
105
103
  })
106
104
 
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
-
117
105
  describe('calculateNextRunFromInterval', () => {
118
106
  it('should calculate next run from current time', () => {
119
107
  const before = new Date()
@@ -134,9 +122,9 @@ describe('intervalParser', () => {
134
122
 
135
123
  it('should handle seconds intervals', () => {
136
124
  const baseDate = new Date('2025-01-27T12:00:00Z')
137
- const nextRun = calculateNextRunFromInterval('60s', baseDate)
125
+ const nextRun = calculateNextRunFromInterval('30s', baseDate)
138
126
 
139
- expect(nextRun).toEqual(new Date('2025-01-27T12:01:00Z'))
127
+ expect(nextRun).toEqual(new Date('2025-01-27T12:00:30Z'))
140
128
  })
141
129
 
142
130
  it('should handle minute intervals', () => {
@@ -191,19 +179,15 @@ describe('intervalParser', () => {
191
179
 
192
180
  describe('validateInterval', () => {
193
181
  it('should return true for valid intervals', () => {
194
- expect(validateInterval('60s')).toBe(true)
195
- expect(validateInterval('1m')).toBe(true)
182
+ expect(validateInterval('30s')).toBe(true)
196
183
  expect(validateInterval('15m')).toBe(true)
197
184
  expect(validateInterval('2h')).toBe(true)
198
185
  expect(validateInterval('1d')).toBe(true)
186
+ expect(validateInterval('0s')).toBe(true)
199
187
  expect(validateInterval('999d')).toBe(true)
200
188
  })
201
189
 
202
190
  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)
207
191
  expect(validateInterval('invalid')).toBe(false)
208
192
  expect(validateInterval('')).toBe(false)
209
193
  expect(validateInterval('15')).toBe(false)
@@ -220,8 +204,7 @@ describe('intervalParser', () => {
220
204
  it('should convert seconds to human readable', () => {
221
205
  expect(intervalToHuman('1s')).toBe('1 second')
222
206
  expect(intervalToHuman('30s')).toBe('30 seconds')
223
- expect(intervalToHuman('60s')).toBe('60 seconds')
224
- expect(intervalToHuman('90s')).toBe('90 seconds')
207
+ expect(intervalToHuman('59s')).toBe('59 seconds')
225
208
  })
226
209
  })
227
210
 
@@ -277,7 +260,6 @@ describe('intervalParser', () => {
277
260
  it('should use plural for other numbers', () => {
278
261
  expect(intervalToHuman('0s')).toBe('0 seconds')
279
262
  expect(intervalToHuman('2s')).toBe('2 seconds')
280
- expect(intervalToHuman('60s')).toBe('60 seconds')
281
263
  expect(intervalToHuman('2m')).toBe('2 minutes')
282
264
  expect(intervalToHuman('2h')).toBe('2 hours')
283
265
  expect(intervalToHuman('2d')).toBe('2 days')
@@ -318,7 +300,7 @@ describe('intervalParser', () => {
318
300
 
319
301
  describe('integration', () => {
320
302
  it('should work end-to-end for various intervals', () => {
321
- const intervals = ['60s', '15m', '2h', '1d']
303
+ const intervals = ['30s', '15m', '2h', '1d']
322
304
 
323
305
  intervals.forEach(interval => {
324
306
  expect(validateInterval(interval)).toBe(true)
@@ -87,5 +87,111 @@ describe('LocalLockStrategy', () => {
87
87
  await expect(strategy.runWithLock('test-key', fn)).rejects.toThrow(fnError)
88
88
  expect(fn).toHaveBeenCalledTimes(1)
89
89
  })
90
+
91
+ it('should run fn outside the claim transaction', async () => {
92
+ ;(mockConnection.execute as any).mockResolvedValue([{ acquired: true }])
93
+
94
+ let transactionOpen = false
95
+ transactionalImpl.mockImplementation(async (cb: any) => {
96
+ transactionOpen = true
97
+ const result = await cb(mockForkedEm)
98
+ transactionOpen = false
99
+ return result
100
+ })
101
+
102
+ let openDuringFn: boolean | null = null
103
+ const fn = jest.fn(async () => {
104
+ openDuringFn = transactionOpen
105
+ return 'ok'
106
+ })
107
+
108
+ const result = await strategy.runWithLock('test-key', fn)
109
+
110
+ expect(result).toEqual({ acquired: true, result: 'ok' })
111
+ expect(openDuringFn).toBe(false)
112
+ })
113
+
114
+ it('should reject a concurrent run for the same key without touching the database', async () => {
115
+ ;(mockConnection.execute as any).mockResolvedValue([{ acquired: true }])
116
+
117
+ let releaseFirst: () => void = () => {}
118
+ const firstDone = new Promise<void>((resolve) => {
119
+ releaseFirst = resolve
120
+ })
121
+ const firstRun = strategy.runWithLock('test-key', async () => {
122
+ await firstDone
123
+ return 'first'
124
+ })
125
+ await Promise.resolve()
126
+
127
+ const secondFn = jest.fn(async () => 'second')
128
+ const secondRun = await strategy.runWithLock('test-key', secondFn)
129
+
130
+ expect(secondRun).toEqual({ acquired: false })
131
+ expect(secondFn).not.toHaveBeenCalled()
132
+ expect(mockConnection.execute).toHaveBeenCalledTimes(1)
133
+
134
+ releaseFirst()
135
+ await expect(firstRun).resolves.toEqual({ acquired: true, result: 'first' })
136
+ })
137
+
138
+ it('should release the key after fn completes or throws', async () => {
139
+ ;(mockConnection.execute as any).mockResolvedValue([{ acquired: true }])
140
+
141
+ await expect(
142
+ strategy.runWithLock('test-key', async () => {
143
+ throw new Error('Callback failed')
144
+ }),
145
+ ).rejects.toThrow('Callback failed')
146
+
147
+ const fn = jest.fn(async () => 'ok')
148
+ await expect(strategy.runWithLock('test-key', fn)).resolves.toEqual({ acquired: true, result: 'ok' })
149
+ expect(fn).toHaveBeenCalledTimes(1)
150
+ })
151
+
152
+ it('should release the key when the claim is not acquired', async () => {
153
+ ;(mockConnection.execute as any).mockResolvedValueOnce([{ acquired: false }])
154
+ ;(mockConnection.execute as any).mockResolvedValueOnce([{ acquired: true }])
155
+
156
+ await expect(strategy.runWithLock('test-key', async () => 'ok')).resolves.toEqual({ acquired: false })
157
+
158
+ const fn = jest.fn(async () => 'ok')
159
+ await expect(strategy.runWithLock('test-key', fn)).resolves.toEqual({ acquired: true, result: 'ok' })
160
+ })
161
+
162
+ it('should release the key when the claim transaction itself rejects', async () => {
163
+ ;(mockConnection.execute as any).mockRejectedValueOnce(new Error('Database connection failed'))
164
+ ;(mockConnection.execute as any).mockResolvedValueOnce([{ acquired: true }])
165
+
166
+ await expect(strategy.runWithLock('test-key', async () => 'ok')).resolves.toEqual({ acquired: false })
167
+
168
+ const fn = jest.fn(async () => 'ok')
169
+ await expect(strategy.runWithLock('test-key', fn)).resolves.toEqual({ acquired: true, result: 'ok' })
170
+ expect(fn).toHaveBeenCalledTimes(1)
171
+ })
172
+
173
+ it('should not let a held key block a different key', async () => {
174
+ ;(mockConnection.execute as any).mockResolvedValue([{ acquired: true }])
175
+
176
+ let releaseFirst: () => void = () => {}
177
+ const firstDone = new Promise<void>((resolve) => {
178
+ releaseFirst = resolve
179
+ })
180
+ const firstRun = strategy.runWithLock('key-a', async () => {
181
+ await firstDone
182
+ return 'first'
183
+ })
184
+ await Promise.resolve()
185
+
186
+ const secondFn = jest.fn(async () => 'second')
187
+ await expect(strategy.runWithLock('key-b', secondFn)).resolves.toEqual({
188
+ acquired: true,
189
+ result: 'second',
190
+ })
191
+ expect(secondFn).toHaveBeenCalledTimes(1)
192
+
193
+ releaseFirst()
194
+ await expect(firstRun).resolves.toEqual({ acquired: true, result: 'first' })
195
+ })
90
196
  })
91
197
  })