|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#6832] `hook.retryPolicy` has ONE answer per key, whether or not the metadata |
| 5 | + * has been through `HookSchema`. |
| 6 | + * |
| 7 | + * `packages/spec/src/data/hook.zod.ts` declares `maxRetries: .default(3)` and |
| 8 | + * `backoffMs: .default(1000)`. `wrapDeclarativeHook` read both with `?? 0`. So |
| 9 | + * "how many times does an under-specified hook retry?" had two answers, and the |
| 10 | + * winner depended on the path: `defineStack` / `PUT /meta` / Studio parse through |
| 11 | + * `HookSchema` and got 3, while the public `wrapDeclarativeHook` export — and |
| 12 | + * `hook-binder.ts:221`, which calls it with unparsed `Hook` metadata — got 0. |
| 13 | + * The generated reference page, the Studio form and the schema all promised a |
| 14 | + * retry that the executor silently did not perform: no error, no log line, no |
| 15 | + * red test, just the recovery the author thought they had configured, gone. |
| 16 | + * |
| 17 | + * That is the shape #4247 removed from flow `errorHandling` (`flow.zod.ts:651`, |
| 18 | + * "one contract, one number") with the numbers swapped, and the ADR-0049 |
| 19 | + * declared-=-enforced case for closing it. |
| 20 | + * |
| 21 | + * The boundary this file exists to pin — because the obvious fix breaks it: |
| 22 | + * `retryPolicy` is `.optional()` with no `.default({})`, so an ABSENT block and |
| 23 | + * an EMPTY one are different declarations. A bare `?? 3` would "fix" the |
| 24 | + * divergence by giving every hook that never wrote a `retryPolicy` three retries |
| 25 | + * it never asked for — a behaviour change for every existing author, worse than |
| 26 | + * the defect. Absent stays 0. |
| 27 | + * |
| 28 | + * 1. block absent → 1 attempt, no retry (unchanged, and correct) |
| 29 | + * 2. block present, empty → schema's 3 retries / 1000ms (was 1 attempt) |
| 30 | + * 3. block half-filled → written key wins, omitted key takes the default |
| 31 | + * 4. parsed ≡ unparsed → the two paths agree, per key |
| 32 | + */ |
| 33 | + |
| 34 | +import { describe, it, expect, vi } from 'vitest'; |
| 35 | +import { wrapDeclarativeHook } from './hook-wrappers.js'; |
| 36 | +import { HookSchema } from '@objectstack/spec/data'; |
| 37 | +import type { Hook, HookContext } from '@objectstack/spec/data'; |
| 38 | + |
| 39 | +const taskObject = { name: 'retry_task', label: 'Task', fields: {} }; |
| 40 | +const qlStub = { getObject: (n: string) => (n === 'retry_task' ? taskObject : undefined) }; |
| 41 | + |
| 42 | +function makeCtx(): HookContext { |
| 43 | + return { |
| 44 | + object: 'retry_task', |
| 45 | + event: 'beforeInsert', |
| 46 | + input: { data: { title: 'x' } }, |
| 47 | + ql: qlStub, |
| 48 | + } as unknown as HookContext; |
| 49 | +} |
| 50 | + |
| 51 | +/** |
| 52 | + * Run an always-failing hook through the declarative wrapper and report how many |
| 53 | + * times the handler was entered. `attempts === 1 + maxRetries`. |
| 54 | + * |
| 55 | + * `retryPolicy` is spread in only when supplied, so "absent" really is an absent |
| 56 | + * key and not `retryPolicy: undefined`. |
| 57 | + */ |
| 58 | +async function attemptsFor(retryPolicy?: Hook['retryPolicy']): Promise<number> { |
| 59 | + let attempts = 0; |
| 60 | + const handler = async () => { |
| 61 | + attempts += 1; |
| 62 | + throw new Error('always fails'); |
| 63 | + }; |
| 64 | + const meta = { |
| 65 | + name: 'h_retry', |
| 66 | + object: 'retry_task', |
| 67 | + events: ['beforeInsert'], |
| 68 | + handler, |
| 69 | + ...(retryPolicy === undefined ? {} : { retryPolicy }), |
| 70 | + } as unknown as Hook; |
| 71 | + |
| 72 | + const wrapped = wrapDeclarativeHook(meta, handler, { logger: { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} } }); |
| 73 | + await expect(wrapped(makeCtx())).rejects.toThrow('always fails'); |
| 74 | + return attempts; |
| 75 | +} |
| 76 | + |
| 77 | +/** The declared defaults, read from the schema so this file restates nothing either. */ |
| 78 | +function declared(): { maxRetries: number; backoffMs: number } { |
| 79 | + return HookSchema.shape.retryPolicy.unwrap().parse({}); |
| 80 | +} |
| 81 | + |
| 82 | +/** |
| 83 | + * Run `fn` with `setTimeout` firing synchronously, and return every delay it was |
| 84 | + * asked for. The retry loop's only use of the clock is the backoff sleep, so the |
| 85 | + * recorded delays ARE the backoff schedule — read without waiting for it. |
| 86 | + */ |
| 87 | +async function recordingBackoff(fn: () => Promise<void>): Promise<number[]> { |
| 88 | + const slept: number[] = []; |
| 89 | + const spy = vi.spyOn(globalThis, 'setTimeout').mockImplementation(((cb: () => void, ms?: number) => { |
| 90 | + slept.push(ms ?? 0); |
| 91 | + cb(); |
| 92 | + return 0 as unknown as ReturnType<typeof setTimeout>; |
| 93 | + }) as unknown as typeof setTimeout); |
| 94 | + try { |
| 95 | + await fn(); |
| 96 | + } finally { |
| 97 | + spy.mockRestore(); |
| 98 | + } |
| 99 | + return slept; |
| 100 | +} |
| 101 | + |
| 102 | +describe('#6832 — hook.retryPolicy defaults agree across the parsed and unparsed paths', () => { |
| 103 | + it('the schema still declares the numbers this file is about', () => { |
| 104 | + // If these ever change, the expectations below follow them rather than |
| 105 | + // drifting: every assertion reads `declared()`. This one exists so a |
| 106 | + // deliberate change to the published contract is visible in the diff. |
| 107 | + expect(declared()).toEqual({ maxRetries: 3, backoffMs: 1000 }); |
| 108 | + }); |
| 109 | + |
| 110 | + describe('case 1 — the block is absent: no policy declared, so no retry', () => { |
| 111 | + it('does not retry, and does NOT pick up the per-key defaults', async () => { |
| 112 | + expect(await attemptsFor(undefined)).toBe(1); |
| 113 | + }); |
| 114 | + |
| 115 | + it('agrees with the parsed path, which leaves retryPolicy undefined', () => { |
| 116 | + const parsed = HookSchema.parse({ |
| 117 | + name: 'h_retry', object: 'retry_task', events: ['beforeInsert'], handler: async () => {}, |
| 118 | + }); |
| 119 | + expect(parsed.retryPolicy).toBeUndefined(); |
| 120 | + }); |
| 121 | + }); |
| 122 | + |
| 123 | + describe('case 2 — the block is present but empty: both keys take the declared default', () => { |
| 124 | + it('retries `maxRetries` times', async () => { |
| 125 | + let attempts = 0; |
| 126 | + await recordingBackoff(async () => { attempts = await attemptsFor({}); }); |
| 127 | + expect(attempts).toBe(1 + declared().maxRetries); |
| 128 | + }); |
| 129 | + |
| 130 | + it('waits the declared backoff between attempts (linear: backoffMs * attempt)', async () => { |
| 131 | + const slept = await recordingBackoff(async () => { await attemptsFor({}); }); |
| 132 | + const base = declared().backoffMs; |
| 133 | + // Three retries after a failed first attempt; the backoff is linear |
| 134 | + // (`retryBackoffMs * attempt`), which matches the declared shape — there |
| 135 | + // is no multiplier or jitter key on `hook.retryPolicy`. |
| 136 | + expect(slept).toEqual([base * 1, base * 2, base * 3]); |
| 137 | + }); |
| 138 | + }); |
| 139 | + |
| 140 | + describe('case 3 — the block is half-filled: written key wins, omitted key defaults', () => { |
| 141 | + it('an omitted `maxRetries` takes the declared count even when `backoffMs` is written', async () => { |
| 142 | + expect(await attemptsFor({ backoffMs: 0 })).toBe(1 + declared().maxRetries); |
| 143 | + }); |
| 144 | + |
| 145 | + it('an omitted `backoffMs` takes the declared delay even when `maxRetries` is written', async () => { |
| 146 | + let attempts = 0; |
| 147 | + const slept = await recordingBackoff(async () => { attempts = await attemptsFor({ maxRetries: 1 }); }); |
| 148 | + expect(attempts).toBe(2); |
| 149 | + expect(slept).toEqual([declared().backoffMs]); |
| 150 | + }); |
| 151 | + |
| 152 | + it('a written value still wins outright, including an explicit 0', async () => { |
| 153 | + expect(await attemptsFor({ maxRetries: 0, backoffMs: 0 })).toBe(1); |
| 154 | + expect(await attemptsFor({ maxRetries: 2, backoffMs: 0 })).toBe(3); |
| 155 | + }); |
| 156 | + }); |
| 157 | + |
| 158 | + describe('case 4 — the two paths answer identically, which is the whole point', () => { |
| 159 | + for (const [label, policy] of [ |
| 160 | + ['absent', undefined], |
| 161 | + ['empty', {}], |
| 162 | + ['half-filled (backoffMs only)', { backoffMs: 0 }], |
| 163 | + ['half-filled (maxRetries only)', { maxRetries: 1 }], |
| 164 | + ['fully written', { maxRetries: 2, backoffMs: 0 }], |
| 165 | + ] as const) { |
| 166 | + it(`${label}: unparsed metadata retries as often as the same metadata parsed`, async () => { |
| 167 | + const parsed = HookSchema.parse({ |
| 168 | + name: 'h_retry', |
| 169 | + object: 'retry_task', |
| 170 | + events: ['beforeInsert'], |
| 171 | + handler: async () => {}, |
| 172 | + ...(policy === undefined ? {} : { retryPolicy: policy }), |
| 173 | + }); |
| 174 | + const parsedMax = parsed.retryPolicy?.maxRetries ?? 0; |
| 175 | + |
| 176 | + let attempts = 0; |
| 177 | + await recordingBackoff(async () => { attempts = await attemptsFor(policy); }); |
| 178 | + expect(attempts).toBe(1 + parsedMax); |
| 179 | + }); |
| 180 | + } |
| 181 | + }); |
| 182 | +}); |
0 commit comments