-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathenvelope.conformance.test.ts
More file actions
239 lines (221 loc) · 10.4 KB
/
Copy pathenvelope.conformance.test.ts
File metadata and controls
239 lines (221 loc) · 10.4 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
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* Response-envelope conformance for `/api/v1/datasources/*` (#3843).
*
* The drift this closes was the WORSE of the two dialects #3843 surveyed: not
* merely a missing `success` flag, but the pre-#3675 `{ error: '<string>' }`,
* with the message a SIBLING of `error` rather than a field of it —
*
* res.status(400).json({ error: 'DATASOURCE_ADMIN_ERROR', message });
*
* so a caller reading `body.error.message` got `undefined` here and the real
* message from the dispatcher. That is the identical asymmetry #3675 opened on,
* still live in this module two issues later because #3675 and #3689 each
* scoped themselves to one service and neither asked whether the same drift
* existed elsewhere.
*
* Driven against the REAL `HonoHttpServer` — the same `IHttpServer` `os serve`
* mounts — so the bodies asserted here are the bytes a client receives, not a
* mock's record of what a handler passed to `json()`. That matters for the
* success arm: `sendOk` sets an explicit `status(200)` where the module used to
* call bare `res.json(…)`, and only a real adapter proves the chain works.
*
* The STATIC half of this conformance — proving no route can bypass the
* `sendOk` / `sendError` pair — is not here. It is
* `scripts/check-route-envelope.mjs`, a repo-wide guard run by
* `pnpm check:route-envelope` in CI. It sits outside any package on purpose: the
* three predecessors of that scan were per-package, which structurally cannot
* notice a route module nobody thought to convert, and two such modules turned up
* the moment it went repo-wide: `share-link-routes.ts` (#3983) and the dev-only
* `hmr-routes.ts`, neither of them in #3843's hand-written survey.
*
* What stays here is the half that has to live next to the routes it drives:
* every branch driven, every body parsed against the real spec schemas.
*/
import { describe, it, expect, vi } from 'vitest';
import { BaseResponseSchema, envelopeViolations } from '@objectstack/spec/api';
import { HonoHttpServer } from '@objectstack/plugin-hono-server';
import { registerDatasourceAdminRoutes } from '../admin-routes.js';
const req = (path: string, init?: RequestInit) =>
new Request(`http://local${path}`, {
...init,
headers: { 'content-type': 'application/json', ...(init?.headers ?? {}) },
});
function mount(svc: unknown) {
const server = new HonoHttpServer(0);
const ctx = { getService: vi.fn().mockReturnValue(svc) } as any;
registerDatasourceAdminRoutes(server, ctx, '/api/v1');
return server.getRawApp();
}
interface Captured {
status: number;
body: any;
}
async function drive(app: any, path: string, init?: RequestInit): Promise<Captured> {
const res = await app.fetch(req(path, init));
return { status: res.status, body: await res.json() };
}
describe('datasource-admin envelope (#3843) — success bodies', () => {
const CASES: Array<{ name: string; status: number; dataKeys: string[]; run: () => Promise<Captured> }> = [
{
name: 'GET /datasources',
status: 200,
dataKeys: ['datasources'],
run: () => drive(mount({ listDatasources: async () => [{ name: 'pg', origin: 'runtime' }] }), '/api/v1/datasources'),
},
{
name: 'GET /datasources/drivers',
status: 200,
dataKeys: ['drivers'],
run: () => drive(mount({}), '/api/v1/datasources/drivers'),
},
{
name: 'GET /datasources/:name/remote-tables',
status: 200,
dataKeys: ['tables'],
run: () => drive(mount({ listRemoteTables: async () => [{ name: 'customers' }] }), '/api/v1/datasources/ext/remote-tables'),
},
{
name: 'GET /datasources/:name',
status: 200,
dataKeys: ['datasource'],
run: () => drive(mount({ getDatasource: async () => ({ name: 'ext', driver: 'sqlite' }) }), '/api/v1/datasources/ext'),
},
{
name: 'POST /datasources/:name/test',
status: 200,
// The service's own verdict object, carried under `data` whole.
dataKeys: ['ok'],
run: () => drive(mount({ testConnection: async () => ({ ok: true, latencyMs: 7 }) }), '/api/v1/datasources/ext/test', { method: 'POST', body: '{}' }),
},
{
name: 'POST /datasources/:name/object-draft',
status: 200,
dataKeys: ['draft'],
run: () => drive(mount({ generateObjectDraft: async () => ({ name: 'customers' }) }), '/api/v1/datasources/ext/object-draft', { method: 'POST', body: JSON.stringify({ table: 'customers' }) }),
},
{
name: 'POST /datasources/test',
status: 200,
dataKeys: ['result'],
run: () => drive(mount({ testConnection: async () => ({ ok: true }) }), '/api/v1/datasources/test', { method: 'POST', body: JSON.stringify({ driver: 'postgres' }) }),
},
{
// The one that carries a non-200 success status — proving `sendOk`'s
// `status` argument survives the real adapter.
name: 'POST /datasources (201)',
status: 201,
dataKeys: ['datasource'],
run: () => drive(mount({ createDatasource: async () => ({ name: 'pg', origin: 'runtime' }) }), '/api/v1/datasources', { method: 'POST', body: JSON.stringify({ name: 'pg', driver: 'postgres' }) }),
},
{
name: 'PATCH /datasources/:name',
status: 200,
dataKeys: ['datasource'],
run: () => drive(mount({ updateDatasource: async () => ({ name: 'pg', origin: 'runtime' }) }), '/api/v1/datasources/pg', { method: 'PATCH', body: JSON.stringify({ active: false }) }),
},
];
for (const c of CASES) {
it(`${c.name} answers ${c.status} { success: true, data }`, async () => {
const { status, body } = await c.run();
expect(status).toBe(c.status);
// The envelope SKELETON, imported. It is not the whole contract: it declares
// no `data` and strips unknown keys, so on its own it passes `{ success: true }`
// and passes a payload duplicated into a stray top-level key. What it DOES
// catch is the missing `success` flag — the drift this line was added for.
const parsed = BaseResponseSchema.safeParse(body);
expect(parsed.success, `body is not a BaseResponse: ${JSON.stringify(body)}`).toBe(true);
// The declared envelope in full — `safeParse` alone passes a body with no
// `data`, or a payload duplicated into a stray top-level key (#4049).
expect(envelopeViolations(body), `not the declared envelope: ${JSON.stringify(body)}`).toEqual([]);
expect(body.success).toBe(true);
expect(body.error).toBeUndefined();
for (const k of c.dataKeys) {
expect(body.data?.[k], `data.${k} missing from ${c.name}`).toBeDefined();
}
});
}
it('the pre-#3843 shape is dead — no payload at the top level', async () => {
for (const c of CASES) {
const { body } = await c.run();
expect(typeof body.success, `${c.name} answers no success flag`).toBe('boolean');
for (const k of c.dataKeys) {
expect(body[k], `${c.name} still answers a top-level ${k}`).toBeUndefined();
}
}
});
it('DELETE /datasources/:name stays a bodiless 204 — nothing to envelope', async () => {
const app = mount({ removeDatasource: async () => undefined });
const res = await app.fetch(req('/api/v1/datasources/pg', { method: 'DELETE' }));
expect(res.status).toBe(204);
expect(await res.text()).toBe('');
});
});
describe('datasource-admin envelope (#3843) — error bodies', () => {
const CASES: Array<{ name: string; status: number; code: string; run: () => Promise<Captured> }> = [
{
name: 'the datasource-admin service is not wired',
status: 503,
code: 'SERVICE_UNAVAILABLE',
run: () => drive(mount(undefined), '/api/v1/datasources'),
},
{
name: 'a lifecycle failure carries the service message',
status: 400,
code: 'DATASOURCE_ADMIN_ERROR',
run: () => drive(mount({ createDatasource: async () => { throw new Error('duplicate name'); } }), '/api/v1/datasources', { method: 'POST', body: JSON.stringify({ name: 'pg' }) }),
},
{
name: 'a missing required body field',
status: 400,
code: 'DATASOURCE_ADMIN_ERROR',
run: () => drive(mount({ generateObjectDraft: async () => ({}) }), '/api/v1/datasources/ext/object-draft', { method: 'POST', body: '{}' }),
},
{
name: 'reading a datasource that does not exist',
status: 404,
code: 'RESOURCE_NOT_FOUND',
run: () => drive(mount({ getDatasource: async () => undefined }), '/api/v1/datasources/nope'),
},
{
name: 'a remote-table introspection failure',
status: 400,
code: 'DATASOURCE_ADMIN_ERROR',
run: () => drive(mount({ listRemoteTables: async () => { throw new Error('no such schema'); } }), '/api/v1/datasources/ext/remote-tables'),
},
{
name: 'a removal failure',
status: 400,
code: 'DATASOURCE_ADMIN_ERROR',
run: () => drive(mount({ removeDatasource: async () => { throw new Error('not runtime-origin'); } }), '/api/v1/datasources/pg', { method: 'DELETE' }),
},
];
for (const c of CASES) {
it(`${c.name} → ${c.status} ${c.code}, in the declared envelope`, async () => {
const { status, body } = await c.run();
expect(status).toBe(c.status);
const parsed = BaseResponseSchema.safeParse(body);
expect(parsed.success, `body is not a BaseResponse: ${JSON.stringify(body)}`).toBe(true);
// The declared envelope in full — `safeParse` alone passes a body with no
// `data`, or a payload duplicated into a stray top-level key (#4049).
expect(envelopeViolations(body), `not the declared envelope: ${JSON.stringify(body)}`).toEqual([]);
expect(body.success).toBe(false);
expect(body.error.code).toBe(c.code);
expect(typeof body.error.message).toBe('string');
expect(body.error.message.length).toBeGreaterThan(0);
// The pre-#3675 shapes, explicitly dead: `error` is no longer a bare
// string, and `message` is no longer a SIBLING of it.
expect(typeof body.error).not.toBe('string');
expect(body.message).toBeUndefined();
});
}
it('the service message reads at `error.message` — the asymmetry #3675 opened on', async () => {
const { body } = await drive(
mount({ createDatasource: async () => { throw new Error('duplicate name'); } }),
'/api/v1/datasources',
{ method: 'POST', body: JSON.stringify({ name: 'pg' }) },
);
// Before #3843 this read `undefined`, and the message sat at `body.message`.
expect(body.error.message).toBe('duplicate name');
});
});