@pplethai/cli 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +100 -99
- package/package.json +1 -1
- package/templates/golden-path/CLAUDE.md +3 -1
- package/templates/golden-path/src/dev-read-dataset.ts +32 -6
- package/templates/golden-path/src/read-dataset.ts +124 -12
- package/templates/golden-path/test/dev-read-dataset.test.ts +70 -0
- package/templates/golden-path/test/read-dataset.test.ts +142 -2
package/package.json
CHANGED
|
@@ -82,7 +82,9 @@ Where the token comes from:
|
|
|
82
82
|
A collection page is `{ objects, next, sweptAt, snapshot }`; a singleton or
|
|
83
83
|
an id lookup is `{ object, sweptAt, snapshot }`. Pass `filter`, `sort` and
|
|
84
84
|
`limit`; pass `id` to look one object up; pass `follow: true` to walk
|
|
85
|
-
`next`.
|
|
85
|
+
`next`. Pass `ifNoneMatch: <etag>` on a page, singleton or lookup to poll:
|
|
86
|
+
a `304` is `{ ok: true, status: 304, etag, notModified: true }` with no `data`
|
|
87
|
+
(check `notModified` after `ok`); `follow: true` refuses it. The user token is `options.userToken` and is sent only when set.
|
|
86
88
|
Platform refusals are `x-pple-error` (`not_found`, `invalid_query`,
|
|
87
89
|
`level_not_met`, and the same codes as `callService`). Locally it reads
|
|
88
90
|
`.pple/registry/<full name>/mocks/<objectType>.json` through the same
|
|
@@ -23,6 +23,10 @@
|
|
|
23
23
|
// overlay, and pages of one file must share a snapshot. A declared Object Type
|
|
24
24
|
// with no mock file is `no_mock`, not an empty page. Offline has no warehouse,
|
|
25
25
|
// and a missing mock is the dev-only miss (ADR-0026).
|
|
26
|
+
//
|
|
27
|
+
// ETags are `"<snapshot>-<query hash>"`, so they are stable already: both parts
|
|
28
|
+
// come from the mock text and the query, not from a clock. A matching
|
|
29
|
+
// `ifNoneMatch` answers `304`, after the refusals, as production does.
|
|
26
30
|
|
|
27
31
|
import { parse as parseYaml } from "yaml";
|
|
28
32
|
import { forcedError, platformRefusal } from "./dev-call-service";
|
|
@@ -42,6 +46,8 @@ export interface OfflineDatasetCall {
|
|
|
42
46
|
/** Query entries, in the order `readDataset` puts them on the URL. */
|
|
43
47
|
search?: readonly (readonly [string, string])[];
|
|
44
48
|
userToken?: string;
|
|
49
|
+
/** `If-None-Match` as the Builder sent it. A match with the ETag this read produces answers `304`. */
|
|
50
|
+
ifNoneMatch?: string;
|
|
45
51
|
/** Active Persona name. An unknown name warns and uses `hq-staff`. */
|
|
46
52
|
persona: string;
|
|
47
53
|
devRegistryError?: string;
|
|
@@ -66,7 +72,7 @@ export function answerOfflineRead(
|
|
|
66
72
|
env: { DEV_PERSONA?: string; DEV_REGISTRY_ERROR?: string },
|
|
67
73
|
entry: string,
|
|
68
74
|
objectType: string,
|
|
69
|
-
request: { id?: string; search?: readonly (readonly [string, string])[]; userToken?: string },
|
|
75
|
+
request: { id?: string; search?: readonly (readonly [string, string])[]; userToken?: string; ifNoneMatch?: string },
|
|
70
76
|
): Response {
|
|
71
77
|
return answerOfflineDataset(overlayFiles(), overlayWrittenAt(), {
|
|
72
78
|
entry,
|
|
@@ -74,6 +80,7 @@ export function answerOfflineRead(
|
|
|
74
80
|
id: request.id,
|
|
75
81
|
search: request.search,
|
|
76
82
|
userToken: request.userToken,
|
|
83
|
+
ifNoneMatch: request.ifNoneMatch,
|
|
77
84
|
persona: env.DEV_PERSONA ?? "",
|
|
78
85
|
devRegistryError: env.DEV_REGISTRY_ERROR,
|
|
79
86
|
});
|
|
@@ -123,7 +130,7 @@ export function answerOfflineDataset(
|
|
|
123
130
|
if (search.length > 0) return platformRefusal("invalid_query");
|
|
124
131
|
const object = parseSingleton(call.entry, call.objectType, mock);
|
|
125
132
|
if (object === undefined) return noMock(unreadableMockMessage(call.entry, call.objectType));
|
|
126
|
-
return
|
|
133
|
+
return answer(call, { object, sweptAt, snapshot }, etag(snapshot, datasetOpaqueHash({ singleton: true })));
|
|
127
134
|
}
|
|
128
135
|
|
|
129
136
|
// A query on an id lookup is invalid even when the declaration cannot be
|
|
@@ -140,8 +147,8 @@ export function answerOfflineDataset(
|
|
|
140
147
|
const id = canonicalId(call.id, declared.spec.idType);
|
|
141
148
|
const found = id === null ? undefined : rows.find((row) => row.id === id);
|
|
142
149
|
if (!found) return platformRefusal("not_found");
|
|
143
|
-
return
|
|
144
|
-
call
|
|
150
|
+
return answer(
|
|
151
|
+
call,
|
|
145
152
|
{ object: found.object, sweptAt, snapshot },
|
|
146
153
|
etag(snapshot, datasetOpaqueHash({ lookup: id })),
|
|
147
154
|
);
|
|
@@ -152,8 +159,8 @@ export function answerOfflineDataset(
|
|
|
152
159
|
const parsed = parseDatasetQuery(params, declared.spec);
|
|
153
160
|
if (!parsed.ok) return platformRefusal("invalid_query");
|
|
154
161
|
const page = applyDatasetQuery(rows, parsed.query, declared.spec);
|
|
155
|
-
return
|
|
156
|
-
call
|
|
162
|
+
return answer(
|
|
163
|
+
call,
|
|
157
164
|
{ objects: page.objects, next: page.next, sweptAt, snapshot },
|
|
158
165
|
etag(snapshot, datasetPageHash(parsed.query)),
|
|
159
166
|
);
|
|
@@ -395,6 +402,25 @@ function unreadableMockMessage(entry: string, objectType: string): string {
|
|
|
395
402
|
return `อ่าน .pple/registry/${entry}/mocks/${objectType}.json ไม่ได้ — รัน pple registry เพื่อรีเฟรช`;
|
|
396
403
|
}
|
|
397
404
|
|
|
405
|
+
/**
|
|
406
|
+
* The 200, or the `304` when the Builder's `If-None-Match` names this ETag.
|
|
407
|
+
* It comes after every refusal, as in production (`dataset-read.ts`): a bad
|
|
408
|
+
* query or an unknown id is refused even when the ETag is current. The match
|
|
409
|
+
* rule is the platform's: a comma list, `W/` and the quotes ignored.
|
|
410
|
+
*/
|
|
411
|
+
function answer(call: OfflineDatasetCall, body: unknown, tag: string): Response {
|
|
412
|
+
if (noneMatch(call.ifNoneMatch, tag)) {
|
|
413
|
+
return new Response(null, { status: 304, headers: { etag: tag, [MOCK_HEADER]: call.entry } });
|
|
414
|
+
}
|
|
415
|
+
return jsonAnswer(call.entry, body, tag);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function noneMatch(header: string | undefined, tag: string): boolean {
|
|
419
|
+
if (!header) return false;
|
|
420
|
+
const want = tag.replaceAll('"', "");
|
|
421
|
+
return header.split(",").some((part) => part.trim().replace(/^W\//i, "").replaceAll('"', "") === want);
|
|
422
|
+
}
|
|
423
|
+
|
|
398
424
|
function jsonAnswer(entry: string, body: unknown, tag: string): Response {
|
|
399
425
|
const headers = new Headers({
|
|
400
426
|
"content-type": "application/json; charset=utf-8",
|
|
@@ -57,6 +57,7 @@ interface ReadDatasetCommon {
|
|
|
57
57
|
export interface ReadDatasetPageOptions extends ReadDatasetCommon {
|
|
58
58
|
shape?: "collection";
|
|
59
59
|
id?: undefined;
|
|
60
|
+
ifNoneMatch?: undefined;
|
|
60
61
|
/** Equality, a repeated value (`in`), or `{ gt, gte, lt, lte }`. */
|
|
61
62
|
filter?: Record<string, DatasetFilterValue>;
|
|
62
63
|
/** `<index>` or `-<index>`. Omitted sorts by id ascending. */
|
|
@@ -76,6 +77,7 @@ export interface ReadDatasetPageOptions extends ReadDatasetCommon {
|
|
|
76
77
|
export interface ReadDatasetSingletonOptions extends ReadDatasetCommon {
|
|
77
78
|
shape: "singleton";
|
|
78
79
|
id?: undefined;
|
|
80
|
+
ifNoneMatch?: undefined;
|
|
79
81
|
/** Sent as-is. The platform answers `invalid_query` for any query on a singleton. */
|
|
80
82
|
filter?: Record<string, DatasetFilterValue>;
|
|
81
83
|
sort?: string;
|
|
@@ -87,17 +89,68 @@ export interface ReadDatasetLookupOptions extends ReadDatasetCommon {
|
|
|
87
89
|
/** Look up this id. A query string as well is `invalid_query`. */
|
|
88
90
|
id: string;
|
|
89
91
|
shape?: "collection" | "singleton";
|
|
92
|
+
ifNoneMatch?: undefined;
|
|
90
93
|
filter?: Record<string, DatasetFilterValue>;
|
|
91
94
|
sort?: string;
|
|
92
95
|
limit?: number;
|
|
93
96
|
next?: string;
|
|
94
97
|
}
|
|
95
98
|
|
|
99
|
+
/**
|
|
100
|
+
* The conditional forms: the same three single-request shapes, plus an
|
|
101
|
+
* `ifNoneMatch` that is sent as `If-None-Match`. Passing one widens the result
|
|
102
|
+
* to include `DatasetNotModified`. `follow: true` is not accepted with it:
|
|
103
|
+
* a walk has one ETag per page, so one conditional request does not apply. It
|
|
104
|
+
* is a type error, and `readDataset` throws if it gets one anyway.
|
|
105
|
+
*/
|
|
106
|
+
interface Conditional {
|
|
107
|
+
/**
|
|
108
|
+
* An `etag` from an earlier success or not-modified result. Sent as
|
|
109
|
+
* `If-None-Match`. When the data has not changed the platform answers `304`
|
|
110
|
+
* and `readDataset` returns `{ ok: true, status: 304, etag, notModified: true }`
|
|
111
|
+
* with no `data`. Otherwise the answer is the usual success or refusal.
|
|
112
|
+
* `undefined` (a first read, with nothing cached yet) sends no header.
|
|
113
|
+
*/
|
|
114
|
+
ifNoneMatch: string | undefined;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export type ReadDatasetConditionalPageOptions = Omit<ReadDatasetPageOptions, "ifNoneMatch" | "follow"> &
|
|
118
|
+
Conditional & { follow?: false };
|
|
119
|
+
export type ReadDatasetConditionalSingletonOptions = Omit<ReadDatasetSingletonOptions, "ifNoneMatch"> &
|
|
120
|
+
Conditional;
|
|
121
|
+
export type ReadDatasetConditionalLookupOptions = Omit<ReadDatasetLookupOptions, "ifNoneMatch"> & Conditional;
|
|
122
|
+
|
|
123
|
+
type AnyReadOptions =
|
|
124
|
+
| ReadDatasetPageOptions
|
|
125
|
+
| ReadDatasetSingletonOptions
|
|
126
|
+
| ReadDatasetLookupOptions
|
|
127
|
+
| ReadDatasetConditionalPageOptions
|
|
128
|
+
| ReadDatasetConditionalSingletonOptions
|
|
129
|
+
| ReadDatasetConditionalLookupOptions;
|
|
130
|
+
|
|
96
131
|
export type DatasetSuccess<T> = {
|
|
97
132
|
ok: true;
|
|
98
133
|
status: number;
|
|
99
134
|
etag: string | null;
|
|
100
135
|
data: T;
|
|
136
|
+
notModified?: undefined;
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The answer to a conditional read (`ifNoneMatch`) when the platform said
|
|
141
|
+
* `304`: what the Builder already holds is still current. There is no `data`.
|
|
142
|
+
* `etag` is the platform's `ETag`, the same value that was sent.
|
|
143
|
+
*
|
|
144
|
+
* It only comes back from a read that passed `ifNoneMatch`. Narrow it with
|
|
145
|
+
* `result.ok && result.notModified`: on `true` the result is this type, and
|
|
146
|
+
* after `if (result.ok && !result.notModified)` it is a `DatasetSuccess` with
|
|
147
|
+
* `data`. A refusal has `ok: false`, so it never has `notModified`.
|
|
148
|
+
*/
|
|
149
|
+
export type DatasetNotModified = {
|
|
150
|
+
ok: true;
|
|
151
|
+
status: 304;
|
|
152
|
+
etag: string | null;
|
|
153
|
+
notModified: true;
|
|
101
154
|
};
|
|
102
155
|
|
|
103
156
|
/**
|
|
@@ -114,6 +167,9 @@ export type DatasetFailure = {
|
|
|
114
167
|
|
|
115
168
|
export type DatasetResult<T> = DatasetSuccess<T> | DatasetFailure;
|
|
116
169
|
|
|
170
|
+
/** What a conditional read returns: a `DatasetResult`, or `DatasetNotModified`. */
|
|
171
|
+
export type DatasetConditionalResult<T> = DatasetResult<T> | DatasetNotModified;
|
|
172
|
+
|
|
117
173
|
const RANGE_OPS = ["gt", "gte", "lt", "lte"] as const;
|
|
118
174
|
const FOLLOW_ATTEMPTS = 3;
|
|
119
175
|
|
|
@@ -126,7 +182,33 @@ const FOLLOW_ATTEMPTS = 3;
|
|
|
126
182
|
* A collection (the default) is a page. `shape: "singleton"` or `id` is one
|
|
127
183
|
* object. `follow: true` walks a collection to the end. The App Key is always
|
|
128
184
|
* `Authorization: Bearer`.
|
|
185
|
+
*
|
|
186
|
+
* Polling: pass `ifNoneMatch: <the last etag>` on a page, a singleton or an id
|
|
187
|
+
* lookup. It is sent as `If-None-Match`. A `304` comes back as
|
|
188
|
+
* `{ ok: true, status: 304, etag, notModified: true }` with no `data`
|
|
189
|
+
* (`DatasetNotModified`), so keep what you read last time. A `200` with a
|
|
190
|
+
* different ETag is the usual success, with the new `etag`. `ifNoneMatch` with
|
|
191
|
+
* `follow: true` is refused: it is a type error, and `readDataset` throws.
|
|
192
|
+
* Offline answers the same way, from the mock's content.
|
|
129
193
|
*/
|
|
194
|
+
export async function readDataset<T extends Record<string, unknown> = Record<string, unknown>>(
|
|
195
|
+
env: CallServiceEnv,
|
|
196
|
+
entry: string,
|
|
197
|
+
objectType: string,
|
|
198
|
+
options: ReadDatasetConditionalLookupOptions,
|
|
199
|
+
): Promise<DatasetConditionalResult<DatasetObject<T>>>;
|
|
200
|
+
export async function readDataset<T extends Record<string, unknown> = Record<string, unknown>>(
|
|
201
|
+
env: CallServiceEnv,
|
|
202
|
+
entry: string,
|
|
203
|
+
objectType: string,
|
|
204
|
+
options: ReadDatasetConditionalSingletonOptions,
|
|
205
|
+
): Promise<DatasetConditionalResult<DatasetObject<T>>>;
|
|
206
|
+
export async function readDataset<T extends Record<string, unknown> = Record<string, unknown>>(
|
|
207
|
+
env: CallServiceEnv,
|
|
208
|
+
entry: string,
|
|
209
|
+
objectType: string,
|
|
210
|
+
options: ReadDatasetConditionalPageOptions,
|
|
211
|
+
): Promise<DatasetConditionalResult<DatasetPage<T>>>;
|
|
130
212
|
export async function readDataset<T extends Record<string, unknown> = Record<string, unknown>>(
|
|
131
213
|
env: CallServiceEnv,
|
|
132
214
|
entry: string,
|
|
@@ -149,8 +231,8 @@ export async function readDataset<T extends Record<string, unknown> = Record<str
|
|
|
149
231
|
env: CallServiceEnv,
|
|
150
232
|
entry: string,
|
|
151
233
|
objectType: string,
|
|
152
|
-
options:
|
|
153
|
-
): Promise<
|
|
234
|
+
options: AnyReadOptions = {},
|
|
235
|
+
): Promise<DatasetConditionalResult<DatasetPage<T> | DatasetObject<T>>> {
|
|
154
236
|
assertEntryName("readDataset", entry);
|
|
155
237
|
if (objectType === "" || /[/\s?#]/.test(objectType)) {
|
|
156
238
|
throw new Error("readDataset objectType must be one path segment");
|
|
@@ -159,6 +241,10 @@ export async function readDataset<T extends Record<string, unknown> = Record<str
|
|
|
159
241
|
throw new Error("readDataset id must not be empty");
|
|
160
242
|
}
|
|
161
243
|
|
|
244
|
+
// The types refuse this pair. A caller that got past them (JS, a cast) throws.
|
|
245
|
+
if (options.ifNoneMatch !== undefined && (options as { follow?: boolean }).follow === true) {
|
|
246
|
+
throw new Error("readDataset ifNoneMatch does not apply with follow: a walk has one ETag per page");
|
|
247
|
+
}
|
|
162
248
|
if (isPageRequest(options) && options.follow === true) {
|
|
163
249
|
return followPages(env, entry, objectType, options);
|
|
164
250
|
}
|
|
@@ -188,7 +274,7 @@ async function walkPages<T extends Record<string, unknown>>(
|
|
|
188
274
|
options: ReadDatasetPageOptions,
|
|
189
275
|
cursor: string | undefined,
|
|
190
276
|
): Promise<{ outcome: "done"; result: DatasetResult<DatasetPage<T>> } | { outcome: "moved" }> {
|
|
191
|
-
const first = await
|
|
277
|
+
const first = await readPage<T>(env, entry, objectType, pageOptions(options, cursor));
|
|
192
278
|
if (!first.ok) return { outcome: "done", result: first };
|
|
193
279
|
if (!isPage<T>(first.data)) return { outcome: "done", result: { ok: false, status: first.status, error: null } };
|
|
194
280
|
|
|
@@ -202,7 +288,7 @@ async function walkPages<T extends Record<string, unknown>>(
|
|
|
202
288
|
while (next !== null) {
|
|
203
289
|
if (seen.has(next)) return { outcome: "done", result: { ok: false, status: 400, error: null } };
|
|
204
290
|
seen.add(next);
|
|
205
|
-
const page = await
|
|
291
|
+
const page = await readPage<T>(env, entry, objectType, pageOptions(options, next));
|
|
206
292
|
if (!page.ok) return { outcome: "done", result: page };
|
|
207
293
|
if (!isPage<T>(page.data)) return { outcome: "done", result: { ok: false, status: page.status, error: null } };
|
|
208
294
|
if (page.data.snapshot !== snapshot) return { outcome: "moved" };
|
|
@@ -227,19 +313,36 @@ function pageOptions(options: ReadDatasetPageOptions, next: string | undefined):
|
|
|
227
313
|
return { ...rest, next };
|
|
228
314
|
}
|
|
229
315
|
|
|
230
|
-
|
|
316
|
+
/** One page of a walk. A walk never sends `ifNoneMatch`, so it is never `304`. */
|
|
317
|
+
async function readPage<T extends Record<string, unknown>>(
|
|
231
318
|
env: CallServiceEnv,
|
|
232
319
|
entry: string,
|
|
233
320
|
objectType: string,
|
|
234
|
-
options: ReadDatasetPageOptions
|
|
321
|
+
options: ReadDatasetPageOptions,
|
|
235
322
|
): Promise<DatasetResult<DatasetPage<T> | DatasetObject<T>>> {
|
|
323
|
+
const result = await readOnce<T>(env, entry, objectType, options);
|
|
324
|
+
if (result.ok && result.notModified) return { ok: false, status: result.status, error: null };
|
|
325
|
+
return result;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
async function readOnce<T extends Record<string, unknown>>(
|
|
329
|
+
env: CallServiceEnv,
|
|
330
|
+
entry: string,
|
|
331
|
+
objectType: string,
|
|
332
|
+
options: AnyReadOptions,
|
|
333
|
+
): Promise<DatasetConditionalResult<DatasetPage<T> | DatasetObject<T>>> {
|
|
236
334
|
const response = await load(env, entry, objectType, options);
|
|
237
335
|
const error = response.headers.get(PLATFORM_ERROR_HEADER);
|
|
238
336
|
if (error !== null) return { ok: false, status: response.status, error };
|
|
337
|
+
const etag = response.headers.get("etag");
|
|
338
|
+
// Only a conditional read can be answered 304. Without `ifNoneMatch` a 304
|
|
339
|
+
// is not something the platform sends, and stays a failure below.
|
|
340
|
+
if (response.status === 304 && sentIfNoneMatch(options)) {
|
|
341
|
+
return { ok: true, status: 304, etag, notModified: true };
|
|
342
|
+
}
|
|
239
343
|
if (!response.ok) return { ok: false, status: response.status, error: null };
|
|
240
344
|
|
|
241
345
|
const body = (await response.json().catch(() => null)) as unknown;
|
|
242
|
-
const etag = response.headers.get("etag");
|
|
243
346
|
if (isObjectRequest(options)) {
|
|
244
347
|
const data = asObject<T>(body);
|
|
245
348
|
if (!data) return { ok: false, status: response.status, error: null };
|
|
@@ -254,9 +357,10 @@ function load(
|
|
|
254
357
|
env: CallServiceEnv,
|
|
255
358
|
entry: string,
|
|
256
359
|
objectType: string,
|
|
257
|
-
options:
|
|
360
|
+
options: AnyReadOptions,
|
|
258
361
|
): Promise<Response> {
|
|
259
362
|
const search = datasetSearch(options);
|
|
363
|
+
const ifNoneMatch = sentIfNoneMatch(options) ? options.ifNoneMatch : undefined;
|
|
260
364
|
// `import.meta.env.DEV` is false in the production build, so this branch
|
|
261
365
|
// and `dev-read-dataset.ts` are absent from the deployed Worker. Vitest
|
|
262
366
|
// keeps the injected fetch even when a Persona is set.
|
|
@@ -265,10 +369,13 @@ function load(
|
|
|
265
369
|
id: "id" in options ? options.id : undefined,
|
|
266
370
|
search,
|
|
267
371
|
userToken: options.userToken,
|
|
372
|
+
ifNoneMatch,
|
|
268
373
|
}));
|
|
269
374
|
}
|
|
270
375
|
const id = "id" in options ? options.id : undefined;
|
|
271
|
-
|
|
376
|
+
const init: RequestInit = { method: "GET" };
|
|
377
|
+
if (ifNoneMatch !== undefined) init.headers = { "if-none-match": ifNoneMatch };
|
|
378
|
+
return callService(env, entry, datasetPath(objectType, id, search), init, {
|
|
272
379
|
userToken: options.userToken,
|
|
273
380
|
fetchImpl: options.fetchImpl,
|
|
274
381
|
});
|
|
@@ -289,7 +396,7 @@ function datasetPath(
|
|
|
289
396
|
}
|
|
290
397
|
|
|
291
398
|
function datasetSearch(
|
|
292
|
-
options:
|
|
399
|
+
options: AnyReadOptions,
|
|
293
400
|
): [string, string][] {
|
|
294
401
|
const entries: [string, string][] = [];
|
|
295
402
|
const filter = "filter" in options ? options.filter : undefined;
|
|
@@ -315,6 +422,11 @@ function datasetSearch(
|
|
|
315
422
|
return entries;
|
|
316
423
|
}
|
|
317
424
|
|
|
425
|
+
/** True when the caller gave a non-empty `ifNoneMatch`. An empty string sends no header. */
|
|
426
|
+
function sentIfNoneMatch(options: AnyReadOptions): options is AnyReadOptions & { ifNoneMatch: string } {
|
|
427
|
+
return typeof options.ifNoneMatch === "string" && options.ifNoneMatch !== "";
|
|
428
|
+
}
|
|
429
|
+
|
|
318
430
|
function isRange(value: DatasetFilterValue): value is DatasetRange {
|
|
319
431
|
if (typeof value !== "object") return false;
|
|
320
432
|
const keys = Object.keys(value);
|
|
@@ -322,13 +434,13 @@ function isRange(value: DatasetFilterValue): value is DatasetRange {
|
|
|
322
434
|
}
|
|
323
435
|
|
|
324
436
|
function isPageRequest(
|
|
325
|
-
options:
|
|
437
|
+
options: AnyReadOptions,
|
|
326
438
|
): options is ReadDatasetPageOptions {
|
|
327
439
|
return !("id" in options && options.id !== undefined) && options.shape !== "singleton";
|
|
328
440
|
}
|
|
329
441
|
|
|
330
442
|
function isObjectRequest(
|
|
331
|
-
options:
|
|
443
|
+
options: AnyReadOptions,
|
|
332
444
|
): boolean {
|
|
333
445
|
return ("id" in options && options.id !== undefined) || options.shape === "singleton";
|
|
334
446
|
}
|
|
@@ -282,6 +282,76 @@ describe("DEV_REGISTRY_ERROR", () => {
|
|
|
282
282
|
});
|
|
283
283
|
});
|
|
284
284
|
|
|
285
|
+
describe("offline readDataset with ifNoneMatch", () => {
|
|
286
|
+
const queries: { name: string; call: Partial<OfflineDatasetCall> & { objectType: string } }[] = [
|
|
287
|
+
{ name: "a page", call: { objectType: "offices", search: [["sort", "-seats"], ["limit", "2"]] } },
|
|
288
|
+
{ name: "an id lookup", call: { objectType: "offices", id: "branch-b" } },
|
|
289
|
+
{ name: "a singleton", call: { objectType: "summary" } },
|
|
290
|
+
];
|
|
291
|
+
|
|
292
|
+
it.each(queries)("answers 304 for $name when the ETag matches, and 200 when it does not", async ({ call }) => {
|
|
293
|
+
const fresh = await read(call);
|
|
294
|
+
const tag = fresh.headers.get("etag") ?? "";
|
|
295
|
+
expect(tag).toMatch(/^"\d+-\w+"$/);
|
|
296
|
+
|
|
297
|
+
// Stable: the same read gives the same ETag, even with a different write time.
|
|
298
|
+
const again = await read(call, { "/fixtures/overlay/branch-list/mocks/offices.json": "2030-01-01T00:00:00.000Z" });
|
|
299
|
+
expect(again.headers.get("etag")).toBe(tag);
|
|
300
|
+
|
|
301
|
+
const hit = await read({ ...call, ifNoneMatch: tag });
|
|
302
|
+
expect(hit.status).toBe(304);
|
|
303
|
+
expect(hit.headers.get("etag")).toBe(tag);
|
|
304
|
+
expect(hit.headers.get("x-pple-mock")).toBe("branch-list");
|
|
305
|
+
expect(await hit.text()).toBe("");
|
|
306
|
+
|
|
307
|
+
for (const stale of ['"1-stale"', '"0-0"']) {
|
|
308
|
+
const miss = await read({ ...call, ifNoneMatch: stale });
|
|
309
|
+
expect(miss.status).toBe(200);
|
|
310
|
+
expect(miss.headers.get("etag")).toBe(tag);
|
|
311
|
+
}
|
|
312
|
+
// The platform's match rule: a comma list, `W/` and quote marks ignored.
|
|
313
|
+
expect((await read({ ...call, ifNoneMatch: `"1-stale", W/${tag}` })).status).toBe(304);
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
it("gives a page a different ETag for a different query, so one ETag does not cover both", async () => {
|
|
317
|
+
const a = await read({ objectType: "offices", search: [["limit", "1"]] });
|
|
318
|
+
const b = await read({ objectType: "offices", search: [["limit", "2"]] });
|
|
319
|
+
expect(a.headers.get("etag")).not.toBe(b.headers.get("etag"));
|
|
320
|
+
const crossed = await read({ objectType: "offices", search: [["limit", "2"]], ifNoneMatch: a.headers.get("etag") ?? "" });
|
|
321
|
+
expect(crossed.status).toBe(200);
|
|
322
|
+
});
|
|
323
|
+
|
|
324
|
+
it("still refuses before it compares: a current ETag does not hide a refusal", async () => {
|
|
325
|
+
const tag = (await read({ objectType: "offices", id: "branch-b" })).headers.get("etag") ?? "";
|
|
326
|
+
const missing = await read({ objectType: "offices", id: "branch-z", ifNoneMatch: tag });
|
|
327
|
+
expect(missing.status).toBe(404);
|
|
328
|
+
expect(platformError(missing)).toBe("not_found");
|
|
329
|
+
|
|
330
|
+
const invalid = await read({ objectType: "offices", search: [["nope", "1"]], ifNoneMatch: tag });
|
|
331
|
+
expect(invalid.status).toBe(400);
|
|
332
|
+
expect(platformError(invalid)).toBe("invalid_query");
|
|
333
|
+
|
|
334
|
+
const refused = await read({ objectType: "roster", persona: "member", ifNoneMatch: tag });
|
|
335
|
+
expect(refused.status).toBe(403);
|
|
336
|
+
expect(platformError(refused)).toBe("level_not_met");
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
it("changes the ETag when the mock text changes", async () => {
|
|
340
|
+
const before = (await read({ objectType: "summary" })).headers.get("etag");
|
|
341
|
+
const key = Object.keys(overlay).find((file) => file.endsWith("branch-list/mocks/summary.json")) ?? "";
|
|
342
|
+
const edited = { ...overlay, [key]: String(overlay[key]).replace("สรุปสาขา", "สรุปสาขา (แก้ไข)") };
|
|
343
|
+
const after = answerOfflineDataset(edited, writtenAt, {
|
|
344
|
+
overlayRoot: "fixtures/overlay/",
|
|
345
|
+
entry: "branch-list",
|
|
346
|
+
persona: "member",
|
|
347
|
+
objectType: "summary",
|
|
348
|
+
ifNoneMatch: before ?? "",
|
|
349
|
+
});
|
|
350
|
+
expect(after.status).toBe(200);
|
|
351
|
+
expect(after.headers.get("etag")).not.toBe(before);
|
|
352
|
+
});
|
|
353
|
+
});
|
|
354
|
+
|
|
285
355
|
function timeFor(suffix: string): string {
|
|
286
356
|
const key = Object.keys(writtenAt).find((file) => file.includes(suffix));
|
|
287
357
|
const value = key ? writtenAt[key] : undefined;
|
|
@@ -1,9 +1,16 @@
|
|
|
1
1
|
// readDataset (issue #270). The harness is the platform: tests see the URL,
|
|
2
2
|
// the headers, the page, and the refusal a Builder would observe.
|
|
3
3
|
|
|
4
|
-
import { describe, expect, it, vi } from "vitest";
|
|
4
|
+
import { describe, expect, expectTypeOf, it, vi } from "vitest";
|
|
5
5
|
import { platformError } from "../src/call-service";
|
|
6
|
-
import {
|
|
6
|
+
import {
|
|
7
|
+
readDataset,
|
|
8
|
+
type DatasetFailure,
|
|
9
|
+
type DatasetNotModified,
|
|
10
|
+
type DatasetObject,
|
|
11
|
+
type DatasetPage,
|
|
12
|
+
type DatasetSuccess,
|
|
13
|
+
} from "../src/read-dataset";
|
|
7
14
|
import { makeHarness, serviceRefusal } from "./harness";
|
|
8
15
|
|
|
9
16
|
const env = {
|
|
@@ -245,3 +252,136 @@ describe("readDataset", () => {
|
|
|
245
252
|
).rejects.toThrow(/PPLE_SERVICES_URL/);
|
|
246
253
|
});
|
|
247
254
|
});
|
|
255
|
+
|
|
256
|
+
describe("readDataset with ifNoneMatch", () => {
|
|
257
|
+
// The platform answers 304 when the header names the current ETag, and a
|
|
258
|
+
// full 200 when it names a stale one (workers/src/services/dataset-read.ts).
|
|
259
|
+
const platform = (req: Request) =>
|
|
260
|
+
req.headers.get("if-none-match") === '"3-abc"'
|
|
261
|
+
? new Response(null, { status: 304, headers: { etag: '"3-abc"' } })
|
|
262
|
+
: Response.json(
|
|
263
|
+
{ objects: [{ id: "branch-a" }], next: null, sweptAt: SWEPT, snapshot: 4 },
|
|
264
|
+
{ headers: { etag: '"4-abc"' } },
|
|
265
|
+
);
|
|
266
|
+
|
|
267
|
+
it("sends If-None-Match and returns the not-modified result on a live 304", async () => {
|
|
268
|
+
const h = makeHarness({ services: platform }, env);
|
|
269
|
+
|
|
270
|
+
const result = await readDataset(h.testEnv, "branch-list", "offices", {
|
|
271
|
+
ifNoneMatch: '"3-abc"',
|
|
272
|
+
fetchImpl: h.fetchImpl,
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
expect(h.calls.services[0]?.headers["if-none-match"]).toBe('"3-abc"');
|
|
276
|
+
expect(result).toEqual({ ok: true, status: 304, etag: '"3-abc"', notModified: true });
|
|
277
|
+
expect(result).not.toHaveProperty("data");
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
it("returns the new page when the ETag is stale, with the new etag to send next time", async () => {
|
|
281
|
+
const h = makeHarness({ services: platform }, env);
|
|
282
|
+
|
|
283
|
+
const result = await readDataset(h.testEnv, "branch-list", "offices", {
|
|
284
|
+
ifNoneMatch: '"2-abc"',
|
|
285
|
+
fetchImpl: h.fetchImpl,
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
expect(h.calls.services[0]?.headers["if-none-match"]).toBe('"2-abc"');
|
|
289
|
+
expect(result).toEqual({
|
|
290
|
+
ok: true,
|
|
291
|
+
status: 200,
|
|
292
|
+
etag: '"4-abc"',
|
|
293
|
+
data: { objects: [{ id: "branch-a" }], next: null, sweptAt: SWEPT, snapshot: 4 },
|
|
294
|
+
});
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
it("works on a singleton and an id lookup, and sends no header when none is given", async () => {
|
|
298
|
+
const object = (req: Request) =>
|
|
299
|
+
req.headers.get("if-none-match") === '"3-abc"'
|
|
300
|
+
? new Response(null, { status: 304, headers: { etag: '"3-abc"' } })
|
|
301
|
+
: Response.json({ object: { id: "x" }, sweptAt: SWEPT, snapshot: 3 }, { headers: { etag: '"3-abc"' } });
|
|
302
|
+
const h = makeHarness({ services: object }, env);
|
|
303
|
+
|
|
304
|
+
const singleton = await readDataset(h.testEnv, "branch-list", "summary", {
|
|
305
|
+
shape: "singleton",
|
|
306
|
+
ifNoneMatch: '"3-abc"',
|
|
307
|
+
fetchImpl: h.fetchImpl,
|
|
308
|
+
});
|
|
309
|
+
const lookup = await readDataset(h.testEnv, "branch-list", "offices", {
|
|
310
|
+
id: "x",
|
|
311
|
+
ifNoneMatch: '"3-abc"',
|
|
312
|
+
fetchImpl: h.fetchImpl,
|
|
313
|
+
});
|
|
314
|
+
const plain = await readDataset(h.testEnv, "branch-list", "offices", { id: "x", fetchImpl: h.fetchImpl });
|
|
315
|
+
const unset = await readDataset(h.testEnv, "branch-list", "offices", {
|
|
316
|
+
id: "x",
|
|
317
|
+
ifNoneMatch: undefined,
|
|
318
|
+
fetchImpl: h.fetchImpl,
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
expect(singleton).toMatchObject({ ok: true, status: 304, notModified: true });
|
|
322
|
+
expect(lookup).toMatchObject({ ok: true, status: 304, notModified: true });
|
|
323
|
+
expect(plain).toMatchObject({ ok: true, status: 200, data: { object: { id: "x" } } });
|
|
324
|
+
expect(unset).toMatchObject({ ok: true, status: 200 });
|
|
325
|
+
expect(h.calls.services.map((call) => call.headers["if-none-match"])).toEqual([
|
|
326
|
+
'"3-abc"',
|
|
327
|
+
'"3-abc"',
|
|
328
|
+
undefined,
|
|
329
|
+
undefined,
|
|
330
|
+
]);
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
it("still reports a platform refusal as a refusal", async () => {
|
|
334
|
+
const h = makeHarness({ services: () => serviceRefusal("level_not_met", 403) }, env);
|
|
335
|
+
const result = await readDataset(h.testEnv, "branch-list", "offices", {
|
|
336
|
+
ifNoneMatch: '"3-abc"',
|
|
337
|
+
fetchImpl: h.fetchImpl,
|
|
338
|
+
});
|
|
339
|
+
expect(result).toEqual({ ok: false, status: 403, error: "level_not_met" });
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
it("does not take a 304 for success when no ifNoneMatch was sent", async () => {
|
|
343
|
+
const h = makeHarness({ services: () => new Response(null, { status: 304 }) }, env);
|
|
344
|
+
const result = await readDataset(h.testEnv, "branch-list", "offices", { fetchImpl: h.fetchImpl });
|
|
345
|
+
expect(result).toEqual({ ok: false, status: 304, error: null });
|
|
346
|
+
});
|
|
347
|
+
|
|
348
|
+
it("refuses ifNoneMatch together with follow, in the types and at runtime", async () => {
|
|
349
|
+
const fetchImpl = vi.fn<typeof fetch>(async () => new Response(null, { status: 304 }));
|
|
350
|
+
await expect(
|
|
351
|
+
readDataset(env, "branch-list", "offices", {
|
|
352
|
+
follow: true,
|
|
353
|
+
// @ts-expect-error a walk has one ETag per page
|
|
354
|
+
ifNoneMatch: '"3-abc"',
|
|
355
|
+
fetchImpl,
|
|
356
|
+
}),
|
|
357
|
+
).rejects.toThrow(/ifNoneMatch does not apply with follow/);
|
|
358
|
+
expect(fetchImpl).not.toHaveBeenCalled();
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
it("narrows the not-modified result apart from data and from a refusal", async () => {
|
|
362
|
+
// Types only: nothing here is awaited, so no request is made.
|
|
363
|
+
const probe = async () => {
|
|
364
|
+
const page = await readDataset(env, "branch-list", "offices", { ifNoneMatch: "e", limit: 1 });
|
|
365
|
+
const one = await readDataset(env, "branch-list", "offices", { id: "x", ifNoneMatch: "e" });
|
|
366
|
+
const single = await readDataset(env, "branch-list", "summary", { shape: "singleton", ifNoneMatch: "e" });
|
|
367
|
+
|
|
368
|
+
if (!page.ok) {
|
|
369
|
+
expectTypeOf(page).toEqualTypeOf<DatasetFailure>();
|
|
370
|
+
} else if (page.notModified) {
|
|
371
|
+
expectTypeOf(page).toEqualTypeOf<DatasetNotModified>();
|
|
372
|
+
// @ts-expect-error a not-modified result has no data
|
|
373
|
+
page.data;
|
|
374
|
+
} else {
|
|
375
|
+
expectTypeOf(page).toEqualTypeOf<DatasetSuccess<DatasetPage>>();
|
|
376
|
+
expectTypeOf(page.data.objects).toEqualTypeOf<Record<string, unknown>[]>();
|
|
377
|
+
}
|
|
378
|
+
if (one.ok && !one.notModified) expectTypeOf(one.data).toEqualTypeOf<DatasetObject>();
|
|
379
|
+
if (single.ok && single.notModified) expectTypeOf(single.status).toEqualTypeOf<304>();
|
|
380
|
+
|
|
381
|
+
// Without ifNoneMatch there is nothing to narrow: `data` is always there on success.
|
|
382
|
+
const plain = await readDataset(env, "branch-list", "offices", { limit: 1 });
|
|
383
|
+
if (plain.ok) expectTypeOf(plain.data).toEqualTypeOf<DatasetPage>();
|
|
384
|
+
};
|
|
385
|
+
expectTypeOf(probe).toBeFunction();
|
|
386
|
+
});
|
|
387
|
+
});
|