@open-mercato/scheduler 0.6.7-develop.6860.1.f796b22e80 → 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
@@ -1,7 +1,6 @@
1
1
  import type { EntityManager } from '@mikro-orm/core'
2
2
  import { ScheduledJob } from '../data/entities.js'
3
- import { calculateNextRunForWrite } from '../lib/nextRunCalculator.js'
4
- import { enforceTenantActiveScheduleLimit } from '../lib/activeScheduleLimits.js'
3
+ import { calculateNextRun } from '../lib/nextRunCalculator.js'
5
4
  import type { BullMQSchedulerService } from './bullmqSchedulerService.js'
6
5
  import { createLogger } from '@open-mercato/shared/lib/logger'
7
6
 
@@ -46,7 +45,7 @@ export class SchedulerService {
46
45
  this.validateTarget(registration)
47
46
 
48
47
  // Calculate next run time
49
- const nextRunAt = calculateNextRunForWrite(
48
+ const nextRunAt = calculateNextRun(
50
49
  registration.scheduleType,
51
50
  registration.scheduleValue,
52
51
  registration.timezone || 'UTC'
@@ -58,12 +57,6 @@ export class SchedulerService {
58
57
 
59
58
  // Check if schedule already exists
60
59
  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
- }
67
60
 
68
61
  if (schedule) {
69
62
  // Update existing
@@ -172,22 +165,6 @@ export class SchedulerService {
172
165
  if (!schedule) {
173
166
  throw new Error(`Schedule not found: ${scheduleId}`)
174
167
  }
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
- }
191
168
 
192
169
  // Apply changes
193
170
  if (changes.name !== undefined) schedule.name = changes.name
@@ -220,8 +197,16 @@ export class SchedulerService {
220
197
  if (changes.targetCommand !== undefined) schedule.targetCommand = changes.targetCommand || null
221
198
  }
222
199
 
223
- if (nextRunAt) {
224
- schedule.nextRunAt = nextRunAt
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
+ }
225
210
  }
226
211
 
227
212
  schedule.updatedAt = new Date()
@@ -2,7 +2,6 @@ import { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'
2
2
  import { ensureTenantScope } from '@open-mercato/shared/lib/commands/scope'
3
3
  import { createQueue } from '@open-mercato/queue'
4
4
  import { ScheduledJob } from '../../data/entities'
5
- import { registerSchedulerSafeCommands } from '../../lib/scheduler-safe-commands'
6
5
  import executeScheduleWorker from '../execute-schedule.worker'
7
6
 
8
7
  const mockCommandExecute = jest.fn()
@@ -42,7 +41,6 @@ function buildCommandSchedule(overrides: Partial<ScheduledJob> = {}): ScheduledJ
42
41
  schedule.scheduleValue = '* * * * *'
43
42
  schedule.timezone = 'UTC'
44
43
  schedule.sourceType = 'user'
45
- schedule.createdByUserId = 'user-a'
46
44
  schedule.createdAt = new Date('2026-01-01T00:00:00.000Z')
47
45
  schedule.updatedAt = new Date('2026-01-01T00:00:00.000Z')
48
46
  Object.assign(schedule, overrides)
@@ -56,7 +54,6 @@ function buildWorkerContext(schedule: ScheduledJob) {
56
54
  }
57
55
  const rbacService = {
58
56
  tenantHasFeature: jest.fn(async () => true),
59
- userHasAllFeatures: jest.fn(async () => true),
60
57
  }
61
58
  return {
62
59
  context: {
@@ -74,15 +71,6 @@ function buildWorkerContext(schedule: ScheduledJob) {
74
71
  }
75
72
 
76
73
  describe('executeScheduleWorker command scope', () => {
77
- beforeAll(() => {
78
- registerSchedulerSafeCommands([
79
- {
80
- commandId: 'scheduler.test.assert-tenant-scope',
81
- requiredFeatures: ['scheduler.jobs.manage'],
82
- },
83
- ])
84
- })
85
-
86
74
  afterEach(() => {
87
75
  mockCommandExecute.mockReset()
88
76
  })
@@ -6,7 +6,6 @@ import { ScheduledJob } from '../data/entities.js'
6
6
  import { CommandBus } from '@open-mercato/shared/lib/commands'
7
7
  import type { AppContainer } from '@open-mercato/shared/lib/di/container'
8
8
  import { emitSchedulerEvent } from '../events.js'
9
- import { assertSchedulerSafeCommandAuthorized } from '../lib/scheduler-safe-commands.js'
10
9
  import { buildScheduledCommandContext } from '../lib/commandContext.js'
11
10
  import { buildQueueTargetPayload, buildSchedulerIdempotencyKey } from '../lib/queueTargetPayload.js'
12
11
  import { createLogger } from '@open-mercato/shared/lib/logger'
@@ -35,11 +34,6 @@ type RbacServiceLike = {
35
34
  feature: string,
36
35
  opts?: { organizationId?: string | null },
37
36
  ): Promise<boolean>
38
- userHasAllFeatures(
39
- userId: string,
40
- required: readonly string[],
41
- scope: { tenantId: string | null; organizationId: string | null },
42
- ): Promise<boolean>
43
37
  }
44
38
 
45
39
  /**
@@ -211,14 +205,6 @@ export default async function executeScheduleWorker(
211
205
 
212
206
  } else if (schedule.targetType === 'command' && schedule.targetCommand) {
213
207
  const commandBus = new CommandBus()
214
- const actorUserId = typeof schedule.createdByUserId === 'string' ? schedule.createdByUserId.trim() : ''
215
- await assertSchedulerSafeCommandAuthorized({
216
- commandId: schedule.targetCommand,
217
- actorUserId,
218
- tenantId: schedule.tenantId,
219
- organizationId: schedule.organizationId,
220
- rbacService,
221
- })
222
208
 
223
209
  const commandInput = {
224
210
  ...((schedule.targetPayload as Record<string, unknown>) || {}),
@@ -226,7 +212,6 @@ export default async function executeScheduleWorker(
226
212
  organizationId: schedule.organizationId,
227
213
  }
228
214
 
229
- // Build the schedule-scoped command context after the allowlist/RBAC gate.
230
215
  const commandCtx = buildScheduledCommandContext(schedule, ctx as unknown as AppContainer)
231
216
 
232
217
  const commandResult = await commandBus.execute(schedule.targetCommand, {
@@ -1,157 +0,0 @@
1
- {
2
- "scheduler.action.create": "새 일정",
3
- "scheduler.action.delete": "삭제",
4
- "scheduler.action.edit": "편집",
5
- "scheduler.action.refresh": "새로고침",
6
- "scheduler.action.trigger": "지금 실행",
7
- "scheduler.action.view": "보기",
8
- "scheduler.audit.create": "일정 생성",
9
- "scheduler.audit.delete": "일정 삭제",
10
- "scheduler.audit.update": "일정 수정",
11
- "scheduler.confirm.delete": "이 일정을 삭제하시겠습니까?",
12
- "scheduler.confirm.trigger": "지금 \"{name}\"을(를) 실행하시겠습니까?\n\n{targetType}이(가) 즉시 실행됩니다.",
13
- "scheduler.create.title": "일정 생성",
14
- "scheduler.details.configuration": "구성",
15
- "scheduler.details.error": "오류",
16
- "scheduler.details.executions_async_only": "실행 기록 및 수동 실행은 비동기 큐 전략(QUEUE_STRATEGY=async)이 필요합니다.",
17
- "scheduler.details.last_run": "마지막 실행",
18
- "scheduler.details.no_executions": "아직 실행 기록이 없습니다",
19
- "scheduler.details.not_found": "찾을 수 없음",
20
- "scheduler.details.payload": "페이로드",
21
- "scheduler.details.recent_executions": "최근 실행",
22
- "scheduler.details.required_feature": "필요한 기능",
23
- "scheduler.details.scope": "범위",
24
- "scheduler.details.source_module": "모듈",
25
- "scheduler.details.source_user": "사용자 생성",
26
- "scheduler.details.triggering": "실행 중...",
27
- "scheduler.edit.title": "일정 편집",
28
- "scheduler.error.access_denied": "접근이 거부되었습니다",
29
- "scheduler.error.active_schedule_limit": "이 테넌트({max})에 대한 활성 예약 작업 제한에 도달했습니다.",
30
- "scheduler.error.async_strategy_hint": "실행 기록을 보려면 QUEUE_STRATEGY=async를 설정하세요",
31
- "scheduler.error.async_strategy_required": "실행 기록에는 QUEUE_STRATEGY=async가 필요합니다",
32
- "scheduler.error.bullmq_required": "BullMQ 작업 로그는 QUEUE_STRATEGY=async에서만 사용할 수 있습니다",
33
- "scheduler.error.delete_failed": "일정 삭제에 실패했습니다",
34
- "scheduler.error.fetch_executions_failed": "실행 기록을 가져오지 못했습니다",
35
- "scheduler.error.fetch_failed": "일정을 불러오지 못했습니다",
36
- "scheduler.error.fetch_job_failed": "작업 상세 정보를 가져오지 못했습니다",
37
- "scheduler.error.forbidden": "접근이 거부되었습니다",
38
- "scheduler.error.invalidPayload": "잘못된 JSON 페이로드입니다",
39
- "scheduler.error.invalid_queue_name": "잘못된 큐 이름입니다",
40
- "scheduler.error.invalid_schedule_value": "일정 값이 잘못되었습니다.",
41
- "scheduler.error.job_not_found": "BullMQ에서 작업을 찾을 수 없습니다 (제거되었을 수 있음)",
42
- "scheduler.error.load_failed": "일정을 불러오지 못했습니다",
43
- "scheduler.error.not_found": "일정을 찾을 수 없습니다",
44
- "scheduler.error.queue_param_required": "queue 매개변수가 필요합니다",
45
- "scheduler.error.trigger_async_hint": "실행 기록 및 수동 실행은 BullMQ(비동기 전략)에서만 사용할 수 있습니다",
46
- "scheduler.error.trigger_async_required": "수동 실행에는 QUEUE_STRATEGY=async가 필요합니다",
47
- "scheduler.error.trigger_failed": "일정 실행에 실패했습니다",
48
- "scheduler.error.unauthorized": "권한이 없습니다",
49
- "scheduler.error.update_failed": "일정 수정에 실패했습니다",
50
- "scheduler.errors.id_required": "일정 식별자는 필수입니다.",
51
- "scheduler.execution.actions": "작업",
52
- "scheduler.execution.completed_message": "이 실행은 오류 없이 성공적으로 완료되었습니다.",
53
- "scheduler.execution.details_title": "실행 상세 정보",
54
- "scheduler.execution.duration": "소요 시간",
55
- "scheduler.execution.error_message": "오류 메시지",
56
- "scheduler.execution.finished_at": "완료 시각",
57
- "scheduler.execution.na": "해당 없음",
58
- "scheduler.execution.queue_job_id": "큐 작업 ID",
59
- "scheduler.execution.queue_name": "큐 이름",
60
- "scheduler.execution.run_id": "실행 ID",
61
- "scheduler.execution.running_message": "이 실행은 현재 진행 중입니다.",
62
- "scheduler.execution.skipped_message": "이 실행은 건너뛰어졌습니다.",
63
- "scheduler.execution.stack_trace": "스택 추적",
64
- "scheduler.execution.started": "시작됨",
65
- "scheduler.execution.started_at": "시작 시각",
66
- "scheduler.execution.status": "상태",
67
- "scheduler.execution.trigger": "트리거",
68
- "scheduler.execution.trigger_type": "트리거 유형",
69
- "scheduler.execution.view_details": "상세 정보 보기",
70
- "scheduler.execution.view_logs": "로그 보기",
71
- "scheduler.execution_status.completed": "완료됨",
72
- "scheduler.execution_status.failed": "실패",
73
- "scheduler.execution_status.running": "실행 중",
74
- "scheduler.execution_status.skipped": "건너뜀",
75
- "scheduler.execution_status.waiting": "대기 중",
76
- "scheduler.field.active": "활성",
77
- "scheduler.field.description": "설명",
78
- "scheduler.field.name": "이름",
79
- "scheduler.field.next_run": "다음 실행",
80
- "scheduler.field.schedule": "일정",
81
- "scheduler.field.schedule_type": "유형",
82
- "scheduler.field.schedule_value": "일정 값",
83
- "scheduler.field.source": "소스",
84
- "scheduler.field.status": "상태",
85
- "scheduler.field.target": "대상",
86
- "scheduler.field.timezone": "표준 시간대",
87
- "scheduler.form.description": "설명",
88
- "scheduler.form.disabled": "비활성화됨",
89
- "scheduler.form.enabled": "활성화됨",
90
- "scheduler.form.group.basic": "기본 정보",
91
- "scheduler.form.group.schedule": "일정 구성",
92
- "scheduler.form.group.target": "대상 구성",
93
- "scheduler.form.is_enabled": "활성화됨",
94
- "scheduler.form.name": "이름",
95
- "scheduler.form.name.required": "이름은 필수입니다",
96
- "scheduler.form.save": "변경 사항 저장",
97
- "scheduler.form.schedule": "일정",
98
- "scheduler.form.schedule.required": "일정은 필수입니다",
99
- "scheduler.form.schedule_type": "일정 유형",
100
- "scheduler.form.schedule_value": "일정 값",
101
- "scheduler.form.schedule_value.description": "cron: cron 표현식을 사용하세요 (예: \"0 0 * * *\"). interval: \"15m\", \"2h\", \"1d\"와 같은 형식을 사용하세요 (s=초, m=분, h=시간, d=일)",
102
- "scheduler.form.schedule_value.placeholder": "예: 0 */6 * * * 또는 15m",
103
- "scheduler.form.scope_type": "범위",
104
- "scheduler.form.scope_type.locked_description": "범위는 일정이 생성될 때 설정되며 이후에는 변경할 수 없습니다.",
105
- "scheduler.form.submit": "일정 생성",
106
- "scheduler.form.target_command": "대상 명령",
107
- "scheduler.form.target_command.placeholder": "명령 검색...",
108
- "scheduler.form.target_payload": "작업 인수 (JSON)",
109
- "scheduler.form.target_payload.description": "명령이나 큐 작업에 전달할 인수가 담긴 선택적 JSON 객체입니다. 유효한 JSON 형식이어야 합니다.",
110
- "scheduler.form.target_payload.invalid_json": "유효한 JSON이어야 합니다",
111
- "scheduler.form.target_payload.placeholder": "{\n \"message\": \"Hello\",\n \"value\": 42\n}",
112
- "scheduler.form.target_queue": "대상 큐",
113
- "scheduler.form.target_queue.placeholder": "큐 검색...",
114
- "scheduler.form.target_type": "대상 유형",
115
- "scheduler.form.timezone": "표준 시간대",
116
- "scheduler.form.timezone.placeholder": "표준 시간대 검색...",
117
- "scheduler.job_logs.attempts": "시도 횟수",
118
- "scheduler.job_logs.duration": "소요 시간",
119
- "scheduler.job_logs.error_message": "오류 메시지",
120
- "scheduler.job_logs.finished": "완료됨",
121
- "scheduler.job_logs.job_id": "작업 ID",
122
- "scheduler.job_logs.load_failed": "작업 상세 정보를 불러오지 못했습니다",
123
- "scheduler.job_logs.no_logs": "사용 가능한 로그가 없습니다",
124
- "scheduler.job_logs.processed": "처리됨",
125
- "scheduler.job_logs.progress": "진행 상황",
126
- "scheduler.job_logs.return_value": "반환 값",
127
- "scheduler.job_logs.stack_trace": "스택 추적",
128
- "scheduler.job_logs.state": "상태",
129
- "scheduler.job_logs.tab_error": "오류 상세 정보",
130
- "scheduler.job_logs.tab_logs": "로그",
131
- "scheduler.job_logs.tab_overview": "개요",
132
- "scheduler.job_logs.tab_payload": "페이로드",
133
- "scheduler.job_logs.title": "큐 작업",
134
- "scheduler.loading": "일정을 불러오는 중...",
135
- "scheduler.module.description": "cron 표현식이나 간단한 간격으로 자동화된 예약 작업을 관리합니다.",
136
- "scheduler.module.title": "예약된 작업",
137
- "scheduler.nav.backToList": "예약된 작업으로 돌아가기",
138
- "scheduler.scope.organization": "조직",
139
- "scheduler.scope.system": "시스템",
140
- "scheduler.scope.tenant": "테넌트",
141
- "scheduler.search.placeholder": "일정 검색...",
142
- "scheduler.status.disabled": "비활성화됨",
143
- "scheduler.status.enabled": "활성화됨",
144
- "scheduler.success.created": "일정이 성공적으로 생성되었습니다",
145
- "scheduler.success.deleted": "일정이 성공적으로 삭제되었습니다",
146
- "scheduler.success.disabled": "일정이 비활성화되었습니다",
147
- "scheduler.success.enabled": "일정이 활성화되었습니다",
148
- "scheduler.success.triggered": "일정이 성공적으로 실행되었습니다",
149
- "scheduler.success.updated": "일정이 성공적으로 수정되었습니다",
150
- "scheduler.target.command": "명령",
151
- "scheduler.target.queue": "큐",
152
- "scheduler.title": "예약된 작업",
153
- "scheduler.trigger_type.manual": "수동",
154
- "scheduler.trigger_type.scheduled": "예약됨",
155
- "scheduler.type.cron": "Cron 표현식",
156
- "scheduler.type.interval": "간단한 간격"
157
- }
@@ -1,44 +0,0 @@
1
- import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
2
- import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
3
- import { createFallbackTranslator } from "@open-mercato/shared/lib/i18n/translate";
4
- import { ScheduledJob } from "../data/entities.js";
5
- const DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT = 100;
6
- const ACTIVE_SCHEDULE_LIMIT_ENV = "OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT";
7
- function getMaxActiveSchedulesPerTenant() {
8
- const parsed = Number.parseInt(process.env[ACTIVE_SCHEDULE_LIMIT_ENV] ?? "", 10);
9
- if (Number.isFinite(parsed) && parsed > 0) return parsed;
10
- return DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT;
11
- }
12
- async function resolveActiveScheduleLimitTranslator() {
13
- try {
14
- const { translate } = await resolveTranslations();
15
- return translate;
16
- } catch {
17
- return createFallbackTranslator({});
18
- }
19
- }
20
- async function enforceTenantActiveScheduleLimit(em, tenantId) {
21
- if (!tenantId) return;
22
- const maxActiveSchedules = getMaxActiveSchedulesPerTenant();
23
- const activeScheduleCount = await em.count(ScheduledJob, {
24
- tenantId,
25
- isEnabled: true,
26
- deletedAt: null
27
- });
28
- if (activeScheduleCount >= maxActiveSchedules) {
29
- const translate = await resolveActiveScheduleLimitTranslator();
30
- throw new CrudHttpError(422, {
31
- error: translate(
32
- "scheduler.error.active_schedule_limit",
33
- "Active scheduled job limit reached for this tenant ({max}).",
34
- { max: maxActiveSchedules }
35
- )
36
- });
37
- }
38
- }
39
- export {
40
- DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT,
41
- enforceTenantActiveScheduleLimit,
42
- getMaxActiveSchedulesPerTenant
43
- };
44
- //# sourceMappingURL=activeScheduleLimits.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../../src/modules/scheduler/lib/activeScheduleLimits.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/core'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { createFallbackTranslator, type TranslateWithFallbackFn } from '@open-mercato/shared/lib/i18n/translate'\nimport { ScheduledJob } from '../data/entities.js'\n\nexport const DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT = 100\nconst ACTIVE_SCHEDULE_LIMIT_ENV = 'OM_SCHEDULER_MAX_ACTIVE_SCHEDULES_PER_TENANT'\n\nexport function getMaxActiveSchedulesPerTenant(): number {\n const parsed = Number.parseInt(process.env[ACTIVE_SCHEDULE_LIMIT_ENV] ?? '', 10)\n if (Number.isFinite(parsed) && parsed > 0) return parsed\n return DEFAULT_MAX_ACTIVE_SCHEDULES_PER_TENANT\n}\n\nasync function resolveActiveScheduleLimitTranslator(): Promise<TranslateWithFallbackFn> {\n try {\n const { translate } = await resolveTranslations()\n return translate\n } catch {\n return createFallbackTranslator({})\n }\n}\n\nexport async function enforceTenantActiveScheduleLimit(\n em: EntityManager,\n tenantId: string | null | undefined,\n): Promise<void> {\n if (!tenantId) return\n\n const maxActiveSchedules = getMaxActiveSchedulesPerTenant()\n const activeScheduleCount = await em.count(ScheduledJob, {\n tenantId,\n isEnabled: true,\n deletedAt: null,\n })\n\n if (activeScheduleCount >= maxActiveSchedules) {\n const translate = await resolveActiveScheduleLimitTranslator()\n throw new CrudHttpError(422, {\n error: translate(\n 'scheduler.error.active_schedule_limit',\n 'Active scheduled job limit reached for this tenant ({max}).',\n { max: maxActiveSchedules },\n ),\n })\n }\n}\n"],
5
- "mappings": "AACA,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,gCAA8D;AACvE,SAAS,oBAAoB;AAEtB,MAAM,0CAA0C;AACvD,MAAM,4BAA4B;AAE3B,SAAS,iCAAyC;AACvD,QAAM,SAAS,OAAO,SAAS,QAAQ,IAAI,yBAAyB,KAAK,IAAI,EAAE;AAC/E,MAAI,OAAO,SAAS,MAAM,KAAK,SAAS,EAAG,QAAO;AAClD,SAAO;AACT;AAEA,eAAe,uCAAyE;AACtF,MAAI;AACF,UAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,WAAO;AAAA,EACT,QAAQ;AACN,WAAO,yBAAyB,CAAC,CAAC;AAAA,EACpC;AACF;AAEA,eAAsB,iCACpB,IACA,UACe;AACf,MAAI,CAAC,SAAU;AAEf,QAAM,qBAAqB,+BAA+B;AAC1D,QAAM,sBAAsB,MAAM,GAAG,MAAM,cAAc;AAAA,IACvD;AAAA,IACA,WAAW;AAAA,IACX,WAAW;AAAA,EACb,CAAC;AAED,MAAI,uBAAuB,oBAAoB;AAC7C,UAAM,YAAY,MAAM,qCAAqC;AAC7D,UAAM,IAAI,cAAc,KAAK;AAAA,MAC3B,OAAO;AAAA,QACL;AAAA,QACA;AAAA,QACA,EAAE,KAAK,mBAAmB;AAAA,MAC5B;AAAA,IACF,CAAC;AAAA,EACH;AACF;",
6
- "names": []
7
- }
@@ -1,73 +0,0 @@
1
- const schedulerSafeCommands = /* @__PURE__ */ new Map();
2
- function normalizeCommandId(commandId) {
3
- if (typeof commandId !== "string") return null;
4
- const trimmed = commandId.trim();
5
- return trimmed.length > 0 ? trimmed : null;
6
- }
7
- function normalizeFeatures(features) {
8
- const normalized = features.map((feature) => feature.trim()).filter((feature) => feature.length > 0);
9
- return normalized.length > 0 ? normalized : null;
10
- }
11
- function registerSchedulerSafeCommands(commands) {
12
- for (const command of commands) {
13
- const commandId = normalizeCommandId(command.commandId);
14
- const requiredFeatures = normalizeFeatures(command.requiredFeatures);
15
- if (!commandId || !requiredFeatures) {
16
- throw new Error("[internal] Scheduler-safe commands require a commandId and requiredFeatures");
17
- }
18
- schedulerSafeCommands.set(commandId, { commandId, requiredFeatures });
19
- }
20
- }
21
- function getSchedulerSafeCommand(commandId) {
22
- const normalized = normalizeCommandId(commandId);
23
- if (!normalized) return null;
24
- return schedulerSafeCommands.get(normalized) ?? null;
25
- }
26
- function isSchedulerSafeCommandId(commandId) {
27
- return getSchedulerSafeCommand(commandId) !== null;
28
- }
29
- function listSchedulerSafeCommands() {
30
- return Array.from(schedulerSafeCommands.values()).sort((a, b) => a.commandId.localeCompare(b.commandId));
31
- }
32
- async function assertSchedulerSafeCommandAuthorized(params) {
33
- const command = getSchedulerSafeCommand(params.commandId);
34
- if (!command) {
35
- throw new Error("Scheduled command is not allowed");
36
- }
37
- const actorUserId = normalizeCommandId(params.actorUserId);
38
- if (!actorUserId) {
39
- throw new Error("Scheduled command requires an authenticated creator");
40
- }
41
- if (typeof params.rbacService.userHasAllFeatures !== "function") {
42
- throw new Error("Scheduled command authorization is unavailable");
43
- }
44
- const authorized = await params.rbacService.userHasAllFeatures(actorUserId, command.requiredFeatures, {
45
- tenantId: params.tenantId ?? null,
46
- organizationId: params.organizationId ?? null
47
- });
48
- if (!authorized) {
49
- throw new Error("Scheduled command creator is not authorized");
50
- }
51
- return command;
52
- }
53
- function clearSchedulerSafeCommandsForTests() {
54
- if (process.env.NODE_ENV !== "test") {
55
- throw new Error("[internal] clearSchedulerSafeCommandsForTests is test-only");
56
- }
57
- schedulerSafeCommands.clear();
58
- }
59
- registerSchedulerSafeCommands([
60
- {
61
- commandId: "scheduler.test.echo",
62
- requiredFeatures: ["scheduler.jobs.manage"]
63
- }
64
- ]);
65
- export {
66
- assertSchedulerSafeCommandAuthorized,
67
- clearSchedulerSafeCommandsForTests,
68
- getSchedulerSafeCommand,
69
- isSchedulerSafeCommandId,
70
- listSchedulerSafeCommands,
71
- registerSchedulerSafeCommands
72
- };
73
- //# sourceMappingURL=scheduler-safe-commands.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../../src/modules/scheduler/lib/scheduler-safe-commands.ts"],
4
- "sourcesContent": ["export type SchedulerSafeCommandDefinition = {\n commandId: string\n requiredFeatures: readonly [string, ...string[]]\n}\n\nexport type SchedulerCommandRbacService = {\n userHasAllFeatures?: (\n userId: string,\n required: readonly string[],\n scope: { tenantId: string | null; organizationId: string | null }\n ) => Promise<boolean>\n}\n\nconst schedulerSafeCommands = new Map<string, SchedulerSafeCommandDefinition>()\n\nfunction normalizeCommandId(commandId: unknown): string | null {\n if (typeof commandId !== 'string') return null\n const trimmed = commandId.trim()\n return trimmed.length > 0 ? trimmed : null\n}\n\nfunction normalizeFeatures(features: readonly string[]): [string, ...string[]] | null {\n const normalized = features\n .map((feature) => feature.trim())\n .filter((feature) => feature.length > 0)\n return normalized.length > 0 ? (normalized as [string, ...string[]]) : null\n}\n\nexport function registerSchedulerSafeCommands(commands: readonly SchedulerSafeCommandDefinition[]): void {\n for (const command of commands) {\n const commandId = normalizeCommandId(command.commandId)\n const requiredFeatures = normalizeFeatures(command.requiredFeatures)\n if (!commandId || !requiredFeatures) {\n throw new Error('[internal] Scheduler-safe commands require a commandId and requiredFeatures')\n }\n schedulerSafeCommands.set(commandId, { commandId, requiredFeatures })\n }\n}\n\nexport function getSchedulerSafeCommand(commandId: unknown): SchedulerSafeCommandDefinition | null {\n const normalized = normalizeCommandId(commandId)\n if (!normalized) return null\n return schedulerSafeCommands.get(normalized) ?? null\n}\n\nexport function isSchedulerSafeCommandId(commandId: unknown): boolean {\n return getSchedulerSafeCommand(commandId) !== null\n}\n\nexport function listSchedulerSafeCommands(): SchedulerSafeCommandDefinition[] {\n return Array.from(schedulerSafeCommands.values()).sort((a, b) => a.commandId.localeCompare(b.commandId))\n}\n\nexport async function assertSchedulerSafeCommandAuthorized(params: {\n commandId: unknown\n actorUserId: string | null | undefined\n tenantId: string | null | undefined\n organizationId: string | null | undefined\n rbacService: SchedulerCommandRbacService\n}): Promise<SchedulerSafeCommandDefinition> {\n const command = getSchedulerSafeCommand(params.commandId)\n if (!command) {\n throw new Error('Scheduled command is not allowed')\n }\n\n const actorUserId = normalizeCommandId(params.actorUserId)\n if (!actorUserId) {\n throw new Error('Scheduled command requires an authenticated creator')\n }\n\n if (typeof params.rbacService.userHasAllFeatures !== 'function') {\n throw new Error('Scheduled command authorization is unavailable')\n }\n\n const authorized = await params.rbacService.userHasAllFeatures(actorUserId, command.requiredFeatures, {\n tenantId: params.tenantId ?? null,\n organizationId: params.organizationId ?? null,\n })\n if (!authorized) {\n throw new Error('Scheduled command creator is not authorized')\n }\n\n return command\n}\n\nexport function clearSchedulerSafeCommandsForTests(): void {\n if (process.env.NODE_ENV !== 'test') {\n throw new Error('[internal] clearSchedulerSafeCommandsForTests is test-only')\n }\n schedulerSafeCommands.clear()\n}\n\nregisterSchedulerSafeCommands([\n {\n commandId: 'scheduler.test.echo',\n requiredFeatures: ['scheduler.jobs.manage'],\n },\n])\n"],
5
- "mappings": "AAaA,MAAM,wBAAwB,oBAAI,IAA4C;AAE9E,SAAS,mBAAmB,WAAmC;AAC7D,MAAI,OAAO,cAAc,SAAU,QAAO;AAC1C,QAAM,UAAU,UAAU,KAAK;AAC/B,SAAO,QAAQ,SAAS,IAAI,UAAU;AACxC;AAEA,SAAS,kBAAkB,UAA2D;AACpF,QAAM,aAAa,SAChB,IAAI,CAAC,YAAY,QAAQ,KAAK,CAAC,EAC/B,OAAO,CAAC,YAAY,QAAQ,SAAS,CAAC;AACzC,SAAO,WAAW,SAAS,IAAK,aAAuC;AACzE;AAEO,SAAS,8BAA8B,UAA2D;AACvG,aAAW,WAAW,UAAU;AAC9B,UAAM,YAAY,mBAAmB,QAAQ,SAAS;AACtD,UAAM,mBAAmB,kBAAkB,QAAQ,gBAAgB;AACnE,QAAI,CAAC,aAAa,CAAC,kBAAkB;AACnC,YAAM,IAAI,MAAM,6EAA6E;AAAA,IAC/F;AACA,0BAAsB,IAAI,WAAW,EAAE,WAAW,iBAAiB,CAAC;AAAA,EACtE;AACF;AAEO,SAAS,wBAAwB,WAA2D;AACjG,QAAM,aAAa,mBAAmB,SAAS;AAC/C,MAAI,CAAC,WAAY,QAAO;AACxB,SAAO,sBAAsB,IAAI,UAAU,KAAK;AAClD;AAEO,SAAS,yBAAyB,WAA6B;AACpE,SAAO,wBAAwB,SAAS,MAAM;AAChD;AAEO,SAAS,4BAA8D;AAC5E,SAAO,MAAM,KAAK,sBAAsB,OAAO,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,EAAE,UAAU,cAAc,EAAE,SAAS,CAAC;AACzG;AAEA,eAAsB,qCAAqC,QAMf;AAC1C,QAAM,UAAU,wBAAwB,OAAO,SAAS;AACxD,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,kCAAkC;AAAA,EACpD;AAEA,QAAM,cAAc,mBAAmB,OAAO,WAAW;AACzD,MAAI,CAAC,aAAa;AAChB,UAAM,IAAI,MAAM,qDAAqD;AAAA,EACvE;AAEA,MAAI,OAAO,OAAO,YAAY,uBAAuB,YAAY;AAC/D,UAAM,IAAI,MAAM,gDAAgD;AAAA,EAClE;AAEA,QAAM,aAAa,MAAM,OAAO,YAAY,mBAAmB,aAAa,QAAQ,kBAAkB;AAAA,IACpG,UAAU,OAAO,YAAY;AAAA,IAC7B,gBAAgB,OAAO,kBAAkB;AAAA,EAC3C,CAAC;AACD,MAAI,CAAC,YAAY;AACf,UAAM,IAAI,MAAM,6CAA6C;AAAA,EAC/D;AAEA,SAAO;AACT;AAEO,SAAS,qCAA2C;AACzD,MAAI,QAAQ,IAAI,aAAa,QAAQ;AACnC,UAAM,IAAI,MAAM,4DAA4D;AAAA,EAC9E;AACA,wBAAsB,MAAM;AAC9B;AAEA,8BAA8B;AAAA,EAC5B;AAAA,IACE,WAAW;AAAA,IACX,kBAAkB,CAAC,uBAAuB;AAAA,EAC5C;AACF,CAAC;",
6
- "names": []
7
- }
@@ -1,76 +0,0 @@
1
- import { NextRequest } from 'next/server'
2
- import { GET } from '../route'
3
- import { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'
4
- import { getModules } from '@open-mercato/shared/lib/modules/registry'
5
- import { registerCommand, unregisterCommand } from '@open-mercato/shared/lib/commands/registry'
6
- import type { CommandHandler } from '@open-mercato/shared/lib/commands/types'
7
- import {
8
- clearSchedulerSafeCommandsForTests,
9
- registerSchedulerSafeCommands,
10
- } from '../../../lib/scheduler-safe-commands'
11
-
12
- jest.mock('@open-mercato/shared/lib/auth/server', () => ({
13
- getAuthFromRequest: jest.fn(),
14
- }))
15
-
16
- jest.mock('@open-mercato/shared/lib/modules/registry', () => ({
17
- getModules: jest.fn(),
18
- }))
19
-
20
- const safeCommand: CommandHandler<unknown, { ok: boolean }> = {
21
- id: 'test.scheduler.safe.route',
22
- async execute() {
23
- return { ok: true }
24
- },
25
- }
26
-
27
- const unsafeCommand: CommandHandler<unknown, { ok: boolean }> = {
28
- id: 'test.scheduler.unsafe.route',
29
- async execute() {
30
- return { ok: true }
31
- },
32
- }
33
-
34
- describe('GET /api/scheduler/targets', () => {
35
- beforeEach(() => {
36
- clearSchedulerSafeCommandsForTests()
37
- unregisterCommand(safeCommand.id)
38
- unregisterCommand(unsafeCommand.id)
39
- registerCommand(safeCommand)
40
- registerCommand(unsafeCommand)
41
- registerSchedulerSafeCommands([
42
- {
43
- commandId: safeCommand.id,
44
- requiredFeatures: ['scheduler.jobs.manage'],
45
- },
46
- ])
47
- ;(getAuthFromRequest as jest.Mock).mockResolvedValue({
48
- sub: 'user-1',
49
- tenantId: 'tenant-1',
50
- orgId: 'org-1',
51
- })
52
- ;(getModules as jest.Mock).mockReturnValue([
53
- { workers: [{ queue: 'z-queue' }] },
54
- { workers: [{ queue: 'a-queue' }] },
55
- ])
56
- })
57
-
58
- afterEach(() => {
59
- unregisterCommand(safeCommand.id)
60
- unregisterCommand(unsafeCommand.id)
61
- })
62
-
63
- it('lists only scheduler-safe commands', async () => {
64
- const response = await GET(new NextRequest('http://localhost/api/scheduler/targets'))
65
- const body = await response.json()
66
-
67
- expect(response.status).toBe(200)
68
- expect(body.queues).toEqual([
69
- { value: 'a-queue', label: 'a-queue' },
70
- { value: 'z-queue', label: 'z-queue' },
71
- ])
72
- expect(body.commands).toEqual([
73
- { value: safeCommand.id, label: safeCommand.id },
74
- ])
75
- })
76
- })