Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/27415-time-relative-descriptor-refusal-unbound.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@objectstack/trigger-schedule': patch
---

fix(trigger-schedule): a time-relative flow whose `timeRelative` descriptor is refused now reads `bound: false` on the automation status, not `bound: true`

Clause-②: no
Metadata-protocol: none

`TimeRelativeTrigger.start` refused an invalid `config.timeRelative` descriptor (both `withinDays` and `offsetDays`, an unknown key, `schedule` nested inside the descriptor) by logging "not bound" and returning. The engine read that return as a successful bind, so `GET /api/v1/automation/_status` reported the flow as `bound: true` with no `unboundCause`, and no sweep ever ran.

The refusal now throws, the same way the trigger's organization and deployment-policy refusals already do. The engine records the flow as unbound: its status row reads `bound: false` with `unboundCause: 'binding_failure'`, and the boot-time binding audit lists it. The `warn` line the server logs is unchanged, and the thrown text is the same sentence. A re-bind with a broken descriptor also cancels the sweep an earlier valid bind armed.

Nothing changes for a valid descriptor. A host that calls `TimeRelativeTrigger.start` directly, outside the engine, should expect it to throw on a refused descriptor.
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

// END-TO-END: the REAL TimeRelativeTrigger wired to the REAL AutomationEngine,
// pinning what the engine's status row (the rows `GET /automation/_status`
// serves) says about a flow the trigger refused on its descriptor.
//
// `FlowTrigger.start` returns `void`, so a trigger that logs "not bound" and
// returns reads to the engine as a successful arm: the engine marks the flow
// bound, and the status row answers `bound: true` beside the trigger's own
// refusal. The trigger throws instead; the engine's catch never marks the flow
// bound, and the row reads `bound: false` with the `binding_failure` cause.
// A valid descriptor on the same engine is the control that still binds.

import { describe, it, expect } from 'vitest';
import { AutomationEngine } from '@objectstack/service-automation';
import type { JobSchedule, JobHandler } from '@objectstack/spec/contracts';
import { TimeRelativeTrigger, type TimeRelativeDataEngine } from './time-relative-trigger.js';
import { withScheduledWorkOn } from './deployment-switch.test-support.js';

function quietLogger(): any {
const l: any = { info() {}, warn() {}, error() {}, debug() {} };
l.child = () => l;
return l;
}

const silent = { info() {}, warn() {}, debug() {} };
const flush = () => new Promise<void>((r) => setTimeout(r, 0));

function fakeJobService() {
const jobs = new Map<string, { schedule: JobSchedule; handler: JobHandler }>();
return {
service: {
async schedule(name: string, schedule: JobSchedule, handler: JobHandler) {
jobs.set(name, { schedule, handler });
},
async cancel(name: string) {
jobs.delete(name);
},
},
has: (name: string) => jobs.has(name),
};
}

const dataEngine: TimeRelativeDataEngine = {
async find() {
return [];
},
getObject(name: string) {
return name === 'contracts' ? { name } : undefined;
},
};

function timeRelativeFlow(name: string, timeRelative: Record<string, unknown>) {
return {
name,
label: name,
type: 'autolaunched',
nodes: [
{ id: 'start', type: 'start', label: 'Start', config: { timeRelative } },
{ id: 'end', type: 'end', label: 'End' },
],
edges: [{ id: 'e1', source: 'start', target: 'end' }],
} as never;
}

// The switch on: every assertion here is about a deployment that RUNS
// package-authored scheduled work, so a refusal can only come from the
// descriptor, never from the deployment policy.
withScheduledWorkOn('single');

describe('time-relative trigger -> engine status: a descriptor refusal reads unbound', () => {
it('an invalid descriptor reads bound:false with the binding-failure cause; a valid one reads bound:true', async () => {
const engine = new AutomationEngine(quietLogger());
engine.registerFlow(
'tr_both',
timeRelativeFlow('tr_both', { object: 'contracts', dateField: 'end_date', withinDays: 30, offsetDays: [7] }),
);
engine.registerFlow(
'tr_ok',
timeRelativeFlow('tr_ok', { object: 'contracts', dateField: 'end_date', withinDays: 30 }),
);
const job = fakeJobService();
engine.registerTrigger(new TimeRelativeTrigger(() => job.service, () => dataEngine, silent));
await flush();

const states = engine.getFlowRuntimeStates();
const refused = states.find((s) => s.name === 'tr_both');
const armed = states.find((s) => s.name === 'tr_ok');

expect(refused, 'the refused flow is listed').toBeTruthy();
expect(refused).toMatchObject({ bound: false, triggerType: 'time_relative' });
expect(refused?.unboundCause).toBe('binding_failure');
expect(job.has('flow-time-relative:tr_both'), 'no sweep armed for the refused flow').toBe(false);

expect(armed, 'control: the valid flow is listed').toBeTruthy();
expect(armed).toMatchObject({ bound: true, triggerType: 'time_relative' });
expect(Object.keys(armed ?? {}), 'control: a bound row carries no unboundCause').not.toContain('unboundCause');
expect(job.has('flow-time-relative:tr_ok'), 'control: the valid flow armed its sweep').toBe(true);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -403,24 +403,76 @@ describe('TimeRelativeTrigger', () => {
);

// Neither withinDays nor offsetDays → invalid.
trigger.start(binding({ object: 'contracts', dateField: 'end_date' }), async () => {});
expect(() => trigger.start(binding({ object: 'contracts', dateField: 'end_date' }), async () => {}))
.toThrow(/flow 'renewal_alert' has no valid `timeRelative` descriptor/);
await flush();

expect(job.jobs.size).toBe(0);
expect(warn).toHaveBeenCalledWith(expect.stringContaining('no valid `timeRelative` descriptor'));
});

it('does not bind when both windowing modes are set (mutually exclusive)', async () => {
const job = fakeJobService();
const { engine } = fakeDataEngine([]);
const trigger = new TimeRelativeTrigger(() => job.service, () => engine, silentLogger(), NOW);
// A descriptor refusal THROWS, so the engine's catch records the flow as
// unbound instead of marking it bound after a "not bound" log line — the
// `_status` row then reads `bound: false`, never `bound: true` beside a
// refusal. Each invalid shape is refused the same way; the valid case is
// the control that `start` still returns on a descriptor it accepts.
describe('an invalid descriptor is a binding failure the host can see', () => {
const INVALID: Array<[string, Record<string, unknown>]> = [
['both windowing modes (mutually exclusive)', { object: 'contracts', dateField: 'end_date', withinDays: 30, offsetDays: [7] }],
['an unknown key', { object: 'contracts', dateField: 'end_date', withinDays: 30, bogus_key: 1 }],
['`schedule` nested inside the descriptor', { object: 'contracts', dateField: 'end_date', withinDays: 30, schedule: { type: 'cron', expression: '0 8 * * *' } }],
];

trigger.start(
binding({ object: 'contracts', dateField: 'end_date', withinDays: 30, offsetDays: [7] }),
async () => {},
);
await flush();
expect(job.jobs.size).toBe(0);
for (const [label, desc] of INVALID) {
it(`${label}: start throws, names the flow, arms nothing`, async () => {
const job = fakeJobService();
const { engine } = fakeDataEngine([]);
const warns: string[] = [];
const trigger = new TimeRelativeTrigger(
() => job.service,
() => engine,
{ info: () => {}, debug: () => {}, warn: (m: string) => void warns.push(String(m)) },
NOW,
);

expect(() => trigger.start(binding(desc), async () => {}))
.toThrow(/flow 'renewal_alert' has no valid `timeRelative` descriptor — not bound/);
await flush();
expect(job.jobs.size, 'no sweep armed').toBe(0);
expect(warns.filter((w) => w.includes('no valid `timeRelative` descriptor')), 'said once').toHaveLength(1);
});
}

it('a re-bind with a broken descriptor drops the sweep the previous bind armed', async () => {
const job = fakeJobService();
const { engine } = fakeDataEngine([]);
const trigger = new TimeRelativeTrigger(() => job.service, () => engine, silentLogger(), NOW);

trigger.start(binding({ object: 'contracts', dateField: 'end_date', withinDays: 30 }), async () => {});
await flush();
expect(job.jobs.size, 'control: the valid bind armed a sweep').toBe(1);

expect(() =>
trigger.start(
binding({ object: 'contracts', dateField: 'end_date', withinDays: 30, offsetDays: [7] }),
async () => {},
),
).toThrow(/no valid `timeRelative` descriptor/);
await flush();
expect(job.jobs.size, 'the refused re-bind left no sweep armed').toBe(0);
});

it('control: a valid descriptor returns without throwing and arms its sweep', async () => {
const job = fakeJobService();
const { engine } = fakeDataEngine([]);
const trigger = new TimeRelativeTrigger(() => job.service, () => engine, silentLogger(), NOW);

expect(() =>
trigger.start(binding({ object: 'contracts', dateField: 'end_date', withinDays: 30 }), async () => {}),
).not.toThrow();
await flush();
expect(job.jobs.size).toBe(1);
});
});

it('warns (but still binds) when the swept object is unknown', async () => {
Expand Down
28 changes: 22 additions & 6 deletions packages/triggers/trigger-schedule/src/time-relative-trigger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -334,12 +334,28 @@ export class TimeRelativeTrigger implements FlowTrigger {
const raw = (binding.config as Record<string, unknown> | undefined)?.timeRelative;
const parsed = TimeRelativeTriggerSchema.safeParse(raw);
if (!parsed.success) {
this.logger.warn(
`[time-relative] flow '${binding.flowName}' has no valid \`timeRelative\` descriptor — not bound. ` +
`Provide { object, dateField, and exactly one of withinDays | offsetDays }. ` +
`(${parsed.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`).join('; ')})`,
);
return;
// A descriptor refusal is a binding failure, so it THROWS rather
// than logging and returning. `FlowTrigger.start` returns `void`,
// and a return here reads to the engine as a successful arm: it
// marks the flow bound, and `GET /automation/_status` answers
// `bound: true` one line after this said "not bound". Throwing is
// the engine's designed path (see `refuseMissingOrganization`'s
// header): its catch never marks the flow bound, so the status row
// reads `bound: false` with the `binding_failure` cause and the
// binding audit lists the flow. Any prior sweep is dropped FIRST,
// for the reason the organization refusal below drops it: a hot
// re-publish that breaks the descriptor must not leave the previous
// job armed behind a line saying it was refused. `warn`, not
// `error`: a trigger that is not armed is a functional degradation,
// and the status row now says so. One sentence for the log line and
// the thrown text, so the two channels cannot drift.
const sentence =
`flow '${binding.flowName}' has no valid \`timeRelative\` descriptor — not bound. ` +
`Provide { object, dateField, and exactly one of withinDays | offsetDays }. ` +
`(${parsed.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`).join('; ')})`;
this.stop(binding.flowName);
this.logger.warn(`[time-relative] ${sentence}`);
throw new Error(sentence);
}
const desc = parsed.data;

Expand Down
Loading