@ahoo-wang/wow-client 10.0.0-alpha.6 → 10.0.0-beta.1
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/README.md +77 -23
- package/README.zh-CN.md +67 -19
- package/dist/commands.cjs +1 -1
- package/dist/commands.cjs.map +1 -1
- package/dist/commands.d.cts +134 -61
- package/dist/commands.d.ts +134 -61
- package/dist/commands.es.js +129 -59
- package/dist/commands.es.js.map +1 -1
- package/dist/developmentCaller.cjs +2 -0
- package/dist/developmentCaller.cjs.map +1 -0
- package/dist/developmentCaller.d.cts +61 -0
- package/dist/developmentCaller.d.ts +61 -0
- package/dist/developmentCaller.es.js +26 -0
- package/dist/developmentCaller.es.js.map +1 -0
- package/dist/dsl/aggregation/admit.cjs +1 -1
- package/dist/dsl/aggregation/admit.cjs.map +1 -1
- package/dist/dsl/aggregation/admit.es.js +93 -93
- package/dist/dsl/aggregation/admit.es.js.map +1 -1
- package/dist/dsl/aggregation/builders.cjs +1 -1
- package/dist/dsl/aggregation/builders.cjs.map +1 -1
- package/dist/dsl/aggregation/builders.d.cts +20 -20
- package/dist/dsl/aggregation/builders.d.ts +20 -20
- package/dist/dsl/aggregation/builders.es.js +88 -88
- package/dist/dsl/aggregation/builders.es.js.map +1 -1
- package/dist/dsl/aggregation/derived.cjs.map +1 -1
- package/dist/dsl/aggregation/derived.d.cts +8 -8
- package/dist/dsl/aggregation/derived.d.ts +8 -8
- package/dist/dsl/aggregation/derived.es.js +1 -2
- package/dist/dsl/aggregation/derived.es.js.map +1 -1
- package/dist/dsl/aggregation/expressionTrees.cjs.map +1 -1
- package/dist/dsl/aggregation/expressionTrees.es.js +1 -2
- package/dist/dsl/aggregation/having.cjs +1 -1
- package/dist/dsl/aggregation/having.cjs.map +1 -1
- package/dist/dsl/aggregation/having.d.cts +12 -12
- package/dist/dsl/aggregation/having.d.ts +12 -12
- package/dist/dsl/aggregation/having.es.js +33 -33
- package/dist/dsl/aggregation/having.es.js.map +1 -1
- package/dist/dsl/aggregation/sort.cjs.map +1 -1
- package/dist/dsl/aggregation/sort.es.js +1 -2
- package/dist/dsl/aggregation/types.cjs +1 -1
- package/dist/dsl/aggregation/types.cjs.map +1 -1
- package/dist/dsl/aggregation/types.d.cts +69 -69
- package/dist/dsl/aggregation/types.d.ts +69 -69
- package/dist/dsl/aggregation/types.es.js +15 -16
- package/dist/dsl/aggregation/types.es.js.map +1 -1
- package/dist/dsl/constantName.cjs +2 -0
- package/dist/dsl/constantName.cjs.map +1 -0
- package/dist/dsl/constantName.d.cts +9 -0
- package/dist/dsl/constantName.d.ts +9 -0
- package/dist/dsl/constantName.es.js +7 -0
- package/dist/dsl/constantName.es.js.map +1 -0
- package/dist/dsl/cursorQuery.cjs.map +1 -1
- package/dist/dsl/cursorQuery.es.js +1 -2
- package/dist/dsl/deletionState.cjs +1 -1
- package/dist/dsl/deletionState.cjs.map +1 -1
- package/dist/dsl/deletionState.d.cts +3 -3
- package/dist/dsl/deletionState.d.ts +3 -3
- package/dist/dsl/deletionState.es.js +2 -3
- package/dist/dsl/deletionState.es.js.map +1 -1
- package/dist/dsl/descriptor.cjs +1 -1
- package/dist/dsl/descriptor.cjs.map +1 -1
- package/dist/dsl/descriptor.d.cts +99 -42
- package/dist/dsl/descriptor.d.ts +99 -42
- package/dist/dsl/descriptor.es.js +37 -29
- package/dist/dsl/descriptor.es.js.map +1 -1
- package/dist/dsl/field.cjs.map +1 -1
- package/dist/dsl/field.es.js +1 -2
- package/dist/dsl/filter/builders.cjs +1 -1
- package/dist/dsl/filter/builders.cjs.map +1 -1
- package/dist/dsl/filter/builders.d.cts +53 -53
- package/dist/dsl/filter/builders.d.ts +53 -53
- package/dist/dsl/filter/builders.es.js +111 -111
- package/dist/dsl/filter/builders.es.js.map +1 -1
- package/dist/dsl/filter/datePattern.cjs.map +1 -1
- package/dist/dsl/filter/datePattern.es.js +1 -2
- package/dist/dsl/filter/operator.cjs +1 -1
- package/dist/dsl/filter/operator.cjs.map +1 -1
- package/dist/dsl/filter/operator.d.cts +57 -57
- package/dist/dsl/filter/operator.d.ts +57 -57
- package/dist/dsl/filter/operator.es.js +4 -5
- package/dist/dsl/filter/operator.es.js.map +1 -1
- package/dist/dsl/filter/scope.cjs +1 -1
- package/dist/dsl/filter/scope.cjs.map +1 -1
- package/dist/dsl/filter/scope.es.js +12 -12
- package/dist/dsl/filter/scope.es.js.map +1 -1
- package/dist/dsl/filter/validate.cjs +1 -1
- package/dist/dsl/filter/validate.cjs.map +1 -1
- package/dist/dsl/filter/validate.es.js +23 -23
- package/dist/dsl/filter/validate.es.js.map +1 -1
- package/dist/dsl/pagination.cjs.map +1 -1
- package/dist/dsl/pagination.es.js +1 -2
- package/dist/dsl/projection.cjs.map +1 -1
- package/dist/dsl/projection.d.cts +1 -1
- package/dist/dsl/projection.d.ts +1 -1
- package/dist/dsl/projection.es.js +1 -2
- package/dist/dsl/projection.es.js.map +1 -1
- package/dist/dsl/queryErrorCodes.cjs +1 -1
- package/dist/dsl/queryErrorCodes.cjs.map +1 -1
- package/dist/dsl/queryErrorCodes.d.cts +59 -48
- package/dist/dsl/queryErrorCodes.d.ts +59 -48
- package/dist/dsl/queryErrorCodes.es.js +51 -50
- package/dist/dsl/queryErrorCodes.es.js.map +1 -1
- package/dist/dsl/queryable.cjs +1 -1
- package/dist/dsl/queryable.cjs.map +1 -1
- package/dist/dsl/queryable.d.cts +25 -21
- package/dist/dsl/queryable.d.ts +25 -21
- package/dist/dsl/queryable.es.js +5 -5
- package/dist/dsl/queryable.es.js.map +1 -1
- package/dist/dsl/sort.cjs +1 -1
- package/dist/dsl/sort.cjs.map +1 -1
- package/dist/dsl/sort.d.cts +2 -2
- package/dist/dsl/sort.d.ts +2 -2
- package/dist/dsl/sort.es.js +4 -5
- package/dist/dsl/sort.es.js.map +1 -1
- package/dist/dsl.cjs +1 -1
- package/dist/dsl.es.js +3 -3
- package/dist/exactJson.cjs.map +1 -1
- package/dist/exactJson.d.cts +4 -4
- package/dist/exactJson.d.ts +4 -4
- package/dist/exactJson.es.js +1 -2
- package/dist/exactJson.es.js.map +1 -1
- package/dist/frameworkErrors.cjs +2 -0
- package/dist/frameworkErrors.cjs.map +1 -0
- package/dist/frameworkErrors.d.cts +121 -0
- package/dist/frameworkErrors.d.ts +121 -0
- package/dist/frameworkErrors.es.js +95 -0
- package/dist/frameworkErrors.es.js.map +1 -0
- package/dist/http.cjs +1 -1
- package/dist/http.cjs.map +1 -1
- package/dist/http.d.cts +4 -7
- package/dist/http.d.ts +4 -7
- package/dist/http.es.js +12 -20
- package/dist/http.es.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +9 -7
- package/dist/index.d.ts +9 -7
- package/dist/index.es.js +11 -9
- package/dist/manifest.cjs +1 -1
- package/dist/manifest.cjs.map +1 -1
- package/dist/manifest.d.cts +37 -95
- package/dist/manifest.d.ts +37 -95
- package/dist/manifest.es.js +12 -7
- package/dist/manifest.es.js.map +1 -1
- package/dist/manifestTypes.d.cts +195 -0
- package/dist/manifestTypes.d.ts +195 -0
- package/dist/problem.cjs +1 -1
- package/dist/problem.cjs.map +1 -1
- package/dist/problem.d.cts +76 -115
- package/dist/problem.d.ts +76 -115
- package/dist/problem.es.js +45 -80
- package/dist/problem.es.js.map +1 -1
- package/dist/queries.cjs +1 -1
- package/dist/queries.cjs.map +1 -1
- package/dist/queries.d.cts +28 -51
- package/dist/queries.d.ts +28 -51
- package/dist/queries.es.js +49 -40
- package/dist/queries.es.js.map +1 -1
- package/dist/routes.cjs +2 -0
- package/dist/routes.cjs.map +1 -0
- package/dist/routes.d.cts +49 -0
- package/dist/routes.d.ts +49 -0
- package/dist/routes.es.js +33 -0
- package/dist/routes.es.js.map +1 -0
- package/dist/state.cjs +1 -1
- package/dist/state.cjs.map +1 -1
- package/dist/state.d.cts +56 -11
- package/dist/state.d.ts +56 -11
- package/dist/state.es.js +56 -21
- package/dist/state.es.js.map +1 -1
- package/dist/streams.cjs +1 -1
- package/dist/streams.cjs.map +1 -1
- package/dist/streams.d.cts +17 -13
- package/dist/streams.d.ts +17 -13
- package/dist/streams.es.js +50 -50
- package/dist/streams.es.js.map +1 -1
- package/dist/testing/wire.cjs +2 -0
- package/dist/testing/wire.cjs.map +1 -0
- package/dist/testing/wire.d.cts +29 -0
- package/dist/testing/wire.d.ts +29 -0
- package/dist/testing/wire.es.js +88 -0
- package/dist/testing/wire.es.js.map +1 -0
- package/dist/testing.cjs +1 -0
- package/dist/testing.d.cts +12 -0
- package/dist/testing.d.ts +12 -0
- package/dist/testing.es.js +3 -0
- package/dist/wait.cjs +1 -1
- package/dist/wait.cjs.map +1 -1
- package/dist/wait.d.cts +68 -19
- package/dist/wait.d.ts +68 -19
- package/dist/wait.es.js +61 -14
- package/dist/wait.es.js.map +1 -1
- package/dist/wire.cjs +1 -1
- package/dist/wire.cjs.map +1 -1
- package/dist/wire.d.cts +101 -50
- package/dist/wire.d.ts +101 -50
- package/dist/wire.es.js +17 -6
- package/dist/wire.es.js.map +1 -1
- package/package.json +23 -3
package/dist/state.es.js
CHANGED
|
@@ -1,25 +1,39 @@
|
|
|
1
1
|
import { eventNumbers as e } from "./exactJson.es.js";
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
import { FrameworkErrorCodes as t } from "./frameworkErrors.es.js";
|
|
3
|
+
import { WowProblemError as n } from "./problem.es.js";
|
|
4
|
+
import { WowHeaders as r, entityTag as i, json as a, send as o } from "./http.es.js";
|
|
5
|
+
// src/state.ts
|
|
6
|
+
var s = class {
|
|
5
7
|
constructor(e, t = {}) {
|
|
6
8
|
this.type = e, this.client = t;
|
|
7
9
|
}
|
|
8
|
-
|
|
9
|
-
|
|
10
|
+
read(e, t = {}) {
|
|
11
|
+
return this.readAt(e, t);
|
|
12
|
+
}
|
|
13
|
+
get(e, t = {}) {
|
|
14
|
+
return this.getAt(e, t);
|
|
15
|
+
}
|
|
16
|
+
find(e, t = {}) {
|
|
17
|
+
return this.findAt(e, t);
|
|
18
|
+
}
|
|
19
|
+
trace(e, t = {}) {
|
|
20
|
+
return this.traceAt(e, t);
|
|
21
|
+
}
|
|
22
|
+
async readAt(e, t) {
|
|
23
|
+
let n = t.at instanceof Date ? t.at.toISOString() : t.at, s = await o(this.client, {
|
|
10
24
|
method: "GET",
|
|
11
25
|
path: this.statePath(e),
|
|
12
26
|
query: {
|
|
13
|
-
version:
|
|
14
|
-
at:
|
|
15
|
-
minVersion:
|
|
27
|
+
version: t.version,
|
|
28
|
+
at: n,
|
|
29
|
+
minVersion: t.minVersion
|
|
16
30
|
},
|
|
17
|
-
headers: { [
|
|
18
|
-
options:
|
|
31
|
+
headers: { [r.IF_NONE_MATCH]: t.ifNoneMatch === void 0 ? void 0 : `"${t.ifNoneMatch}"` },
|
|
32
|
+
options: t,
|
|
19
33
|
notModified: !0
|
|
20
34
|
});
|
|
21
35
|
if (s.status === 304) {
|
|
22
|
-
let e =
|
|
36
|
+
let e = i(s) ?? t.ifNoneMatch ?? "";
|
|
23
37
|
return {
|
|
24
38
|
notModified: !0,
|
|
25
39
|
version: Number.parseInt(e, 10),
|
|
@@ -28,17 +42,25 @@ var a = class {
|
|
|
28
42
|
}
|
|
29
43
|
return {
|
|
30
44
|
notModified: !1,
|
|
31
|
-
|
|
32
|
-
etag:
|
|
45
|
+
snapshot: await a(s, this.stateNumbers),
|
|
46
|
+
etag: i(s)
|
|
33
47
|
};
|
|
34
48
|
}
|
|
35
|
-
async
|
|
36
|
-
let n = await this.
|
|
49
|
+
async getAt(e, t) {
|
|
50
|
+
let n = await this.readAt(e, t);
|
|
37
51
|
if (n.notModified) throw Error("A read without If-None-Match was answered 304.");
|
|
38
|
-
return n.
|
|
52
|
+
return n.snapshot;
|
|
53
|
+
}
|
|
54
|
+
async findAt(e, r) {
|
|
55
|
+
try {
|
|
56
|
+
return await this.getAt(e, r);
|
|
57
|
+
} catch (e) {
|
|
58
|
+
if (e instanceof n && e.status === 404 && e.code === t.AGGREGATE_NOT_FOUND) return;
|
|
59
|
+
throw e;
|
|
60
|
+
}
|
|
39
61
|
}
|
|
40
|
-
async
|
|
41
|
-
return
|
|
62
|
+
async traceAt(e, t) {
|
|
63
|
+
return a(await o(this.client, {
|
|
42
64
|
method: "GET",
|
|
43
65
|
path: `${this.statePath(e)}/trace`,
|
|
44
66
|
query: {
|
|
@@ -61,10 +83,23 @@ var a = class {
|
|
|
61
83
|
} } };
|
|
62
84
|
}
|
|
63
85
|
statePath(e) {
|
|
64
|
-
|
|
86
|
+
let t = `/${this.type.context}/${this.type.name}`;
|
|
87
|
+
return e === void 0 ? `${t}/state` : `${t}/${encodeURIComponent(e)}/state`;
|
|
88
|
+
}
|
|
89
|
+
}, c = class extends s {
|
|
90
|
+
readOwn(e = {}) {
|
|
91
|
+
return this.readAt(void 0, e);
|
|
92
|
+
}
|
|
93
|
+
getOwn(e = {}) {
|
|
94
|
+
return this.getAt(void 0, e);
|
|
95
|
+
}
|
|
96
|
+
findOwn(e = {}) {
|
|
97
|
+
return this.findAt(void 0, e);
|
|
98
|
+
}
|
|
99
|
+
traceOwn(e = {}) {
|
|
100
|
+
return this.traceAt(void 0, e);
|
|
65
101
|
}
|
|
66
102
|
};
|
|
67
|
-
|
|
68
|
-
export { a as StateClient };
|
|
103
|
+
export { c as OwnStateClient, s as StateClient };
|
|
69
104
|
|
|
70
105
|
//# sourceMappingURL=state.es.js.map
|
package/dist/state.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state.es.js","names":["StateClient","type","client","at","options","response","send","id","WowHeaders","etag","entityTag","json","result","state","events","eventNumbers"],"sources":["../src/state.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n entityTag,\n json,\n type RequestOptions,\n send,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport { eventNumbers, type TextNumbers } from './exactJson.js';\nimport type {\n AggregateType,\n EventView,\n StateTrace,\n StateView,\n} from './wire.js';\n\n/** Which state a read asks for: the latest, at a version or as of a time. */\nexport interface StateReadOptions extends RequestOptions {\n /** The committed state at this version. */\n readonly version?: number;\n /** The committed state as of this instant (ISO-8601, or a `Date`). */\n readonly at?: string | Date;\n /**\n * The latest state at this version or later (review R4-Q, Q-13: read your\n * writes), such as the `version` of a command's result: a lagging snapshot is\n * caught up with the log. Not with `version` or `at`. One not reached within\n * the server's wait rejects with 409 `wow.query.min-version-not-reached`,\n * whose `version` is the current one.\n */\n readonly minVersion?: number;\n /**\n * The entity tag of the state already held, as a read answered it\n * (`etag`): a 304 then answers `notModified`. The tag is the version and a\n * digest of the body (`3-<digest>`), so it changes whenever what is read\n * does, not only with the version.\n */\n readonly ifNoneMatch?: string;\n}\n\n/**\n * A state read: the view and its entity tag, or `notModified` when the state\n * held is current, with its tag and the version the tag names.\n */\nexport type StateReadResult<S> =\n | {\n readonly notModified: false;\n readonly view: StateView<S>;\n readonly etag?: string;\n }\n | {\n readonly notModified: true;\n readonly version: number;\n readonly etag: string;\n };\n\n/** Which commits a trace reads (decision D40). */\nexport interface StateTraceOptions extends RequestOptions {\n /** The first version; 1 when absent. */\n readonly from?: number;\n /** The last version; the latest when absent. */\n readonly to?: number;\n /** The most commits, at most 1000; 100 when absent. */\n readonly limit?: number;\n}\n\n/**\n * Reads an aggregate type's states (decisions D40, D112):\n * `GET /{context}/{aggregate}/{id}/state` with `?version=`, `?at=` or `?minVersion=`, and\n * its trace, `…/state/trace`. A state that does not exist rejects with 404\n * `wow.aggregate.not-found`.\n *\n * @typeParam S - The state's type.\n * @typeParam E - The events' type of a trace.\n */\nexport class StateClient<S = unknown, E extends EventView = EventView> {\n /**\n * @param type - The aggregate type\n * @param client - How the service is reached\n */\n constructor(\n readonly type: AggregateType,\n readonly client: WowClientOptions = {},\n ) {}\n\n /** The state the options ask for. */\n async read(\n id: string,\n options: StateReadOptions = {},\n ): Promise<StateReadResult<S>> {\n const at =\n options.at instanceof Date ? options.at.toISOString() : options.at;\n const response = await send(this.client, {\n method: 'GET',\n path: this.statePath(id),\n query: { version: options.version, at, minVersion: options.minVersion },\n headers: {\n [WowHeaders.IF_NONE_MATCH]:\n options.ifNoneMatch === undefined\n ? undefined\n : `\"${options.ifNoneMatch}\"`,\n },\n options,\n notModified: true,\n });\n if (response.status === 304) {\n const etag = entityTag(response) ?? options.ifNoneMatch ?? '';\n return {\n notModified: true,\n version: Number.parseInt(etag, 10),\n etag,\n };\n }\n return {\n notModified: false,\n view: await json<StateView<S>>(response, this.stateNumbers),\n etag: entityTag(response),\n };\n }\n\n /** The latest state, or the one the options ask for, without a cache. */\n async get(\n id: string,\n options: Omit<StateReadOptions, 'ifNoneMatch'> = {},\n ): Promise<StateView<S>> {\n const result = await this.read(id, options);\n if (result.notModified) {\n throw new Error('A read without If-None-Match was answered 304.');\n }\n return result.view;\n }\n\n /** The commits from `from` to `to`, each with its events and the state after it. */\n async trace(\n id: string,\n options: StateTraceOptions = {},\n ): Promise<StateTrace<S, E>> {\n return json<StateTrace<S, E>>(\n await send(this.client, {\n method: 'GET',\n path: `${this.statePath(id)}/trace`,\n query: { from: options.from, to: options.to, limit: options.limit },\n options,\n }),\n this.traceNumbers,\n );\n }\n\n /** The exact numbers of a state view: its state's. */\n private get stateNumbers(): TextNumbers | undefined {\n const state = this.type.textNumbers?.state;\n return state === undefined ? undefined : { state };\n }\n\n /** The exact numbers of a trace: each commit's state and events. */\n private get traceNumbers(): TextNumbers | undefined {\n const state = this.type.textNumbers?.state;\n const events = eventNumbers(this.type);\n if (state === undefined && events === undefined) return undefined;\n return {\n commits: {\n '*': {\n ...(state === undefined ? {} : { state }),\n ...(events === undefined ? {} : { events: { '*': events } }),\n },\n },\n };\n }\n\n private statePath(id: string): string {\n return `/${this.type.context}/${this.type.name}/${encodeURIComponent(id)}/state`;\n }\n}\n"],"mappings":";;;AAuFA,IAAaA,IAAb,MAAuE;CAKrE,YACE,GACA,IAAoC,CAAC,GACrC;EADS,AADA,KAAA,OAAAC,GACA,KAAA,SAAAC;CACR;CAGH,MAAM,KACJ,GACA,IAA4B,CAAC,GACA;EAC7B,IAAMC,IACJC,EAAQ,cAAc,OAAOA,EAAQ,GAAG,YAAY,IAAIA,EAAQ,IAC5DC,IAAW,MAAMC,EAAK,KAAK,QAAQ;GACvC,QAAQ;GACR,MAAM,KAAK,UAAUC,CAAE;GACvB,OAAO;IAAE,SAASH,EAAQ;IAAS;IAAI,YAAYA,EAAQ;GAAW;GACtE,SAAS,GACNI,EAAW,gBACVJ,EAAQ,gBAAgB,KAAA,IACpB,KAAA,IACA,IAAIA,EAAQ,YAAY,GAChC;GACA;GACA,aAAa;EACf,CAAC;EACD,IAAIC,EAAS,WAAW,KAAK;GAC3B,IAAMI,IAAOC,EAAUL,CAAQ,KAAKD,EAAQ,eAAe;GAC3D,OAAO;IACL,aAAa;IACb,SAAS,OAAO,SAASK,GAAM,EAAE;IACjC;GACF;EACF;EACA,OAAO;GACL,aAAa;GACb,MAAM,MAAME,EAAmBN,GAAU,KAAK,YAAY;GAC1D,MAAMK,EAAUL,CAAQ;EAC1B;CACF;CAGA,MAAM,IACJ,GACA,IAAiD,CAAC,GAC3B;EACvB,IAAMO,IAAS,MAAM,KAAK,KAAKL,GAAIH,CAAO;EAC1C,IAAIQ,EAAO,aACT,MAAU,MAAM,gDAAgD;EAElE,OAAOA,EAAO;CAChB;CAGA,MAAM,MACJ,GACA,IAA6B,CAAC,GACH;EAC3B,OAAOD,EACL,MAAML,EAAK,KAAK,QAAQ;GACtB,QAAQ;GACR,MAAM,GAAG,KAAK,UAAUC,CAAE,EAAE;GAC5B,OAAO;IAAE,MAAMH,EAAQ;IAAM,IAAIA,EAAQ;IAAI,OAAOA,EAAQ;GAAM;GAClE;EACF,CAAC,GACD,KAAK,YACP;CACF;CAGA,IAAY,eAAwC;EAClD,IAAMS,IAAQ,KAAK,KAAK,aAAa;EACrC,OAAOA,MAAU,KAAA,IAAY,KAAA,IAAY,EAAE,SAAM;CACnD;CAGA,IAAY,eAAwC;EAClD,IAAMA,IAAQ,KAAK,KAAK,aAAa,OAC/BC,IAASC,EAAa,KAAK,IAAI;EACrC,IAAIF,MAAU,KAAA,KAAaC,MAAW,KAAA,GACtC,OAAO,EACL,SAAS,EACP,KAAK;GACH,GAAID,MAAU,KAAA,IAAY,CAAC,IAAI,EAAE,SAAM;GACvC,GAAIC,MAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAKA,EAAO,EAAE;EAC5D,EACF,EACF;CACF;CAEA,UAAkB,GAAoB;EACpC,OAAO,IAAI,KAAK,KAAK,QAAQ,GAAG,KAAK,KAAK,KAAK,GAAG,mBAAmBP,CAAE,EAAE;CAC3E;AACF"}
|
|
1
|
+
{"version":3,"file":"state.es.js","names":["StateClient","type","client","id","options","at","response","send","WowHeaders","etag","entityTag","json","result","error","WowProblemError","FrameworkErrorCodes","state","events","eventNumbers","base","OwnStateClient"],"sources":["../src/state.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n entityTag,\n json,\n type RequestOptions,\n send,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport { eventNumbers, type TextNumbers } from './exactJson.js';\nimport { FrameworkErrorCodes, WowProblemError } from './problem.js';\nimport type {\n AggregateType,\n CommittedEvent,\n StateTrace,\n Snapshot,\n} from './wire.js';\n\n/** Which state a read asks for: the latest, at a version or as of a time. */\nexport interface StateReadOptions extends RequestOptions {\n /** The committed state at this version. */\n readonly version?: number;\n /** The committed state as of this instant (ISO-8601, or a `Date`). */\n readonly at?: string | Date;\n /**\n * The latest state at this version or later (review R4-Q, Q-13: read your\n * writes), such as the `version` of a command's result: a lagging snapshot is\n * caught up with the log. Not with `version` or `at`. One not reached within\n * the server's wait rejects with 409 `wow.query.min-version-not-reached`,\n * whose `version` is the current one.\n */\n readonly minVersion?: number;\n /**\n * The entity tag of the state already held, as a read answered it\n * (`etag`): a 304 then answers `notModified`. The tag is the version and a\n * digest of the body (`3-<digest>`), so it changes whenever what is read\n * does, not only with the version.\n */\n readonly ifNoneMatch?: string;\n}\n\n/**\n * A state read: the snapshot and its entity tag, or `notModified` when the\n * state held is current, with its tag and the version the tag names.\n */\nexport type StateReadResult<S> =\n | {\n readonly notModified: false;\n readonly snapshot: Snapshot<S>;\n readonly etag?: string;\n }\n | {\n readonly notModified: true;\n readonly version: number;\n readonly etag: string;\n };\n\n/** Which commits a trace reads. */\nexport interface StateTraceOptions extends RequestOptions {\n /** The first version; 1 when absent. */\n readonly from?: number;\n /** The last version; the latest when absent. */\n readonly to?: number;\n /** The most commits, at most 1000; 100 when absent. */\n readonly limit?: number;\n}\n\n/**\n * Reads an aggregate type's states:\n * `GET /{context}/{aggregate}/{id}/state` with `?version=`, `?at=` or `?minVersion=`, and\n * its trace, `…/state/trace`; {@link OwnStateClient} reads the caller's own\n * of a type whose id is its owner's. A state that does not exist rejects with 404\n * `wow.aggregate.not-found`, except through {@link StateClient.find}, which\n * answers `undefined`.\n *\n * @typeParam S - The state's type.\n * @typeParam E - The events' type of a trace.\n */\nexport class StateClient<\n S = unknown,\n E extends CommittedEvent = CommittedEvent,\n> {\n /**\n * @param type - The aggregate type\n * @param client - How the service is reached\n */\n constructor(\n readonly type: AggregateType,\n readonly client: WowClientOptions = {},\n ) {}\n\n /** The state the options ask for. */\n read(\n id: string,\n options: StateReadOptions = {},\n ): Promise<StateReadResult<S>> {\n return this.readAt(id, options);\n }\n\n /** The latest state, or the one the options ask for, without a cache. */\n get(\n id: string,\n options: Omit<StateReadOptions, 'ifNoneMatch'> = {},\n ): Promise<Snapshot<S>> {\n return this.getAt(id, options);\n }\n\n /**\n * The latest state, or the one the options ask for, or `undefined` when the\n * aggregate does not exist (404 `wow.aggregate.not-found`), as Kotlin's\n * `SnapshotQueries.state` answers null. Any other 404, such as a route that\n * does not exist, rejects.\n */\n find(\n id: string,\n options: Omit<StateReadOptions, 'ifNoneMatch'> = {},\n ): Promise<Snapshot<S> | undefined> {\n return this.findAt(id, options);\n }\n\n /** The commits from `from` to `to`, each with its events and the state after it. */\n trace(\n id: string,\n options: StateTraceOptions = {},\n ): Promise<StateTrace<S, E>> {\n return this.traceAt(id, options);\n }\n\n /**\n * {@link StateClient.read} of the aggregate `id`, or by no id of the\n * caller's own ({@link OwnStateClient}).\n */\n protected async readAt(\n id: string | undefined,\n options: StateReadOptions,\n ): Promise<StateReadResult<S>> {\n const at =\n options.at instanceof Date ? options.at.toISOString() : options.at;\n const response = await send(this.client, {\n method: 'GET',\n path: this.statePath(id),\n query: { version: options.version, at, minVersion: options.minVersion },\n headers: {\n [WowHeaders.IF_NONE_MATCH]:\n options.ifNoneMatch === undefined\n ? undefined\n : `\"${options.ifNoneMatch}\"`,\n },\n options,\n notModified: true,\n });\n if (response.status === 304) {\n const etag = entityTag(response) ?? options.ifNoneMatch ?? '';\n return {\n notModified: true,\n version: Number.parseInt(etag, 10),\n etag,\n };\n }\n return {\n notModified: false,\n snapshot: await json<Snapshot<S>>(response, this.stateNumbers),\n etag: entityTag(response),\n };\n }\n\n /** {@link StateClient.get} of the aggregate `id`, or of the caller's own. */\n protected async getAt(\n id: string | undefined,\n options: Omit<StateReadOptions, 'ifNoneMatch'>,\n ): Promise<Snapshot<S>> {\n const result = await this.readAt(id, options);\n if (result.notModified) {\n throw new Error('A read without If-None-Match was answered 304.');\n }\n return result.snapshot;\n }\n\n /** {@link StateClient.find} of the aggregate `id`, or of the caller's own. */\n protected async findAt(\n id: string | undefined,\n options: Omit<StateReadOptions, 'ifNoneMatch'>,\n ): Promise<Snapshot<S> | undefined> {\n try {\n return await this.getAt(id, options);\n } catch (error) {\n if (\n error instanceof WowProblemError &&\n error.status === 404 &&\n error.code === FrameworkErrorCodes.AGGREGATE_NOT_FOUND\n ) {\n return undefined;\n }\n throw error;\n }\n }\n\n /** {@link StateClient.trace} of the aggregate `id`, or of the caller's own. */\n protected async traceAt(\n id: string | undefined,\n options: StateTraceOptions,\n ): Promise<StateTrace<S, E>> {\n return json<StateTrace<S, E>>(\n await send(this.client, {\n method: 'GET',\n path: `${this.statePath(id)}/trace`,\n query: { from: options.from, to: options.to, limit: options.limit },\n options,\n }),\n this.traceNumbers,\n );\n }\n\n /** The exact numbers of a state read: its state's. */\n private get stateNumbers(): TextNumbers | undefined {\n const state = this.type.textNumbers?.state;\n return state === undefined ? undefined : { state };\n }\n\n /** The exact numbers of a trace: each commit's state and events. */\n private get traceNumbers(): TextNumbers | undefined {\n const state = this.type.textNumbers?.state;\n const events = eventNumbers(this.type);\n if (state === undefined && events === undefined) return undefined;\n return {\n commits: {\n '*': {\n ...(state === undefined ? {} : { state }),\n ...(events === undefined ? {} : { events: { '*': events } }),\n },\n },\n };\n }\n\n private statePath(id: string | undefined): string {\n const base = `/${this.type.context}/${this.type.name}`;\n return id === undefined\n ? `${base}/state`\n : `${base}/${encodeURIComponent(id)}/state`;\n }\n}\n\n/**\n * Reads the states of an aggregate type whose id is its owner's\n * (`@AggregateRoot(idSource = OWNER)`, the Manifest's `idSource: \"owner\"`):\n * by id as {@link StateClient} does, for a caller with no owner, and the\n * caller's own by no id, `GET /{context}/{aggregate}/state` and\n * `…/state/trace`, its id the owner the caller reads as. An unauthenticated\n * caller is refused with 401 `wow.auth.unauthenticated`, one with no owner\n * with 400 `wow.query.malformed`.\n *\n * @typeParam S - The state's type.\n * @typeParam E - The events' type of a trace.\n */\nexport class OwnStateClient<\n S = unknown,\n E extends CommittedEvent = CommittedEvent,\n> extends StateClient<S, E> {\n /** {@link StateClient.read} of the caller's own aggregate. */\n readOwn(options: StateReadOptions = {}): Promise<StateReadResult<S>> {\n return this.readAt(undefined, options);\n }\n\n /** {@link StateClient.get} of the caller's own aggregate. */\n getOwn(\n options: Omit<StateReadOptions, 'ifNoneMatch'> = {},\n ): Promise<Snapshot<S>> {\n return this.getAt(undefined, options);\n }\n\n /**\n * {@link StateClient.find} of the caller's own aggregate: `undefined` until\n * the caller's first command creates it.\n */\n findOwn(\n options: Omit<StateReadOptions, 'ifNoneMatch'> = {},\n ): Promise<Snapshot<S> | undefined> {\n return this.findAt(undefined, options);\n }\n\n /** {@link StateClient.trace} of the caller's own aggregate. */\n traceOwn(options: StateTraceOptions = {}): Promise<StateTrace<S, E>> {\n return this.traceAt(undefined, options);\n }\n}\n"],"mappings":";;;;;AA0FA,IAAaA,IAAb,MAGE;CAKA,YACE,GACA,IAAoC,CAAC,GACrC;EADS,AADA,KAAA,OAAAC,GACA,KAAA,SAAAC;CACR;CAGH,KACE,GACA,IAA4B,CAAC,GACA;EAC7B,OAAO,KAAK,OAAOC,GAAIC,CAAO;CAChC;CAGA,IACE,GACA,IAAiD,CAAC,GAC5B;EACtB,OAAO,KAAK,MAAMD,GAAIC,CAAO;CAC/B;CAQA,KACE,GACA,IAAiD,CAAC,GAChB;EAClC,OAAO,KAAK,OAAOD,GAAIC,CAAO;CAChC;CAGA,MACE,GACA,IAA6B,CAAC,GACH;EAC3B,OAAO,KAAK,QAAQD,GAAIC,CAAO;CACjC;CAMA,MAAgB,OACd,GACA,GAC6B;EAC7B,IAAMC,IACJD,EAAQ,cAAc,OAAOA,EAAQ,GAAG,YAAY,IAAIA,EAA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IAAY,KAAA,IAAY,EAAE,SAAM;CACnD;CAGA,IAAY,eAAwC;EAClD,IAAMA,IAAQ,KAAK,KAAK,aAAa,OAC/BC,IAASC,EAAa,KAAK,IAAI;EACrC,IAAIF,MAAU,KAAA,KAAaC,MAAW,KAAA,GACtC,OAAO,EACL,SAAS,EACP,KAAK;GACH,GAAID,MAAU,KAAA,IAAY,CAAC,IAAI,EAAE,SAAM;GACvC,GAAIC,MAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAKA,EAAO,EAAE;EAC5D,EACF,EACF;CACF;CAEA,UAAkB,GAAgC;EAChD,IAAME,IAAO,IAAI,KAAK,KAAK,QAAQ,GAAG,KAAK,KAAK;EAChD,OAAOhB,MAAO,KAAA,IACV,GAAGgB,EAAK,UACR,GAAGA,EAAK,GAAG,mBAAmBhB,CAAE,EAAE;CACxC;AACF,GAcaiB,IAAb,cAGUpB,EAAkB;CAE1B,QAAQ,IAA4B,CAAC,GAAgC;EACnE,OAAO,KAAK,OAAO,KAAA,GAAWI,CAAO;CACvC;CAGA,OACE,IAAiD,CAAC,GAC5B;EACtB,OAAO,KAAK,MAAM,KAAA,GAAWA,CAAO;CACtC;CAMA,QACE,IAAiD,CAAC,GAChB;EAClC,OAAO,KAAK,OAAO,KAAA,GAAWA,CAAO;CACvC;CAGA,SAAS,IAA6B,CAAC,GAA8B;EACnE,OAAO,KAAK,QAAQ,KAAA,GAAWA,CAAO;CACxC;AACF"}
|
package/dist/streams.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./exactJson.cjs"),t=require("./problem.cjs");let
|
|
1
|
+
const e=require("./exactJson.cjs"),t=require("./frameworkErrors.cjs"),n=require("./problem.cjs");let r=require("@ahoo-wang/fetcher-eventstream");var i=`row`,a=`error`,o=`end`,s=`message`;function c(e){return(0,r.toJsonServerSentEventStream)((0,r.toServerSentEventStream)(e)).pipeThrough(new TransformStream({transform(e,t){t.enqueue(e.data)}}))}var l=`hold-expired`,u=`complete`;function d(e,t){return new Promise((n,r)=>{let i=()=>{clearTimeout(a),r(t?.reason)},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);t?.addEventListener(`abort`,i)})}function f(e){return new n.WowProblemError(n.isProblem(e)?e:{type:`about:blank`,title:`Query failed`,status:500})}function p(c,p,m={}){let{maxRetries:h=t.DEFAULT_RETRY.attempts-1,initialDelayMs:g=t.DEFAULT_RETRY.backoffMs,maxDelayMs:_=t.DEFAULT_RETRY.maxWaitMs,signal:v}=m,y=m.numbers,b=t=>(e.marksNothing(y)?(0,r.toJsonServerSentEventStream)((0,r.toServerSentEventStream)(t)):(0,r.toServerSentEventStream)(t).pipeThrough(new TransformStream({transform(t,n){let r=t.event===i||t.event===s;n.enqueue({...t,data:e.parseJson(t.data,r?y:void 0)})}}))).getReader(),x=b(c),S=m.lastEventId,C=0,w=0,T=!1;async function E(e,t){for(;;){if(v?.aborted)throw v.reason;if(w++>=h)throw e;let r=t??Math.min(_,g*2**(w-1));r>0&&await d(r,v);try{let e=await p(S,C);return e&&(x=b(e)),e!==void 0}catch(r){if(v?.aborted||r instanceof n.WowProblemError&&r.retry===`none`)throw r;t=r.retryAfterMs,e=r}}}return new ReadableStream({async pull(e){for(;;){let t,r;try{let n=await x.read();if(n.done)t=TypeError(`The query stream was cut off.`);else{let{event:c,id:d,data:p}=n.value;if(c===i||c===s){d&&(S=d),C++,w=0,e.enqueue(d?{row:p,position:d}:{row:p});return}if(c===o){let n=p;if(n.reason===u){e.close();return}if(t=TypeError(`The query stream ended: ${n.reason}.`),!n.resumable)throw t;n.reason===l&&(r=0)}else if(c===a){let e=f(p);if(e.retry===`none`)throw e;t=e,r=e.retryAfterMs}else continue}}catch(e){if(e===t||e instanceof n.WowProblemError)throw e;t=e}if(T)return;if(v?.aborted)throw v.reason;if(S===void 0&&C>0)throw t;if(!await E(t,r)){e.close();return}}},cancel(e){return T=!0,x.cancel(e)}})}exports.commandResults=c,exports.resumableQueryRows=p;
|
|
2
2
|
//# sourceMappingURL=streams.cjs.map
|
package/dist/streams.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streams.cjs","names":["toJsonServerSentEventStream","toServerSentEventStream","WowProblemError","isProblem","marksNothing","parseJson","require_exactJson","require_problem","_ahoo_wang_fetcher_eventstream","ROW_EVENT","ERROR_EVENT","END_EVENT","UNNAMED_EVENT","commandResults","response","controller","event","HOLD_EXPIRED","COMPLETE","sleep","abort","timer","reject","signal","resolve","ms","problemOf","data","resumableQueryRows","options","numbers","events","from","row","reader","lastEventId","received","failures","cancelled","resume","maxRetries","cause","wait","delayMs","maxDelayMs","initialDelayMs","next","reopen","error","stop","id","end","reason"],"sources":["../src/streams.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type JsonServerSentEvent,\n type ServerSentEvent,\n toJsonServerSentEventStream,\n toServerSentEventStream,\n} from '@ahoo-wang/fetcher-eventstream';\nimport { marksNothing, parseJson, type TextNumbers } from './exactJson.js';\nimport type { CommandResult } from './wire.js';\nimport { isProblem, WowProblemError } from './problem.js';\n\n/** The event of each record of a streamed query list. */\nconst ROW_EVENT = 'row';\n\n/** The event that ends a streamed query list that failed: the problem. */\nconst ERROR_EVENT = 'error';\n\n/** The event that ends a resumable streamed query list (decision D253). */\nconst END_EVENT = 'end';\n\n/** The name an event without one is read under. */\nconst UNNAMED_EVENT = 'message';\n\n/**\n * The results of a command's event stream (`Accept: text/event-stream`), one\n * per hop, each event named by its stage. A rejection or a failure after\n * admission is the stream's last result, not an error.\n */\nexport type CommandResultStream<R = Record<string, unknown>> = ReadableStream<\n CommandResult<R>\n>;\n\n/** The data of each event of `response`'s server-sent event stream. */\nexport function commandResults<R>(response: Response): CommandResultStream<R> {\n return toJsonServerSentEventStream<CommandResult<R>>(\n toServerSentEventStream(response),\n ).pipeThrough(\n new TransformStream<\n JsonServerSentEvent<CommandResult<R>>,\n CommandResult<R>\n >({\n transform(event, controller) {\n controller.enqueue(event.data);\n },\n }),\n );\n}\n\n/**\n * Why a resumable streamed list ended (decision D253): `complete` once every\n * record was sent; the others are the server's, and resumable: the stream ran\n * for its hold time, its store had no query permit for its next chunk, or\n * the node is stopping.\n */\nexport type StreamEndReason =\n 'complete' | 'hold-expired' | 'permit-reclaimed' | 'node-stopping';\n\n/** The data of the `end` event that ends a resumable streamed list. */\nexport interface StreamEnd {\n /** Why it ended. */\n readonly reason: StreamEndReason | (string & {});\n /** Whether asking again with `Last-Event-ID` goes on where it ended. */\n readonly resumable: boolean;\n}\n\n/** One record of a streamed list, with its position. */\nexport interface StreamedRow<T> {\n /** The record. */\n readonly record: T;\n /**\n * The record's position, its event's `id`: an opaque cursor token to\n * resume after it ({@link StreamResumeOptions.lastEventId}). Absent from a\n * list whose sort cannot order a cursor, which cannot be resumed.\n */\n readonly position?: string;\n}\n\n/**\n * How a streamed list resumes (decision D253). A stream the server ends with\n * a resumable `end`, one cut off before its `end`, and one that fails with a\n * retryable problem (a 429 after its `Retry-After`) are asked for again with\n * `Last-Event-ID`, the position of the last record read, and go on strictly\n * after it.\n */\nexport interface StreamResumeOptions {\n /** Starts after this position: a {@link StreamedRow.position} read before. */\n readonly lastEventId?: string;\n /**\n * How many times in a row the stream may be resumed without a record in\n * between before it fails with what stopped it; 5 by default, 0 never\n * resumes.\n */\n readonly maxRetries?: number;\n /** The wait before the first such retry, doubled for each next; 200 ms by default. */\n readonly initialDelayMs?: number;\n /** The longest wait between retries; 10 s by default. */\n readonly maxDelayMs?: number;\n}\n\nconst HOLD_EXPIRED: StreamEndReason = 'hold-expired';\nconst COMPLETE: StreamEndReason = 'complete';\n\n/** Waits `ms`, or rejects once `signal` aborts. */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const abort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', abort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', abort);\n });\n}\n\nfunction problemOf(data: unknown): WowProblemError {\n return new WowProblemError(\n isProblem(data)\n ? data\n : { type: 'about:blank', title: 'Query failed', status: 500 },\n );\n}\n\n/**\n * The records of a resumable streamed list (decision D253), read from\n * `response` and, each time the stream is to be resumed, from what `reopen`\n * answers for the position of the last record read (none before the first),\n * with how many records were read so far: `undefined` when no more are\n * wanted. Each record comes with its position. An `error` event that is not\n * retryable, a failure `reopen` cannot get past, and an abort of `signal`\n * error the stream.\n *\n * @param response - The first response\n * @param reopen - Asks for the stream again after a position\n * @param options - How the stream resumes, and what cancels it\n */\nexport function resumableQueryRows<T>(\n response: Response,\n reopen: (\n lastEventId: string | undefined,\n received: number,\n ) => Promise<Response | undefined>,\n options: StreamResumeOptions & {\n readonly signal?: AbortSignal;\n /** The numbers of each record read as their exact text (review R4-Q, Q-9). */\n readonly numbers?: TextNumbers;\n } = {},\n): ReadableStream<StreamedRow<T>> {\n const {\n maxRetries = 5,\n initialDelayMs = 200,\n maxDelayMs = 10_000,\n signal,\n } = options;\n const numbers = options.numbers;\n const events = (from: Response) =>\n (marksNothing(numbers)\n ? toJsonServerSentEventStream<unknown>(toServerSentEventStream(from))\n : toServerSentEventStream(from).pipeThrough(\n new TransformStream<ServerSentEvent, JsonServerSentEvent<unknown>>({\n transform(event, controller) {\n const row =\n event.event === ROW_EVENT || event.event === UNNAMED_EVENT;\n controller.enqueue({\n ...event,\n data: parseJson(event.data, row ? numbers : undefined),\n });\n },\n }),\n )\n ).getReader();\n let reader = events(response);\n let lastEventId = options.lastEventId;\n let received = 0;\n let failures = 0;\n // Set once the reader cancels: a read in flight then ends, and must not be\n // taken for a cut-off stream to ask for again.\n let cancelled = false;\n\n /** Asks for the stream again, or throws `cause` once out of retries. */\n async function resume(cause: unknown, delayMs?: number): Promise<boolean> {\n for (;;) {\n if (signal?.aborted) throw signal.reason;\n if (failures++ >= maxRetries) throw cause;\n const wait =\n delayMs ?? Math.min(maxDelayMs, initialDelayMs * 2 ** (failures - 1));\n if (wait > 0) await sleep(wait, signal);\n try {\n const next = await reopen(lastEventId, received);\n if (next) reader = events(next);\n return next !== undefined;\n } catch (error) {\n if (\n signal?.aborted ||\n (error instanceof WowProblemError && !error.retry.retryable)\n ) {\n throw error;\n }\n delayMs = (error as WowProblemError).retry?.afterMs;\n cause = error;\n }\n }\n }\n\n return new ReadableStream<StreamedRow<T>>({\n async pull(controller) {\n for (;;) {\n let stop: unknown;\n let delayMs: number | undefined;\n try {\n const next = await reader.read();\n if (next.done) {\n // Every stream ends with `end`: one without was cut off.\n stop = new TypeError('The query stream was cut off.');\n } else {\n const { event, id, data } = next.value;\n if (event === ROW_EVENT || event === UNNAMED_EVENT) {\n if (id) lastEventId = id;\n received++;\n failures = 0;\n controller.enqueue(\n id\n ? { record: data as T, position: id }\n : { record: data as T },\n );\n return;\n }\n if (event === END_EVENT) {\n const end = data as StreamEnd;\n if (end.reason === COMPLETE) {\n controller.close();\n return;\n }\n stop = new TypeError(`The query stream ended: ${end.reason}.`);\n if (!end.resumable) throw stop;\n if (end.reason === HOLD_EXPIRED) delayMs = 0;\n } else if (event === ERROR_EVENT) {\n const error = problemOf(data);\n if (!error.retry.retryable) throw error;\n stop = error;\n delayMs = error.retry.afterMs;\n } else {\n continue;\n }\n }\n } catch (error) {\n if (error === stop || error instanceof WowProblemError) throw error;\n stop = error;\n }\n if (cancelled) return;\n // Only a stream read from the start, or whose records have positions, can be asked for again.\n if (signal?.aborted) throw signal.reason;\n if (lastEventId === undefined && received > 0) throw stop;\n if (!(await resume(stop, delayMs))) {\n controller.close();\n return;\n }\n }\n },\n cancel(reason) {\n cancelled = true;\n return reader.cancel(reason);\n },\n });\n}\n"],"mappings":"8GAwBA,IAAMS,EAAY,MAGZC,EAAc,QAGdC,EAAY,MAGZC,EAAgB,UAYtB,SAAgBC,EAAkB,EAA4C,CAC5E,OAAA,EAAOb,EAAAA,4BAAAA,EAAAA,EACLC,EAAAA,wBAAAA,CAAwBa,CAAQ,CAClC,CAAC,CAAC,YACA,IAAI,gBAGF,CACA,UAAU,EAAO,EAAY,CAC3BC,EAAW,QAAQC,EAAM,IAAI,CAC/B,CACF,CAAC,CACH,CACF,CAqDA,IAAMC,EAAgC,eAChCC,EAA4B,WAGlC,SAASC,EAAM,EAAY,EAAqC,CAC9D,OAAO,IAAI,SAAS,EAAS,IAAW,CACtC,IAAMC,MAAc,CAClB,aAAaC,CAAK,EAClBC,EAAOC,GAAQ,MAAM,CACvB,EACMF,EAAQ,eAAiB,CAC7BE,GAAQ,oBAAoB,QAASH,CAAK,EAC1CI,EAAQ,CACV,EAAGC,CAAE,EACLF,GAAQ,iBAAiB,QAASH,CAAK,CACzC,CAAC,CACH,CAEA,SAASM,EAAU,EAAgC,CACjD,OAAO,IAAIxB,EAAAA,gBACTC,EAAAA,UAAUwB,CAAI,EACVA,EACA,CAAE,KAAM,cAAe,MAAO,eAAgB,OAAQ,GAAI,CAChE,CACF,CAeA,SAAgBC,EACd,EACA,EAIA,EAII,CAAC,EAC2B,CAChC,GAAM,CACJ,aAAa,EACb,iBAAiB,IACjB,aAAa,IACb,UACEC,EACEC,EAAUD,EAAQ,QAClBE,EAAU,IACb3B,EAAAA,aAAa0B,CAAO,GAAA,EACjB9B,EAAAA,4BAAAA,EAAAA,EAAqCC,EAAAA,wBAAAA,CAAwB+B,CAAI,CAAC,GAAA,EAClE/B,EAAAA,wBAAAA,CAAwB+B,CAAI,CAAC,CAAC,YAC5B,IAAI,gBAA+D,CACjE,UAAU,EAAO,EAAY,CAC3B,IAAMC,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AAW,CACvB,IAAMwC,EAAMxB,EACZ,GAAIwB,EAAI,SAAWjC,EAAU,CAC3BH,EAAW,MAAM,EACjB,MACF,CAEA,GADA,EAAW,UAAU,2BAA2BoC,EAAI,OAAO,EAAE,EACzD,CAACA,EAAI,UAAW,MAAMF,EACtBE,EAAI,SAAWlC,IAAc,EAAU,EAC7C,MAAO,GAAID,IAAUN,EAAa,CAChC,IAAMsC,EAAQtB,EAAUC,CAAI,EAC5B,GAAI,CAACqB,EAAM,MAAM,UAAW,MAAMA,EAClC,EAAOA,EACP,EAAUA,EAAM,MAAM,OACxB,MACE,QAEJ,CACF,OAASA,EAAO,CACd,GAAIA,IAAUC,GAAQD,aAAiB9C,EAAAA,gBAAiB,MAAM8C,EAC9D,EAAOA,CACT,CACA,GAAIV,EAAW,OAEf,GAAIf,GAAQ,QAAS,MAAMA,EAAO,OAClC,GAAIY,IAAgB,IAAA,IAAaC,EAAW,EAAG,MAAMa,EACrD,GAAI,CAAE,MAAMV,EAAOU,EAAMN,CAAO,EAAI,CAClC5B,EAAW,MAAM,EACjB,MACF,CACF,CACF,EACA,OAAO,EAAQ,CAEb,MADA,GAAY,GACLmB,EAAO,OAAOkB,CAAM,CAC7B,CACF,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"streams.cjs","names":["toJsonServerSentEventStream","toServerSentEventStream","WowProblemError","isProblem","DEFAULT_RETRY","marksNothing","parseJson","require_exactJson","require_frameworkErrors","require_problem","_ahoo_wang_fetcher_eventstream","ROW_EVENT","ERROR_EVENT","END_EVENT","UNNAMED_EVENT","commandResults","response","controller","event","HOLD_EXPIRED","COMPLETE","sleep","abort","timer","reject","signal","resolve","ms","problemOf","data","resumableQueryRows","options","numbers","events","from","row","reader","lastEventId","received","failures","cancelled","resume","maxRetries","cause","wait","delayMs","maxDelayMs","initialDelayMs","next","reopen","error","stop","id","end","reason"],"sources":["../src/streams.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type JsonServerSentEvent,\n type ServerSentEvent,\n toJsonServerSentEventStream,\n toServerSentEventStream,\n} from '@ahoo-wang/fetcher-eventstream';\nimport { marksNothing, parseJson, type TextNumbers } from './exactJson.js';\nimport type { CommandResult } from './wire.js';\nimport { DEFAULT_RETRY } from './frameworkErrors.js';\nimport { isProblem, WowProblemError } from './problem.js';\n\n/** The event of each record of a streamed query list. */\nconst ROW_EVENT = 'row';\n\n/** The event that ends a streamed query list that failed: the problem. */\nconst ERROR_EVENT = 'error';\n\n/** The event that ends a resumable streamed query list (decision D253). */\nconst END_EVENT = 'end';\n\n/** The name an event without one is read under. */\nconst UNNAMED_EVENT = 'message';\n\n/**\n * The results of a command's event stream (`Accept: text/event-stream`), one\n * per hop, each event named by its stage. A rejection or a failure after\n * admission is the stream's last result, not an error.\n */\nexport type CommandResultStream<R = Record<string, unknown>> = ReadableStream<\n CommandResult<R>\n>;\n\n/** The data of each event of `response`'s server-sent event stream. */\nexport function commandResults<R>(response: Response): CommandResultStream<R> {\n return toJsonServerSentEventStream<CommandResult<R>>(\n toServerSentEventStream(response),\n ).pipeThrough(\n new TransformStream<\n JsonServerSentEvent<CommandResult<R>>,\n CommandResult<R>\n >({\n transform(event, controller) {\n controller.enqueue(event.data);\n },\n }),\n );\n}\n\n/**\n * Why a resumable streamed list ended: `complete` once every\n * record was sent; the others are the server's, and resumable: the stream ran\n * for its hold time, its store had no query permit for its next chunk, or\n * the node is stopping.\n */\nexport type StreamEndReason =\n 'complete' | 'hold-expired' | 'permit-reclaimed' | 'node-stopping';\n\n/** The data of the `end` event that ends a resumable streamed list. */\nexport interface StreamEnd {\n /** Why it ended. */\n readonly reason: StreamEndReason | (string & {});\n /** Whether asking again with `Last-Event-ID` goes on where it ended. */\n readonly resumable: boolean;\n}\n\n/** One row of a streamed list, with its position. Kotlin's `Positioned`. */\nexport interface Positioned<T> {\n /** The row. */\n readonly row: T;\n /**\n * The record's position, its event's `id`: an opaque cursor token to\n * resume after it ({@link StreamResumeOptions.lastEventId}). Absent from a\n * list whose sort cannot order a cursor, which cannot be resumed.\n */\n readonly position?: string;\n}\n\n/**\n * How a streamed list resumes. A stream the server ends with\n * a resumable `end`, one cut off before its `end`, and one that fails with a\n * retryable problem (a 429 after its `Retry-After`) are asked for again with\n * `Last-Event-ID`, the position of the last record read, and go on strictly\n * after it.\n */\nexport interface StreamResumeOptions {\n /** Starts after this position: a {@link Positioned.position} read before. */\n readonly lastEventId?: string;\n /**\n * How many times in a row the stream may be resumed without a record in\n * between before it fails with what stopped it; by default one fewer than\n * the catalog's attempts ({@link DEFAULT_RETRY}, as the Kotlin client), 0\n * never resumes.\n */\n readonly maxRetries?: number;\n /**\n * The wait before the first such retry, doubled for each next; the\n * catalog's backoff by default ({@link DEFAULT_RETRY}).\n */\n readonly initialDelayMs?: number;\n /** The longest wait between retries; the catalog's by default ({@link DEFAULT_RETRY}). */\n readonly maxDelayMs?: number;\n}\n\nconst HOLD_EXPIRED: StreamEndReason = 'hold-expired';\nconst COMPLETE: StreamEndReason = 'complete';\n\n/** Waits `ms`, or rejects once `signal` aborts. */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const abort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', abort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', abort);\n });\n}\n\nfunction problemOf(data: unknown): WowProblemError {\n return new WowProblemError(\n isProblem(data)\n ? data\n : { type: 'about:blank', title: 'Query failed', status: 500 },\n );\n}\n\n/**\n * The records of a resumable streamed list, read from\n * `response` and, each time the stream is to be resumed, from what `reopen`\n * answers for the position of the last record read (none before the first),\n * with how many records were read so far: `undefined` when no more are\n * wanted. Each record comes with its position. An `error` event that is not\n * retryable, a failure `reopen` cannot get past, and an abort of `signal`\n * error the stream.\n *\n * @param response - The first response\n * @param reopen - Asks for the stream again after a position\n * @param options - How the stream resumes, and what cancels it\n */\nexport function resumableQueryRows<T>(\n response: Response,\n reopen: (\n lastEventId: string | undefined,\n received: number,\n ) => Promise<Response | undefined>,\n options: StreamResumeOptions & {\n readonly signal?: AbortSignal;\n /** The numbers of each record read as their exact text (review R4-Q, Q-9). */\n readonly numbers?: TextNumbers;\n } = {},\n): ReadableStream<Positioned<T>> {\n const {\n maxRetries = DEFAULT_RETRY.attempts - 1,\n initialDelayMs = DEFAULT_RETRY.backoffMs,\n maxDelayMs = DEFAULT_RETRY.maxWaitMs,\n signal,\n } = options;\n const numbers = options.numbers;\n const events = (from: Response) =>\n (marksNothing(numbers)\n ? toJsonServerSentEventStream<unknown>(toServerSentEventStream(from))\n : toServerSentEventStream(from).pipeThrough(\n new TransformStream<ServerSentEvent, JsonServerSentEvent<unknown>>({\n transform(event, controller) {\n const row =\n event.event === ROW_EVENT || event.event === UNNAMED_EVENT;\n controller.enqueue({\n ...event,\n data: parseJson(event.data, row ? numbers : undefined),\n });\n },\n }),\n )\n ).getReader();\n let reader = events(response);\n let lastEventId = options.lastEventId;\n let received = 0;\n let failures = 0;\n // Set once the reader cancels: a read in flight then ends, and must not be\n // taken for a cut-off stream to ask for again.\n let cancelled = false;\n\n /** Asks for the stream again, or throws `cause` once out of retries. */\n async function resume(cause: unknown, delayMs?: number): Promise<boolean> {\n for (;;) {\n if (signal?.aborted) throw signal.reason;\n if (failures++ >= maxRetries) throw cause;\n const wait =\n delayMs ?? Math.min(maxDelayMs, initialDelayMs * 2 ** (failures - 1));\n if (wait > 0) await sleep(wait, signal);\n try {\n const next = await reopen(lastEventId, received);\n if (next) reader = events(next);\n return next !== undefined;\n } catch (error) {\n if (\n signal?.aborted ||\n (error instanceof WowProblemError && error.retry === 'none')\n ) {\n throw error;\n }\n delayMs = (error as WowProblemError).retryAfterMs;\n cause = error;\n }\n }\n }\n\n return new ReadableStream<Positioned<T>>({\n async pull(controller) {\n for (;;) {\n let stop: unknown;\n let delayMs: number | undefined;\n try {\n const next = await reader.read();\n if (next.done) {\n // Every stream ends with `end`: one without was cut off.\n stop = new TypeError('The query stream was cut off.');\n } else {\n const { event, id, data } = next.value;\n if (event === ROW_EVENT || event === UNNAMED_EVENT) {\n if (id) lastEventId = id;\n received++;\n failures = 0;\n controller.enqueue(\n id ? { row: data as T, position: id } : { row: data as T },\n );\n return;\n }\n if (event === END_EVENT) {\n const end = data as StreamEnd;\n if (end.reason === COMPLETE) {\n controller.close();\n return;\n }\n stop = new TypeError(`The query stream ended: ${end.reason}.`);\n if (!end.resumable) throw stop;\n if (end.reason === HOLD_EXPIRED) delayMs = 0;\n } else if (event === ERROR_EVENT) {\n const error = problemOf(data);\n if (error.retry === 'none') throw error;\n stop = error;\n delayMs = error.retryAfterMs;\n } else {\n continue;\n }\n }\n } catch (error) {\n if (error === stop || error instanceof WowProblemError) throw error;\n stop = error;\n }\n if (cancelled) return;\n // Only a stream read from the start, or whose records have positions, can be asked for again.\n if (signal?.aborted) throw signal.reason;\n if (lastEventId === undefined && received > 0) throw stop;\n if (!(await resume(stop, delayMs))) {\n controller.close();\n return;\n }\n }\n },\n cancel(reason) {\n cancelled = true;\n return reader.cancel(reason);\n },\n });\n}\n"],"mappings":"A,iJAyBA,IAAMW,EAAY,MAGZC,EAAc,QAGdC,EAAY,MAGZC,EAAgB,UAYtB,SAAgBC,EAAkB,EAA4C,CAC5E,OAAA,EAAOf,EAAAA,4BAAAA,EAAAA,EACLC,EAAAA,wBAAAA,CAAwBe,CAAQ,CAClC,CAAC,CAAC,YACA,IAAI,gBAGF,CACA,UAAU,EAAO,EAAY,CAC3BC,EAAW,QAAQ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U,OAAQ,MAAMA,EAClC,EAAOA,EACP,EAAUA,EAAM,YAClB,MACE,QAEJ,CACF,OAASA,EAAO,CACd,GAAIA,IAAUC,GAAQD,aAAiBhD,EAAAA,gBAAiB,MAAMgD,EAC9D,EAAOA,CACT,CACA,GAAIV,EAAW,OAEf,GAAIf,GAAQ,QAAS,MAAMA,EAAO,OAClC,GAAIY,IAAgB,IAAA,IAAaC,EAAW,EAAG,MAAMa,EACrD,GAAI,CAAE,MAAMV,EAAOU,EAAMN,CAAO,EAAI,CAClC5B,EAAW,MAAM,EACjB,MACF,CACF,CACF,EACA,OAAO,EAAQ,CAEb,MADA,GAAY,GACLmB,EAAO,OAAOkB,CAAM,CAC7B,CACF,CAAC,CACH,C"}
|
package/dist/streams.d.cts
CHANGED
|
@@ -9,7 +9,7 @@ export type CommandResultStream<R = Record<string, unknown>> = ReadableStream<Co
|
|
|
9
9
|
/** The data of each event of `response`'s server-sent event stream. */
|
|
10
10
|
export declare function commandResults<R>(response: Response): CommandResultStream<R>;
|
|
11
11
|
/**
|
|
12
|
-
* Why a resumable streamed list ended
|
|
12
|
+
* Why a resumable streamed list ended: `complete` once every
|
|
13
13
|
* record was sent; the others are the server's, and resumable: the stream ran
|
|
14
14
|
* for its hold time, its store had no query permit for its next chunk, or
|
|
15
15
|
* the node is stopping.
|
|
@@ -22,10 +22,10 @@ export interface StreamEnd {
|
|
|
22
22
|
/** Whether asking again with `Last-Event-ID` goes on where it ended. */
|
|
23
23
|
readonly resumable: boolean;
|
|
24
24
|
}
|
|
25
|
-
/** One
|
|
26
|
-
export interface
|
|
27
|
-
/** The
|
|
28
|
-
readonly
|
|
25
|
+
/** One row of a streamed list, with its position. Kotlin's `Positioned`. */
|
|
26
|
+
export interface Positioned<T> {
|
|
27
|
+
/** The row. */
|
|
28
|
+
readonly row: T;
|
|
29
29
|
/**
|
|
30
30
|
* The record's position, its event's `id`: an opaque cursor token to
|
|
31
31
|
* resume after it ({@link StreamResumeOptions.lastEventId}). Absent from a
|
|
@@ -34,28 +34,32 @@ export interface StreamedRow<T> {
|
|
|
34
34
|
readonly position?: string;
|
|
35
35
|
}
|
|
36
36
|
/**
|
|
37
|
-
* How a streamed list resumes
|
|
37
|
+
* How a streamed list resumes. A stream the server ends with
|
|
38
38
|
* a resumable `end`, one cut off before its `end`, and one that fails with a
|
|
39
39
|
* retryable problem (a 429 after its `Retry-After`) are asked for again with
|
|
40
40
|
* `Last-Event-ID`, the position of the last record read, and go on strictly
|
|
41
41
|
* after it.
|
|
42
42
|
*/
|
|
43
43
|
export interface StreamResumeOptions {
|
|
44
|
-
/** Starts after this position: a {@link
|
|
44
|
+
/** Starts after this position: a {@link Positioned.position} read before. */
|
|
45
45
|
readonly lastEventId?: string;
|
|
46
46
|
/**
|
|
47
47
|
* How many times in a row the stream may be resumed without a record in
|
|
48
|
-
* between before it fails with what stopped it;
|
|
49
|
-
*
|
|
48
|
+
* between before it fails with what stopped it; by default one fewer than
|
|
49
|
+
* the catalog's attempts ({@link DEFAULT_RETRY}, as the Kotlin client), 0
|
|
50
|
+
* never resumes.
|
|
50
51
|
*/
|
|
51
52
|
readonly maxRetries?: number;
|
|
52
|
-
/**
|
|
53
|
+
/**
|
|
54
|
+
* The wait before the first such retry, doubled for each next; the
|
|
55
|
+
* catalog's backoff by default ({@link DEFAULT_RETRY}).
|
|
56
|
+
*/
|
|
53
57
|
readonly initialDelayMs?: number;
|
|
54
|
-
/** The longest wait between retries;
|
|
58
|
+
/** The longest wait between retries; the catalog's by default ({@link DEFAULT_RETRY}). */
|
|
55
59
|
readonly maxDelayMs?: number;
|
|
56
60
|
}
|
|
57
61
|
/**
|
|
58
|
-
* The records of a resumable streamed list
|
|
62
|
+
* The records of a resumable streamed list, read from
|
|
59
63
|
* `response` and, each time the stream is to be resumed, from what `reopen`
|
|
60
64
|
* answers for the position of the last record read (none before the first),
|
|
61
65
|
* with how many records were read so far: `undefined` when no more are
|
|
@@ -71,4 +75,4 @@ export declare function resumableQueryRows<T>(response: Response, reopen: (lastE
|
|
|
71
75
|
readonly signal?: AbortSignal;
|
|
72
76
|
/** The numbers of each record read as their exact text (review R4-Q, Q-9). */
|
|
73
77
|
readonly numbers?: TextNumbers;
|
|
74
|
-
}): ReadableStream<
|
|
78
|
+
}): ReadableStream<Positioned<T>>;
|
package/dist/streams.d.ts
CHANGED
|
@@ -9,7 +9,7 @@ export type CommandResultStream<R = Record<string, unknown>> = ReadableStream<Co
|
|
|
9
9
|
/** The data of each event of `response`'s server-sent event stream. */
|
|
10
10
|
export declare function commandResults<R>(response: Response): CommandResultStream<R>;
|
|
11
11
|
/**
|
|
12
|
-
* Why a resumable streamed list ended
|
|
12
|
+
* Why a resumable streamed list ended: `complete` once every
|
|
13
13
|
* record was sent; the others are the server's, and resumable: the stream ran
|
|
14
14
|
* for its hold time, its store had no query permit for its next chunk, or
|
|
15
15
|
* the node is stopping.
|
|
@@ -22,10 +22,10 @@ export interface StreamEnd {
|
|
|
22
22
|
/** Whether asking again with `Last-Event-ID` goes on where it ended. */
|
|
23
23
|
readonly resumable: boolean;
|
|
24
24
|
}
|
|
25
|
-
/** One
|
|
26
|
-
export interface
|
|
27
|
-
/** The
|
|
28
|
-
readonly
|
|
25
|
+
/** One row of a streamed list, with its position. Kotlin's `Positioned`. */
|
|
26
|
+
export interface Positioned<T> {
|
|
27
|
+
/** The row. */
|
|
28
|
+
readonly row: T;
|
|
29
29
|
/**
|
|
30
30
|
* The record's position, its event's `id`: an opaque cursor token to
|
|
31
31
|
* resume after it ({@link StreamResumeOptions.lastEventId}). Absent from a
|
|
@@ -34,28 +34,32 @@ export interface StreamedRow<T> {
|
|
|
34
34
|
readonly position?: string;
|
|
35
35
|
}
|
|
36
36
|
/**
|
|
37
|
-
* How a streamed list resumes
|
|
37
|
+
* How a streamed list resumes. A stream the server ends with
|
|
38
38
|
* a resumable `end`, one cut off before its `end`, and one that fails with a
|
|
39
39
|
* retryable problem (a 429 after its `Retry-After`) are asked for again with
|
|
40
40
|
* `Last-Event-ID`, the position of the last record read, and go on strictly
|
|
41
41
|
* after it.
|
|
42
42
|
*/
|
|
43
43
|
export interface StreamResumeOptions {
|
|
44
|
-
/** Starts after this position: a {@link
|
|
44
|
+
/** Starts after this position: a {@link Positioned.position} read before. */
|
|
45
45
|
readonly lastEventId?: string;
|
|
46
46
|
/**
|
|
47
47
|
* How many times in a row the stream may be resumed without a record in
|
|
48
|
-
* between before it fails with what stopped it;
|
|
49
|
-
*
|
|
48
|
+
* between before it fails with what stopped it; by default one fewer than
|
|
49
|
+
* the catalog's attempts ({@link DEFAULT_RETRY}, as the Kotlin client), 0
|
|
50
|
+
* never resumes.
|
|
50
51
|
*/
|
|
51
52
|
readonly maxRetries?: number;
|
|
52
|
-
/**
|
|
53
|
+
/**
|
|
54
|
+
* The wait before the first such retry, doubled for each next; the
|
|
55
|
+
* catalog's backoff by default ({@link DEFAULT_RETRY}).
|
|
56
|
+
*/
|
|
53
57
|
readonly initialDelayMs?: number;
|
|
54
|
-
/** The longest wait between retries;
|
|
58
|
+
/** The longest wait between retries; the catalog's by default ({@link DEFAULT_RETRY}). */
|
|
55
59
|
readonly maxDelayMs?: number;
|
|
56
60
|
}
|
|
57
61
|
/**
|
|
58
|
-
* The records of a resumable streamed list
|
|
62
|
+
* The records of a resumable streamed list, read from
|
|
59
63
|
* `response` and, each time the stream is to be resumed, from what `reopen`
|
|
60
64
|
* answers for the position of the last record read (none before the first),
|
|
61
65
|
* with how many records were read so far: `undefined` when no more are
|
|
@@ -71,4 +75,4 @@ export declare function resumableQueryRows<T>(response: Response, reopen: (lastE
|
|
|
71
75
|
readonly signal?: AbortSignal;
|
|
72
76
|
/** The numbers of each record read as their exact text (review R4-Q, Q-9). */
|
|
73
77
|
readonly numbers?: TextNumbers;
|
|
74
|
-
}): ReadableStream<
|
|
78
|
+
}): ReadableStream<Positioned<T>>;
|
package/dist/streams.es.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import { marksNothing as e, parseJson as t } from "./exactJson.es.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
2
|
+
import { DEFAULT_RETRY as n } from "./frameworkErrors.es.js";
|
|
3
|
+
import { WowProblemError as r, isProblem as i } from "./problem.es.js";
|
|
4
|
+
import { toJsonServerSentEventStream as a, toServerSentEventStream as o } from "@ahoo-wang/fetcher-eventstream";
|
|
5
|
+
// src/streams.ts
|
|
6
|
+
var s = "row", c = "error", l = "end", u = "message";
|
|
7
|
+
function d(e) {
|
|
8
|
+
return a(o(e)).pipeThrough(new TransformStream({ transform(e, t) {
|
|
8
9
|
t.enqueue(e.data);
|
|
9
10
|
} }));
|
|
10
11
|
}
|
|
11
|
-
var
|
|
12
|
-
function
|
|
12
|
+
var f = "hold-expired", p = "complete";
|
|
13
|
+
function m(e, t) {
|
|
13
14
|
return new Promise((n, r) => {
|
|
14
15
|
let i = () => {
|
|
15
16
|
clearTimeout(a), r(t?.reason);
|
|
@@ -19,85 +20,84 @@ function p(e, t) {
|
|
|
19
20
|
t?.addEventListener("abort", i);
|
|
20
21
|
});
|
|
21
22
|
}
|
|
22
|
-
function
|
|
23
|
-
return new
|
|
23
|
+
function h(e) {
|
|
24
|
+
return new r(i(e) ? e : {
|
|
24
25
|
type: "about:blank",
|
|
25
26
|
title: "Query failed",
|
|
26
27
|
status: 500
|
|
27
28
|
});
|
|
28
29
|
}
|
|
29
|
-
function
|
|
30
|
-
let { maxRetries:
|
|
31
|
-
let r = e.event ===
|
|
30
|
+
function g(i, d, g = {}) {
|
|
31
|
+
let { maxRetries: _ = n.attempts - 1, initialDelayMs: v = n.backoffMs, maxDelayMs: y = n.maxWaitMs, signal: b } = g, x = g.numbers, S = (n) => (e(x) ? a(o(n)) : o(n).pipeThrough(new TransformStream({ transform(e, n) {
|
|
32
|
+
let r = e.event === s || e.event === u;
|
|
32
33
|
n.enqueue({
|
|
33
34
|
...e,
|
|
34
|
-
data: t(e.data, r ?
|
|
35
|
+
data: t(e.data, r ? x : void 0)
|
|
35
36
|
});
|
|
36
|
-
} }))).getReader(),
|
|
37
|
-
async function
|
|
37
|
+
} }))).getReader(), C = S(i), w = g.lastEventId, T = 0, E = 0, D = !1;
|
|
38
|
+
async function O(e, t) {
|
|
38
39
|
for (;;) {
|
|
39
|
-
if (
|
|
40
|
-
if (
|
|
41
|
-
let
|
|
42
|
-
|
|
40
|
+
if (b?.aborted) throw b.reason;
|
|
41
|
+
if (E++ >= _) throw e;
|
|
42
|
+
let n = t ?? Math.min(y, v * 2 ** (E - 1));
|
|
43
|
+
n > 0 && await m(n, b);
|
|
43
44
|
try {
|
|
44
|
-
let e = await
|
|
45
|
-
return e && (
|
|
46
|
-
} catch (
|
|
47
|
-
if (
|
|
48
|
-
t =
|
|
45
|
+
let e = await d(w, T);
|
|
46
|
+
return e && (C = S(e)), e !== void 0;
|
|
47
|
+
} catch (n) {
|
|
48
|
+
if (b?.aborted || n instanceof r && n.retry === "none") throw n;
|
|
49
|
+
t = n.retryAfterMs, e = n;
|
|
49
50
|
}
|
|
50
51
|
}
|
|
51
52
|
}
|
|
52
53
|
return new ReadableStream({
|
|
53
54
|
async pull(e) {
|
|
54
55
|
for (;;) {
|
|
55
|
-
let t,
|
|
56
|
+
let t, n;
|
|
56
57
|
try {
|
|
57
|
-
let
|
|
58
|
-
if (
|
|
58
|
+
let r = await C.read();
|
|
59
|
+
if (r.done) t = /* @__PURE__ */ TypeError("The query stream was cut off.");
|
|
59
60
|
else {
|
|
60
|
-
let { event: i, id: a, data:
|
|
61
|
-
if (i ===
|
|
62
|
-
a && (
|
|
63
|
-
|
|
61
|
+
let { event: i, id: a, data: o } = r.value;
|
|
62
|
+
if (i === s || i === u) {
|
|
63
|
+
a && (w = a), T++, E = 0, e.enqueue(a ? {
|
|
64
|
+
row: o,
|
|
64
65
|
position: a
|
|
65
|
-
} : {
|
|
66
|
+
} : { row: o });
|
|
66
67
|
return;
|
|
67
68
|
}
|
|
68
|
-
if (i ===
|
|
69
|
-
let
|
|
70
|
-
if (
|
|
69
|
+
if (i === l) {
|
|
70
|
+
let r = o;
|
|
71
|
+
if (r.reason === p) {
|
|
71
72
|
e.close();
|
|
72
73
|
return;
|
|
73
74
|
}
|
|
74
|
-
if (t = /* @__PURE__ */ TypeError(`The query stream ended: ${
|
|
75
|
-
|
|
76
|
-
} else if (i ===
|
|
77
|
-
let e =
|
|
78
|
-
if (
|
|
79
|
-
t = e,
|
|
75
|
+
if (t = /* @__PURE__ */ TypeError(`The query stream ended: ${r.reason}.`), !r.resumable) throw t;
|
|
76
|
+
r.reason === f && (n = 0);
|
|
77
|
+
} else if (i === c) {
|
|
78
|
+
let e = h(o);
|
|
79
|
+
if (e.retry === "none") throw e;
|
|
80
|
+
t = e, n = e.retryAfterMs;
|
|
80
81
|
} else continue;
|
|
81
82
|
}
|
|
82
83
|
} catch (e) {
|
|
83
|
-
if (e === t || e instanceof
|
|
84
|
+
if (e === t || e instanceof r) throw e;
|
|
84
85
|
t = e;
|
|
85
86
|
}
|
|
86
|
-
if (
|
|
87
|
-
if (
|
|
88
|
-
if (
|
|
89
|
-
if (!await
|
|
87
|
+
if (D) return;
|
|
88
|
+
if (b?.aborted) throw b.reason;
|
|
89
|
+
if (w === void 0 && T > 0) throw t;
|
|
90
|
+
if (!await O(t, n)) {
|
|
90
91
|
e.close();
|
|
91
92
|
return;
|
|
92
93
|
}
|
|
93
94
|
}
|
|
94
95
|
},
|
|
95
96
|
cancel(e) {
|
|
96
|
-
return
|
|
97
|
+
return D = !0, C.cancel(e);
|
|
97
98
|
}
|
|
98
99
|
});
|
|
99
100
|
}
|
|
100
|
-
|
|
101
|
-
export { u as commandResults, h as resumableQueryRows };
|
|
101
|
+
export { d as commandResults, g as resumableQueryRows };
|
|
102
102
|
|
|
103
103
|
//# sourceMappingURL=streams.es.js.map
|
package/dist/streams.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streams.es.js","names":["ROW_EVENT","ERROR_EVENT","END_EVENT","UNNAMED_EVENT","commandResults","toJsonServerSentEventStream","toServerSentEventStream","response","event","HOLD_EXPIRED","COMPLETE","sleep","abort","timer","reject","signal","resolve","ms","problemOf","WowProblemError","isProblem","data","resumableQueryRows","options","numbers","events","marksNothing","from","row","parseJson","reader","lastEventId","received","failures","cancelled","resume","maxRetries","cause","wait","delayMs","maxDelayMs","initialDelayMs","next","reopen","error","stop","id","controller","end","reason"],"sources":["../src/streams.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type JsonServerSentEvent,\n type ServerSentEvent,\n toJsonServerSentEventStream,\n toServerSentEventStream,\n} from '@ahoo-wang/fetcher-eventstream';\nimport { marksNothing, parseJson, type TextNumbers } from './exactJson.js';\nimport type { CommandResult } from './wire.js';\nimport { isProblem, WowProblemError } from './problem.js';\n\n/** The event of each record of a streamed query list. */\nconst ROW_EVENT = 'row';\n\n/** The event that ends a streamed query list that failed: the problem. */\nconst ERROR_EVENT = 'error';\n\n/** The event that ends a resumable streamed query list (decision D253). */\nconst END_EVENT = 'end';\n\n/** The name an event without one is read under. */\nconst UNNAMED_EVENT = 'message';\n\n/**\n * The results of a command's event stream (`Accept: text/event-stream`), one\n * per hop, each event named by its stage. A rejection or a failure after\n * admission is the stream's last result, not an error.\n */\nexport type CommandResultStream<R = Record<string, unknown>> = ReadableStream<\n CommandResult<R>\n>;\n\n/** The data of each event of `response`'s server-sent event stream. */\nexport function commandResults<R>(response: Response): CommandResultStream<R> {\n return toJsonServerSentEventStream<CommandResult<R>>(\n toServerSentEventStream(response),\n ).pipeThrough(\n new TransformStream<\n JsonServerSentEvent<CommandResult<R>>,\n CommandResult<R>\n >({\n transform(event, controller) {\n controller.enqueue(event.data);\n },\n }),\n );\n}\n\n/**\n * Why a resumable streamed list ended (decision D253): `complete` once every\n * record was sent; the others are the server's, and resumable: the stream ran\n * for its hold time, its store had no query permit for its next chunk, or\n * the node is stopping.\n */\nexport type StreamEndReason =\n 'complete' | 'hold-expired' | 'permit-reclaimed' | 'node-stopping';\n\n/** The data of the `end` event that ends a resumable streamed list. */\nexport interface StreamEnd {\n /** Why it ended. */\n readonly reason: StreamEndReason | (string & {});\n /** Whether asking again with `Last-Event-ID` goes on where it ended. */\n readonly resumable: boolean;\n}\n\n/** One record of a streamed list, with its position. */\nexport interface StreamedRow<T> {\n /** The record. */\n readonly record: T;\n /**\n * The record's position, its event's `id`: an opaque cursor token to\n * resume after it ({@link StreamResumeOptions.lastEventId}). Absent from a\n * list whose sort cannot order a cursor, which cannot be resumed.\n */\n readonly position?: string;\n}\n\n/**\n * How a streamed list resumes (decision D253). A stream the server ends with\n * a resumable `end`, one cut off before its `end`, and one that fails with a\n * retryable problem (a 429 after its `Retry-After`) are asked for again with\n * `Last-Event-ID`, the position of the last record read, and go on strictly\n * after it.\n */\nexport interface StreamResumeOptions {\n /** Starts after this position: a {@link StreamedRow.position} read before. */\n readonly lastEventId?: string;\n /**\n * How many times in a row the stream may be resumed without a record in\n * between before it fails with what stopped it; 5 by default, 0 never\n * resumes.\n */\n readonly maxRetries?: number;\n /** The wait before the first such retry, doubled for each next; 200 ms by default. */\n readonly initialDelayMs?: number;\n /** The longest wait between retries; 10 s by default. */\n readonly maxDelayMs?: number;\n}\n\nconst HOLD_EXPIRED: StreamEndReason = 'hold-expired';\nconst COMPLETE: StreamEndReason = 'complete';\n\n/** Waits `ms`, or rejects once `signal` aborts. */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const abort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', abort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', abort);\n });\n}\n\nfunction problemOf(data: unknown): WowProblemError {\n return new WowProblemError(\n isProblem(data)\n ? data\n : { type: 'about:blank', title: 'Query failed', status: 500 },\n );\n}\n\n/**\n * The records of a resumable streamed list (decision D253), read from\n * `response` and, each time the stream is to be resumed, from what `reopen`\n * answers for the position of the last record read (none before the first),\n * with how many records were read so far: `undefined` when no more are\n * wanted. Each record comes with its position. An `error` event that is not\n * retryable, a failure `reopen` cannot get past, and an abort of `signal`\n * error the stream.\n *\n * @param response - The first response\n * @param reopen - Asks for the stream again after a position\n * @param options - How the stream resumes, and what cancels it\n */\nexport function resumableQueryRows<T>(\n response: Response,\n reopen: (\n lastEventId: string | undefined,\n received: number,\n ) => Promise<Response | undefined>,\n options: StreamResumeOptions & {\n readonly signal?: AbortSignal;\n /** The numbers of each record read as their exact text (review R4-Q, Q-9). */\n readonly numbers?: TextNumbers;\n } = {},\n): ReadableStream<StreamedRow<T>> {\n const {\n maxRetries = 5,\n initialDelayMs = 200,\n maxDelayMs = 10_000,\n signal,\n } = options;\n const numbers = options.numbers;\n const events = (from: Response) =>\n (marksNothing(numbers)\n ? toJsonServerSentEventStream<unknown>(toServerSentEventStream(from))\n : toServerSentEventStream(from).pipeThrough(\n new TransformStream<ServerSentEvent, JsonServerSentEvent<unknown>>({\n transform(event, controller) {\n const row =\n event.event === ROW_EVENT || event.event === UNNAMED_EVENT;\n controller.enqueue({\n ...event,\n data: parseJson(event.data, row ? numbers : undefined),\n });\n },\n }),\n )\n ).getReader();\n let reader = events(response);\n let lastEventId = options.lastEventId;\n let received = 0;\n let failures = 0;\n // Set once the reader cancels: a read in flight then ends, and must not be\n // taken for a cut-off stream to ask for again.\n let cancelled = false;\n\n /** Asks for the stream again, or throws `cause` once out of retries. */\n async function resume(cause: unknown, delayMs?: number): Promise<boolean> {\n for (;;) {\n if (signal?.aborted) throw signal.reason;\n if (failures++ >= maxRetries) throw cause;\n const wait =\n delayMs ?? Math.min(maxDelayMs, initialDelayMs * 2 ** (failures - 1));\n if (wait > 0) await sleep(wait, signal);\n try {\n const next = await reopen(lastEventId, received);\n if (next) reader = events(next);\n return next !== undefined;\n } catch (error) {\n if (\n signal?.aborted ||\n (error instanceof WowProblemError && !error.retry.retryable)\n ) {\n throw error;\n }\n delayMs = (error as WowProblemError).retry?.afterMs;\n cause = error;\n }\n }\n }\n\n return new ReadableStream<StreamedRow<T>>({\n async pull(controller) {\n for (;;) {\n let stop: unknown;\n let delayMs: number | undefined;\n try {\n const next = await reader.read();\n if (next.done) {\n // Every stream ends with `end`: one without was cut off.\n stop = new TypeError('The query stream was cut off.');\n } else {\n const { event, id, data } = next.value;\n if (event === ROW_EVENT || event === UNNAMED_EVENT) {\n if (id) lastEventId = id;\n received++;\n failures = 0;\n controller.enqueue(\n id\n ? { record: data as T, position: id }\n : { record: data as T },\n );\n return;\n }\n if (event === END_EVENT) {\n const end = data as StreamEnd;\n if (end.reason === COMPLETE) {\n controller.close();\n return;\n }\n stop = new TypeError(`The query stream ended: ${end.reason}.`);\n if (!end.resumable) throw stop;\n if (end.reason === HOLD_EXPIRED) delayMs = 0;\n } else if (event === ERROR_EVENT) {\n const error = problemOf(data);\n if (!error.retry.retryable) throw error;\n stop = error;\n delayMs = error.retry.afterMs;\n } else {\n continue;\n }\n }\n } catch (error) {\n if (error === stop || error instanceof WowProblemError) throw error;\n stop = error;\n }\n if (cancelled) return;\n // Only a stream read from the start, or whose records have positions, can be asked for again.\n if (signal?.aborted) throw signal.reason;\n if (lastEventId === undefined && received > 0) throw stop;\n if (!(await resume(stop, delayMs))) {\n controller.close();\n return;\n }\n }\n },\n cancel(reason) {\n cancelled = true;\n return reader.cancel(reason);\n },\n });\n}\n"],"mappings":";;;;AAwBA,IAAMA,IAAY,OAGZC,IAAc,SAGdC,IAAY,OAGZC,IAAgB;AAY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AAUG,CAAI;OAC5B,IAAI,CAACuB,EAAM,MAAM,WAAW,MAAMA;OAElC,AADA,IAAOA,GACP,IAAUA,EAAM,MAAM;MACxB,OACE;KAEJ;IACF,SAASA,GAAO;KACd,IAAIA,MAAUC,KAAQD,aAAiBzB,GAAiB,MAAMyB;KAC9D,IAAOA;IACT;IACA,IAAIV,GAAW;IAEf,IAAInB,GAAQ,SAAS,MAAMA,EAAO;IAClC,IAAIgB,MAAgB,KAAA,KAAaC,IAAW,GAAG,MAAMa;IACrD,IAAI,CAAE,MAAMV,EAAOU,GAAMN,CAAO,GAAI;KAClC,EAAW,MAAM;KACjB;IACF;GACF;EACF;EACA,OAAO,GAAQ;GAEb,OADA,IAAY,IACLT,EAAO,OAAOmB,CAAM;EAC7B;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"streams.es.js","names":["ROW_EVENT","ERROR_EVENT","END_EVENT","UNNAMED_EVENT","commandResults","toJsonServerSentEventStream","toServerSentEventStream","response","event","HOLD_EXPIRED","COMPLETE","sleep","abort","timer","reject","signal","resolve","ms","problemOf","WowProblemError","isProblem","data","resumableQueryRows","DEFAULT_RETRY","options","numbers","events","marksNothing","from","row","parseJson","reader","lastEventId","received","failures","cancelled","resume","maxRetries","cause","wait","delayMs","maxDelayMs","initialDelayMs","next","reopen","error","stop","id","controller","end","reason"],"sources":["../src/streams.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type JsonServerSentEvent,\n type ServerSentEvent,\n toJsonServerSentEventStream,\n toServerSentEventStream,\n} from '@ahoo-wang/fetcher-eventstream';\nimport { marksNothing, parseJson, type TextNumbers } from './exactJson.js';\nimport type { CommandResult } from './wire.js';\nimport { DEFAULT_RETRY } from './frameworkErrors.js';\nimport { isProblem, WowProblemError } from './problem.js';\n\n/** The event of each record of a streamed query list. */\nconst ROW_EVENT = 'row';\n\n/** The event that ends a streamed query list that failed: the problem. */\nconst ERROR_EVENT = 'error';\n\n/** The event that ends a resumable streamed query list (decision D253). */\nconst END_EVENT = 'end';\n\n/** The name an event without one is read under. */\nconst UNNAMED_EVENT = 'message';\n\n/**\n * The results of a command's event stream (`Accept: text/event-stream`), one\n * per hop, each event named by its stage. A rejection or a failure after\n * admission is the stream's last result, not an error.\n */\nexport type CommandResultStream<R = Record<string, unknown>> = ReadableStream<\n CommandResult<R>\n>;\n\n/** The data of each event of `response`'s server-sent event stream. */\nexport function commandResults<R>(response: Response): CommandResultStream<R> {\n return toJsonServerSentEventStream<CommandResult<R>>(\n toServerSentEventStream(response),\n ).pipeThrough(\n new TransformStream<\n JsonServerSentEvent<CommandResult<R>>,\n CommandResult<R>\n >({\n transform(event, controller) {\n controller.enqueue(event.data);\n },\n }),\n );\n}\n\n/**\n * Why a resumable streamed list ended: `complete` once every\n * record was sent; the others are the server's, and resumable: the stream ran\n * for its hold time, its store had no query permit for its next chunk, or\n * the node is stopping.\n */\nexport type StreamEndReason =\n 'complete' | 'hold-expired' | 'permit-reclaimed' | 'node-stopping';\n\n/** The data of the `end` event that ends a resumable streamed list. */\nexport interface StreamEnd {\n /** Why it ended. */\n readonly reason: StreamEndReason | (string & {});\n /** Whether asking again with `Last-Event-ID` goes on where it ended. */\n readonly resumable: boolean;\n}\n\n/** One row of a streamed list, with its position. Kotlin's `Positioned`. */\nexport interface Positioned<T> {\n /** The row. */\n readonly row: T;\n /**\n * The record's position, its event's `id`: an opaque cursor token to\n * resume after it ({@link StreamResumeOptions.lastEventId}). Absent from a\n * list whose sort cannot order a cursor, which cannot be resumed.\n */\n readonly position?: string;\n}\n\n/**\n * How a streamed list resumes. A stream the server ends with\n * a resumable `end`, one cut off before its `end`, and one that fails with a\n * retryable problem (a 429 after its `Retry-After`) are asked for again with\n * `Last-Event-ID`, the position of the last record read, and go on strictly\n * after it.\n */\nexport interface StreamResumeOptions {\n /** Starts after this position: a {@link Positioned.position} read before. */\n readonly lastEventId?: string;\n /**\n * How many times in a row the stream may be resumed without a record in\n * between before it fails with what stopped it; by default one fewer than\n * the catalog's attempts ({@link DEFAULT_RETRY}, as the Kotlin client), 0\n * never resumes.\n */\n readonly maxRetries?: number;\n /**\n * The wait before the first such retry, doubled for each next; the\n * catalog's backoff by default ({@link DEFAULT_RETRY}).\n */\n readonly initialDelayMs?: number;\n /** The longest wait between retries; the catalog's by default ({@link DEFAULT_RETRY}). */\n readonly maxDelayMs?: number;\n}\n\nconst HOLD_EXPIRED: StreamEndReason = 'hold-expired';\nconst COMPLETE: StreamEndReason = 'complete';\n\n/** Waits `ms`, or rejects once `signal` aborts. */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const abort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', abort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', abort);\n });\n}\n\nfunction problemOf(data: unknown): WowProblemError {\n return new WowProblemError(\n isProblem(data)\n ? data\n : { type: 'about:blank', title: 'Query failed', status: 500 },\n );\n}\n\n/**\n * The records of a resumable streamed list, read from\n * `response` and, each time the stream is to be resumed, from what `reopen`\n * answers for the position of the last record read (none before the first),\n * with how many records were read so far: `undefined` when no more are\n * wanted. Each record comes with its position. An `error` event that is not\n * retryable, a failure `reopen` cannot get past, and an abort of `signal`\n * error the stream.\n *\n * @param response - The first response\n * @param reopen - Asks for the stream again after a position\n * @param options - How the stream resumes, and what cancels it\n */\nexport function resumableQueryRows<T>(\n response: Response,\n reopen: (\n lastEventId: string | undefined,\n received: number,\n ) => Promise<Response | undefined>,\n options: StreamResumeOptions & {\n readonly signal?: AbortSignal;\n /** The numbers of each record read as their exact text (review R4-Q, Q-9). */\n readonly numbers?: TextNumbers;\n } = {},\n): ReadableStream<Positioned<T>> {\n const {\n maxRetries = DEFAULT_RETRY.attempts - 1,\n initialDelayMs = DEFAULT_RETRY.backoffMs,\n maxDelayMs = DEFAULT_RETRY.maxWaitMs,\n signal,\n } = options;\n const numbers = options.numbers;\n const events = (from: Response) =>\n (marksNothing(numbers)\n ? toJsonServerSentEventStream<unknown>(toServerSentEventStream(from))\n : toServerSentEventStream(from).pipeThrough(\n new TransformStream<ServerSentEvent, JsonServerSentEvent<unknown>>({\n transform(event, controller) {\n const row =\n event.event === ROW_EVENT || event.event === UNNAMED_EVENT;\n controller.enqueue({\n ...event,\n data: parseJson(event.data, row ? numbers : undefined),\n });\n },\n }),\n )\n ).getReader();\n let reader = events(response);\n let lastEventId = options.lastEventId;\n let received = 0;\n let failures = 0;\n // Set once the reader cancels: a read in flight then ends, and must not be\n // taken for a cut-off stream to ask for again.\n let cancelled = false;\n\n /** Asks for the stream again, or throws `cause` once out of retries. */\n async function resume(cause: unknown, delayMs?: number): Promise<boolean> {\n for (;;) {\n if (signal?.aborted) throw signal.reason;\n if (failures++ >= maxRetries) throw cause;\n const wait =\n delayMs ?? Math.min(maxDelayMs, initialDelayMs * 2 ** (failures - 1));\n if (wait > 0) await sleep(wait, signal);\n try {\n const next = await reopen(lastEventId, received);\n if (next) reader = events(next);\n return next !== undefined;\n } catch (error) {\n if (\n signal?.aborted ||\n (error instanceof WowProblemError && error.retry === 'none')\n ) {\n throw error;\n }\n delayMs = (error as WowProblemError).retryAfterMs;\n cause = error;\n }\n }\n }\n\n return new ReadableStream<Positioned<T>>({\n async pull(controller) {\n for (;;) {\n let stop: unknown;\n let delayMs: number | undefined;\n try {\n const next = await reader.read();\n if (next.done) {\n // Every stream ends with `end`: one without was cut off.\n stop = new TypeError('The query stream was cut off.');\n } else {\n const { event, id, data } = next.value;\n if (event === ROW_EVENT || event === UNNAMED_EVENT) {\n if (id) lastEventId = id;\n received++;\n failures = 0;\n controller.enqueue(\n id ? { row: data as T, position: id } : { row: data as T },\n );\n return;\n }\n if (event === END_EVENT) {\n const end = data as StreamEnd;\n if (end.reason === COMPLETE) {\n controller.close();\n return;\n }\n stop = new TypeError(`The query stream ended: ${end.reason}.`);\n if (!end.resumable) throw stop;\n if (end.reason === HOLD_EXPIRED) delayMs = 0;\n } else if (event === ERROR_EVENT) {\n const error = problemOf(data);\n if (error.retry === 'none') throw error;\n stop = error;\n delayMs = error.retryAfterMs;\n } else {\n continue;\n }\n }\n } catch (error) {\n if (error === stop || error instanceof WowProblemError) throw error;\n stop = error;\n }\n if (cancelled) return;\n // Only a stream read from the start, or whose records have positions, can be asked for again.\n if (signal?.aborted) throw signal.reason;\n if (lastEventId === undefined && received > 0) throw stop;\n if (!(await resume(stop, delayMs))) {\n controller.close();\n return;\n }\n }\n },\n cancel(reason) {\n cancelled = true;\n return reader.cancel(reason);\n },\n });\n}\n"],"mappings":";;;;;AAyBA,IAAMA,IAAY,OAGZC,IAAc,SAGdC,IAAY,OAGZC,IAAgB;AAYtB,SAAgBC,EAAkB,GAA4C;CAC5E,OAAOC,EACLC,EAAwBC,CAAQ,CAClC,CAAC,CAAC,YACA,IAAI,gBAGF,EACA,UAAU,GAAO,GAAY;EAC3B,EAAW,QAAQC,EAAM,IAAI;CAC/B,EACF,CAAC,CACH;AACF;AAyDA,IAAMC,IAAgC,gBAChCC,IAA4B;AAGlC,SAASC,EAAM,GAAY,GAAqC;CAC9D,OAAO,IAAI,SAAS,GAAS,MAAW;EACtC,IAAMC,UAAc;GAElB,AADA,aAAaC,CAAK,GAClBC,EAAOC,GAAQ,MAAM;EACvB,GACMF,IAAQ,iBAAiB;GAE7B,AADAE,GAAQ,oBAAoB,SAASH,CAAK,GAC1CI,EAAQ;EACV,GAAGC,CAAE;EACL,GAAQ,iBAAiB,SAASL,CAAK;CACzC,CAAC;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
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../frameworkErrors.cjs"),t=require("../wire.cjs");function n(n,r={}){let{context:i,name:a}=n.type,o=r.status??t.CommandResultStatus.SUCCEEDED,s=r.commandId??`command-1`;return{format:1,commandId:s,requestId:`request-1`,correlationId:s,ref:n,hop:{stage:t.Stage.COMMITTED,context:i},function:{kind:t.FunctionKind.COMMAND,context:i,processor:a,name:`Command`},status:o,version:1,duplicate:!1,error:o===t.CommandResultStatus.SUCCEEDED?null:{code:o===t.CommandResultStatus.REJECTED?e.FrameworkErrorCodes.COMMAND_REFUSED:e.FrameworkErrorCodes.COMMAND_FAILED,message:`The command was ${o.toLowerCase()}.`},results:{},derived:[],signalTime:0,...r}}var r={400:`Bad Request`,401:`Unauthorized`,403:`Forbidden`,404:`Not Found`,409:`Conflict`,410:`Gone`,412:`Precondition Failed`,429:`Too Many Requests`,500:`Internal Server Error`,503:`Service Unavailable`,504:`Gateway Timeout`};function i(e,t,n={}){return{type:t===void 0?`about:blank`:`urn:wow:error:${t}`,title:r[e]??`HTTP ${e}`,status:e,...t===void 0?{}:{code:t},...n}}function a(e,t={}){let{extensions:n,...r}=e,i=new Headers(t.headers);return i.set(`Content-Type`,`application/problem+json`),new Response(JSON.stringify({...n,...r}),{...t,status:e.status,headers:i})}function o(e,t,n={}){return{tenantId:e.tenantId,aggregateId:e.id,version:1,ownerId:null,spaceId:null,deleted:!1,tags:{},firstEventTime:0,lastEventTime:0,operator:null,firstOperator:null,schedules:{},state:t,...n}}exports.commandResultOf=n,exports.problemOf=i,exports.problemResponse=a,exports.snapshotOf=o;
|
|
2
|
+
//# sourceMappingURL=wire.cjs.map
|