@open-mercato/scheduler 0.6.7 → 0.6.8-develop.6875.1.871a4afc94
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/dist/modules/scheduler/__integration__/TC-SCHED-007.spec.js +4 -1
- package/dist/modules/scheduler/__integration__/TC-SCHED-007.spec.js.map +2 -2
- package/dist/modules/scheduler/api/jobs/[id]/executions/route.js +4 -2
- package/dist/modules/scheduler/api/jobs/[id]/executions/route.js.map +2 -2
- package/dist/modules/scheduler/api/queue-jobs/[jobId]/route.js +4 -2
- package/dist/modules/scheduler/api/queue-jobs/[jobId]/route.js.map +2 -2
- package/dist/modules/scheduler/api/targets/route.js +5 -4
- package/dist/modules/scheduler/api/targets/route.js.map +2 -2
- package/dist/modules/scheduler/commands/jobs.js +33 -14
- package/dist/modules/scheduler/commands/jobs.js.map +2 -2
- package/dist/modules/scheduler/components/ExecutionDetailsDialog.js +1 -1
- package/dist/modules/scheduler/components/ExecutionDetailsDialog.js.map +2 -2
- package/dist/modules/scheduler/components/JobLogsModal.js +1 -1
- package/dist/modules/scheduler/components/JobLogsModal.js.map +2 -2
- package/dist/modules/scheduler/data/validators.js +27 -1
- package/dist/modules/scheduler/data/validators.js.map +2 -2
- package/dist/modules/scheduler/i18n/de.json +2 -0
- package/dist/modules/scheduler/i18n/en.json +2 -0
- package/dist/modules/scheduler/i18n/es.json +2 -0
- package/dist/modules/scheduler/i18n/ko.json +157 -0
- package/dist/modules/scheduler/i18n/pl.json +2 -0
- package/dist/modules/scheduler/lib/activeScheduleLimits.js +44 -0
- package/dist/modules/scheduler/lib/activeScheduleLimits.js.map +7 -0
- package/dist/modules/scheduler/lib/intervalParser.js +8 -3
- package/dist/modules/scheduler/lib/intervalParser.js.map +2 -2
- package/dist/modules/scheduler/lib/nextRunCalculator.js +8 -1
- package/dist/modules/scheduler/lib/nextRunCalculator.js.map +2 -2
- package/dist/modules/scheduler/lib/scheduler-safe-commands.js +73 -0
- package/dist/modules/scheduler/lib/scheduler-safe-commands.js.map +7 -0
- package/dist/modules/scheduler/services/bullmqSchedulerService.js +92 -43
- package/dist/modules/scheduler/services/bullmqSchedulerService.js.map +2 -2
- package/dist/modules/scheduler/services/localSchedulerService.js +9 -0
- package/dist/modules/scheduler/services/localSchedulerService.js.map +2 -2
- package/dist/modules/scheduler/services/schedulerService.js +23 -11
- package/dist/modules/scheduler/services/schedulerService.js.map +2 -2
- package/dist/modules/scheduler/workers/execute-schedule.worker.js +9 -0
- package/dist/modules/scheduler/workers/execute-schedule.worker.js.map +2 -2
- package/package.json +10 -9
- package/src/modules/scheduler/__integration__/TC-SCHED-007.spec.ts +6 -4
- package/src/modules/scheduler/api/jobs/[id]/executions/route.ts +4 -2
- package/src/modules/scheduler/api/queue-jobs/[jobId]/route.ts +4 -2
- package/src/modules/scheduler/api/targets/__tests__/route.test.ts +76 -0
- package/src/modules/scheduler/api/targets/route.ts +7 -7
- package/src/modules/scheduler/commands/__tests__/jobs.active-limit.test.ts +184 -0
- package/src/modules/scheduler/commands/jobs.ts +40 -15
- package/src/modules/scheduler/components/ExecutionDetailsDialog.tsx +1 -1
- package/src/modules/scheduler/components/JobLogsModal.tsx +1 -1
- package/src/modules/scheduler/data/__tests__/validators.test.ts +69 -9
- package/src/modules/scheduler/data/validators.ts +30 -1
- package/src/modules/scheduler/i18n/de.json +2 -0
- package/src/modules/scheduler/i18n/en.json +2 -0
- package/src/modules/scheduler/i18n/es.json +2 -0
- package/src/modules/scheduler/i18n/ko.json +157 -0
- package/src/modules/scheduler/i18n/pl.json +2 -0
- package/src/modules/scheduler/lib/__tests__/intervalParser.test.ts +27 -9
- package/src/modules/scheduler/lib/__tests__/nextRunCalculator.test.ts +18 -7
- package/src/modules/scheduler/lib/activeScheduleLimits.ts +48 -0
- package/src/modules/scheduler/lib/intervalParser.ts +8 -3
- package/src/modules/scheduler/lib/nextRunCalculator.ts +14 -1
- package/src/modules/scheduler/lib/scheduler-safe-commands.ts +98 -0
- package/src/modules/scheduler/services/__tests__/bullmqSchedulerService.test.ts +246 -149
- package/src/modules/scheduler/services/__tests__/localSchedulerService.test.ts +97 -1
- package/src/modules/scheduler/services/__tests__/schedulerService.test.ts +101 -0
- package/src/modules/scheduler/services/bullmqSchedulerService.ts +135 -49
- package/src/modules/scheduler/services/localSchedulerService.ts +11 -0
- package/src/modules/scheduler/services/schedulerService.ts +27 -12
- package/src/modules/scheduler/workers/__tests__/execute-schedule.worker.test.ts +12 -0
- package/src/modules/scheduler/workers/execute-schedule.worker.ts +15 -0
|
@@ -0,0 +1,184 @@
|
|
|
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, params?: Record<string, unknown>) => (
|
|
13
|
+
params?.max === undefined ? `translated:${key}` : `translated:${key}:max=${params.max}`
|
|
14
|
+
),
|
|
15
|
+
}),
|
|
16
|
+
}))
|
|
17
|
+
|
|
18
|
+
function loadCommands() {
|
|
19
|
+
let create: CommandHandler<ScheduleCreateInput, { id: string }> | undefined
|
|
20
|
+
let update: CommandHandler<ScheduleUpdateInput, { ok: boolean }> | undefined
|
|
21
|
+
jest.isolateModules(() => {
|
|
22
|
+
require('../jobs')
|
|
23
|
+
create = registerCommand.mock.calls.find(([command]) => command.id === 'scheduler.jobs.create')?.[0]
|
|
24
|
+
update = registerCommand.mock.calls.find(([command]) => command.id === 'scheduler.jobs.update')?.[0]
|
|
25
|
+
})
|
|
26
|
+
if (!create || !update) throw new Error('[internal] Scheduler commands were not registered')
|
|
27
|
+
return { create, update }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function makeEm(schedule: Record<string, unknown> | null) {
|
|
31
|
+
return {
|
|
32
|
+
fork: jest.fn().mockReturnThis(),
|
|
33
|
+
findOne: jest.fn().mockResolvedValue(schedule),
|
|
34
|
+
count: jest.fn(),
|
|
35
|
+
create: jest.fn((_entity: unknown, data: Record<string, unknown>) => ({ id: 'new-job', ...data })),
|
|
36
|
+
persist: jest.fn(),
|
|
37
|
+
flush: jest.fn().mockResolvedValue(undefined),
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function makeCtx(em: ReturnType<typeof makeEm>): CommandRuntimeContext {
|
|
42
|
+
return {
|
|
43
|
+
auth: { isSuperAdmin: false, tenantId: 'tenant-a', orgId: 'org-a' },
|
|
44
|
+
container: { resolve: jest.fn(() => em) },
|
|
45
|
+
} as unknown as CommandRuntimeContext
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function createInput(overrides: Record<string, unknown> = {}) {
|
|
49
|
+
return {
|
|
50
|
+
name: 'Tenant schedule',
|
|
51
|
+
scopeType: 'tenant',
|
|
52
|
+
tenantId: 'tenant-a',
|
|
53
|
+
scheduleType: 'interval',
|
|
54
|
+
scheduleValue: '15m',
|
|
55
|
+
targetType: 'queue',
|
|
56
|
+
targetQueue: 'scheduler',
|
|
57
|
+
isEnabled: true,
|
|
58
|
+
...overrides,
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
describe('scheduler.jobs active schedule tenant limit', () => {
|
|
63
|
+
const originalLimit = process.env.OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT
|
|
64
|
+
|
|
65
|
+
beforeEach(() => {
|
|
66
|
+
jest.clearAllMocks()
|
|
67
|
+
jest.resetModules()
|
|
68
|
+
process.env.OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT = '2'
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
afterEach(() => {
|
|
72
|
+
if (originalLimit === undefined) delete process.env.OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT
|
|
73
|
+
else process.env.OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT = originalLimit
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
it('rejects creating an enabled tenant-scoped schedule after the tenant reaches the active cap', async () => {
|
|
77
|
+
const { create } = loadCommands()
|
|
78
|
+
const em = makeEm(null)
|
|
79
|
+
em.count.mockResolvedValue(2)
|
|
80
|
+
|
|
81
|
+
await expect(create.execute(createInput(), makeCtx(em))).rejects.toMatchObject({
|
|
82
|
+
status: 422,
|
|
83
|
+
body: { error: 'translated:scheduler.error.active_schedule_limit:max=2' },
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
expect(em.count).toHaveBeenCalledWith(expect.any(Function), {
|
|
87
|
+
tenantId: 'tenant-a',
|
|
88
|
+
isEnabled: true,
|
|
89
|
+
deletedAt: null,
|
|
90
|
+
})
|
|
91
|
+
expect(em.persist).not.toHaveBeenCalled()
|
|
92
|
+
expect(em.flush).not.toHaveBeenCalled()
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
it('rejects direct command creates below the interval floor', async () => {
|
|
96
|
+
const { create } = loadCommands()
|
|
97
|
+
const em = makeEm(null)
|
|
98
|
+
em.count.mockResolvedValue(0)
|
|
99
|
+
|
|
100
|
+
await expect(create.execute(createInput({ scheduleValue: '1s' }), makeCtx(em))).rejects.toThrow(
|
|
101
|
+
'Failed to calculate next run time',
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
expect(em.persist).not.toHaveBeenCalled()
|
|
105
|
+
expect(em.flush).not.toHaveBeenCalled()
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
it('rejects enabling a disabled tenant-scoped schedule after the tenant reaches the active cap', async () => {
|
|
109
|
+
const { update } = loadCommands()
|
|
110
|
+
const schedule = {
|
|
111
|
+
id: 'job-1',
|
|
112
|
+
tenantId: 'tenant-a',
|
|
113
|
+
organizationId: null,
|
|
114
|
+
scopeType: 'tenant',
|
|
115
|
+
isEnabled: false,
|
|
116
|
+
scheduleType: 'interval',
|
|
117
|
+
scheduleValue: '15m',
|
|
118
|
+
timezone: 'UTC',
|
|
119
|
+
}
|
|
120
|
+
const em = makeEm(schedule)
|
|
121
|
+
em.count.mockResolvedValue(2)
|
|
122
|
+
|
|
123
|
+
await expect(update.execute({ id: 'job-1', isEnabled: true }, makeCtx(em))).rejects.toMatchObject({
|
|
124
|
+
status: 422,
|
|
125
|
+
body: { error: 'translated:scheduler.error.active_schedule_limit:max=2' },
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
expect(em.count).toHaveBeenCalledWith(expect.any(Function), {
|
|
129
|
+
tenantId: 'tenant-a',
|
|
130
|
+
isEnabled: true,
|
|
131
|
+
deletedAt: null,
|
|
132
|
+
})
|
|
133
|
+
expect(schedule.isEnabled).toBe(false)
|
|
134
|
+
expect(em.flush).not.toHaveBeenCalled()
|
|
135
|
+
})
|
|
136
|
+
|
|
137
|
+
it('does not count an already-enabled schedule when updating other fields', async () => {
|
|
138
|
+
const { update } = loadCommands()
|
|
139
|
+
const schedule = {
|
|
140
|
+
id: 'job-1',
|
|
141
|
+
tenantId: 'tenant-a',
|
|
142
|
+
organizationId: null,
|
|
143
|
+
scopeType: 'tenant',
|
|
144
|
+
isEnabled: true,
|
|
145
|
+
scheduleType: 'interval',
|
|
146
|
+
scheduleValue: '15m',
|
|
147
|
+
timezone: 'UTC',
|
|
148
|
+
}
|
|
149
|
+
const em = makeEm(schedule)
|
|
150
|
+
|
|
151
|
+
await expect(update.execute({ id: 'job-1', name: 'Renamed' }, makeCtx(em))).resolves.toEqual({ ok: true })
|
|
152
|
+
|
|
153
|
+
expect(em.count).not.toHaveBeenCalled()
|
|
154
|
+
expect(schedule.name).toBe('Renamed')
|
|
155
|
+
expect(em.flush).toHaveBeenCalled()
|
|
156
|
+
})
|
|
157
|
+
|
|
158
|
+
it('rejects direct command interval updates below one minute', async () => {
|
|
159
|
+
const { update } = loadCommands()
|
|
160
|
+
const schedule = {
|
|
161
|
+
id: 'job-1',
|
|
162
|
+
tenantId: 'tenant-a',
|
|
163
|
+
organizationId: null,
|
|
164
|
+
scopeType: 'tenant',
|
|
165
|
+
isEnabled: true,
|
|
166
|
+
scheduleType: 'interval',
|
|
167
|
+
scheduleValue: '15m',
|
|
168
|
+
timezone: 'UTC',
|
|
169
|
+
nextRunAt: new Date('2026-01-01T00:15:00.000Z'),
|
|
170
|
+
}
|
|
171
|
+
const em = makeEm(schedule)
|
|
172
|
+
|
|
173
|
+
await expect(
|
|
174
|
+
update.execute({ id: 'job-1', scheduleType: 'interval', scheduleValue: '1s' }, makeCtx(em)),
|
|
175
|
+
).rejects.toMatchObject({
|
|
176
|
+
status: 422,
|
|
177
|
+
body: { error: 'translated:scheduler.error.invalid_schedule_value' },
|
|
178
|
+
})
|
|
179
|
+
|
|
180
|
+
expect(schedule.scheduleValue).toBe('15m')
|
|
181
|
+
expect(schedule.nextRunAt).toEqual(new Date('2026-01-01T00:15:00.000Z'))
|
|
182
|
+
expect(em.flush).not.toHaveBeenCalled()
|
|
183
|
+
})
|
|
184
|
+
})
|
|
@@ -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 {
|
|
9
|
+
import { calculateNextRunForWrite } from '../lib/nextRunCalculator.js'
|
|
10
|
+
import { enforceTenantActiveScheduleLimit } from '../lib/activeScheduleLimits.js'
|
|
10
11
|
import type {
|
|
11
12
|
ScheduleCreateInput,
|
|
12
13
|
ScheduleUpdateInput,
|
|
@@ -82,6 +83,14 @@ function toDate(value: Date | string | null | undefined): Date | null {
|
|
|
82
83
|
return value instanceof Date ? value : new Date(value)
|
|
83
84
|
}
|
|
84
85
|
|
|
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
|
+
|
|
85
94
|
/**
|
|
86
95
|
* Build a full create seed (including the original id and Date-coerced timestamps)
|
|
87
96
|
* from a snapshot. Shared by `materializeScheduleFromSnapshot` (delete-undo) and the
|
|
@@ -188,8 +197,12 @@ const createScheduleCommand: CommandHandler<ScheduleCreateInput, { id: string }>
|
|
|
188
197
|
|
|
189
198
|
const em = ctx.container.resolve<EntityManager>('em').fork()
|
|
190
199
|
|
|
200
|
+
if (input.isEnabled ?? true) {
|
|
201
|
+
await enforceTenantActiveScheduleLimit(em, input.tenantId)
|
|
202
|
+
}
|
|
203
|
+
|
|
191
204
|
// Calculate next run time
|
|
192
|
-
const nextRunAt =
|
|
205
|
+
const nextRunAt = calculateNextRunForWrite(
|
|
193
206
|
input.scheduleType,
|
|
194
207
|
input.scheduleValue,
|
|
195
208
|
input.timezone || 'UTC'
|
|
@@ -218,7 +231,7 @@ const createScheduleCommand: CommandHandler<ScheduleCreateInput, { id: string }>
|
|
|
218
231
|
sourceType: input.sourceType ?? 'user',
|
|
219
232
|
sourceModule: input.sourceModule ?? null,
|
|
220
233
|
nextRunAt,
|
|
221
|
-
createdByUserId: (ctx
|
|
234
|
+
createdByUserId: resolveCommandActorUserId(ctx),
|
|
222
235
|
createdAt: new Date(),
|
|
223
236
|
updatedAt: new Date(),
|
|
224
237
|
})
|
|
@@ -297,6 +310,26 @@ const updateScheduleCommand: CommandHandler<ScheduleUpdateInput, { ok: boolean }
|
|
|
297
310
|
if (schedule.organizationId) ensureOrganizationScope(ctx, schedule.organizationId)
|
|
298
311
|
ensureCanManageSystemScopedJob(ctx, schedule)
|
|
299
312
|
|
|
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
|
+
|
|
300
333
|
// Update fields
|
|
301
334
|
if (input.name !== undefined) schedule.name = input.name
|
|
302
335
|
if (input.description !== undefined) schedule.description = input.description ?? null
|
|
@@ -326,20 +359,12 @@ const updateScheduleCommand: CommandHandler<ScheduleUpdateInput, { ok: boolean }
|
|
|
326
359
|
if (input.targetCommand !== undefined) schedule.targetCommand = input.targetCommand
|
|
327
360
|
}
|
|
328
361
|
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
const nextRunAt = calculateNextRun(
|
|
332
|
-
schedule.scheduleType,
|
|
333
|
-
schedule.scheduleValue,
|
|
334
|
-
schedule.timezone
|
|
335
|
-
)
|
|
336
|
-
if (nextRunAt) {
|
|
337
|
-
schedule.nextRunAt = nextRunAt
|
|
338
|
-
}
|
|
362
|
+
if (nextRunAt) {
|
|
363
|
+
schedule.nextRunAt = nextRunAt
|
|
339
364
|
}
|
|
340
365
|
|
|
341
366
|
schedule.updatedAt = new Date()
|
|
342
|
-
schedule.updatedByUserId = (ctx
|
|
367
|
+
schedule.updatedByUserId = resolveCommandActorUserId(ctx)
|
|
343
368
|
|
|
344
369
|
await em.flush()
|
|
345
370
|
|
|
@@ -430,7 +455,7 @@ const deleteScheduleCommand: CommandHandler<{ id: string }, { ok: boolean }> = {
|
|
|
430
455
|
// Soft delete
|
|
431
456
|
schedule.deletedAt = new Date()
|
|
432
457
|
schedule.updatedAt = new Date()
|
|
433
|
-
schedule.updatedByUserId = (ctx
|
|
458
|
+
schedule.updatedByUserId = resolveCommandActorUserId(ctx)
|
|
434
459
|
|
|
435
460
|
await em.flush()
|
|
436
461
|
|
|
@@ -147,7 +147,7 @@ export function ExecutionDetailsDialog({
|
|
|
147
147
|
{run.status === 'failed' && run.errorMessage && (
|
|
148
148
|
<div>
|
|
149
149
|
<Label className="text-sm font-medium text-muted-foreground">{t('scheduler.execution.error_message', 'Error Message')}</Label>
|
|
150
|
-
<Alert
|
|
150
|
+
<Alert status="error" className="mt-2">
|
|
151
151
|
<AlertDescription>
|
|
152
152
|
<div className="flex items-start gap-2">
|
|
153
153
|
<span className="text-lg">⚠️</span>
|
|
@@ -7,19 +7,38 @@ import {
|
|
|
7
7
|
scheduleTriggerSchema,
|
|
8
8
|
scheduleRunsQuerySchema,
|
|
9
9
|
} from '../validators'
|
|
10
|
-
import { registerCommand } from '@open-mercato/shared/lib/commands'
|
|
11
|
-
import type { CommandHandler } from '@open-mercato/shared/lib/commands'
|
|
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'
|
|
12
16
|
|
|
13
|
-
// Register
|
|
14
|
-
const testCommand: CommandHandler<
|
|
17
|
+
// Register test commands for validation tests
|
|
18
|
+
const testCommand: CommandHandler<unknown, { ok: boolean }> = {
|
|
15
19
|
id: 'test.command.for.validators',
|
|
16
20
|
async execute() {
|
|
17
21
|
return { ok: true }
|
|
18
22
|
},
|
|
19
23
|
}
|
|
20
24
|
|
|
25
|
+
const schedulableTestCommand: CommandHandler<unknown, { ok: boolean }> = {
|
|
26
|
+
id: 'test.command.schedulable',
|
|
27
|
+
async execute() {
|
|
28
|
+
return { ok: true }
|
|
29
|
+
},
|
|
30
|
+
}
|
|
31
|
+
|
|
21
32
|
beforeAll(() => {
|
|
33
|
+
clearSchedulerSafeCommandsForTests()
|
|
22
34
|
registerCommand(testCommand)
|
|
35
|
+
registerCommand(schedulableTestCommand)
|
|
36
|
+
registerSchedulerSafeCommands([
|
|
37
|
+
{
|
|
38
|
+
commandId: 'test.command.schedulable',
|
|
39
|
+
requiredFeatures: ['scheduler.jobs.manage'],
|
|
40
|
+
},
|
|
41
|
+
])
|
|
23
42
|
})
|
|
24
43
|
|
|
25
44
|
const tenantId = '123e4567-e89b-12d3-a456-426614174000'
|
|
@@ -56,7 +75,7 @@ describe('scheduleCreateSchema', () => {
|
|
|
56
75
|
scheduleValue: '1h',
|
|
57
76
|
timezone: 'America/New_York',
|
|
58
77
|
targetType: 'command',
|
|
59
|
-
targetCommand: 'test.command.
|
|
78
|
+
targetCommand: 'test.command.schedulable',
|
|
60
79
|
targetPayload: { foo: 'bar' },
|
|
61
80
|
isEnabled: true,
|
|
62
81
|
})
|
|
@@ -68,7 +87,7 @@ describe('scheduleCreateSchema', () => {
|
|
|
68
87
|
expect(result.scheduleType).toBe('interval')
|
|
69
88
|
expect(result.scheduleValue).toBe('1h')
|
|
70
89
|
expect(result.targetType).toBe('command')
|
|
71
|
-
expect(result.targetCommand).toBe('test.command.
|
|
90
|
+
expect(result.targetCommand).toBe('test.command.schedulable')
|
|
72
91
|
})
|
|
73
92
|
|
|
74
93
|
it('should accept valid tenant-scoped schedule', () => {
|
|
@@ -126,7 +145,8 @@ describe('scheduleCreateSchema', () => {
|
|
|
126
145
|
|
|
127
146
|
it('should accept various interval formats', () => {
|
|
128
147
|
const validIntervals = [
|
|
129
|
-
'
|
|
148
|
+
'60s', // 60 seconds
|
|
149
|
+
'1m', // 1 minute
|
|
130
150
|
'15m', // 15 minutes
|
|
131
151
|
'2h', // 2 hours
|
|
132
152
|
'1d', // 1 day
|
|
@@ -270,6 +290,19 @@ describe('scheduleCreateSchema', () => {
|
|
|
270
290
|
})
|
|
271
291
|
).toThrow(/Command does not exist/)
|
|
272
292
|
})
|
|
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
|
+
})
|
|
273
306
|
})
|
|
274
307
|
|
|
275
308
|
describe('schedule validation', () => {
|
|
@@ -324,6 +357,23 @@ describe('scheduleCreateSchema', () => {
|
|
|
324
357
|
})
|
|
325
358
|
).toThrow(/Invalid schedule value/)
|
|
326
359
|
})
|
|
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
|
+
})
|
|
327
377
|
})
|
|
328
378
|
|
|
329
379
|
describe('field constraints', () => {
|
|
@@ -436,6 +486,16 @@ describe('scheduleUpdateSchema', () => {
|
|
|
436
486
|
).toThrow(/Invalid schedule value/)
|
|
437
487
|
})
|
|
438
488
|
|
|
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
|
+
|
|
439
499
|
it('should require targetQueue when changing to queue target', () => {
|
|
440
500
|
expect(() =>
|
|
441
501
|
scheduleUpdateSchema.parse({
|
|
@@ -458,11 +518,11 @@ describe('scheduleUpdateSchema', () => {
|
|
|
458
518
|
const result = scheduleUpdateSchema.parse({
|
|
459
519
|
id: scheduleId,
|
|
460
520
|
targetType: 'command',
|
|
461
|
-
targetCommand: 'test.command.
|
|
521
|
+
targetCommand: 'test.command.schedulable',
|
|
462
522
|
})
|
|
463
523
|
|
|
464
524
|
expect(result.targetType).toBe('command')
|
|
465
|
-
expect(result.targetCommand).toBe('test.command.
|
|
525
|
+
expect(result.targetCommand).toBe('test.command.schedulable')
|
|
466
526
|
})
|
|
467
527
|
|
|
468
528
|
it('should reject non-existent command on update', () => {
|
|
@@ -1,8 +1,9 @@
|
|
|
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'
|
|
4
|
+
import { commandRegistry } from '@open-mercato/shared/lib/commands/registry'
|
|
5
5
|
import { parseBooleanToken } from '@open-mercato/shared/lib/boolean'
|
|
6
|
+
import { isSchedulerSafeCommandId } from '../lib/scheduler-safe-commands'
|
|
6
7
|
|
|
7
8
|
/**
|
|
8
9
|
* Validate that a command exists in the command registry
|
|
@@ -11,6 +12,10 @@ function validateCommandExists(commandId: string): boolean {
|
|
|
11
12
|
return commandRegistry.has(commandId)
|
|
12
13
|
}
|
|
13
14
|
|
|
15
|
+
function validateCommandIsSchedulable(commandId: string): boolean {
|
|
16
|
+
return isSchedulerSafeCommandId(commandId)
|
|
17
|
+
}
|
|
18
|
+
|
|
14
19
|
/**
|
|
15
20
|
* Base schedule fields
|
|
16
21
|
*/
|
|
@@ -103,6 +108,18 @@ export const scheduleCreateSchema = scheduleBaseSchema
|
|
|
103
108
|
path: ['targetCommand'],
|
|
104
109
|
}
|
|
105
110
|
)
|
|
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
|
+
)
|
|
106
123
|
|
|
107
124
|
/**
|
|
108
125
|
* Update schedule schema (all fields optional except id)
|
|
@@ -185,6 +202,18 @@ export const scheduleUpdateSchema = z.object({
|
|
|
185
202
|
path: ['targetCommand'],
|
|
186
203
|
}
|
|
187
204
|
)
|
|
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
|
+
)
|
|
188
217
|
|
|
189
218
|
/**
|
|
190
219
|
* Delete schedule schema
|
|
@@ -26,6 +26,7 @@
|
|
|
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}).",
|
|
29
30
|
"scheduler.error.async_strategy_hint": "Bitte setzen Sie QUEUE_STRATEGY=async, um den Ausführungsverlauf einzusehen",
|
|
30
31
|
"scheduler.error.async_strategy_required": "Ausführungsverlauf erfordert QUEUE_STRATEGY=async",
|
|
31
32
|
"scheduler.error.bullmq_required": "BullMQ-Job-Logs sind nur mit QUEUE_STRATEGY=async verfügbar",
|
|
@@ -36,6 +37,7 @@
|
|
|
36
37
|
"scheduler.error.forbidden": "Verboten",
|
|
37
38
|
"scheduler.error.invalidPayload": "Ungültiges JSON-Payload",
|
|
38
39
|
"scheduler.error.invalid_queue_name": "Ungültiger Queue-Name",
|
|
40
|
+
"scheduler.error.invalid_schedule_value": "Ungültiger Zeitplanwert.",
|
|
39
41
|
"scheduler.error.job_not_found": "Job in BullMQ nicht gefunden (möglicherweise entfernt)",
|
|
40
42
|
"scheduler.error.load_failed": "Fehler beim Laden des Zeitplans",
|
|
41
43
|
"scheduler.error.not_found": "Zeitplan nicht gefunden",
|
|
@@ -26,6 +26,7 @@
|
|
|
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}).",
|
|
29
30
|
"scheduler.error.async_strategy_hint": "Please set QUEUE_STRATEGY=async to view execution history",
|
|
30
31
|
"scheduler.error.async_strategy_required": "Execution history requires QUEUE_STRATEGY=async",
|
|
31
32
|
"scheduler.error.bullmq_required": "BullMQ job logs are only available with QUEUE_STRATEGY=async",
|
|
@@ -36,6 +37,7 @@
|
|
|
36
37
|
"scheduler.error.forbidden": "Forbidden",
|
|
37
38
|
"scheduler.error.invalidPayload": "Invalid JSON payload",
|
|
38
39
|
"scheduler.error.invalid_queue_name": "Invalid queue name",
|
|
40
|
+
"scheduler.error.invalid_schedule_value": "Invalid schedule value.",
|
|
39
41
|
"scheduler.error.job_not_found": "Job not found in BullMQ (may have been removed)",
|
|
40
42
|
"scheduler.error.load_failed": "Failed to load schedule",
|
|
41
43
|
"scheduler.error.not_found": "Schedule not found",
|
|
@@ -26,6 +26,7 @@
|
|
|
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}).",
|
|
29
30
|
"scheduler.error.async_strategy_hint": "Configure QUEUE_STRATEGY=async para ver el historial de ejecución",
|
|
30
31
|
"scheduler.error.async_strategy_required": "El historial de ejecución requiere QUEUE_STRATEGY=async",
|
|
31
32
|
"scheduler.error.bullmq_required": "Los registros de trabajos de BullMQ solo están disponibles con QUEUE_STRATEGY=async",
|
|
@@ -36,6 +37,7 @@
|
|
|
36
37
|
"scheduler.error.forbidden": "Prohibido",
|
|
37
38
|
"scheduler.error.invalidPayload": "Carga JSON no válida",
|
|
38
39
|
"scheduler.error.invalid_queue_name": "Nombre de cola inválido",
|
|
40
|
+
"scheduler.error.invalid_schedule_value": "Valor de programación no válido.",
|
|
39
41
|
"scheduler.error.job_not_found": "Trabajo no encontrado en BullMQ (puede haber sido eliminado)",
|
|
40
42
|
"scheduler.error.load_failed": "Error al cargar la programación",
|
|
41
43
|
"scheduler.error.not_found": "Programación no encontrada",
|