Skip to content

Commit a7fbb14

Browse files
committed
fix(automation): dry-run text slots render as the live executor does, unread grants refuse a runAs system draft, a throwing write check is a denial, and predicate writes ask the engine's dispatch
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5kYk6G1CvandwWbbhe
1 parent 2e47ef2 commit a7fbb14

4 files changed

Lines changed: 255 additions & 24 deletions

File tree

‎packages/services/service-automation/src/builtin/save-notice-node.ts‎

Lines changed: 33 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,38 @@ import { flowNoticeMessageKey } from '@objectstack/spec/system';
3232
import type { AutomationEngine } from '../engine.js';
3333
import { refuseNode } from '../guard-refusal.js';
3434
import { parseNodeConfig } from './parse-config.js';
35-
import { renderTextSlot } from './template.js';
35+
import type { AutomationContext } from '@objectstack/spec/contracts';
36+
import { renderTextSlot, type VariableMap } from './template.js';
37+
38+
/**
39+
* The save notice's message as a run renders it: translated at
40+
* `flowNoticeMessageKey(flowName, nodeId)` in `context.locale`, its holes
41+
* filled through the engine's one text renderer, and the authored template
42+
* when the run names no flow. ONE spelling, asked by this executor and by a
43+
* dry run's outbound payload (`dry-run.ts`), so the sentence a dry run reports
44+
* is the sentence the saver would read in the same locale.
45+
*/
46+
export function renderSaveNoticeMessage(
47+
engine: Pick<AutomationEngine, 'renderFlowTextSlot'>,
48+
flowName: string | undefined,
49+
nodeId: string,
50+
authored: unknown,
51+
variables: VariableMap,
52+
context: AutomationContext,
53+
): string | undefined {
54+
return flowName === undefined
55+
? renderTextSlot(authored, variables, context.currency)
56+
: engine.renderFlowTextSlot(
57+
{
58+
key: flowNoticeMessageKey(flowName, nodeId),
59+
authored,
60+
subject: `flow '${flowName}' save_notice '${nodeId}'`,
61+
shownAs: 'the save notice',
62+
},
63+
variables,
64+
context,
65+
);
66+
}
3667

3768
export function registerSaveNoticeNode(engine: AutomationEngine, _ctx: PluginContext): void {
3869
engine.registerNodeExecutor({
@@ -77,18 +108,7 @@ export function registerSaveNoticeNode(engine: AutomationEngine, _ctx: PluginCon
77108
// The writer's locale, not the run's: a record-change run carries
78109
// none of its own, and the reader of this sentence is the writer.
79110
const renderContext = channel.locale ? { ...context, locale: channel.locale } : context;
80-
const message = flowName === undefined
81-
? renderTextSlot(parsed.config.message, variables, context.currency)
82-
: engine.renderFlowTextSlot(
83-
{
84-
key: flowNoticeMessageKey(flowName, node.id),
85-
authored: parsed.config.message,
86-
subject: `flow '${flowName}' save_notice '${node.id}'`,
87-
shownAs: 'the save notice',
88-
},
89-
variables,
90-
renderContext,
91-
);
111+
const message = renderSaveNoticeMessage(engine, flowName, node.id, parsed.config.message, variables, renderContext);
92112
if (typeof message !== 'string' || message.trim() === '') {
93113
return {
94114
success: false,

‎packages/services/service-automation/src/dry-run.test.ts‎

Lines changed: 169 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,20 @@
1010
* is read off the calls it never got, not off the result.
1111
*/
1212
import { describe, it, expect } from 'vitest';
13-
import { AI_ACCOUNT_ELEVATED_START_REFUSAL, requiredPermissionsRefusal } from '@objectstack/core';
14-
import { assertEngineDeleteDispatch, assertEngineFindOnePredicate, assertEngineUpdateDispatch } from '@objectstack/metadata-core';
13+
import { AI_ACCOUNT_ELEVATED_START_REFUSAL, createMemoryI18n, requiredPermissionsRefusal } from '@objectstack/core';
14+
import {
15+
assertEngineDeleteDispatch, assertEngineFindOnePredicate, assertEngineUpdateDispatch,
16+
ENGINE_DELETE_REJECT_MESSAGE, ENGINE_UPDATE_REJECT_MESSAGE,
17+
} from '@objectstack/metadata-core';
1518
import { defineActionDescriptor } from '@objectstack/spec/automation';
19+
import { flowNoticeMessageKey, flowRefusalMessageKey } from '@objectstack/spec/system';
1620
import type { FlowDryRunResult } from '@objectstack/spec/contracts';
1721
import { AutomationEngine, type FlowUserGrants } from './engine.js';
1822
import { registerCrudNodes } from './builtin/crud-nodes.js';
1923
import { registerLogicNodes } from './builtin/logic-nodes.js';
2024
import { registerLoopNode } from './builtin/loop-node.js';
25+
import { registerSaveNoticeNode } from './builtin/save-notice-node.js';
26+
import { i18nServiceReader } from './plugin.js';
2127

2228
function makeLogger(): any {
2329
const l: any = { info() {}, warn() {}, error() {}, debug() {} };
@@ -72,6 +78,10 @@ interface Harness {
7278
function harness(opts: {
7379
grants?: Partial<FlowUserGrants>;
7480
canWrite?: (object: string, operation: string) => boolean;
81+
/** Translation bundles by locale, served through the engine's one i18n source. */
82+
bundles?: Record<string, Record<string, unknown>>;
83+
/** The grants read fails (the resolver throws). */
84+
grantsFail?: boolean;
7585
} = {}): Harness {
7686
const { data, calls } = liveData();
7787
const writeChecks: Harness['writeChecks'] = [];
@@ -91,6 +101,17 @@ function harness(opts: {
91101
registerLogicNodes(engine, ctx);
92102
registerCrudNodes(engine, ctx);
93103
registerLoopNode(engine, ctx);
104+
registerSaveNoticeNode(engine, ctx);
105+
if (opts.bundles) {
106+
const i18n = createMemoryI18n();
107+
for (const [locale, data] of Object.entries(opts.bundles)) i18n.loadTranslations(locale, data);
108+
engine.setI18nServiceSource(i18nServiceReader({
109+
getService: (<T>(name: string) => {
110+
if (name === 'i18n') return i18n as T;
111+
throw new Error(`service '${name}' not registered`);
112+
}) as never,
113+
}));
114+
}
94115
const h: Harness = { engine, calls, approvalCalls: 0, writeChecks };
95116
// An approval node as the approvals plugin declares it: it pauses, so a
96117
// dry run must stop at it and never call it (that would create a request).
@@ -102,7 +123,7 @@ function harness(opts: {
102123
} as any),
103124
async execute() { h.approvalCalls++; return { success: true, suspend: true }; },
104125
});
105-
engine.setUserGrantsResolver(async () => ({
126+
engine.setUserGrantsResolver(async () => opts.grantsFail ? Promise.reject(new Error('grants store unreachable')) : ({
106127
positions: [],
107128
permissions: [],
108129
accessible_org_ids: ['org_1'],
@@ -112,6 +133,16 @@ function harness(opts: {
112133
return h;
113134
}
114135

136+
/** A bundle holding `text` at the dotted translation `key`. */
137+
function bundleAt(key: string, text: string): Record<string, unknown> {
138+
const parts = key.split('.');
139+
const root: Record<string, unknown> = {};
140+
let at = root;
141+
for (const part of parts.slice(0, -1)) at = (at[part] = {}) as Record<string, unknown>;
142+
at[parts[parts.length - 1]] = text;
143+
return root;
144+
}
145+
115146
const writes = (h: Harness) => h.calls.filter((c) => c.op === 'insert' || c.op === 'update' || c.op === 'delete');
116147

117148
function flow(nodes: any[], edges: any[], extra: Record<string, unknown> = {}) {
@@ -289,6 +320,14 @@ describe('dryRun — admission (the by-name start rules, ruling B for runAs syst
289320
expect(result.steps).toEqual([]);
290321
});
291322

323+
it('refuses a runAs system definition when the named user\'s grants cannot be read (the account rule fails closed)', async () => {
324+
const h = harness({ grantsFail: true });
325+
const result = await h.engine.dryRun(gated({ type: 'schedule', runAs: 'system' }), { userId: 'usr_maker' });
326+
expect(result.status).toBe('refused');
327+
expect(result.steps).toEqual([]);
328+
expect(result.refusal?.code).toBe('PERMISSION_DENIED');
329+
});
330+
292331
it('admits a runAs system schedule draft for the named user and never elevates it (ruling B)', async () => {
293332
const h = harness({ canWrite: () => true });
294333
const result = await h.engine.dryRun(flow([
@@ -380,3 +419,130 @@ describe('dryRun — unarmed, unregistered, and its own answers', () => {
380419
});
381420
});
382421
});
422+
423+
describe('dryRun — text slots render as the live executor renders them, in options.locale', () => {
424+
const NOTICE = 'Sent {{ record.name }} for approval';
425+
const ZH_NOTICE = '已将 {{ record.name }} 提交审批';
426+
const noticeDraft = () => ({
427+
name: 'deal_submit', label: 'Deal submit', type: 'record_change',
428+
nodes: [
429+
{ id: 'start', type: 'start', label: 'Start', config: { objectName: 'deal', triggerType: 'record-after-update' } },
430+
{ id: 'tell', type: 'save_notice', label: 'Tell', config: { message: NOTICE } },
431+
{ id: 'done', type: 'end', label: 'Done' },
432+
],
433+
edges: chain('start', 'tell', 'done'),
434+
});
435+
const record = { id: 'd1', name: 'Acme renewal' };
436+
437+
it('a save_notice payload carries the zh-CN translation at flows.NAME.notices.NODE.message, and the authored text with no locale', async () => {
438+
const h = harness({ bundles: { 'zh-CN': bundleAt(flowNoticeMessageKey('deal_submit', 'tell'), ZH_NOTICE) } });
439+
440+
const zh = await h.engine.dryRun(noticeDraft(), { userId: 'usr_maker', record, locale: 'zh-CN' });
441+
const plain = await h.engine.dryRun(noticeDraft(), { userId: 'usr_maker', record });
442+
443+
expect(zh.status).toBe('completed');
444+
expect(zh.steps.find((s) => s.nodeId === 'tell')).toMatchObject({ kind: 'outbound', payload: { message: '已将 Acme renewal 提交审批' } });
445+
expect(plain.steps.find((s) => s.nodeId === 'tell')).toMatchObject({ kind: 'outbound', payload: { message: 'Sent Acme renewal for approval' } });
446+
});
447+
448+
it('a refusing end node carries the zh-CN translation of its message', async () => {
449+
const h = harness({ bundles: { 'zh-CN': bundleAt(flowRefusalMessageKey('draft_flow', 'finish'), '{{ record.name }} 不能提交') } });
450+
const draft = flow([
451+
{ id: 'start', type: 'start', label: 'Start' },
452+
{ id: 'finish', type: 'end', label: 'Finish', config: { outcome: 'refused', message: '{{ record.name }} cannot be submitted' } },
453+
], chain('start', 'finish'));
454+
455+
const zh = await h.engine.dryRun(draft, { userId: 'usr_maker', record, locale: 'zh-CN' });
456+
const plain = await h.engine.dryRun(draft, { userId: 'usr_maker', record });
457+
458+
expect(zh.steps.find((s) => s.nodeId === 'finish')).toMatchObject({ refusalMessage: 'Acme renewal 不能提交' });
459+
expect(plain.steps.find((s) => s.nodeId === 'finish')).toMatchObject({ refusalMessage: 'Acme renewal cannot be submitted' });
460+
});
461+
});
462+
463+
describe('dryRun — a refused write a fault edge contains', () => {
464+
it('goes on along the fault edge: the write step carries the refusal and the handler runs after it', async () => {
465+
const h = harness({ canWrite: () => false });
466+
const result = await h.engine.dryRun(flow([
467+
{ id: 'start', type: 'start', label: 'Start' },
468+
{ id: 'mk', type: 'create_record', label: 'Create', config: { objectName: 'deal', fields: { stage: 'open' } } },
469+
{ id: 'handler', type: 'assignment', label: 'Handle', config: { assignments: { handled: { dialect: 'cel', source: 'true' } } } },
470+
{ id: 'ok', type: 'end', label: 'Ok' },
471+
{ id: 'end', type: 'end', label: 'End' },
472+
], [
473+
{ id: 'e0', source: 'start', target: 'mk' },
474+
{ id: 'e1', source: 'mk', target: 'ok' },
475+
{ id: 'e_fault', source: 'mk', target: 'handler', type: 'fault' },
476+
{ id: 'e2', source: 'handler', target: 'end' },
477+
]), { userId: 'usr_maker' });
478+
479+
expect(result.status).not.toBe('failed');
480+
expect(writes(h)).toEqual([]);
481+
const ids = result.steps.map((s) => s.nodeId);
482+
expect(result.steps.find((s) => s.nodeId === 'mk')).toMatchObject({
483+
kind: 'write', permission: 'refused', refusal: { code: 'PERMISSION_DENIED' },
484+
});
485+
expect(ids.indexOf('handler')).toBeGreaterThan(ids.indexOf('mk'));
486+
expect(ids).not.toContain('ok');
487+
});
488+
});
489+
490+
describe('dryRun — an object-level write check that throws', () => {
491+
it('reports the write refused, as a denial, and the run fails there', async () => {
492+
const h = harness({ canWrite: () => { throw new Error('permission store unreachable'); } });
493+
const result = await h.engine.dryRun(flow([
494+
{ id: 'start', type: 'start', label: 'Start' },
495+
{ id: 'mk', type: 'create_record', label: 'Create', config: { objectName: 'deal', fields: { stage: 'open' } } },
496+
{ id: 'end', type: 'end', label: 'End' },
497+
], chain('start', 'mk', 'end')), { userId: 'usr_maker' });
498+
499+
expect(result.status).toBe('failed');
500+
expect(writes(h)).toEqual([]);
501+
expect(result.steps.find((s) => s.nodeId === 'mk')).toMatchObject({
502+
kind: 'write', permission: 'refused', refusal: { code: 'PERMISSION_DENIED' },
503+
});
504+
});
505+
});
506+
507+
describe('dryRun — a predicate write the engine refuses without multi', () => {
508+
const predicateWrite = (node: Record<string, unknown>) => flow([
509+
{ id: 'start', type: 'start', label: 'Start' },
510+
node,
511+
{ id: 'end', type: 'end', label: 'End' },
512+
], chain('start', String(node.id), 'end'));
513+
514+
it('an update by predicate with no multi fails with the engine\'s own error, targeting and reading no row', async () => {
515+
const h = harness({ canWrite: () => true });
516+
const result = await h.engine.dryRun(predicateWrite(
517+
{ id: 'up', type: 'update_record', label: 'Update', config: { objectName: 'deal', filter: { stage: 'open' }, fields: { stage: 'won' } } },
518+
), { userId: 'usr_maker' });
519+
520+
expect(result.status).toBe('failed');
521+
expect(writes(h)).toEqual([]);
522+
expect(h.calls.filter((c) => c.op === 'find' || c.op === 'findOne')).toEqual([]);
523+
expect(result.steps.find((s) => s.nodeId === 'up')).toMatchObject({ kind: 'write', operation: 'update', recordIds: [] });
524+
expect(String(result.steps.find((s) => s.nodeId === 'up')?.error)).toContain(ENGINE_UPDATE_REJECT_MESSAGE);
525+
});
526+
527+
it('a delete by predicate with no multi fails with the engine\'s own error', async () => {
528+
const h = harness();
529+
const result = await h.engine.dryRun(predicateWrite(
530+
{ id: 'rm', type: 'delete_record', label: 'Delete', config: { objectName: 'deal', filter: { stage: 'open' } } },
531+
), { userId: 'usr_maker' });
532+
533+
expect(result.status).toBe('failed');
534+
expect(writes(h)).toEqual([]);
535+
expect(result.steps.find((s) => s.nodeId === 'rm')).toMatchObject({ kind: 'write', operation: 'delete', recordIds: [] });
536+
expect(String(result.steps.find((s) => s.nodeId === 'rm')?.error)).toContain(ENGINE_DELETE_REJECT_MESSAGE);
537+
});
538+
539+
it('CONTROL — the same update declaring multi lists every row it matches', async () => {
540+
const h = harness({ canWrite: () => true });
541+
const result = await h.engine.dryRun(predicateWrite(
542+
{ id: 'up', type: 'update_record', label: 'Update', config: { objectName: 'deal', filter: { stage: 'open' }, fields: { stage: 'won' }, multi: true } },
543+
), { userId: 'usr_maker' });
544+
545+
expect(result.status).toBe('completed');
546+
expect(result.steps.find((s) => s.nodeId === 'up')).toMatchObject({ kind: 'write', operation: 'update', recordIds: ['d1'] });
547+
});
548+
});

0 commit comments

Comments
 (0)