-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathhttp-dispatcher.test.ts
More file actions
4599 lines (4106 loc) · 252 KB
/
Copy pathhttp-dispatcher.test.ts
File metadata and controls
4599 lines (4106 loc) · 252 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { HttpDispatcher } from './http-dispatcher.js';
import { ObjectKernel } from '@objectstack/core';
import { ApiErrorSchema } from '@objectstack/spec/api';
import type { ConnectorDescriptor } from '@objectstack/spec/integration';
import type { IAuthService, IAutomationService } from '@objectstack/spec/contracts';
// [#10126] Pay the first transform of these dist-resolved workspace deps at MODULE
// LOAD. Each is reached below through a dynamic `import()` inside an `it()` body or a
// hook -- both of which vitest clocks, while collection is clocked against nothing. See
// `scripts/check-test-source-alias.mjs` (the clocked-window rule) and #10115 / PR #10120,
// where the same shape cost 30 ejected merge-queue builds in one night.
import '@objectstack/metadata-protocol';
/**
* [#4127] Mock-shape guard: every key must be a method the contract DECLARES.
*
* Signatures stay `unknown` on purpose — `vi.fn()` does not match a contract
* signature, and forcing it to would push these mocks straight back to `as any`,
* which is the state this is fixing. What it catches is the failure that keeps
* actually happening: a mock naming a method the contract does not have, so the
* handler and its test agree with each other and with no implementation.
* `upload(file, { request })` in #4087, `authService.handler` and
* `automation.trigger` here — each one sat green for months behind a mock
* written to the handler's wish rather than the declared surface.
*/
type ContractMock<T> = Partial<Record<keyof T, unknown>>;
/**
* [#5519] The dispatch domains below (`/actions`, `/automation`) now stand on
* the platform anonymous-deny baseline, so a route-behaviour test needs a
* caller. These cases are about ROUTING — which service method a path reaches,
* which status a miss returns — and were only ever anonymous incidentally
* (`{ request: {} }` is the smallest context that compiles). Anonymity itself
* is pinned in `domains/anonymous-gate-actions-automation.test.ts`; giving
* these a session keeps each file testing the thing it is named after.
*/
const AUTHED_CALLER = () => ({ request: {}, executionContext: { userId: 'u_test', isSystem: false, positions: [], permissions: [], systemPermissions: [] } }) as any;
/**
* [#7019] The same move as `AUTHED_CALLER` above, one rung up: the dispatcher's
* `/meta` PUT now demands the `manage_metadata` authoring capability (ADR-0066
* D1), matching the gate #6603 put on the REST twin and the one
* `POST /_migrate-stored` already had next door.
*
* The PUT cases below are about ROUTING and ERROR MAPPING — which service
* method a path reaches, whether a 422's issues survive, whether the 501
* fallback still means "no kernel support". They were written when a session
* alone could write metadata, i.e. their `{ userId: 'u1' }` stub encoded
* exactly the premise the gate destroys, so without a capability they now stop
* at the 403 before reaching the behaviour each one is named after. Only the
* caller changes here; every mechanism, assertion and expected value is
* untouched. The gate itself is pinned in `domains/meta-save-capability-gate.test.ts`.
*/
const METADATA_AUTHOR = () => ({ request: {}, executionContext: { userId: 'u1', systemPermissions: ['manage_metadata'] } }) as any;
/**
* [#7033 / #7023] The same move again for the `/packages` domain, which now
* carries an anonymous-deny floor plus per-route capability predicates
* (`manage_metadata` for every state-changing route, `studio.access` /
* `setup.access` for every read). The package tests below are about ROUTING and
* ERROR MAPPING — which protocol/metadata method a path reaches, which status a
* miss returns — and were only ever anonymous incidentally, so without a caller
* they would now all stop at the 401 floor before reaching the behaviour each
* one is named after. This caller holds ALL three capabilities so a single
* context clears both the write and the read gate; the gates themselves are
* pinned in `domains/packages-capability-gate.test.ts`.
*/
const PKG_ADMIN = () => ({ request: {}, executionContext: { userId: 'u_pkg_admin', systemPermissions: ['manage_metadata', 'studio.access', 'setup.access'] } }) as any;
/**
* [#10145] The same move for the `/automation` DEFINITION writes — `POST /`,
* `PUT /:name` and `DELETE /:name` now demand `manage_metadata`, the authoring
* capability the metadata plane these flows live on already required. The cases
* using this caller are about ROUTING — which automation-service method a
* path reaches and with which arguments — and were written when an ordinary
* session could register a flow, which is precisely the premise the gate
* destroys. Only the caller changes; the gate itself is pinned in
* `domains/automation-write-capability-gate.test.ts`.
*
* [#10243] `POST /:name/toggle` uses this caller too, since the 2026-08-23
* ruling put enablement in the same write set. The EXECUTION routes on the
* domain (trigger / resume) keep `AUTHED_CALLER`, deliberately — that half of
* the line did not move.
*/
const FLOW_AUTHOR = () => ({ request: {}, executionContext: { userId: 'u_flow_author', systemPermissions: ['manage_metadata'] } }) as any;
describe('HttpDispatcher', () => {
let kernel: ObjectKernel;
let dispatcher: HttpDispatcher;
let mockProtocol: any;
let mockObjectQL: any;
beforeEach(() => {
// Mock Kernel
mockProtocol = {
saveMetaItem: vi.fn().mockResolvedValue({ success: true, message: 'Saved' }),
getMetaItem: vi.fn().mockResolvedValue({ success: true, item: { foo: 'bar' } }),
findData: vi.fn().mockResolvedValue({ object: 'test', records: [], total: 0 }),
getData: vi.fn().mockResolvedValue({ object: 'test', id: '1', record: {} }),
};
mockObjectQL = {
insert: vi.fn().mockResolvedValue({ id: 'new_1' }),
find: vi.fn().mockResolvedValue([]),
update: vi.fn().mockResolvedValue({}),
delete: vi.fn().mockResolvedValue({}),
getObjects: vi.fn().mockReturnValue({}),
registry: {
getObject: vi.fn().mockReturnValue({ name: 'test_obj' }),
getRegisteredTypes: vi.fn().mockReturnValue([]),
getAllPackages: vi.fn().mockReturnValue([]),
},
};
kernel = {
context: {
getService: (name: string) => {
if (name === 'protocol') return mockProtocol;
if (name === 'objectql') return mockObjectQL;
return null;
}
}
} as any;
dispatcher = new HttpDispatcher(kernel);
});
describe('handleMetadata', () => {
it('should handle PUT /metadata/:type/:name by calling protocol.saveMetaItem', async () => {
const context = METADATA_AUTHOR();
const body = { label: 'New Label' };
const path = '/objects/my_obj';
const result = await dispatcher.handleMetadata(path, context, 'PUT', body);
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(mockProtocol.saveMetaItem).toHaveBeenCalledWith({
type: 'objects',
name: 'my_obj',
item: body,
// [#10888] Server-stated, and asserted here rather than relaxed
// to `objectContaining`: this door's whole claim to the face is
// that it answers through `errorFromThrown`, which carries a
// refusal's `issues[]` in `details` (pinned below). If the face
// ever stops being stated, `saveMetaItem`'s 422 silently goes
// back to restating prose the envelope already carries — an
// exact-match assertion is what makes that visible.
//
// [#11095] The exact-match did its job: this value CHANGED, and
// it changed HERE first, deliberately, rather than quietly
// starting to pass somewhere. `'meta-envelope'` asserted "I am
// one of the doors that carry `issues[]` structurally", which is
// still true of this one — but the same field also answers the
// 409's question, "which remedy exists on this door", and there
// the answer diverged: both REST `PUT`s read `?force` off a
// query string (the compound-name twin as of this card), while
// this branch is reached with a path, a method and a body and
// has no query string at all. So it names itself. The 422
// behaviour is unmoved — `specValidationFindings` lists the two
// faces on ONE `case` — and what moved is the destructive 409's
// remedy clause, pinned in
// `domains/meta-save-destructive-remedy.test.ts`.
writeFace: 'meta-dispatch',
});
expect(result.response?.body).toEqual({
success: true,
data: { success: true, message: 'Saved' },
meta: undefined
});
});
it('[#12195] should NOT handle a compound name — the 3+ segment fold is retired', async () => {
const context = METADATA_AUTHOR();
const body = { density: 'compact' };
// `/metadata/lead/views/all_leads` used to resolve as type='lead',
// name='views/all_leads' — the dispatcher's own compound arity,
// folding every trailing segment into one slash-bearing key.
//
// #12176 retired compound metadata item names (maintainer ruling
// 2026-08-25); #12194 refuses every slash-bearing name at the
// publish door, so the fold could only address names that can no
// longer be created; #12195 removes it. The domain now DECLINES,
// and nothing is written.
const path = '/lead/views/all_leads';
const result = await dispatcher.handleMetadata(path, context, 'PUT', body);
// A LOCATED refusal: ADR-0112 code AND status, never a bare 404.
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(404);
expect(result.response?.body?.error?.code).toBe('ROUTE_NOT_FOUND');
expect(mockProtocol.saveMetaItem).not.toHaveBeenCalled();
});
it('[#12195] still handles the ENCODED spelling as ONE two-segment name', async () => {
const context = METADATA_AUTHOR();
const body = { density: 'compact' };
// The replacement spelling. This dispatcher splits the RAW path and
// nothing decodes for it, so `%2F` keeps the path at two segments
// and `decodeMetaNameSegment` restores the stored key — which is
// what keeps a pre-grammar residue row addressable here, per
// #12194's "any stored junk name remains listable and clearable".
const result = await dispatcher.handleMetadata('/lead/views%2Fall_leads', context, 'PUT', body);
expect(result.handled).toBe(true);
expect(mockProtocol.saveMetaItem).toHaveBeenCalledWith(
expect.objectContaining({ type: 'lead', name: 'views/all_leads' }),
);
});
it('should fallback to MetadataService when protocol is missing saveMetaItem', async () => {
// Mock protocol without saveMetaItem, but MetadataService with saveItem
const mockMetaSvc = {
saveItem: vi.fn().mockResolvedValue({ success: true, fromMetaSvc: true }),
};
(kernel as any).context.getService = (name: string) => {
if (name === 'protocol') return {};
if (name === 'metadata') return mockMetaSvc;
if (name === 'objectql') return mockObjectQL;
return null;
};
const context = METADATA_AUTHOR();
const body = { label: 'Fallback' };
const path = '/objects/my_obj';
const result = await dispatcher.handleMetadata(path, context, 'PUT', body);
expect(result.handled).toBe(true);
expect(mockMetaSvc.saveItem).toHaveBeenCalledWith('objects', 'my_obj', body);
expect(result.response?.body?.data).toEqual({ success: true, fromMetaSvc: true });
});
it('should return error if save fails', async () => {
mockProtocol.saveMetaItem.mockRejectedValue(new Error('Save failed'));
const context = METADATA_AUTHOR();
const body = {};
const path = '/objects/bad_obj';
const result = await dispatcher.handleMetadata(path, context, 'PUT', body);
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(400);
expect(result.response?.body?.error?.message).toBe('Save failed');
});
it('preserves the 422 status + structured spec-validation issues on save', async () => {
// protocol.saveMetaItem throws a spec-validation error carrying the
// field-anchored issues; the dispatcher must pass them through (not
// flatten to a single 400 message) so the Studio can point at fields.
const err: any = new Error('[invalid_metadata] object/bad failed spec validation: fields.amount.type: Required');
err.code = 'INVALID_METADATA';
err.status = 422;
err.issues = [
{ path: 'fields.amount.type', message: 'Required', code: 'invalid_type' },
{ path: 'label', message: 'Required', code: 'invalid_type' },
];
mockProtocol.saveMetaItem.mockRejectedValue(err);
const result = await dispatcher.handleMetadata('/objects/bad', METADATA_AUTHOR(), 'PUT', {});
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(422); // NOT the old hardcoded 400
const error = result.response?.body?.error;
// [#3842] The spec-validation code is the `error.code`; the
// field-anchored issues stay in `details`, which is what they are.
expect(error?.code).toBe('INVALID_METADATA');
expect(error?.details?.issues).toEqual(err.issues);
expect(error?.details?.issues[0].path).toBe('fields.amount.type');
});
it('should handle READ operations via ObjectQL registry', async () => {
mockObjectQL.registry.getObject.mockReturnValue({ name: 'my_obj', fields: {} });
const context = { request: {}, executionContext: { userId: 'u1' } };
const result = await dispatcher.handleMetadata('/objects/my_obj', context, 'GET');
expect(result.handled).toBe(true);
expect(mockObjectQL.registry.getObject).toHaveBeenCalledWith('my_obj');
});
});
describe('handleAutomation', () => {
let mockAutomationService: any;
beforeEach(() => {
// [#4127] Everything the CONTRACT declares, checked against it.
const contractMethods = {
listFlows: vi.fn().mockResolvedValue(['flow_a', 'flow_b']),
getFlow: vi.fn().mockResolvedValue({ name: 'flow_a', label: 'Flow A' }),
registerFlow: vi.fn(),
unregisterFlow: vi.fn(),
execute: vi.fn().mockResolvedValue({ success: true, output: {} }),
toggleFlow: vi.fn().mockResolvedValue(undefined),
listRuns: vi.fn().mockResolvedValue([{ id: 'run_1', status: 'completed' }]),
getRun: vi.fn().mockResolvedValue({ id: 'run_1', status: 'completed' }),
resume: vi.fn().mockResolvedValue({ success: true, output: {}, durationMs: 7 }),
// ASYNC per IAutomationService (#4515) — `Promise<ScreenSpec | null>`.
// It has to be: a screen re-fetch answers for any genuinely
// suspended run, which after a restart means reading the
// durable suspended-run store, not just the hot cache.
getSuspendedScreen: vi.fn().mockResolvedValue({ nodeId: 'collect', fields: [] }),
getActionDescriptors: vi.fn().mockReturnValue([
{ type: 'decision', name: 'Decision', category: 'logic', paradigms: ['flow'], source: 'builtin' },
{ type: 'http_request', name: 'HTTP Request', category: 'io', paradigms: ['flow', 'approval'], source: 'builtin' },
{ type: 'send_sms', name: 'Send SMS', category: 'io', paradigms: ['flow'], source: 'plugin' },
]),
// [#4127] Typed as `ConnectorDescriptor[]` now that the contract
// declares `getConnectorDescriptors`, so this fixture cannot
// drift from the shape the route serves. The previous untyped
// literal was already missing `origin` and `state` — both
// REQUIRED, and both the fields a designer reads to tell a
// declarative instance from a plugin one, or a degraded
// connector from a live one (#3017).
getConnectorDescriptors: vi.fn().mockReturnValue([
{ name: 'rest', label: 'REST', type: 'api', origin: 'plugin', state: 'ready', actions: [{ key: 'request', label: 'Request' }] },
{ name: 'slack', label: 'Slack', type: 'api', origin: 'plugin', state: 'ready', actions: [{ key: 'chat.postMessage', label: 'Post Message' }] },
{ name: 'pg', label: 'Postgres', type: 'database', origin: 'declarative', state: 'degraded', degradedReason: 'upstream unreachable', actions: [] },
] satisfies ConnectorDescriptor[]),
getFlowRuntimeStates: vi.fn().mockReturnValue([
{ name: 'flow_a', enabled: true, bound: true },
{ name: 'flow_b', enabled: false, bound: false },
]),
} satisfies ContractMock<IAutomationService>;
mockAutomationService = {
...contractMethods,
// NEGATIVE CONTROL (#4143) — deliberately NOT on the contract.
// Nothing in the repo implements `trigger` on the automation
// slot; it exists here only so the legacy-route test below can
// assert it is never called. Kept outside the checked literal
// so it reads as the exception it is, instead of quietly
// re-opening the hole the check above closes.
trigger: vi.fn().mockResolvedValue({ success: true }),
};
// Set up kernel services to include automation
(kernel as any).services = new Map([
['automation', mockAutomationService],
]);
});
it('should list flows via GET /', async () => {
const result = await dispatcher.handleAutomation('', 'GET', {}, AUTHED_CALLER());
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.flows).toEqual(['flow_a', 'flow_b']);
});
it('should return per-flow runtime enable/bound state via GET /_status', async () => {
const result = await dispatcher.handleAutomation('_status', 'GET', {}, AUTHED_CALLER());
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.flows).toEqual([
{ name: 'flow_a', enabled: true, bound: true },
{ name: 'flow_b', enabled: false, bound: false },
]);
// `_status` must NOT be treated as a flow name (getFlow catch-all).
expect(mockAutomationService.getFlow).not.toHaveBeenCalledWith('_status');
});
it('should get a flow via GET /:name', async () => {
const result = await dispatcher.handleAutomation('flow_a', 'GET', {}, AUTHED_CALLER());
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.name).toBe('flow_a');
});
it('should return 404 for non-existent flow via GET /:name', async () => {
mockAutomationService.getFlow.mockResolvedValue(null);
const result = await dispatcher.handleAutomation('missing', 'GET', {}, AUTHED_CALLER());
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(404);
});
it('should create a flow via POST /', async () => {
const body = { name: 'new_flow', label: 'New Flow' };
const result = await dispatcher.handleAutomation('', 'POST', body, FLOW_AUTHOR());
expect(result.handled).toBe(true);
expect(mockAutomationService.registerFlow).toHaveBeenCalledWith('new_flow', body);
});
it('should update a flow via PUT /:name', async () => {
const body = { definition: { label: 'Updated' } };
const result = await dispatcher.handleAutomation('flow_a', 'PUT', body, FLOW_AUTHOR());
expect(result.handled).toBe(true);
expect(mockAutomationService.registerFlow).toHaveBeenCalledWith('flow_a', { label: 'Updated' });
});
it('should delete a flow via DELETE /:name', async () => {
const result = await dispatcher.handleAutomation('flow_a', 'DELETE', {}, FLOW_AUTHOR());
expect(result.handled).toBe(true);
expect(mockAutomationService.unregisterFlow).toHaveBeenCalledWith('flow_a');
expect(result.response?.body?.data?.deleted).toBe(true);
});
it('should trigger a flow via POST /:name/trigger', async () => {
const result = await dispatcher.handleAutomation('flow_a/trigger', 'POST', { key: 'val' }, AUTHED_CALLER());
expect(result.handled).toBe(true);
expect(mockAutomationService.execute).toHaveBeenCalledWith('flow_a', expect.objectContaining({
params: expect.objectContaining({ key: 'val' }),
event: 'manual',
}));
});
it('should toggle a flow via POST /:name/toggle', async () => {
// [#10243] `FLOW_AUTHOR`, not `AUTHED_CALLER`: toggle joined the
// `manage_metadata` write set by ruling. This case is about ROUTING
// — which service method the path reaches, with which arguments —
// so only the caller changes.
const result = await dispatcher.handleAutomation('flow_a/toggle', 'POST', { enabled: false }, FLOW_AUTHOR());
expect(result.handled).toBe(true);
expect(mockAutomationService.toggleFlow).toHaveBeenCalledWith('flow_a', false);
});
it('should list runs via GET /:name/runs', async () => {
const result = await dispatcher.handleAutomation('flow_a/runs', 'GET', {}, AUTHED_CALLER());
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.runs).toHaveLength(1);
});
it('should get a run via GET /:name/runs/:runId', async () => {
const result = await dispatcher.handleAutomation('flow_a/runs/run_1', 'GET', {}, AUTHED_CALLER());
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.id).toBe('run_1');
});
it('should return 404 for non-existent run', async () => {
mockAutomationService.getRun.mockResolvedValue(null);
const result = await dispatcher.handleAutomation('flow_a/runs/missing', 'GET', {}, AUTHED_CALLER());
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(404);
});
// ── screen-flow runtime (ADR-0019 durable pause, #3528) ──────────
it('should resume a paused run via POST /:name/runs/:runId/resume', async () => {
const result = await dispatcher.handleAutomation(
'flow_a/runs/run_1/resume', 'POST', { inputs: { new_assignee: 'ada' } }, AUTHED_CALLER(),
);
expect(result.handled).toBe(true);
expect(mockAutomationService.resume).toHaveBeenCalledWith('run_1', {
variables: { new_assignee: 'ada' },
});
expect(result.response?.body?.data?.success).toBe(true);
});
it('should accept `variables` as an alias for `inputs` on resume', async () => {
await dispatcher.handleAutomation(
'flow_a/runs/run_1/resume', 'POST', { variables: { note: 'hi' } }, AUTHED_CALLER(),
);
expect(mockAutomationService.resume).toHaveBeenCalledWith('run_1', {
variables: { note: 'hi' },
});
});
it('should forward approval-style output + branchLabel on resume', async () => {
await dispatcher.handleAutomation(
'flow_a/runs/run_1/resume', 'POST',
{ output: { comment: 'ok' }, branchLabel: 'approve' }, AUTHED_CALLER(),
);
expect(mockAutomationService.resume).toHaveBeenCalledWith('run_1', {
output: { comment: 'ok' },
branchLabel: 'approve',
});
});
it('should resume with an empty signal when the body carries no input', async () => {
await dispatcher.handleAutomation('flow_a/runs/run_1/resume', 'POST', undefined, AUTHED_CALLER());
expect(mockAutomationService.resume).toHaveBeenCalledWith('run_1', {});
});
it('should surface the next screen when a resumed run pauses again', async () => {
mockAutomationService.resume.mockResolvedValue({
success: true, status: 'paused', runId: 'run_1',
screen: { nodeId: 'step2', title: 'Confirm', fields: [] },
});
const result = await dispatcher.handleAutomation(
'flow_a/runs/run_1/resume', 'POST', { inputs: {} }, AUTHED_CALLER(),
);
expect(result.response?.body?.data?.status).toBe('paused');
expect(result.response?.body?.data?.screen?.nodeId).toBe('step2');
});
// #3801: a run parked on a service-gated node (an `approval` pause,
// resumable only through ApprovalService) comes back `forbidden` from
// the engine. That is an AUTHORIZATION answer and must read as one —
// a 200 carrying `success: false` reads as "your resume ran and the
// flow failed", which is the opposite of what happened.
it('should answer 403 when the engine refuses the resume as service-gated', async () => {
mockAutomationService.resume.mockResolvedValue({
success: false, code: 'PERMISSION_DENIED',
error: "Run 'run_1' is paused at an 'approval' node, which only its owning service may resume",
});
const result = await dispatcher.handleAutomation(
'flow_a/runs/run_1/resume', 'POST', { branchLabel: 'approve' }, AUTHED_CALLER(),
);
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(403);
expect(result.response?.body?.error?.message ?? result.response?.body?.message)
.toMatch(/only its owning service may resume/);
});
// A run that resumed and then FAILED is not an authorization answer —
// and since #8684 it is not a 200 either.
//
// This assertion used to demand the ordinary success envelope
// (`body.data.success === false`), which is exactly the double envelope
// #3962 ruled out for `/actions`: a caller that branches on the HTTP
// status alone read a failed run as a successful one. #8684 inherits that
// ruling for this route and IS the documented decision that flipped this
// pin — the same way #3962's own checklist flipped
// `actions-validation-envelope.test.ts`. The 403 half of the name is
// unchanged and still the point: a failed run is not an authorization
// answer.
it('should not 403 an ordinary failed resume — it answers 400 FLOW_FAILED', async () => {
mockAutomationService.resume.mockResolvedValue({ success: false, error: 'node blew up' });
const result = await dispatcher.handleAutomation(
'flow_a/runs/run_1/resume', 'POST', { inputs: {} }, AUTHED_CALLER(),
);
expect(result.response?.status).not.toBe(403);
expect(result.response?.status).toBe(400);
expect(result.response?.body?.error?.code).toBe('FLOW_FAILED');
expect(result.response?.body?.error?.message).toBe('node blew up');
// The double envelope is gone, not merely re-labelled: there is no
// inner `data` for a status-blind caller to misread.
expect(result.response?.body?.data).toBeUndefined();
expect(result.response?.body?.success).toBe(false);
});
// [#8684] The WIRE SHAPE of that 400, pinned field by field rather than
// by status alone — this is the single point where the consumer contract
// can be silently lost. objectui reads the flow author's own failure text
// from `error.details.errorMessage` and from nowhere else (module header
// of `packages/app-shell/src/utils/flowResponse.ts`, PR #4899): the
// ADR-0112 envelope has no `data`, so a producer that builds its message
// out of `result.error` alone drops the author's words while every status
// assertion stays green. The live `/actions` producer used to do exactly
// that; since #9585 it ships both fields through its typed refusal
// carrier (`action-execution.ts`), pinned door-against-door in
// `actions-flow-dispatch-status.test.ts`.
it('should carry the flow-authored errorMessage and the run summary in the 400 details', async () => {
mockAutomationService.resume.mockResolvedValue({
success: false,
error: "Node 'create_opportunity' failed: Amount must be greater than zero",
errorMessage: 'We could not create the opportunity — check the amount and try again.',
durationMs: 45,
summary: { selected: 0, acted: 0, skipped: 0, unmeasured: 0, nodes: [
{ nodeId: 'create_opportunity', nodeType: 'create_record', status: 'failure', runs: 1, failures: 1 },
] },
});
const result = await dispatcher.handleAutomation(
'flow_a/runs/run_1/resume', 'POST', { inputs: { amount: 0 } }, AUTHED_CALLER(),
);
expect(result.response?.status).toBe(400);
expect(result.response?.body?.error?.code).toBe('FLOW_FAILED');
// The raw node error stays the human-readable message …
expect(result.response?.body?.error?.message)
.toMatch(/Node 'create_opportunity' failed/);
// … and the author's message is NOT folded into it, nor dropped.
expect(result.response?.body?.error?.details?.errorMessage)
.toBe('We could not create the opportunity — check the amount and try again.');
// Which node failed survives the envelope change.
expect(result.response?.body?.error?.details?.summary?.nodes?.[0]?.status).toBe('failure');
// `code` is promoted out of `details` into the declared field, never
// duplicated in both (`error-envelope.ts`).
expect(result.response?.body?.error?.details?.code).toBeUndefined();
});
// [#8684] The other half of the producer-first split: an exit where
// nothing ran because the suspension is STALE — the flow was
// deregistered, or the node was edited away under a live pause. The
// engine now reports both under `RUN_NOT_FOUND`, so they answer 404
// (terminal, unresumable) instead of being mislabelled a business
// rejection. The route reads the engine's classification; it does not
// infer one from the shape of the result.
it('should answer 404 when the suspension is stale rather than the run having failed', async () => {
mockAutomationService.resume.mockResolvedValue({
success: false, code: 'RUN_NOT_FOUND',
error: "Suspended node 'collect' no longer exists in flow 'flow_a'",
});
const result = await dispatcher.handleAutomation(
'flow_a/runs/run_1/resume', 'POST', { inputs: {} }, AUTHED_CALLER(),
);
expect(result.response?.status).toBe(404);
expect(result.response?.body?.error?.message).toMatch(/no longer exists in flow/);
expect(result.response?.body?.error?.code).not.toBe('FLOW_FAILED');
});
// [#8684] `INVALID_SIGNAL` / `INVALID_SCREEN_INPUT` are refusals the
// engine makes BEFORE consuming the suspension, so the pause is still
// live and the caller can correct the submission and retry. They must
// keep their own codes: the console treats only `FLOW_FAILED` as terminal
// (PR #4899), so folding a retryable refusal into it would close the
// wizard on a submission the user could have fixed.
it('should keep INVALID_SCREEN_INPUT distinct from FLOW_FAILED', async () => {
mockAutomationService.resume.mockResolvedValue({
success: false, code: 'INVALID_SCREEN_INPUT',
error: "Invalid screen input: Unknown screen field \"nickname\" — declared fields: 'full_name'",
});
const result = await dispatcher.handleAutomation(
'flow_a/runs/run_1/resume', 'POST', { inputs: { nickname: 'ada' } }, AUTHED_CALLER(),
);
expect(result.response?.status).toBe(400);
expect(result.response?.body?.error?.code).not.toBe('FLOW_FAILED');
expect(result.response?.body?.error?.message).toMatch(/Unknown screen field/);
});
// #3853 follow-up: the reserved-name rule lives in the ENGINE, at the one
// place a signal reaches the variable map — the route only maps its
// verdict onto a status. (Guarding one body field at a time here is what
// let `output` reopen the hole `inputs` had just closed.)
it('should answer 400 when the engine rejects the signal as engine-internal', async () => {
mockAutomationService.resume.mockResolvedValue({
success: false, code: 'INVALID_SIGNAL',
error: "Resume signal may not set engine-internal variables (signoffs.$mapItemDone) — " +
"names starting with '$' (or containing '.$') are reserved by the flow engine",
});
const result = await dispatcher.handleAutomation(
'flow_a/runs/run_1/resume', 'POST',
{ output: { $mapItemDone: true } }, AUTHED_CALLER(),
);
expect(result.response?.status).toBe(400);
expect(result.response?.body?.error?.message).toMatch(/reserved by the flow engine/);
});
// Both body fields reach the engine verbatim — it, not the route, decides.
it('should forward `output` and `inputs` unfiltered for the engine to judge', async () => {
await dispatcher.handleAutomation(
'flow_a/runs/run_1/resume', 'POST',
{ inputs: { new_assignee: 'ada', 'collect.note': 'hi', price$: 3 }, output: { decision: 'ok' } },
AUTHED_CALLER(),
);
expect(mockAutomationService.resume).toHaveBeenCalledWith('run_1', {
variables: { new_assignee: 'ada', 'collect.note': 'hi', price$: 3 },
output: { decision: 'ok' },
});
});
it('should return 501 when the automation service cannot resume', async () => {
delete mockAutomationService.resume;
const result = await dispatcher.handleAutomation(
'flow_a/runs/run_1/resume', 'POST', { inputs: {} }, AUTHED_CALLER(),
);
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(501);
});
it('should get the pending screen via GET /:name/runs/:runId/screen', async () => {
const result = await dispatcher.handleAutomation('flow_a/runs/run_1/screen', 'GET', {}, AUTHED_CALLER());
expect(result.handled).toBe(true);
expect(mockAutomationService.getSuspendedScreen).toHaveBeenCalledWith('run_1');
expect(result.response?.body?.data?.screen?.nodeId).toBe('collect');
// `screen` must NOT be swallowed by the getRun route below it.
//
// [#7968] Asserted on the ANSWER, not on `getRun` being unused: the
// screen route now reads the run to resolve its trigger identity
// for the read gate, so "getRun was never called" stopped being a
// proxy for "the path did not fall through". What the routing claim
// actually says is that the caller got the SCREEN envelope
// (`{ runId, screen }`) and not the `ExecutionLogEntry` the
// `/:name/runs/:runId` branch serves verbatim — which the mock
// makes distinguishable: that entry is `{ id: 'run_1', status:
// 'completed' }`, carrying neither key below.
expect(result.response?.body?.data?.runId).toBe('run_1');
expect(result.response?.body?.data?.id).toBeUndefined();
expect(result.response?.body?.data?.status).toBeUndefined();
});
it('should return 404 when the run is not awaiting a screen', async () => {
mockAutomationService.getSuspendedScreen.mockResolvedValue(null);
const result = await dispatcher.handleAutomation('flow_a/runs/run_1/screen', 'GET', {}, AUTHED_CALLER());
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(404);
});
/**
* [#4127] This used to assert `trigger('flow_a', { data: 1 }, { request })`
* — a method the mock invented. Nothing in the repo implements `trigger`
* on the automation slot and `IAutomationService` never declared it, so
* the branch it pinned was dead on every deployment while the "fallback"
* to `execute` was the actual route. Same test shape that let #4087 sit
* green on a `/storage` handler calling `upload` with the wrong
* arguments: mock what the handler wants, and the handler always agrees.
*
* The route goes through the CONTRACT method now, with the body
* translated into an AutomationContext. Identity forwarding is covered
* in domain-handler-registry.test.ts, which can seed an
* executionContext without dispatch() overwriting it.
*/
it('routes the legacy POST /trigger/:name through execute, never a non-contract trigger()', async () => {
const result = await dispatcher.handleAutomation('trigger/flow_a', 'POST', { data: 1 }, AUTHED_CALLER());
expect(result.handled).toBe(true);
expect(mockAutomationService.trigger).not.toHaveBeenCalled();
expect(mockAutomationService.execute).toHaveBeenCalledTimes(1);
const [name, ctx] = mockAutomationService.execute.mock.calls[0];
expect(name).toBe('flow_a');
// A flat body survives as flow params rather than being handed to
// the engine as an AutomationContext it cannot read anything from.
expect(ctx.params).toEqual({ data: 1 });
expect(ctx.event).toBe('manual');
});
// ── GET /actions — action descriptor registry (ADR-0018) ──────────
it('should list action descriptors via GET /actions', async () => {
const result = await dispatcher.handleAutomation('actions', 'GET', {}, AUTHED_CALLER());
expect(result.handled).toBe(true);
expect(mockAutomationService.getActionDescriptors).toHaveBeenCalled();
expect(result.response?.body?.data?.total).toBe(3);
expect(result.response?.body?.data?.actions.map((a: any) => a.type)).toEqual(
['decision', 'http_request', 'send_sms'],
);
});
it('must NOT let GET /actions be shadowed by the /:name flow lookup', async () => {
const result = await dispatcher.handleAutomation('actions', 'GET', {}, AUTHED_CALLER());
expect(result.handled).toBe(true);
// The actions registry is returned, NOT a getFlow('actions') result.
expect(mockAutomationService.getFlow).not.toHaveBeenCalled();
expect(result.response?.body?.data?.actions).toBeDefined();
});
it('should filter GET /actions by ?source', async () => {
const result = await dispatcher.handleAutomation('actions', 'GET', {}, AUTHED_CALLER(), { source: 'plugin' });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.total).toBe(1);
expect(result.response?.body?.data?.actions[0].type).toBe('send_sms');
});
it('should filter GET /actions by ?paradigm', async () => {
const result = await dispatcher.handleAutomation('actions', 'GET', {}, AUTHED_CALLER(), { paradigm: 'approval' });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.total).toBe(1);
expect(result.response?.body?.data?.actions[0].type).toBe('http_request');
});
it('should return an empty registry when the service lacks getActionDescriptors', async () => {
delete mockAutomationService.getActionDescriptors;
const result = await dispatcher.handleAutomation('actions', 'GET', {}, AUTHED_CALLER());
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.actions).toEqual([]);
expect(result.response?.body?.data?.total).toBe(0);
});
// ── GET /connectors — connector descriptor registry (ADR-0022) ────
it('should list connector descriptors via GET /connectors', async () => {
const result = await dispatcher.handleAutomation('connectors', 'GET', {}, AUTHED_CALLER());
expect(result.handled).toBe(true);
expect(mockAutomationService.getConnectorDescriptors).toHaveBeenCalled();
expect(result.response?.body?.data?.total).toBe(3);
expect(result.response?.body?.data?.connectors.map((c: any) => c.name)).toEqual(
['rest', 'slack', 'pg'],
);
});
it('must NOT let GET /connectors be shadowed by the /:name flow lookup', async () => {
const result = await dispatcher.handleAutomation('connectors', 'GET', {}, AUTHED_CALLER());
expect(result.handled).toBe(true);
// The connector registry is returned, NOT a getFlow('connectors') result.
expect(mockAutomationService.getFlow).not.toHaveBeenCalled();
expect(result.response?.body?.data?.connectors).toBeDefined();
});
it('should filter GET /connectors by ?type', async () => {
const result = await dispatcher.handleAutomation('connectors', 'GET', {}, AUTHED_CALLER(), { type: 'database' });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.total).toBe(1);
expect(result.response?.body?.data?.connectors[0].name).toBe('pg');
});
// [#4127] The route serves the WHOLE descriptor. `origin` and `state`
// are what the designer reads to distinguish a live declarative
// instance from a plugin connector, and a dispatchable one from a
// degraded one (ADR-0097 §4, #3017) — while the contract did not
// declare the method, nothing pinned that they survive the hop.
it('should preserve origin / state / degradedReason on GET /connectors', async () => {
const result = await dispatcher.handleAutomation('connectors', 'GET', {}, AUTHED_CALLER());
expect(result.handled).toBe(true);
const byName = Object.fromEntries(
result.response?.body?.data?.connectors.map((c: ConnectorDescriptor) => [c.name, c]),
);
expect(byName.rest).toMatchObject({ origin: 'plugin', state: 'ready' });
expect(byName.pg).toMatchObject({
origin: 'declarative',
state: 'degraded',
degradedReason: 'upstream unreachable',
});
});
it('should return an empty registry when the service lacks getConnectorDescriptors', async () => {
delete mockAutomationService.getConnectorDescriptors;
const result = await dispatcher.handleAutomation('connectors', 'GET', {}, AUTHED_CALLER());
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.connectors).toEqual([]);
expect(result.response?.body?.data?.total).toBe(0);
});
});
// ═══════════════════════════════════════════════════════════════
// Async Service Resolution Tests
// Covers: getService awaits Promise-based (async factory) services
// ═══════════════════════════════════════════════════════════════
describe('Async service resolution (Promise-based injection)', () => {
describe('handleAnalytics with async service', () => {
it('should resolve analytics service from Promise (async factory)', async () => {
const mockAnalytics = {
query: vi.fn().mockResolvedValue({ rows: [{ id: 1 }], total: 1 }),
getMeta: vi.fn().mockResolvedValue({ tables: ['t1'] }),
generateSql: vi.fn().mockResolvedValue({ sql: 'SELECT 1' }),
};
// Inject as Promise (simulates async factory registration)
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'analytics') return Promise.resolve(mockAnalytics);
return null;
});
const result = await dispatcher.handleAnalytics('query', 'POST', { cube: 't1', measures: ['count'] }, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(mockAnalytics.query).toHaveBeenCalled();
});
// [#2852] The execution context must reach the analytics service so
// it scopes each object by its per-object read filter (tenant + RLS).
// Previously it was dropped and the query ran UNSCOPED.
it('threads the execution context into analytics.query and generateSql (RLS scoping)', async () => {
const mockAnalytics = {
query: vi.fn().mockResolvedValue({ rows: [], total: 0 }),
generateSql: vi.fn().mockResolvedValue({ sql: 'SELECT 1', params: [] }),
};
(kernel as any).getService = vi.fn().mockImplementation((name: string) =>
name === 'analytics' ? mockAnalytics : null,
);
const ec = { userId: 'u1', positions: [], permissions: [], tenantId: 'org-1' };
// [#3878] The ORIGINAL body must be forwarded (no parse-output
// substitution): a parsed body would carry the schema's
// `timezone: 'UTC'` default and override org-timezone resolution.
const body = { cube: 'leads', measures: ['count'] };
await dispatcher.handleAnalytics('query', 'POST', body, { request: {}, executionContext: ec } as any);
expect(mockAnalytics.query).toHaveBeenCalledWith(body, ec);
expect(mockAnalytics.query.mock.calls[0][0]).toBe(body);
await dispatcher.handleAnalytics('sql', 'POST', body, { request: {}, executionContext: ec } as any);
expect(mockAnalytics.generateSql).toHaveBeenCalledWith(body, ec);
});
it('should handle POST /analytics/sql with async service', async () => {
const mockAnalytics = {
generateSql: vi.fn().mockResolvedValue({ sql: 'SELECT * FROM t' }),
};
(kernel as any).getService = vi.fn().mockResolvedValue(mockAnalytics);
const result = await dispatcher.handleAnalytics('sql', 'POST', { cube: 'test', measures: ['count'] }, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(mockAnalytics.generateSql).toHaveBeenCalled();
});
it('should handle GET /analytics/meta with async service', async () => {
const mockAnalytics = {
getMeta: vi.fn().mockResolvedValue({ tables: ['users', 'orders'] }),
};
(kernel as any).getService = vi.fn().mockResolvedValue(mockAnalytics);
const result = await dispatcher.handleAnalytics('meta', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(result.response?.body?.data?.tables).toEqual(['users', 'orders']);
});
// [#3584] GET /analytics/meta?cube=<name> — the optional single-cube
// filter the client's analytics.meta(cube) sends. The cube name must
// reach AnalyticsService.getMeta(cubeName?); absent/empty stays a
// full listing (getMeta called with undefined).
it('threads the ?cube= filter into getMeta, full dispatch path included', async () => {
const mockAnalytics = {
getMeta: vi.fn().mockResolvedValue([{ name: 'leads' }]),
};
(kernel as any).getService = vi.fn().mockResolvedValue(mockAnalytics);
const viaDispatch = await dispatcher.dispatch('GET', '/analytics/meta', undefined, { cube: 'leads' }, { request: {} });
expect(viaDispatch.handled).toBe(true);
expect(mockAnalytics.getMeta).toHaveBeenCalledWith('leads');
mockAnalytics.getMeta.mockClear();
await dispatcher.handleAnalytics('meta', 'GET', undefined, { request: {} }, { cube: '' });
expect(mockAnalytics.getMeta).toHaveBeenCalledWith(undefined);
});
it('should return unhandled when analytics service is not registered', async () => {
(kernel as any).getService = vi.fn().mockResolvedValue(null);
(kernel as any).services = new Map();
const result = await dispatcher.handleAnalytics('query', 'POST', {}, { request: {} });
expect(result.handled).toBe(false);
});
// [#4000] ADR-0076 D12 conclusion 3 binds consumers: only
// `handlerReady: true` is a real capability. The dispatcher gated
// on presence alone, so anything occupying the slot got called and
// its fabricated rows went back as a 200 — the shape #3891 retired
// one layer up, kept alive in dev by plugin-dev's analytics stub
// (retired with this change). A stub slot is an empty slot.
it('returns unhandled when the analytics slot holds a self-declared stub, without calling it', async () => {
const stub = {
__serviceInfo: { status: 'stub' },
query: vi.fn().mockResolvedValue({ rows: [], fields: [] }),
getMeta: vi.fn().mockResolvedValue([]),
generateSql: vi.fn().mockResolvedValue({ sql: '', params: [] }),
};
(kernel as any).getService = vi.fn().mockResolvedValue(stub);
for (const [sub, method] of [['query', 'POST'], ['meta', 'GET'], ['sql', 'POST']] as const) {
const result = await dispatcher.handleAnalytics(sub, method, { cube: 'leads', measures: ['count'] }, { request: {} });
expect(result.handled, `${method} /analytics/${sub}`).toBe(false);
}
expect(stub.query).not.toHaveBeenCalled();
expect(stub.getMeta).not.toHaveBeenCalled();
expect(stub.generateSql).not.toHaveBeenCalled();
});
// The same gate read through the standard descriptor, and its other
// half: `degraded` means "working, but partial" — `handlerReady`
// defaults to true there, so it keeps serving. Only a self-confessed
// non-handler is treated as an empty slot.
it('honours __serviceInfo: stub 404s, degraded still serves', async () => {
const make = (info: Record<string, unknown>) => ({
__serviceInfo: info,
query: vi.fn().mockResolvedValue({ rows: [], fields: [] }),
});
const stub = make({ status: 'stub', message: 'dev fake' });
(kernel as any).getService = vi.fn().mockResolvedValue(stub);
expect((await dispatcher.handleAnalytics('query', 'POST', { cube: 'leads', measures: ['count'] }, { request: {} })).handled).toBe(false);
expect(stub.query).not.toHaveBeenCalled();
const degraded = make({ status: 'degraded' });
(kernel as any).getService = vi.fn().mockResolvedValue(degraded);
expect((await dispatcher.handleAnalytics('query', 'POST', { cube: 'leads', measures: ['count'] }, { request: {} })).handled).toBe(true);
expect(degraded.query).toHaveBeenCalled();
});
it('should return unhandled for unknown analytics sub-path', async () => {
const mockAnalytics = { query: vi.fn() };
(kernel as any).getService = vi.fn().mockResolvedValue(mockAnalytics);
const result = await dispatcher.handleAnalytics('unknown', 'POST', {}, { request: {} });
expect(result.handled).toBe(false);
});
// [#3878] Entry validation: a malformed body raises the duck-typed
// VALIDATION_FAILED shape BEFORE the service runs — previously it
// reached the engine, inferred a column-less cube, and died as an
// SQL syntax error (or had its off-contract filter silently
// dropped). The domain throws through (same contract as service
// errors, see 'should propagate analytics query error'); the HTTP
// bridge maps the shape to a 400 envelope — pinned end-to-end in
// `dispatcher-validation-error.real.test.ts`.
describe('AnalyticsQuery body validation (#3878)', () => {
const service = () => {
const mockAnalytics = {
query: vi.fn().mockResolvedValue({ rows: [] }),
generateSql: vi.fn().mockResolvedValue({ sql: 'SELECT 1', params: [] }),
};
(kernel as any).getService = vi.fn().mockResolvedValue(mockAnalytics);
return mockAnalytics;
};
it('rejects the retired {cube, query:{...}} envelope with the tombstone prescription', async () => {
const mockAnalytics = service();
await expect(dispatcher.dispatch(
'POST', '/analytics/query', { cube: 'x', query: { measures: ['count'] } }, {}, { request: {} },
)).rejects.toMatchObject({
name: 'ValidationError',
code: 'VALIDATION_FAILED',
message: expect.stringContaining('top level'),
});
expect(mockAnalytics.query).not.toHaveBeenCalled();
});
it('rejects a `filters` key, pointing at the contract field `where`', async () => {
const mockAnalytics = service();
await expect(dispatcher.dispatch(
'POST', '/analytics/query',
{ cube: 'x', measures: ['count'], filters: [{ member: 'status', operator: 'equals', values: ['active'] }] },
{}, { request: {} },
)).rejects.toMatchObject({
code: 'VALIDATION_FAILED',
message: expect.stringContaining('`where`'),
});
expect(mockAnalytics.query).not.toHaveBeenCalled();
});
it('rejects a body with no measures, naming the missing field', async () => {
const mockAnalytics = service();
await expect(dispatcher.dispatch(
'POST', '/analytics/query', { cube: 'x' }, {}, { request: {} },