@sincpro/client-framework 2.2.0 → 2.4.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/AGENTS.md +9 -6
- package/MANIFESTO.md +2 -1
- package/README.md +100 -5
- package/dist/client/domain/selection.d.ts +84 -0
- package/dist/client/domain/selection.js +92 -0
- package/dist/client/index.d.ts +5 -2
- package/dist/client/index.js +5 -2
- package/dist/client/services/selection.d.ts +32 -0
- package/dist/client/services/selection.js +39 -0
- package/dist/core/domain/batch.d.ts +39 -0
- package/dist/core/domain/batch.js +1 -0
- package/dist/core/domain/services.d.ts +9 -0
- package/dist/core/domain/services.js +22 -0
- package/dist/core/entrypoint/batch.d.ts +47 -0
- package/dist/core/entrypoint/batch.js +65 -0
- package/dist/core/entrypoint/bounded-context.d.ts +25 -10
- package/dist/core/entrypoint/bounded-context.js +10 -7
- package/dist/core/index.d.ts +6 -3
- package/dist/core/index.js +1 -11
- package/dist/core/services/event-handlers.d.ts +14 -3
- package/dist/core/services/event-handlers.js +7 -5
- package/dist/event_driven/entrypoint/subscriber.d.ts +7 -4
- package/dist/event_driven/entrypoint/subscriber.js +2 -2
- package/package.json +1 -1
package/AGENTS.md
CHANGED
|
@@ -70,12 +70,15 @@ module has only the layers it needs, and says what it offers in its own `index.t
|
|
|
70
70
|
- **A service is a singleton of its generation.** What a method writes on `this` lands on the
|
|
71
71
|
instance, shared by the next call, the call beside it and every `scoped` variant — as in
|
|
72
72
|
sincpro_framework. What belongs to one request goes in its arguments or its context.
|
|
73
|
-
- **A service's name is the framework's, taken at registration.**
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
`
|
|
77
|
-
|
|
78
|
-
|
|
73
|
+
- **A service's name is the framework's, taken at registration.** The registration may give it
|
|
74
|
+
(`feature(dto, { name })`, `appService`, `handler` — a string literal, so a minifier never
|
|
75
|
+
touches it); else a standard decorator hands it the class's name as the code wrote it
|
|
76
|
+
(`context.name`, untouched by a minifier); otherwise the class's `name` — so a production build
|
|
77
|
+
keeps class names (`keep_classnames`, `keepNames`) or names each service (Next.js: legacy
|
|
78
|
+
decorators, no `keepNames`). `class Cancel` gives `project/Cancel`, identity `project.Cancel`.
|
|
79
|
+
Nothing on a service declares it, and `{ name }` stays optional: without it every form —
|
|
80
|
+
standard decorator, legacy decorator, a call — behaves as before. Commands and events route by
|
|
81
|
+
exact constructor identity — a generated one by its identity or wire name.
|
|
79
82
|
- **An event's name is declared; a Command's identity is the framework's.** `static eventName` is
|
|
80
83
|
required and dotted (`<context>.<aggregate>.vN.<fact>`); `name` is reserved for it. A Command's
|
|
81
84
|
identity is given when a bounded context registers it — `<context>.<Command>`, the backend's
|
package/MANIFESTO.md
CHANGED
|
@@ -54,7 +54,8 @@ server-side render, in a script and in a test, unchanged.**
|
|
|
54
54
|
wire — with its REST and JSON-RPC adapters (a platform adds gRPC or its own); the `Transport`
|
|
55
55
|
port and its implementations (REST, memory), `entity()` with
|
|
56
56
|
typed commands and answers, the service's client contract, model definitions read once from
|
|
57
|
-
the server and the server's `Problem
|
|
57
|
+
the server and the server's `Problem`; which records were chosen (`Selection`) and a step run
|
|
58
|
+
once per record with one outcome each (`runBatch`, the backend's `BatchResult`).
|
|
58
59
|
7. **The values of the wire.** How every value travels, as the backend writes it — a decimal as
|
|
59
60
|
text, a money with its currency, a day that is never an instant, bytes tagged, ids as UUID v7 —
|
|
60
61
|
and the exact arithmetic a client needs on them (`Decimal`, `Money`). Only the wire form and
|
package/README.md
CHANGED
|
@@ -79,10 +79,12 @@ only). A Response may be a class, a plain object, a page, a primitive or `void`.
|
|
|
79
79
|
the bases every dependency typed on `this` — the backend's `class Feature(_Feature,
|
|
80
80
|
DependencyContextType)` —; `addDependency` supplies them, and reading one never supplied fails.
|
|
81
81
|
A replacement names what it replaces: `addDependency(name, next, { replaces: previous })`.
|
|
82
|
-
- **The framework names a service when it registers it**:
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
esbuild and Vite)
|
|
82
|
+
- **The framework names a service when it registers it**: the name the registration gives
|
|
83
|
+
(`{ name: "Total" }`), else its class, as the code wrote it — a standard decorator hands the
|
|
84
|
+
name over before any minifier runs —, else the class's `name`. A production build keeps class
|
|
85
|
+
names (`keep_classnames` in Metro's minifier, `keepNames` in esbuild and Vite) or names each
|
|
86
|
+
service ([Names that survive a minifier](#names-that-survive-a-minifier)). Nothing on the class
|
|
87
|
+
declares it.
|
|
86
88
|
- **One service, N DTOs.** `feature([CommandX, EventY])` registers one service for each, as the
|
|
87
89
|
backend's `DTORegistration`; a DTO still has one service, across both layers, dispatched by
|
|
88
90
|
its exact class — or, generated, by its identity.
|
|
@@ -106,6 +108,53 @@ called: `salesBoundedContext.feature(CommandTotal)(Total)`. No DI library and no
|
|
|
106
108
|
where it is written; `services/index.ts` imports each file, so all are registered before anyone
|
|
107
109
|
executes.
|
|
108
110
|
|
|
111
|
+
### Names that survive a minifier
|
|
112
|
+
|
|
113
|
+
A service's name is what its spans, logs and reports say (`cursos/LeerCursos`), and what its
|
|
114
|
+
bounded context keys it by; an event handler's is also the consumer a stored queue acknowledges
|
|
115
|
+
(`app/OnCursoCreado`). Taken from the class, it is only as stable as the build: a production
|
|
116
|
+
minifier renames classes, so the same service reads `cursos/c5`, and two services renamed alike
|
|
117
|
+
collide — `Service name already registered: l` — and the application does not start.
|
|
118
|
+
|
|
119
|
+
A standard decorator hands over the name as written (`context.name`), and Vite and Metro can keep
|
|
120
|
+
class names. Next.js can do neither: its compiler lowers standard decorators in a version this
|
|
121
|
+
package does not read, so an application on Next uses legacy decorators
|
|
122
|
+
(`experimentalDecorators`), which hand over no name, and it has no `keepNames`. There — or
|
|
123
|
+
anywhere a build renames classes — the registration gives the name, a string literal no minifier
|
|
124
|
+
touches:
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
@cursosBoundedContext.feature(CommandLeerCursos, { name: "LeerCursos" })
|
|
128
|
+
class LeerCursos extends Feature<CommandLeerCursos, ResponseCursos> { … }
|
|
129
|
+
|
|
130
|
+
@cursosBoundedContext.appService(CommandInscribir, { name: "Inscribir" })
|
|
131
|
+
class Inscribir extends ApplicationService<CommandInscribir, ResponseInscripcion> { … }
|
|
132
|
+
|
|
133
|
+
@appSubscriber.handler([CursoCreado], { name: "AvisarCursoCreado" })
|
|
134
|
+
class AvisarCursoCreado extends EventHandler<CursoCreado> { … }
|
|
135
|
+
|
|
136
|
+
class CommandLeerCursos extends Command<ResponseCursos> {
|
|
137
|
+
static readonly commandName = "cursos.CommandLeerCursos"; // its identity, likewise
|
|
138
|
+
}
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
- **Precedence:** `{ name }`, then a standard decorator's `context.name`, then the class's
|
|
142
|
+
`name`. Without `{ name }` nothing changes, in any of the three forms (standard decorator,
|
|
143
|
+
legacy decorator, a call).
|
|
144
|
+
- **It is a class's name:** an identifier (`LeerCursos`, `AñadirCurso`) — never `cursos/leer` or
|
|
145
|
+
`leer cursos` —, unique in its bounded context or subscriber, as a class's is; refused where the
|
|
146
|
+
registration is written otherwise. With `replaces`, the replacement says the name it replaced.
|
|
147
|
+
- **The same in every realm.** It is a string in the module, nothing read from the platform: a
|
|
148
|
+
browser and a server rendering the same modules (SSR, React server components) name the
|
|
149
|
+
service alike.
|
|
150
|
+
- **A Command's identity comes from its class's name too** (`<context>.<Command>`): a Command
|
|
151
|
+
that must keep it under a minifier — two renamed alike collide as
|
|
152
|
+
`Command identity already registered` — declares `static commandName`. An event's wire name is
|
|
153
|
+
always declared (`eventName`).
|
|
154
|
+
|
|
155
|
+
The tests lower legacy decorators with TypeScript and minify with Vite's own minifier, and read
|
|
156
|
+
the names back from the spans.
|
|
157
|
+
|
|
109
158
|
### Replacing a service
|
|
110
159
|
|
|
111
160
|
An application takes the place of a service a module registered, as the backend's `replaces=`:
|
|
@@ -260,7 +309,8 @@ await appSubscriber.receive(message); // CloudEvents, structured or { headers, b
|
|
|
260
309
|
the ones that do not have it yet.
|
|
261
310
|
- **A handler** runs in the pipeline of a use case, in its own layer (`event_handler`): its span
|
|
262
311
|
`<owner>/<Handler>`, `this.logger`, `this.execution.causationId` (the message's id), and what it
|
|
263
|
-
executes is its child.
|
|
312
|
+
executes is its child. `<owner>/<Handler>` is the key a stored queue keeps: a build that renames
|
|
313
|
+
classes names it (`handler([SalePaid], { name: "OnSalePaid" })`). A handler takes N events: its type is their union, and TypeScript checks
|
|
264
314
|
it accepts every event listed.
|
|
265
315
|
- **A Command** is executed by the one bounded context that registered it, continuing the
|
|
266
316
|
message's flow — **only when declared** (`commands`). A bus never hands all its Commands to
|
|
@@ -731,6 +781,51 @@ history — is each reader's to decide. A transport given `changes` announces th
|
|
|
731
781
|
a transport that must not be heard), and a platform's own adapter wraps its `send` in
|
|
732
782
|
`announced(feed, method, route, body, send)`.
|
|
733
783
|
|
|
784
|
+
### Acting on many records
|
|
785
|
+
|
|
786
|
+
What a person chose — or a script found — is a `Selection`: a value, plain data, never a store.
|
|
787
|
+
THESE records by their keys (`chosen(keys)`), or EVERY ONE a question matches but some
|
|
788
|
+
(`allMatching(question, total)`, then `toggled` unticks one). `criteriaOf` is the one question
|
|
789
|
+
that asks for exactly them; `keysOf` reads their keys when someone needs them, as one page of
|
|
790
|
+
references, and refuses past a ceiling (`SelectionTooLarge`) instead of answering a part.
|
|
791
|
+
|
|
792
|
+
```ts
|
|
793
|
+
const recipients = toggled(
|
|
794
|
+
allMatching({ field: "company", operator: "=", value: "SINCPRO" }, 37),
|
|
795
|
+
"C-9",
|
|
796
|
+
);
|
|
797
|
+
sizeOf(recipients); // 36
|
|
798
|
+
const keys = await keysOf(recipients, {
|
|
799
|
+
transport,
|
|
800
|
+
route: "/contacts",
|
|
801
|
+
identity: "id",
|
|
802
|
+
limit: 200,
|
|
803
|
+
});
|
|
804
|
+
```
|
|
805
|
+
|
|
806
|
+
`runBatch` is `for rec in self:` — a step once per item, one outcome per item, a failure that
|
|
807
|
+
item's and never the batch's. The step is any work for one item; through a bounded context each
|
|
808
|
+
item is its own use case (span, context, error handling):
|
|
809
|
+
|
|
810
|
+
```ts
|
|
811
|
+
const result = await runBatch(
|
|
812
|
+
keys,
|
|
813
|
+
(key, { signal }) =>
|
|
814
|
+
billingBoundedContext.execute(new CommandConfirmInvoice(key), { signal }),
|
|
815
|
+
{
|
|
816
|
+
concurrency: 1,
|
|
817
|
+
signal,
|
|
818
|
+
onOutcome: (outcome, { settled, total }) => progress(settled, total),
|
|
819
|
+
},
|
|
820
|
+
);
|
|
821
|
+
result.outcomes; // [done F-1, failed F-7 (conflict: ALREADY_CANCELLED), done F-9]
|
|
822
|
+
```
|
|
823
|
+
|
|
824
|
+
In order by default; `concurrency` runs more at once, the outcomes still in the items' order.
|
|
825
|
+
`stopOnFailure` starts nothing after a failure; a cancelled batch skips what had not started and
|
|
826
|
+
hands its signal to what runs. `BatchResult` is sincpro_framework's (#185, «per index, the answer
|
|
827
|
+
or the problem»): a batch the server runs at once, when the backend has one, answers the same.
|
|
828
|
+
|
|
734
829
|
### Writing an adapter for another wire
|
|
735
830
|
|
|
736
831
|
An adapter is one function: read the operation's binding for its wire, send the input, answer the
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { AnyRecord, Expression } from "@sincpro/criteria";
|
|
2
|
+
/**
|
|
3
|
+
* Which records of one entity a person — or a script — chose: THESE, by their keys, or EVERY ONE a
|
|
4
|
+
* question matches («the 37 contacts of SINCPRO»), but these.
|
|
5
|
+
*
|
|
6
|
+
* chosen(["F-1", "F-7"]) these two
|
|
7
|
+
* allMatching(overdue, 187) the 187 the server counted for `overdue`
|
|
8
|
+
* toggled(allMatching(overdue, 187), "F-9") all 187 but F-9: 186
|
|
9
|
+
*
|
|
10
|
+
* Context: acting on many records — confirming three invoices, paying the months ticked, adding
|
|
11
|
+
* every contact of a company to a mail, a script closing what is overdue — is the same on every
|
|
12
|
+
* platform, and each one kept it its own way: a list held the keys of its page in its state, the
|
|
13
|
+
* workspace heard references, and «every one that matches» could be drawn but not held. It is a
|
|
14
|
+
* VALUE here — plain data, never a store —, so it crosses whatever a platform puts it through: a
|
|
15
|
+
* screen's state, a chooser's answer, a link.
|
|
16
|
+
*
|
|
17
|
+
* Two forms, because a person chooses in two ways. Ticking chooses keys; «all that match» chooses
|
|
18
|
+
* a question, whose records are the server's to count and may be millions — they are never
|
|
19
|
+
* brought here to be chosen (`keysOf` reads them, with a ceiling, when someone needs them).
|
|
20
|
+
*/
|
|
21
|
+
export type Selection<T = AnyRecord> = ChosenKeys | AllMatching<T>;
|
|
22
|
+
/** These records, by their keys, in the order they were chosen. */
|
|
23
|
+
export type ChosenKeys = {
|
|
24
|
+
readonly by: "keys";
|
|
25
|
+
readonly keys: readonly string[];
|
|
26
|
+
};
|
|
27
|
+
/** Every record the question matches, but `except`. `total` is how many the server counted for
|
|
28
|
+
* the question — `null` when it did not say. */
|
|
29
|
+
export type AllMatching<T = AnyRecord> = {
|
|
30
|
+
readonly by: "matching";
|
|
31
|
+
/** The question; `undefined` is every record of the entity. */
|
|
32
|
+
readonly matching: Expression<T> | undefined;
|
|
33
|
+
readonly total: number | null;
|
|
34
|
+
readonly except: readonly string[];
|
|
35
|
+
};
|
|
36
|
+
/** These keys, each once, in the order given. */
|
|
37
|
+
export declare function chosen(keys: Iterable<string>): ChosenKeys;
|
|
38
|
+
/** No record. */
|
|
39
|
+
export declare const NOTHING_CHOSEN: ChosenKeys;
|
|
40
|
+
/** Every record `matching` asks for — `total` as the server counted it. */
|
|
41
|
+
export declare function allMatching<T = AnyRecord>(matching: Expression<T> | undefined, total?: number | null): AllMatching<T>;
|
|
42
|
+
/** Whether the record of `key` is among the chosen. */
|
|
43
|
+
export declare function isChosen<T>(selection: Selection<T>, key: string): boolean;
|
|
44
|
+
/**
|
|
45
|
+
* The same choice with `key` flipped: added if it was not chosen, taken out if it was. Out of an
|
|
46
|
+
* «all that match», a key is an exception — what Gmail does when one row is unticked after
|
|
47
|
+
* «select all».
|
|
48
|
+
*/
|
|
49
|
+
export declare function toggled<T>(selection: Selection<T>, key: string): Selection<T>;
|
|
50
|
+
/** How many records are chosen; `null` when «all that match» has no count from the server. */
|
|
51
|
+
export declare function sizeOf<T>(selection: Selection<T>): number | null;
|
|
52
|
+
/** Whether nothing is chosen — an «all that match» of unknown size is not known to be empty. */
|
|
53
|
+
export declare function isEmpty<T>(selection: Selection<T>): boolean;
|
|
54
|
+
/**
|
|
55
|
+
* The one question that asks for exactly the chosen records — what a reading or a server batch
|
|
56
|
+
* sends. `identity` is the field the keys are of (the model's `get_id` or `identity`).
|
|
57
|
+
*
|
|
58
|
+
* criteriaOf(chosen(["F-1", "F-7"]), "number")
|
|
59
|
+
* -> { field: "number", operator: "in", value: ["F-1", "F-7"] }
|
|
60
|
+
* criteriaOf(toggled(allMatching(overdue), "F-9"), "number")
|
|
61
|
+
* -> { all: [overdue, { field: "number", operator: "not in", value: ["F-9"] }] }
|
|
62
|
+
*
|
|
63
|
+
* No key chosen asks for no record (`in []`); «all that match» with no question and no exception
|
|
64
|
+
* is every record (`undefined`, no condition).
|
|
65
|
+
*/
|
|
66
|
+
export declare function criteriaOf<T>(selection: Selection<T>, identity: string): Expression<T> | undefined;
|
|
67
|
+
/**
|
|
68
|
+
* A selection asked for more keys than its caller takes at once — «all that match» counted 5 000
|
|
69
|
+
* where a mail takes 200. Declared `invalid`: the caller narrows the question or acts on the server
|
|
70
|
+
* with it, never on a part of it chosen at random.
|
|
71
|
+
*/
|
|
72
|
+
export declare class SelectionTooLarge extends Error {
|
|
73
|
+
/** How many the caller takes. */
|
|
74
|
+
readonly limit: number;
|
|
75
|
+
/** How many were chosen, when known. */
|
|
76
|
+
readonly size: number | null;
|
|
77
|
+
static readonly failureKind = "invalid";
|
|
78
|
+
readonly reason = "SELECTION_TOO_LARGE";
|
|
79
|
+
constructor(
|
|
80
|
+
/** How many the caller takes. */
|
|
81
|
+
limit: number,
|
|
82
|
+
/** How many were chosen, when known. */
|
|
83
|
+
size: number | null);
|
|
84
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/** These keys, each once, in the order given. */
|
|
2
|
+
export function chosen(keys) {
|
|
3
|
+
return Object.freeze({ by: "keys", keys: Object.freeze([...new Set(keys)]) });
|
|
4
|
+
}
|
|
5
|
+
/** No record. */
|
|
6
|
+
export const NOTHING_CHOSEN = chosen([]);
|
|
7
|
+
/** Every record `matching` asks for — `total` as the server counted it. */
|
|
8
|
+
export function allMatching(matching, total = null) {
|
|
9
|
+
return Object.freeze({ by: "matching", matching, total, except: Object.freeze([]) });
|
|
10
|
+
}
|
|
11
|
+
/** Whether the record of `key` is among the chosen. */
|
|
12
|
+
export function isChosen(selection, key) {
|
|
13
|
+
return selection.by === "keys"
|
|
14
|
+
? selection.keys.includes(key)
|
|
15
|
+
: !selection.except.includes(key);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The same choice with `key` flipped: added if it was not chosen, taken out if it was. Out of an
|
|
19
|
+
* «all that match», a key is an exception — what Gmail does when one row is unticked after
|
|
20
|
+
* «select all».
|
|
21
|
+
*/
|
|
22
|
+
export function toggled(selection, key) {
|
|
23
|
+
if (selection.by === "keys")
|
|
24
|
+
return chosen(selection.keys.includes(key)
|
|
25
|
+
? selection.keys.filter((one) => one !== key)
|
|
26
|
+
: [...selection.keys, key]);
|
|
27
|
+
const except = selection.except.includes(key)
|
|
28
|
+
? selection.except.filter((one) => one !== key)
|
|
29
|
+
: [...selection.except, key];
|
|
30
|
+
return Object.freeze({ ...selection, except: Object.freeze(except) });
|
|
31
|
+
}
|
|
32
|
+
/** How many records are chosen; `null` when «all that match» has no count from the server. */
|
|
33
|
+
export function sizeOf(selection) {
|
|
34
|
+
if (selection.by === "keys")
|
|
35
|
+
return selection.keys.length;
|
|
36
|
+
return selection.total === null
|
|
37
|
+
? null
|
|
38
|
+
: Math.max(0, selection.total - selection.except.length);
|
|
39
|
+
}
|
|
40
|
+
/** Whether nothing is chosen — an «all that match» of unknown size is not known to be empty. */
|
|
41
|
+
export function isEmpty(selection) {
|
|
42
|
+
return sizeOf(selection) === 0;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The one question that asks for exactly the chosen records — what a reading or a server batch
|
|
46
|
+
* sends. `identity` is the field the keys are of (the model's `get_id` or `identity`).
|
|
47
|
+
*
|
|
48
|
+
* criteriaOf(chosen(["F-1", "F-7"]), "number")
|
|
49
|
+
* -> { field: "number", operator: "in", value: ["F-1", "F-7"] }
|
|
50
|
+
* criteriaOf(toggled(allMatching(overdue), "F-9"), "number")
|
|
51
|
+
* -> { all: [overdue, { field: "number", operator: "not in", value: ["F-9"] }] }
|
|
52
|
+
*
|
|
53
|
+
* No key chosen asks for no record (`in []`); «all that match» with no question and no exception
|
|
54
|
+
* is every record (`undefined`, no condition).
|
|
55
|
+
*/
|
|
56
|
+
export function criteriaOf(selection, identity) {
|
|
57
|
+
if (selection.by === "keys")
|
|
58
|
+
return { field: identity, operator: "in", value: [...selection.keys] };
|
|
59
|
+
if (selection.except.length === 0)
|
|
60
|
+
return selection.matching;
|
|
61
|
+
const except = {
|
|
62
|
+
field: identity,
|
|
63
|
+
operator: "not in",
|
|
64
|
+
value: [...selection.except],
|
|
65
|
+
};
|
|
66
|
+
return selection.matching === undefined
|
|
67
|
+
? except
|
|
68
|
+
: { all: [selection.matching, except] };
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* A selection asked for more keys than its caller takes at once — «all that match» counted 5 000
|
|
72
|
+
* where a mail takes 200. Declared `invalid`: the caller narrows the question or acts on the server
|
|
73
|
+
* with it, never on a part of it chosen at random.
|
|
74
|
+
*/
|
|
75
|
+
export class SelectionTooLarge extends Error {
|
|
76
|
+
limit;
|
|
77
|
+
size;
|
|
78
|
+
static failureKind = "invalid";
|
|
79
|
+
reason = "SELECTION_TOO_LARGE";
|
|
80
|
+
constructor(
|
|
81
|
+
/** How many the caller takes. */
|
|
82
|
+
limit,
|
|
83
|
+
/** How many were chosen, when known. */
|
|
84
|
+
size) {
|
|
85
|
+
super(size === null
|
|
86
|
+
? `more than ${limit} records chosen`
|
|
87
|
+
: `${size} records chosen, ${limit} at most`);
|
|
88
|
+
this.limit = limit;
|
|
89
|
+
this.size = size;
|
|
90
|
+
this.name = "SelectionTooLarge";
|
|
91
|
+
}
|
|
92
|
+
}
|
package/dist/client/index.d.ts
CHANGED
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
* commands, the service's client contract, and how a run's trace and context reach the wire.
|
|
4
4
|
*
|
|
5
5
|
* domain/ the port and the server's words: `Transport`, `TransportError`, `entity()`, the
|
|
6
|
-
* client contract, what a write changed (`Change`, `ChangeFeed`)
|
|
6
|
+
* client contract, what a write changed (`Change`, `ChangeFeed`), which records
|
|
7
|
+
* were chosen (`Selection`)
|
|
7
8
|
* adapters/ REST, memory, and Parquet (optional entry `./parquet`)
|
|
8
9
|
* services/ discovery, retry keys, propagation (`traceparent`, `sincpro-context`), the
|
|
9
|
-
* process's change feed (`processChanges`)
|
|
10
|
+
* process's change feed (`processChanges`), the keys of a selection (`keysOf`)
|
|
10
11
|
*/
|
|
11
12
|
export { JsonRpcError, jsonRpcOperations, type JsonRpcOptions, } from "./adapters/json-rpc.js";
|
|
12
13
|
export { type AssignableOptions, assignableValues, type MemoryOptions, type MemoryTable, memoryTransport, } from "./adapters/memory.js";
|
|
@@ -16,8 +17,10 @@ export { type Change, type ChangeFeed, changeOf, } from "./domain/changes.js";
|
|
|
16
17
|
export { type ClientContract, entityKeyOf, eventMetasOf, kindOf, metasOf, versionsOf, } from "./domain/contract.js";
|
|
17
18
|
export { bodyFor, type CommandAnswers, type CommandBodies, type CommandRoute, type Entity, entity, type EntityRoutes, type ExportFormat, exportRoute, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, type ResourceRef, SCOPE_NAME_PARAM, SCOPE_PARAM, scopeNameOf, scopeOfRef, startingValuesOf, type SummaryFields, type SummaryPart, TRAIL_PARAM, WITH_PARAM, type WriteRoute, writeRoute, } from "./domain/entity.js";
|
|
18
19
|
export { OperationNotPublished, type OperationOptions, type OperationTransport, type RemoteOperation, } from "./domain/operation.js";
|
|
20
|
+
export { type AllMatching, allMatching, chosen, type ChosenKeys, criteriaOf, isChosen, isEmpty, NOTHING_CHOSEN, type Selection, SelectionTooLarge, sizeOf, toggled, } from "./domain/selection.js";
|
|
19
21
|
export { type CallOptions, type Decoder, type Download, downloadRoute, type Draft, markedAs, type Method, type One, readRoute, SCREENS, type SendOptions, type Transport, TransportError, } from "./domain/transport.js";
|
|
20
22
|
export { announced, changeFeed, processChanges, } from "./services/changes.js";
|
|
21
23
|
export { guardedTransport } from "./services/guarded.js";
|
|
22
24
|
export { bindable, bindableOperations, bindableTransport, bindOperations, bindTransport, headersOf, } from "./services/propagation.js";
|
|
23
25
|
export { type RetryKeys, retryKeys, unanswered, } from "./services/retry.js";
|
|
26
|
+
export { keysOf } from "./services/selection.js";
|
package/dist/client/index.js
CHANGED
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
* commands, the service's client contract, and how a run's trace and context reach the wire.
|
|
4
4
|
*
|
|
5
5
|
* domain/ the port and the server's words: `Transport`, `TransportError`, `entity()`, the
|
|
6
|
-
* client contract, what a write changed (`Change`, `ChangeFeed`)
|
|
6
|
+
* client contract, what a write changed (`Change`, `ChangeFeed`), which records
|
|
7
|
+
* were chosen (`Selection`)
|
|
7
8
|
* adapters/ REST, memory, and Parquet (optional entry `./parquet`)
|
|
8
9
|
* services/ discovery, retry keys, propagation (`traceparent`, `sincpro-context`), the
|
|
9
|
-
* process's change feed (`processChanges`)
|
|
10
|
+
* process's change feed (`processChanges`), the keys of a selection (`keysOf`)
|
|
10
11
|
*/
|
|
11
12
|
export { JsonRpcError, jsonRpcOperations, } from "./adapters/json-rpc.js";
|
|
12
13
|
export { assignableValues, memoryTransport, } from "./adapters/memory.js";
|
|
@@ -16,8 +17,10 @@ export { changeOf, } from "./domain/changes.js";
|
|
|
16
17
|
export { entityKeyOf, eventMetasOf, kindOf, metasOf, versionsOf, } from "./domain/contract.js";
|
|
17
18
|
export { bodyFor, entity, exportRoute, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, SCOPE_NAME_PARAM, SCOPE_PARAM, scopeNameOf, scopeOfRef, startingValuesOf, TRAIL_PARAM, WITH_PARAM, writeRoute, } from "./domain/entity.js";
|
|
18
19
|
export { OperationNotPublished, } from "./domain/operation.js";
|
|
20
|
+
export { allMatching, chosen, criteriaOf, isChosen, isEmpty, NOTHING_CHOSEN, SelectionTooLarge, sizeOf, toggled, } from "./domain/selection.js";
|
|
19
21
|
export { downloadRoute, markedAs, readRoute, SCREENS, TransportError, } from "./domain/transport.js";
|
|
20
22
|
export { announced, changeFeed, processChanges, } from "./services/changes.js";
|
|
21
23
|
export { guardedTransport } from "./services/guarded.js";
|
|
22
24
|
export { bindable, bindableOperations, bindableTransport, bindOperations, bindTransport, headersOf, } from "./services/propagation.js";
|
|
23
25
|
export { retryKeys, unanswered, } from "./services/retry.js";
|
|
26
|
+
export { keysOf } from "./services/selection.js";
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type Selection } from "../domain/selection.js";
|
|
2
|
+
import type { Transport } from "../domain/transport.js";
|
|
3
|
+
/**
|
|
4
|
+
* The keys of the chosen records — what a Command run once per record needs, what a many2many
|
|
5
|
+
* stores —, never more than `limit`.
|
|
6
|
+
*
|
|
7
|
+
* await keysOf(chosen(["F-1", "F-7"]), { transport, route: "/invoices", identity: "number", limit: 200 })
|
|
8
|
+
* -> ["F-1", "F-7"]
|
|
9
|
+
* await keysOf(allMatching(ofSincpro, 37), { …, identity: "id", limit: 200 })
|
|
10
|
+
* -> the 37 keys, read as one page of references
|
|
11
|
+
*
|
|
12
|
+
* Context: «all that match» is a question, and its records may be millions: they are read only
|
|
13
|
+
* when someone needs their keys, as references (the identity alone, `specification`), one page
|
|
14
|
+
* of `limit + 1`. Past the ceiling it refuses (`SelectionTooLarge`) instead of answering a part:
|
|
15
|
+
* running a Command on 200 of 5 000 chosen, with nothing said, is worse than running none.
|
|
16
|
+
*
|
|
17
|
+
* 1. A size already known past the ceiling is refused before anything is read.
|
|
18
|
+
* 2. Keys are in hand: they are the answer.
|
|
19
|
+
* 3. Else one page of references for exactly the chosen records (`criteriaOf`), one more than the
|
|
20
|
+
* ceiling — the one more says the ceiling was passed.
|
|
21
|
+
* Final: the keys, in the order the server answered them.
|
|
22
|
+
*/
|
|
23
|
+
export declare function keysOf<T>(selection: Selection<T>, options: {
|
|
24
|
+
transport: Transport;
|
|
25
|
+
/** Where the entity is listed: `listRoute(entity.list)`. */
|
|
26
|
+
route: string;
|
|
27
|
+
/** The field the keys are of: the model's `get_id`, else its `identity`. */
|
|
28
|
+
identity: string;
|
|
29
|
+
/** The most keys the caller takes at once. */
|
|
30
|
+
limit: number;
|
|
31
|
+
signal?: AbortSignal;
|
|
32
|
+
}): Promise<readonly string[]>;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { criteriaOf, SelectionTooLarge, sizeOf, } from "../domain/selection.js";
|
|
2
|
+
/**
|
|
3
|
+
* The keys of the chosen records — what a Command run once per record needs, what a many2many
|
|
4
|
+
* stores —, never more than `limit`.
|
|
5
|
+
*
|
|
6
|
+
* await keysOf(chosen(["F-1", "F-7"]), { transport, route: "/invoices", identity: "number", limit: 200 })
|
|
7
|
+
* -> ["F-1", "F-7"]
|
|
8
|
+
* await keysOf(allMatching(ofSincpro, 37), { …, identity: "id", limit: 200 })
|
|
9
|
+
* -> the 37 keys, read as one page of references
|
|
10
|
+
*
|
|
11
|
+
* Context: «all that match» is a question, and its records may be millions: they are read only
|
|
12
|
+
* when someone needs their keys, as references (the identity alone, `specification`), one page
|
|
13
|
+
* of `limit + 1`. Past the ceiling it refuses (`SelectionTooLarge`) instead of answering a part:
|
|
14
|
+
* running a Command on 200 of 5 000 chosen, with nothing said, is worse than running none.
|
|
15
|
+
*
|
|
16
|
+
* 1. A size already known past the ceiling is refused before anything is read.
|
|
17
|
+
* 2. Keys are in hand: they are the answer.
|
|
18
|
+
* 3. Else one page of references for exactly the chosen records (`criteriaOf`), one more than the
|
|
19
|
+
* ceiling — the one more says the ceiling was passed.
|
|
20
|
+
* Final: the keys, in the order the server answered them.
|
|
21
|
+
*/
|
|
22
|
+
export async function keysOf(selection, options) {
|
|
23
|
+
const { transport, route, identity, limit, signal } = options;
|
|
24
|
+
const size = sizeOf(selection);
|
|
25
|
+
if (size !== null && size > limit)
|
|
26
|
+
throw new SelectionTooLarge(limit, size);
|
|
27
|
+
if (selection.by === "keys")
|
|
28
|
+
return selection.keys;
|
|
29
|
+
// Read untyped: what comes back is references — the identity alone —, never a `T`.
|
|
30
|
+
const question = criteriaOf(selection, identity);
|
|
31
|
+
const page = await transport.list(route, {
|
|
32
|
+
...(question === undefined ? {} : { selection: question }),
|
|
33
|
+
pagination: { limit: limit + 1 },
|
|
34
|
+
specification: { [identity]: {} },
|
|
35
|
+
}, signal);
|
|
36
|
+
if (page.rows.length > limit)
|
|
37
|
+
throw new SelectionTooLarge(limit, page.count?.value ?? null);
|
|
38
|
+
return page.rows.map((row) => String(row[identity]));
|
|
39
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Failure } from "../../common/failures.js";
|
|
2
|
+
/**
|
|
3
|
+
* What became of one item of a batch: its answer, its failure, or nothing — it never ran.
|
|
4
|
+
*
|
|
5
|
+
* `index` is its place among the items given, whatever order they finished in; `item` is the
|
|
6
|
+
* item itself (a key, a body), so a screen names what failed without looking it up again.
|
|
7
|
+
*/
|
|
8
|
+
export type ItemOutcome<I, R> = {
|
|
9
|
+
readonly index: number;
|
|
10
|
+
readonly item: I;
|
|
11
|
+
readonly status: "done";
|
|
12
|
+
readonly answer: R;
|
|
13
|
+
} | {
|
|
14
|
+
readonly index: number;
|
|
15
|
+
readonly item: I;
|
|
16
|
+
readonly status: "failed";
|
|
17
|
+
/** What kind of failure it was, read once (`failureOf`): what a screen says and decides on. */
|
|
18
|
+
readonly failure: Failure;
|
|
19
|
+
/** What was thrown, as it was. */
|
|
20
|
+
readonly error: unknown;
|
|
21
|
+
} | {
|
|
22
|
+
readonly index: number;
|
|
23
|
+
readonly item: I;
|
|
24
|
+
readonly status: "skipped";
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* One outcome per item, in the items' order — sincpro_framework's `BatchResult` (#185): «per
|
|
28
|
+
* index, the answer or the problem». A batch the client ran one item at a time and one a server
|
|
29
|
+
* ran at once answer the same shape.
|
|
30
|
+
*
|
|
31
|
+
* { outcomes: [done F-1, failed F-7 (conflict), done F-9], done: 2, failed: 1, skipped: 0 }
|
|
32
|
+
*/
|
|
33
|
+
export type BatchResult<I, R> = {
|
|
34
|
+
readonly outcomes: readonly ItemOutcome<I, R>[];
|
|
35
|
+
readonly done: number;
|
|
36
|
+
readonly failed: number;
|
|
37
|
+
/** Never ran: the batch was cancelled, or stopped at a failure (`stopOnFailure`). */
|
|
38
|
+
readonly skipped: number;
|
|
39
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -129,3 +129,12 @@ export declare function handlersWith<D extends object, Context extends object =
|
|
|
129
129
|
};
|
|
130
130
|
/** @internal — what a run finds on `this` that no dependency may take. */
|
|
131
131
|
export declare const RESERVED_MEMBERS: ReadonlySet<string>;
|
|
132
|
+
/**
|
|
133
|
+
* @internal — the name a registration gives its service or event handler, or `undefined` when
|
|
134
|
+
* it gives none (the framework then takes the class's). A string literal: no minifier rewrites
|
|
135
|
+
* it, and every realm that evaluates the module — a browser, a server rendering it — reads the
|
|
136
|
+
* same one.
|
|
137
|
+
*/
|
|
138
|
+
export declare function givenNameOf(options: {
|
|
139
|
+
readonly name?: unknown;
|
|
140
|
+
} | undefined): string | undefined;
|
|
@@ -88,3 +88,25 @@ export const RESERVED_MEMBERS = new Set([
|
|
|
88
88
|
"signal",
|
|
89
89
|
"execution",
|
|
90
90
|
]);
|
|
91
|
+
/**
|
|
92
|
+
* A name given at registration (`{ name }`): it stands where a class's name would, so it is one —
|
|
93
|
+
* an identifier, as `LeerCursos` —, with no `/` or `.` inside the span's `<context>/<Name>`, the
|
|
94
|
+
* use case's `<context>.<Name>` or the consumer a stored queue acknowledges (`<owner>/<Name>`).
|
|
95
|
+
*/
|
|
96
|
+
const SERVICE_NAME = /^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u;
|
|
97
|
+
/**
|
|
98
|
+
* @internal — the name a registration gives its service or event handler, or `undefined` when
|
|
99
|
+
* it gives none (the framework then takes the class's). A string literal: no minifier rewrites
|
|
100
|
+
* it, and every realm that evaluates the module — a browser, a server rendering it — reads the
|
|
101
|
+
* same one.
|
|
102
|
+
*/
|
|
103
|
+
export function givenNameOf(options) {
|
|
104
|
+
const name = options?.name;
|
|
105
|
+
if (name === undefined)
|
|
106
|
+
return undefined;
|
|
107
|
+
if (typeof name !== "string" || !SERVICE_NAME.test(name)) {
|
|
108
|
+
const shown = typeof name === "string" ? JSON.stringify(name) : String(name);
|
|
109
|
+
throw new TypeError(`${shown} is not a service's name: an identifier, as its class would be called (LeerCursos)`);
|
|
110
|
+
}
|
|
111
|
+
return name;
|
|
112
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { BatchResult, ItemOutcome } from "../domain/batch.js";
|
|
2
|
+
/** What a batch's step is handed beside its item. */
|
|
3
|
+
export type BatchStep<I, R> = (item: I, run: {
|
|
4
|
+
/** The item's place among those given. */
|
|
5
|
+
readonly index: number;
|
|
6
|
+
/** The batch's signal: hand it to what the step runs, so cancelling stops the item too. */
|
|
7
|
+
readonly signal: AbortSignal | undefined;
|
|
8
|
+
}) => Promise<R>;
|
|
9
|
+
export type BatchOptions<I, R> = {
|
|
10
|
+
/** How many items run at once. One by default: in order, as `for rec in self`. */
|
|
11
|
+
concurrency?: number;
|
|
12
|
+
/** Cancels the batch: what has not started is skipped, what runs gets the signal. */
|
|
13
|
+
signal?: AbortSignal;
|
|
14
|
+
/** At the first failure, start nothing more — what is running finishes. */
|
|
15
|
+
stopOnFailure?: boolean;
|
|
16
|
+
/** Heard as each item settles, in the order they settle: a screen's progress. */
|
|
17
|
+
onOutcome?: (outcome: ItemOutcome<I, R>, progress: {
|
|
18
|
+
settled: number;
|
|
19
|
+
total: number;
|
|
20
|
+
}) => void;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Runs a step once per item and answers one outcome per item — Odoo's `for rec in self:`, where a
|
|
24
|
+
* failure is that item's, not the batch's.
|
|
25
|
+
*
|
|
26
|
+
* const result = await runBatch(keys, (key, { signal }) =>
|
|
27
|
+
* billingBoundedContext.execute(new CommandConfirmInvoice(key), { signal }),
|
|
28
|
+
* );
|
|
29
|
+
* result.failed // 1
|
|
30
|
+
* result.outcomes // [done F-1, failed F-7 (conflict: already cancelled), done F-9]
|
|
31
|
+
*
|
|
32
|
+
* Context: confirming the invoices ticked, paying the months chosen, closing what a script finds
|
|
33
|
+
* overdue — each platform wrote its loop, and each loop stopped at the first error or swallowed
|
|
34
|
+
* it. The step is any work for one item: a bounded context's `execute` — each item then runs as
|
|
35
|
+
* its own use case, with its span, its context and its error handling: nothing escapes
|
|
36
|
+
* execution —, a generated client's operation, a transport's send.
|
|
37
|
+
*
|
|
38
|
+
* A failure is read once (`failureOf`) and kept as that item's outcome: never thrown out of the
|
|
39
|
+
* batch, never reported again — the run that failed already reported it if it had to. The
|
|
40
|
+
* outcomes come in the items' order, whatever order they settled in.
|
|
41
|
+
*
|
|
42
|
+
* 1. Up to `concurrency` items run at once, each taking the next one not started.
|
|
43
|
+
* 2. Before starting one: cancelled, or stopped by a failure (`stopOnFailure`)? Then no more start.
|
|
44
|
+
* 3. Each settles as done (its answer) or failed (its failure); `onOutcome` hears it.
|
|
45
|
+
* Final: every item has an outcome — the ones never started, skipped — and the counts.
|
|
46
|
+
*/
|
|
47
|
+
export declare function runBatch<I, R>(items: readonly I[], step: BatchStep<I, R>, options?: BatchOptions<I, R>): Promise<BatchResult<I, R>>;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { failureOf } from "../../common/failures.js";
|
|
2
|
+
/**
|
|
3
|
+
* Runs a step once per item and answers one outcome per item — Odoo's `for rec in self:`, where a
|
|
4
|
+
* failure is that item's, not the batch's.
|
|
5
|
+
*
|
|
6
|
+
* const result = await runBatch(keys, (key, { signal }) =>
|
|
7
|
+
* billingBoundedContext.execute(new CommandConfirmInvoice(key), { signal }),
|
|
8
|
+
* );
|
|
9
|
+
* result.failed // 1
|
|
10
|
+
* result.outcomes // [done F-1, failed F-7 (conflict: already cancelled), done F-9]
|
|
11
|
+
*
|
|
12
|
+
* Context: confirming the invoices ticked, paying the months chosen, closing what a script finds
|
|
13
|
+
* overdue — each platform wrote its loop, and each loop stopped at the first error or swallowed
|
|
14
|
+
* it. The step is any work for one item: a bounded context's `execute` — each item then runs as
|
|
15
|
+
* its own use case, with its span, its context and its error handling: nothing escapes
|
|
16
|
+
* execution —, a generated client's operation, a transport's send.
|
|
17
|
+
*
|
|
18
|
+
* A failure is read once (`failureOf`) and kept as that item's outcome: never thrown out of the
|
|
19
|
+
* batch, never reported again — the run that failed already reported it if it had to. The
|
|
20
|
+
* outcomes come in the items' order, whatever order they settled in.
|
|
21
|
+
*
|
|
22
|
+
* 1. Up to `concurrency` items run at once, each taking the next one not started.
|
|
23
|
+
* 2. Before starting one: cancelled, or stopped by a failure (`stopOnFailure`)? Then no more start.
|
|
24
|
+
* 3. Each settles as done (its answer) or failed (its failure); `onOutcome` hears it.
|
|
25
|
+
* Final: every item has an outcome — the ones never started, skipped — and the counts.
|
|
26
|
+
*/
|
|
27
|
+
export async function runBatch(items, step, options = {}) {
|
|
28
|
+
const { concurrency = 1, signal, stopOnFailure = false, onOutcome } = options;
|
|
29
|
+
if (!Number.isInteger(concurrency) || concurrency < 1)
|
|
30
|
+
throw new RangeError(`concurrency must be a whole number of at least 1, not ${concurrency}`);
|
|
31
|
+
const outcomes = new Array(items.length);
|
|
32
|
+
let next = 0;
|
|
33
|
+
let settled = 0;
|
|
34
|
+
let stopped = false;
|
|
35
|
+
const settle = (outcome) => {
|
|
36
|
+
outcomes[outcome.index] = outcome;
|
|
37
|
+
settled += 1;
|
|
38
|
+
onOutcome?.(outcome, { settled, total: items.length });
|
|
39
|
+
};
|
|
40
|
+
const worker = async () => {
|
|
41
|
+
while (next < items.length && !stopped && signal?.aborted !== true) {
|
|
42
|
+
const index = next++;
|
|
43
|
+
const item = items[index];
|
|
44
|
+
try {
|
|
45
|
+
// Through a promise: a step that throws before it awaits fails its item, not the batch.
|
|
46
|
+
const answer = await Promise.resolve().then(() => step(item, { index, signal }));
|
|
47
|
+
settle({ index, item, status: "done", answer });
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
if (stopOnFailure)
|
|
51
|
+
stopped = true;
|
|
52
|
+
settle({ index, item, status: "failed", failure: failureOf(error), error });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, worker));
|
|
57
|
+
const all = items.map((item, index) => outcomes[index] ?? { index, item, status: "skipped" });
|
|
58
|
+
const count = (status) => all.filter((one) => one.status === status).length;
|
|
59
|
+
return {
|
|
60
|
+
outcomes: all,
|
|
61
|
+
done: count("done"),
|
|
62
|
+
failed: count("failed"),
|
|
63
|
+
skipped: count("skipped"),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
@@ -7,7 +7,7 @@ import { type Answer, type AnyCommand, type Command, type CommandClass, type Com
|
|
|
7
7
|
import type { ErrorClass, ErrorHandler } from "../domain/errors.js";
|
|
8
8
|
import type { Cause, ExecuteOptions, ExecutionCompleted, ExecutionFailed, ExecutionStarted, Extension, Interceptor, Listener } from "../domain/pipeline.js";
|
|
9
9
|
import { type HandledEvent } from "../domain/services.js";
|
|
10
|
-
import { type HandlerRegistrar } from "../services/event-handlers.js";
|
|
10
|
+
import { type HandlerOptions, type HandlerRegistrar } from "../services/event-handlers.js";
|
|
11
11
|
import type { LayerLogger } from "../../observability/domain/logging.js";
|
|
12
12
|
interface Executor<C extends Executable, R> {
|
|
13
13
|
execute(executable: C): R | Promise<R>;
|
|
@@ -15,9 +15,18 @@ interface Executor<C extends Executable, R> {
|
|
|
15
15
|
type ServiceClass<C extends Executable, R> = new () => Executor<C, R>;
|
|
16
16
|
/** What a registration is for when it names none: everything; else the DTOs it names. */
|
|
17
17
|
type Of<K> = [K] extends [never] ? Executable : ExecutableOf<K>;
|
|
18
|
-
/**
|
|
18
|
+
/** How a service is registered: what it takes the place of, and what it is called. */
|
|
19
19
|
export type RegistrationOptions = {
|
|
20
|
+
/** The service registered now that this one takes the place of, as the backend's `replaces=`. */
|
|
20
21
|
replaces?: abstract new (...args: never[]) => object;
|
|
22
|
+
/**
|
|
23
|
+
* Its name — what its spans, logs and reports say, and what this bounded context keys it by
|
|
24
|
+
* —, given as a string literal so no minifier rewrites it: an identifier, as its class would be
|
|
25
|
+
* called (`"LeerCursos"`). Without it, a standard decorator's `context.name`, else the class's
|
|
26
|
+
* `name`, as always. A build that renames classes and registers with legacy decorators
|
|
27
|
+
* (`experimentalDecorators`) or a call — Next.js, which has no `keepNames` — gives it.
|
|
28
|
+
*/
|
|
29
|
+
name?: string;
|
|
21
30
|
};
|
|
22
31
|
/** What `feature(...)` and `appService(...)` answer: the function that registers the service. */
|
|
23
32
|
export type Registrar<T extends Executable> = <S extends ServiceClass<NoInfer<T>, Answer<NoInfer<T>>>>(Service: S, decorator?: ClassDecoratorContext<S>) => S;
|
|
@@ -68,10 +77,14 @@ export declare class BoundedContext<D extends object = Record<never, never>, C e
|
|
|
68
77
|
* Registers the Feature that executes a DTO — or each DTO listed, as the backend's
|
|
69
78
|
* `feature([CommandX, EventY])`: a Command's class, a domain event's (the use case of the event:
|
|
70
79
|
* registering it is the subscription), or a generated one's entry (`operations.X`, `events.X`).
|
|
71
|
-
* With `replaces`, it takes the place of the service registered now for each
|
|
80
|
+
* With `replaces`, it takes the place of the service registered now for each; with `name`, it
|
|
81
|
+
* is called that instead of its class's name — which a minifier rewrites.
|
|
72
82
|
*
|
|
73
83
|
* @billingBoundedContext.feature([CommandIssueInvoice, OrderPaid])
|
|
74
84
|
* class IssueInvoice extends Feature<CommandIssueInvoice | OrderPaid, ResponseInvoice> { … }
|
|
85
|
+
*
|
|
86
|
+
* @cursosBoundedContext.feature(CommandLeerCursos, { name: "LeerCursos" })
|
|
87
|
+
* class LeerCursos extends Feature<CommandLeerCursos, ResponseCursos> { … }
|
|
75
88
|
*/
|
|
76
89
|
feature<const K extends readonly DtoKey[]>(dtos: K, options?: RegistrationOptions): Registrar<ExecutableOf<K[number]>>;
|
|
77
90
|
feature<T extends AnyCommand>(command: CommandClass<T>, options?: RegistrationOptions): Registrar<T>;
|
|
@@ -96,11 +109,12 @@ export declare class BoundedContext<D extends object = Record<never, never>, C e
|
|
|
96
109
|
* salesBoundedContext.handler([SalePaid, SaleCancelled])(OnSaleChanged);
|
|
97
110
|
*
|
|
98
111
|
* An event may have its use case and N handlers here; each is its own consumer
|
|
99
|
-
* (`sales/OnSaleChanged`), acknowledged apart by the queue
|
|
112
|
+
* (`sales/OnSaleChanged`), acknowledged apart by the queue — by that name, so a build that
|
|
113
|
+
* renames classes gives it one: `handler([SalePaid], { name: "OnSaleChanged" })`.
|
|
100
114
|
*/
|
|
101
|
-
handler<const K extends readonly EventKey[]>(events: K): HandlerRegistrar<ExecutableOf<K[number]> & HandledEvent>;
|
|
102
|
-
handler<E extends DomainEvent>(event: EventClass<E
|
|
103
|
-
handler<E extends RemoteEvent = RemoteEvent>(event: EventDescriptor): HandlerRegistrar<E>;
|
|
115
|
+
handler<const K extends readonly EventKey[]>(events: K, options?: HandlerOptions): HandlerRegistrar<ExecutableOf<K[number]> & HandledEvent>;
|
|
116
|
+
handler<E extends DomainEvent>(event: EventClass<E>, options?: HandlerOptions): HandlerRegistrar<E>;
|
|
117
|
+
handler<E extends RemoteEvent = RemoteEvent>(event: EventDescriptor, options?: HandlerOptions): HandlerRegistrar<E>;
|
|
104
118
|
/** The service registered now for a DTO — what a `replaces` names. */
|
|
105
119
|
handlerOf(dto: DtoKey): (abstract new (...args: never[]) => object) | undefined;
|
|
106
120
|
/**
|
|
@@ -180,9 +194,10 @@ export declare class BoundedContext<D extends object = Record<never, never>, C e
|
|
|
180
194
|
* 1. The service is of the layer it is registered in, for a DTO: a Command's or a domain event's
|
|
181
195
|
* class, or a generated one's entry.
|
|
182
196
|
* 2. The DTO has no service yet — or, with `replaces`, the one it has is that one.
|
|
183
|
-
* 3. Its name is the
|
|
184
|
-
*
|
|
185
|
-
* `name
|
|
197
|
+
* 3. Its name is the one its registration gives (`{ name }`, a string no minifier touches); else
|
|
198
|
+
* the framework's to take, at registration: the class's name as the code wrote it (a standard
|
|
199
|
+
* decorator's `context.name`, which a minifier does not touch), else the class's `name` — a
|
|
200
|
+
* production build keeps class names (`keep_classnames`, `keepNames`) or names it. No other
|
|
186
201
|
* service here has it; the same service may take N DTOs.
|
|
187
202
|
* 4. An event's wire name is given, and no other event here has it; a Command's identity, when
|
|
188
203
|
* it declares one, likewise: a name or an identity means one DTO.
|
|
@@ -3,7 +3,7 @@ import { contextAt, } from "../../context/entrypoint/context.js";
|
|
|
3
3
|
import { processContext, processStore, } from "../../context/infrastructure/process.js";
|
|
4
4
|
import { FeatureBus, optionsOf, } from "../domain/bus.js";
|
|
5
5
|
import { EVENT_NAME, } from "../domain/dto.js";
|
|
6
|
-
import { ApplicationService, Feature, RESERVED_MEMBERS, } from "../domain/services.js";
|
|
6
|
+
import { ApplicationService, Feature, givenNameOf, RESERVED_MEMBERS, } from "../domain/services.js";
|
|
7
7
|
import { processHearing } from "../infrastructure/listeners.js";
|
|
8
8
|
import { bindDependency } from "../services/binding.js";
|
|
9
9
|
import { describeDto, identityOf, isCommandClass, isCommandDescriptor, isDtoKey, keyIdentity, } from "../services/dto-keys.js";
|
|
@@ -121,9 +121,9 @@ export class BoundedContext {
|
|
|
121
121
|
appService(dto, options) {
|
|
122
122
|
return this.registrar(dto, "application_service", options);
|
|
123
123
|
}
|
|
124
|
-
handler(events) {
|
|
124
|
+
handler(events, options) {
|
|
125
125
|
const keys = eventKeysOf(events);
|
|
126
|
-
return handlerRegistrar((Handler, name) => this.registerHandler(Handler, name, keys));
|
|
126
|
+
return handlerRegistrar((Handler, name) => this.registerHandler(Handler, name, keys), options);
|
|
127
127
|
}
|
|
128
128
|
/** The service registered now for a DTO — what a `replaces` names. */
|
|
129
129
|
handlerOf(dto) {
|
|
@@ -326,14 +326,16 @@ export class BoundedContext {
|
|
|
326
326
|
const dtos = Array.isArray(dto) ? dto : [dto];
|
|
327
327
|
if (dtos.length === 0)
|
|
328
328
|
throw new TypeError("A service is registered for one DTO at least");
|
|
329
|
+
const given = givenNameOf(options);
|
|
329
330
|
return (Service, decorator) => {
|
|
330
331
|
// All the DTOs listed, or none: a refused one leaves the registrations as they were.
|
|
331
332
|
const register = () => {
|
|
332
333
|
const before = [...this.registrations];
|
|
333
334
|
const revision = this.revision;
|
|
335
|
+
const written = given ?? decorator?.name;
|
|
334
336
|
try {
|
|
335
337
|
for (const one of dtos)
|
|
336
|
-
this.registerService(one, Service, layer, options.replaces,
|
|
338
|
+
this.registerService(one, Service, layer, options.replaces, written);
|
|
337
339
|
}
|
|
338
340
|
catch (error) {
|
|
339
341
|
this.registrations.clear();
|
|
@@ -355,9 +357,10 @@ export class BoundedContext {
|
|
|
355
357
|
* 1. The service is of the layer it is registered in, for a DTO: a Command's or a domain event's
|
|
356
358
|
* class, or a generated one's entry.
|
|
357
359
|
* 2. The DTO has no service yet — or, with `replaces`, the one it has is that one.
|
|
358
|
-
* 3. Its name is the
|
|
359
|
-
*
|
|
360
|
-
* `name
|
|
360
|
+
* 3. Its name is the one its registration gives (`{ name }`, a string no minifier touches); else
|
|
361
|
+
* the framework's to take, at registration: the class's name as the code wrote it (a standard
|
|
362
|
+
* decorator's `context.name`, which a minifier does not touch), else the class's `name` — a
|
|
363
|
+
* production build keeps class names (`keep_classnames`, `keepNames`) or names it. No other
|
|
361
364
|
* service here has it; the same service may take N DTOs.
|
|
362
365
|
* 4. An event's wire name is given, and no other event here has it; a Command's identity, when
|
|
363
366
|
* it declares one, likewise: a name or an identity means one DTO.
|
package/dist/core/index.d.ts
CHANGED
|
@@ -4,19 +4,22 @@
|
|
|
4
4
|
* handlers — and the process they run in.
|
|
5
5
|
*
|
|
6
6
|
* domain/ DTOs (classes, and generated ones the bus recognizes), the bus, the service
|
|
7
|
-
* bases (`servicesWith`: typed with a context's dependencies), the error
|
|
7
|
+
* bases (`servicesWith`: typed with a context's dependencies), the error
|
|
8
|
+
* handlers, a batch's outcomes (`BatchResult`)
|
|
8
9
|
* services/ the execution pipeline, dependency binding, the handler chain
|
|
9
|
-
* entrypoint/ `BoundedContext`, `screensTransport`
|
|
10
|
+
* entrypoint/ `BoundedContext`, `screensTransport`, `runBatch`
|
|
10
11
|
* infrastructure/ `configureProcess`, `configureLogger`
|
|
11
12
|
*/
|
|
13
|
+
export type { BatchResult, ItemOutcome } from "./domain/batch.js";
|
|
12
14
|
export { type CommandBus, FeatureBus } from "./domain/bus.js";
|
|
13
15
|
export type { EventConsumer, EventKey, } from "./domain/consumers.js";
|
|
14
16
|
export { type AnyCommand, Command, COMMAND_IDENTITY, type CommandClass, type CommandDescriptor, type CommandNamed, commandOf, DataTransferObject, DomainEvent, type DtoKey, type EventClass, type EventDescriptor, type Executable, type ExecutableOf, type RemoteCommand, type RemoteEvent, Response, } from "./domain/dto.js";
|
|
15
17
|
export type { ErrorClass, ErrorHandler } from "./domain/errors.js";
|
|
16
18
|
export type { CallNext, Cause, ExecuteOptions, ExecutionCompleted, ExecutionFailed, ExecutionStarted, Extension, InterceptedRun, Interceptor, Listener, PipelineLayer, } from "./domain/pipeline.js";
|
|
17
19
|
export { ApplicationService, type ApplicationServiceWith, type BoundedContextHandlerWith, EventHandler, type EventHandlerWith, Feature, type FeatureWith, type HandledEvent, handlersWith, type ServiceInput, servicesWith, } from "./domain/services.js";
|
|
20
|
+
export { type BatchOptions, type BatchStep, runBatch, } from "./entrypoint/batch.js";
|
|
18
21
|
export { BoundedContext, type Registrar, type RegistrationOptions, } from "./entrypoint/bounded-context.js";
|
|
19
22
|
export { screensTransport } from "./entrypoint/screens.js";
|
|
20
23
|
export { processListeners } from "./infrastructure/listeners.js";
|
|
21
24
|
export { configureLogger, configureProcess, type LoggerConfiguration, processIdentity, type ProcessOptions, } from "./infrastructure/process.js";
|
|
22
|
-
export type { HandlerRegistrar } from "./services/event-handlers.js";
|
|
25
|
+
export type { HandlerOptions, HandlerRegistrar, } from "./services/event-handlers.js";
|
package/dist/core/index.js
CHANGED
|
@@ -1,17 +1,7 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The application core (`./core`): the backend's application abstractions — class Commands and
|
|
3
|
-
* Responses, Features and ApplicationServices, a bounded context that is their bus, its error
|
|
4
|
-
* handlers — and the process they run in.
|
|
5
|
-
*
|
|
6
|
-
* domain/ DTOs (classes, and generated ones the bus recognizes), the bus, the service
|
|
7
|
-
* bases (`servicesWith`: typed with a context's dependencies), the error handlers
|
|
8
|
-
* services/ the execution pipeline, dependency binding, the handler chain
|
|
9
|
-
* entrypoint/ `BoundedContext`, `screensTransport`
|
|
10
|
-
* infrastructure/ `configureProcess`, `configureLogger`
|
|
11
|
-
*/
|
|
12
1
|
export { FeatureBus } from "./domain/bus.js";
|
|
13
2
|
export { Command, COMMAND_IDENTITY, commandOf, DataTransferObject, DomainEvent, Response, } from "./domain/dto.js";
|
|
14
3
|
export { ApplicationService, EventHandler, Feature, handlersWith, servicesWith, } from "./domain/services.js";
|
|
4
|
+
export { runBatch, } from "./entrypoint/batch.js";
|
|
15
5
|
export { BoundedContext, } from "./entrypoint/bounded-context.js";
|
|
16
6
|
export { screensTransport } from "./entrypoint/screens.js";
|
|
17
7
|
export { processListeners } from "./infrastructure/listeners.js";
|
|
@@ -26,12 +26,23 @@ export type HandlerRegistrar<E extends HandledEvent> = <S extends new () => {
|
|
|
26
26
|
* event's entry, with a valid wire name, none twice.
|
|
27
27
|
*/
|
|
28
28
|
export declare function eventKeysOf(events: EventKey | readonly EventKey[]): readonly EventKey[];
|
|
29
|
+
/** How an event handler is registered: what it is called. */
|
|
30
|
+
export type HandlerOptions = {
|
|
31
|
+
/**
|
|
32
|
+
* Its name — `<owner>/<Name>` on its spans and logs, and the consumer a stored queue
|
|
33
|
+
* acknowledges —, given as a string literal so no minifier rewrites it: an identifier, as its
|
|
34
|
+
* class would be called (`"OnSaleChanged"`). Without it, a standard decorator's
|
|
35
|
+
* `context.name`, else the class's `name`, as always.
|
|
36
|
+
*/
|
|
37
|
+
name?: string;
|
|
38
|
+
};
|
|
29
39
|
/**
|
|
30
40
|
* Registers `Handler` with `register`, at once or — applied as a standard decorator — once its
|
|
31
|
-
* class is defined; its name is the
|
|
32
|
-
*
|
|
41
|
+
* class is defined; its name is the one `options` gives (a string, untouched by a minifier),
|
|
42
|
+
* else the class's as the code wrote it (a decorator's `context.name`, untouched too), else its
|
|
43
|
+
* `name`.
|
|
33
44
|
*/
|
|
34
|
-
export declare function handlerRegistrar<E extends HandledEvent>(register: (Handler: HandlerClass, name: string) => void): HandlerRegistrar<E>;
|
|
45
|
+
export declare function handlerRegistrar<E extends HandledEvent>(register: (Handler: HandlerClass, name: string) => void, options?: HandlerOptions): HandlerRegistrar<E>;
|
|
35
46
|
/** Whether a handler registered for `key` handles the event `known` identifies. */
|
|
36
47
|
export declare function handles(key: EventKey, known: DtoIdentity): boolean;
|
|
37
48
|
/** What a run of an event handler needs besides the handler and the event. */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { EVENT_NAME } from "../domain/dto.js";
|
|
2
|
-
import { EventHandler, } from "../domain/services.js";
|
|
2
|
+
import { EventHandler, givenNameOf, } from "../domain/services.js";
|
|
3
3
|
import { isEventClass, isEventDescriptor, keyIdentity, } from "./dto-keys.js";
|
|
4
4
|
import { executeService, failedAt, } from "./execution.js";
|
|
5
5
|
import { observabilityNow } from "../../observability/infrastructure/registry.js";
|
|
@@ -28,16 +28,18 @@ export function eventKeysOf(events) {
|
|
|
28
28
|
}
|
|
29
29
|
/**
|
|
30
30
|
* Registers `Handler` with `register`, at once or — applied as a standard decorator — once its
|
|
31
|
-
* class is defined; its name is the
|
|
32
|
-
*
|
|
31
|
+
* class is defined; its name is the one `options` gives (a string, untouched by a minifier),
|
|
32
|
+
* else the class's as the code wrote it (a decorator's `context.name`, untouched too), else its
|
|
33
|
+
* `name`.
|
|
33
34
|
*/
|
|
34
|
-
export function handlerRegistrar(register) {
|
|
35
|
+
export function handlerRegistrar(register, options) {
|
|
36
|
+
const given = givenNameOf(options);
|
|
35
37
|
return (Handler, decorator) => {
|
|
36
38
|
const take = () => {
|
|
37
39
|
if (!(Handler.prototype instanceof EventHandler)) {
|
|
38
40
|
throw new TypeError("An event handler extends EventHandler");
|
|
39
41
|
}
|
|
40
|
-
const name = decorator?.name ?? Handler.name;
|
|
42
|
+
const name = given ?? decorator?.name ?? Handler.name;
|
|
41
43
|
if (typeof name !== "string" || name.trim() === "") {
|
|
42
44
|
throw new Error("An event handler is a named class: its name is said in spans and logs");
|
|
43
45
|
}
|
|
@@ -2,7 +2,7 @@ import type { EventConsumer, EventKey } from "../../core/domain/consumers.js";
|
|
|
2
2
|
import type { AnyCommand, CommandClass, CommandDescriptor, DomainEvent, DtoKey, EventClass, EventDescriptor, Executable, ExecutableOf, RemoteCommand, RemoteEvent } from "../../core/domain/dto.js";
|
|
3
3
|
import type { Cause, ExecuteOptions } from "../../core/domain/pipeline.js";
|
|
4
4
|
import { type HandledEvent } from "../../core/domain/services.js";
|
|
5
|
-
import { type HandlerRegistrar } from "../../core/services/event-handlers.js";
|
|
5
|
+
import { type HandlerOptions, type HandlerRegistrar } from "../../core/services/event-handlers.js";
|
|
6
6
|
import type { Envelope } from "../domain/envelope.js";
|
|
7
7
|
import type { BinaryMessage, Message } from "../domain/messages.js";
|
|
8
8
|
import type { CommandType, EventType, Handled, Subscribes } from "../domain/queue.js";
|
|
@@ -99,10 +99,13 @@ export declare class Subscriber<D extends object = Record<never, never>> impleme
|
|
|
99
99
|
* export class OnSaleChanged extends EventHandler<SalePaid | SaleCancelled> { … }
|
|
100
100
|
*
|
|
101
101
|
* appSubscriber.handler([SalePaid, SaleCancelled])(OnSaleChanged);
|
|
102
|
+
*
|
|
103
|
+
* Its name (`app/OnSaleChanged`) is the consumer the stored queue acknowledges: a build that
|
|
104
|
+
* renames classes gives it one, `handler([SalePaid], { name: "OnSaleChanged" })`.
|
|
102
105
|
*/
|
|
103
|
-
handler<const K extends readonly EventKey[]>(events: K): HandlerRegistrar<ExecutableOf<K[number]> & HandledEvent>;
|
|
104
|
-
handler<E extends DomainEvent>(event: EventClass<E
|
|
105
|
-
handler<E extends RemoteEvent = RemoteEvent>(event: EventDescriptor): HandlerRegistrar<E>;
|
|
106
|
+
handler<const K extends readonly EventKey[]>(events: K, options?: HandlerOptions): HandlerRegistrar<ExecutableOf<K[number]> & HandledEvent>;
|
|
107
|
+
handler<E extends DomainEvent>(event: EventClass<E>, options?: HandlerOptions): HandlerRegistrar<E>;
|
|
108
|
+
handler<E extends RemoteEvent = RemoteEvent>(event: EventDescriptor, options?: HandlerOptions): HandlerRegistrar<E>;
|
|
106
109
|
/** What an event of that wire name is rebuilt as, or `undefined` when nobody here hears it. */
|
|
107
110
|
eventTypeOf(name: string): EventType | undefined;
|
|
108
111
|
/** What a consumed Command of that identity is rebuilt as, or `undefined` when it is not consumed here. */
|
|
@@ -148,7 +148,7 @@ export class Subscriber {
|
|
|
148
148
|
this.buses.push({ context: boundedContext, key });
|
|
149
149
|
return this;
|
|
150
150
|
}
|
|
151
|
-
handler(events) {
|
|
151
|
+
handler(events, options) {
|
|
152
152
|
const keys = eventKeysOf(events);
|
|
153
153
|
return handlerRegistrar((Handler, name) => {
|
|
154
154
|
if (this.name === "") {
|
|
@@ -161,7 +161,7 @@ export class Subscriber {
|
|
|
161
161
|
throw new Error(`Event handler name already registered: ${name}`);
|
|
162
162
|
}
|
|
163
163
|
this.handlers.push({ name, Handler, events: keys });
|
|
164
|
-
});
|
|
164
|
+
}, options);
|
|
165
165
|
}
|
|
166
166
|
/** What an event of that wire name is rebuilt as, or `undefined` when nobody here hears it. */
|
|
167
167
|
eventTypeOf(name) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sincpro/client-framework",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.4.0",
|
|
4
4
|
"description": "The client side of sincpro_framework, for every platform: Feature and ApplicationService traced and reported by default, applications made of domains, and the typed client generated from a service's contract. No React, no DOM.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|