|
| 1 | +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; |
| 4 | +import type { PluginContext } from '@objectstack/core'; |
| 5 | +import { defineJob } from '@objectstack/spec/system'; |
| 6 | +import { InMemoryMetricsRegistry, OBSERVABILITY_METRICS_SERVICE, SEMCONV } from '@objectstack/observability'; |
| 7 | +import { CronJobAdapter } from '@objectstack/service-job'; |
| 8 | +import { AppPlugin } from './app-plugin.js'; |
| 9 | + |
| 10 | +/** |
| 11 | + * #4567 — declarative cron jobs must actually reach the scheduler. |
| 12 | + * |
| 13 | + * These run AppPlugin against the REAL `CronJobAdapter` (croner underneath), |
| 14 | + * not a recording double: the bug was that the authored schedule was rejected |
| 15 | + * *inside* the adapter and the throw was swallowed, so a double that records |
| 16 | + * whatever it is handed cannot see it. |
| 17 | + */ |
| 18 | +describe('AppPlugin — declarative background jobs (#4567)', () => { |
| 19 | + let adapter: CronJobAdapter; |
| 20 | + let metrics: InMemoryMetricsRegistry; |
| 21 | + let ctx: PluginContext; |
| 22 | + let readyHooks: Array<() => Promise<void>>; |
| 23 | + |
| 24 | + beforeEach(() => { |
| 25 | + adapter = new CronJobAdapter(); |
| 26 | + metrics = new InMemoryMetricsRegistry(); |
| 27 | + readyHooks = []; |
| 28 | + ctx = { |
| 29 | + logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }, |
| 30 | + registerService: vi.fn(), |
| 31 | + getService: vi.fn((name: string) => { |
| 32 | + if (name === 'job') return adapter; |
| 33 | + if (name === OBSERVABILITY_METRICS_SERVICE) return metrics; |
| 34 | + if (name === 'objectql') return {}; |
| 35 | + return undefined; |
| 36 | + }), |
| 37 | + getServices: vi.fn(() => []), |
| 38 | + hook: vi.fn((event: string, cb: () => Promise<void>) => { |
| 39 | + if (event === 'kernel:ready') readyHooks.push(cb); |
| 40 | + }), |
| 41 | + trigger: vi.fn(), |
| 42 | + } as unknown as PluginContext; |
| 43 | + }); |
| 44 | + |
| 45 | + afterEach(async () => { |
| 46 | + await adapter.destroy(); |
| 47 | + }); |
| 48 | + |
| 49 | + const fireReady = async () => { |
| 50 | + for (const cb of readyHooks) await cb(); |
| 51 | + }; |
| 52 | + |
| 53 | + const errorLogs = () => vi.mocked(ctx.logger.error).mock.calls.map(c => String(c[0])); |
| 54 | + const warnLogs = () => vi.mocked(ctx.logger.warn).mock.calls.map(c => String(c[0])); |
| 55 | + |
| 56 | + it('schedules a defineJob cron job end-to-end — the adapter holds a live cron task', async () => { |
| 57 | + const sweep = vi.fn(async () => { /* handler body */ }); |
| 58 | + const job = defineJob({ |
| 59 | + name: 'health_sweep', |
| 60 | + schedule: { type: 'cron', expression: '0 1 * * *' }, |
| 61 | + handler: 'sweep', |
| 62 | + }); |
| 63 | + const plugin = new AppPlugin({ |
| 64 | + id: 'com.test.jobs', |
| 65 | + jobs: [job], |
| 66 | + functions: { sweep }, |
| 67 | + }); |
| 68 | + |
| 69 | + await plugin.start!(ctx); |
| 70 | + await fireReady(); |
| 71 | + |
| 72 | + // Scheduler state, not merely "did not throw": the adapter only records |
| 73 | + // a job after `new Cron(...)` succeeded. |
| 74 | + expect(await adapter.listJobs()).toContain('health_sweep'); |
| 75 | + const task = (adapter as unknown as { jobs: Map<string, { task?: { nextRun(): Date | null } }> }) |
| 76 | + .jobs.get('health_sweep')?.task; |
| 77 | + const next = task?.nextRun(); |
| 78 | + expect(next).toBeInstanceOf(Date); |
| 79 | + // '0 1 * * *' with the schema-defaulted UTC timezone. |
| 80 | + expect(next!.getUTCHours()).toBe(1); |
| 81 | + expect(next!.getUTCMinutes()).toBe(0); |
| 82 | + |
| 83 | + // And the registered task really runs the bundle handler. |
| 84 | + await adapter.trigger('health_sweep'); |
| 85 | + expect(sweep).toHaveBeenCalledTimes(1); |
| 86 | + |
| 87 | + expect(errorLogs()).toEqual([]); |
| 88 | + expect(metrics.totalCounter(SEMCONV.jobScheduleFailuresTotal)).toBe(0); |
| 89 | + }); |
| 90 | + |
| 91 | + it('REVERT-PROOF: the raw authored schedule still breaks the adapter, exactly as #4567 reported', async () => { |
| 92 | + const job = defineJob({ |
| 93 | + name: 'health_sweep', |
| 94 | + schedule: { type: 'cron', expression: '0 1 * * *' }, |
| 95 | + handler: 'sweep', |
| 96 | + }); |
| 97 | + |
| 98 | + // What AppPlugin used to pass verbatim. The adapter's contract is a bare |
| 99 | + // string and it stays strict — remove the downgrade in AppPlugin and the |
| 100 | + // end-to-end test above fails with precisely this croner error. |
| 101 | + await expect( |
| 102 | + adapter.schedule('health_sweep', job.schedule as never, async () => { /* noop */ }), |
| 103 | + ).rejects.toThrow(/Pattern has to be of type string/i); |
| 104 | + expect(await adapter.listJobs()).not.toContain('health_sweep'); |
| 105 | + }); |
| 106 | + |
| 107 | + it('interval jobs keep working (no envelope on that branch)', async () => { |
| 108 | + const plugin = new AppPlugin({ |
| 109 | + id: 'com.test.jobs', |
| 110 | + jobs: [defineJob({ name: 'ping', schedule: { type: 'interval', intervalMs: 60_000 }, handler: 'h' })], |
| 111 | + functions: { h: vi.fn(async () => { /* noop */ }) }, |
| 112 | + }); |
| 113 | + |
| 114 | + await plugin.start!(ctx); |
| 115 | + await fireReady(); |
| 116 | + |
| 117 | + expect(await adapter.listJobs()).toContain('ping'); |
| 118 | + expect(errorLogs()).toEqual([]); |
| 119 | + }); |
| 120 | + |
| 121 | + it('a job that cannot be scheduled logs ERROR (not a silent warn) and counts', async () => { |
| 122 | + const plugin = new AppPlugin({ |
| 123 | + id: 'com.test.jobs', |
| 124 | + jobs: [{ |
| 125 | + name: 'bad_job', |
| 126 | + // A CEL envelope where a cron one belongs — unusable at the boundary. |
| 127 | + schedule: { type: 'cron', expression: { dialect: 'cel', source: 'now()' } }, |
| 128 | + handler: 'h', |
| 129 | + enabled: true, |
| 130 | + }], |
| 131 | + functions: { h: vi.fn(async () => { /* noop */ }) }, |
| 132 | + }); |
| 133 | + |
| 134 | + await plugin.start!(ctx); |
| 135 | + await fireReady(); |
| 136 | + |
| 137 | + expect(await adapter.listJobs()).not.toContain('bad_job'); |
| 138 | + |
| 139 | + // Loud: error level, its own distinct message, and a counter. |
| 140 | + const errors = errorLogs(); |
| 141 | + expect(errors.some(m => m.includes('FAILED TO SCHEDULE'))).toBe(true); |
| 142 | + expect(errors.some(m => m.includes('declared but NOT scheduled'))).toBe(true); |
| 143 | + expect(vi.mocked(ctx.logger.error).mock.calls[0][2]).toMatchObject({ job: 'bad_job' }); |
| 144 | + expect(metrics.totalCounter(SEMCONV.jobScheduleFailuresTotal, { job: 'bad_job' })).toBe(1); |
| 145 | + |
| 146 | + // NOT folded into the warn stream that "handler missing"/"disabled" use. |
| 147 | + expect(warnLogs().some(m => /schedule/i.test(m))).toBe(false); |
| 148 | + }); |
| 149 | + |
| 150 | + it('a missing handler stays a warn — the two failures are not one signal', async () => { |
| 151 | + const plugin = new AppPlugin({ |
| 152 | + id: 'com.test.jobs', |
| 153 | + jobs: [defineJob({ name: 'orphan', schedule: { type: 'cron', expression: '0 1 * * *' }, handler: 'nope' })], |
| 154 | + functions: {}, |
| 155 | + }); |
| 156 | + |
| 157 | + await plugin.start!(ctx); |
| 158 | + await fireReady(); |
| 159 | + |
| 160 | + expect(warnLogs().some(m => m.includes('job handler not found'))).toBe(true); |
| 161 | + expect(errorLogs()).toEqual([]); |
| 162 | + expect(metrics.totalCounter(SEMCONV.jobScheduleFailuresTotal)).toBe(0); |
| 163 | + }); |
| 164 | +}); |
0 commit comments