@akterjs/conformance 0.0.0-stage → 0.1.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.
Files changed (57) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +52 -2
  3. package/dist/client-contract.suite.d.mts +23 -0
  4. package/dist/client-contract.suite.mjs +279 -0
  5. package/dist/client-target.errors.d.mts +8 -0
  6. package/dist/client-target.errors.mjs +4 -0
  7. package/dist/engine-conformance.suite.d.mts +19 -0
  8. package/dist/engine-conformance.suite.mjs +357 -0
  9. package/dist/fork/fork-conformance.suite.d.mts +20 -0
  10. package/dist/fork/fork-conformance.suite.mjs +167 -0
  11. package/dist/guarantee-titles.pure.d.mts +31 -0
  12. package/dist/guarantee-titles.pure.mjs +32 -0
  13. package/dist/ledger/ledger-calls.pure.d.mts +79 -0
  14. package/dist/ledger/ledger-calls.pure.mjs +111 -0
  15. package/dist/ledger/ledger-checks.pure.d.mts +21 -0
  16. package/dist/ledger/ledger-checks.pure.mjs +37 -0
  17. package/dist/ledger/ledger.actor.d.mts +13 -0
  18. package/dist/ledger/ledger.actor.mjs +115 -0
  19. package/dist/ledger/ledger.contract.d.mts +310 -0
  20. package/dist/ledger/ledger.contract.mjs +112 -0
  21. package/dist/ledger/plain-ledger.actor.d.mts +4 -0
  22. package/dist/ledger/plain-ledger.actor.mjs +214 -0
  23. package/dist/rejected.errors.d.mts +8 -0
  24. package/dist/rejected.errors.mjs +4 -0
  25. package/dist/tally-clients.layer.d.mts +39 -0
  26. package/dist/tally-clients.layer.mjs +97 -0
  27. package/dist/tally.actor.d.mts +49 -0
  28. package/dist/tally.actor.mjs +26 -0
  29. package/dist/tally.contract.d.mts +51 -0
  30. package/dist/tally.contract.mjs +28 -0
  31. package/dist/workbench/computer-conformance.suite.d.mts +15 -0
  32. package/dist/workbench/computer-conformance.suite.mjs +330 -0
  33. package/dist/workbench/workbench-calls.pure.d.mts +45 -0
  34. package/dist/workbench/workbench-calls.pure.mjs +75 -0
  35. package/dist/workbench/workbench.actor.d.mts +4 -0
  36. package/dist/workbench/workbench.actor.mjs +107 -0
  37. package/dist/workbench/workbench.contract.d.mts +220 -0
  38. package/dist/workbench/workbench.contract.mjs +54 -0
  39. package/package.json +86 -3
  40. package/src/client-contract.suite.ts +413 -0
  41. package/src/client-target.errors.ts +7 -0
  42. package/src/engine-conformance.suite.ts +484 -0
  43. package/src/fork/fork-conformance.suite.ts +204 -0
  44. package/src/guarantee-titles.pure.ts +50 -0
  45. package/src/ledger/ledger-calls.pure.ts +179 -0
  46. package/src/ledger/ledger-checks.pure.ts +84 -0
  47. package/src/ledger/ledger.actor.ts +196 -0
  48. package/src/ledger/ledger.contract.ts +76 -0
  49. package/src/ledger/plain-ledger.actor.ts +246 -0
  50. package/src/rejected.errors.ts +6 -0
  51. package/src/tally-clients.layer.ts +221 -0
  52. package/src/tally.actor.ts +28 -0
  53. package/src/tally.contract.ts +22 -0
  54. package/src/workbench/computer-conformance.suite.ts +380 -0
  55. package/src/workbench/workbench-calls.pure.ts +92 -0
  56. package/src/workbench/workbench.actor.ts +175 -0
  57. package/src/workbench/workbench.contract.ts +47 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,53 @@
1
- # Temporary Holding Version
1
+ # @akterjs/conformance
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The guarantees of an Akter engine as executable tests. The local engine in `@akterjs/effect` runs it here, and akter-cloud runs it against its production engine. Every guarantee the docs make links to the test here that proves it, by the test's title.
4
+
5
+ ```ts
6
+ import { it } from "@effect/vitest";
7
+ import { conformance } from "@akterjs/conformance";
8
+
9
+ it.layer(NodeFileSystem.layer)("the local engine on a folder passes engine conformance", conformance(LocalEngine));
10
+ ```
11
+
12
+ An engine under test is an effect that opens fresh storage for one test and returns the engine on it, a `Layer<ActorHost | ActorRegistry>` (the seam `Akter.serve` needs). The suite builds that layer more than once to restart the engine on the same storage, and drives it only through `ActorHost` with the wire's JSON payloads and replies, so it runs against any engine. The local engine is `Akter.local` on a temporary folder (`tests/engine-conformance.suite.test.ts`). An engine that doesn't serve a guarantee yet skips it by name with `conformanceOf({ engine, skip: { migrationsOnOpen: "why, and the issue that tracks it" } })`, keyed as in `guaranteeTitles`. Every other guarantee runs, so a guarantee added later never goes unchecked. A host that keeps its own tables in the actor's database declares their prefix, `conformanceOf({ engine, hostTables: "engine_", skip: {} })`, and provides the same prefix to `HostedRuntime.hostTables`. The migrations guarantee then ignores only the tables under that prefix, and it checks that an app migration creating a table under it is refused. The suite refuses an empty prefix and `akter_`.
13
+
14
+ Guarantees, one test each, run with the suite's own `Ledger` actor. By default it is the Effect SDK's (`src/ledger/ledger.actor.ts`). `@akterjs/conformance/plain` exports `plainLedgers`, the same Ledger written with the plain SDK and zod, with the same wire contract, and `conformanceOf({ engine, ledgers: plainLedgers, skip: {} })` runs every guarantee on it, so an engine is checked under both SDKs:
15
+
16
+ - a reply means the command committed: an engine reopened on the same storage sees every replied command
17
+ - a retried command id returns the recorded outcome and runs the handler once
18
+ - a handler failure rolls back every write the command made
19
+ - caller checks run before the handler: a caller the command doesn't allow changes nothing
20
+ - migrations run when an actor opens, before its first call, and a migration added later runs on the next open
21
+ - queries never write: a write inside a query fails and leaves the actor unchanged
22
+ - a handler may read akter_* tables but never write them: the write fails, names the table and changes nothing
23
+ - live queries update only after a commit: a subscriber sees each committed change and nothing from a rolled-back command
24
+ - a message a command sends is delivered after the command commits, at least once, and a rolled-back command sends none
25
+ - a timer fires once at its due time, and not again after the engine restarts
26
+
27
+ The computer guarantees are a second suite, `computerConformanceOf({ engine, skip })` from `@akterjs/conformance/computers`, with the suite's `Workbench` actor (`src/workbench/`, Effect SDK only), whose `run` command starts a job that makes each computer call in its own activity and records what each answered, so the suite reads the outcomes back with the `runs` query. An engine serves `Workbench/bench-1` with its computers bound to the job runtime's `Actor.computer(key)`: the local engine with `AKTER_LOCAL_COMPUTERS=true` in the test's `ConfigProvider` (`tests/engine-conformance.suite.test.ts`), so it reaches the Workbench's `Akter.jobs` too. They run on the real clock, because computer calls wait on real processes and machines. A `starting` and a `running` computer both read as `up`, because an engine may answer `ensure` before the machine is running.
28
+
29
+ - a computer step runs once by its key: sent again, even after the engine restarts, it reads back the outcome it recorded
30
+ - a computer keeps its files across pause, resume, stop and an engine restart
31
+ - a held computer stays paused, or stopped if it was stopped: an ensure, a step, and a resume or pause without its hold are refused until its hold resumes it
32
+ - a computer past the store's limit is refused with ComputerLimitError and makes nothing, and one fits again once another is removed
33
+ - a removed computer is gone with its disk: calls to it fail with ComputerNotFoundError, and ensuring it again starts it empty
34
+
35
+ The fork guarantees are a third suite, `forkConformanceOf({ engine, skip })` from `@akterjs/conformance/fork`, which forks the suite's `acct-1` Ledger into `acct-5`, and its `bench-1` Workbench, with a running and a stopped computer, into `bench-250`, through `ActorHost.fork`. An engine under test serves all four keys, with the Workbench's computers bound both to its jobs and to its fork, and an engine that places an actor by its key puts each fork's key on its parent's shard, because Akter Cloud forks only within a shard (`acct-5` and `bench-250` hash to their parents' shards there). The local engine runs it with `AKTER_LOCAL_COMPUTERS=true` in `tests/engine-conformance.suite.test.ts`.
36
+
37
+ - a fork copies an actor as committed at its cut and starts quiet: the copy keeps no pending timer, the two change independently, and a retried fork id makes one copy
38
+ - a fork copies each of the actor's computers by its disk at the cut, stopped: the copy holds the files written before the cut, the original's computers go back to where they were, and the two change independently
39
+
40
+ The docs page `apps/docs/content/reference/guarantees.md` lists each guarantee with a link titled like its test, and `tests/guarantee-titles.pure.test.ts` fails when a listed guarantee has no test with that title or a test is missing from the page. The titles live in `src/guarantee-titles.pure.ts`.
41
+
42
+ `pnpm test` runs the suite on Node and `pnpm test:bun` runs it on Bun. `vitest.config.ts` names the runtime as `@akterjs/effect`'s does, so every result reads `|node|` or `|bun|`.
43
+
44
+ ## The client contract
45
+
46
+ `@akterjs/conformance/client` exports `clientConformanceOf({ target, skip })`, the public-contract fixture for the exported clients. It runs each case through both the Effect client (`akterClient` from `@akterjs/client/effect`) and the Promise client (`createClient` from `@akterjs/client`) against a served app holding the suite's `Tally` actor (`@akterjs/conformance/tally` exports its handlers, `TallyLive`, for the server under test). A target is an effect that serves the app for one test and returns its `url` and the headers of four callers: `user`, whom `Tally` allows; `stranger`, an authenticated caller of a kind `Tally` doesn't declare; `unauthenticated`, whose credentials are missing or invalid; and optionally `foreign`, a caller from another organization or app. A target may also give `freshKey`, the effect that names each case's new actor key; by default it is a random `tally-<uuid>`, and a target that serves only some shards, such as akter-cloud's local harness, supplies keys on those. The cases: create and ensure; a command's success and its contract's typed error; queries, state and live updates with increasing versions; a query right after the caller's own command, which reads that command's write; warm; a refused stranger (`CallerNotAllowedError`) and an unauthenticated caller (`UnauthenticatedError`) that change nothing; a foreign caller refused with `CallerNotAllowedError`; a command whose reply the fixture's `fetch` drops after the server answered, retried with its id and applied once; a live subscription whose sockets the fixture closes, which reconnects and resumes without repeating an update; and disposal, which closes every live socket. Register it with `excludeTestServices: true`, because it runs over a real network on the real clock. `tests/client-contract.suite.test.ts` runs it against `akter dev` (`Akter.serve` on `Akter.local`), skipping `foreign`, and against a deployed stage. A target that can't serve this run fails with `ClientTargetUnsetError` (exported beside the fixture), and each case reports as skipped with its reason.
47
+
48
+ The stage target reads `AKTER_CLIENT_CONTRACT_URL`, the gateway URL of an app that serves `Tally`, and three bearer tokens: `AKTER_CLIENT_CONTRACT_USER_TOKEN` (a developer of the app's organization), `AKTER_CLIENT_CONTRACT_STRANGER_TOKEN` (a caller the stage lets call but `Tally` doesn't declare, such as a call-scoped API key) and `AKTER_CLIENT_CONTRACT_FOREIGN_TOKEN` (a caller from another organization). Its unauthenticated caller sends a bearer that isn't a token. Without the URL every stage case skips. Deploy the app with `akter deploy --entry packages/conformance/src/tally.actor.ts`, which exports it as `app`, then run `pnpm --filter @akterjs/conformance exec vitest run tests/client-contract.suite.test.ts -t "a deployed stage"` with the four variables set.
49
+
50
+ Status: the guarantees above pass on the local engine with both SDKs' Ledgers, on Node and on Bun, and the computer guarantees pass on akter-cloud's engine over its simulated control plane. The fork guarantees fork into a key on the parent's own shard, and don't cover a fork across shards; the one with computers checks their disks and states, not that a copy runs none of the original's processes, which the engines' own tests check. The computer guarantees don't cover a computer's processes or memory across a pause, egress, credentials, ingress, or a step's timeout and output limit.
51
+
52
+ - Depends on: `@akterjs/effect` and `@akterjs/client`; peers `effect`, `vitest` and `@effect/vitest`, and optionally `@akterjs/sdk` and `zod` for `@akterjs/conformance/plain`.
53
+ - Must not depend on: any private package.
@@ -0,0 +1,23 @@
1
+ import { ClientTargetUnsetError } from "./client-target.errors.mjs";
2
+ import { Headers } from "./tally-clients.layer.mjs";
3
+ import { Vitest } from "@effect/vitest";
4
+ import { Effect, Scope } from "effect";
5
+ interface ClientCallers {
6
+ readonly foreign?: Headers;
7
+ readonly stranger: Headers;
8
+ readonly unauthenticated: Headers;
9
+ readonly user: Headers;
10
+ }
11
+ interface ClientTarget {
12
+ readonly callers: ClientCallers;
13
+ readonly freshKey?: Effect.Effect<string>;
14
+ readonly url: string;
15
+ }
16
+ type Target<Failure, Services> = Effect.Effect<ClientTarget, ClientTargetUnsetError | Failure, Scope.Scope | Services>;
17
+ type CaseName = "commands" | "creation" | "disposal" | "foreign" | "forking" | "lostReply" | "readYourWrites" | "reads" | "reconnect" | "refusals" | "warming";
18
+ interface ClientContract<Failure, Services> {
19
+ readonly skip: Readonly<Partial<Record<CaseName, string>>>;
20
+ readonly target: Target<Failure, Services>;
21
+ }
22
+ declare const clientConformanceOf: <Failure, Services>({ skip, target }: ClientContract<Failure, Services>) => (test: Vitest.MethodsNonLive<Services>) => void;
23
+ export { type CaseName, type ClientCallers, type ClientTarget, ClientTargetUnsetError, clientConformanceOf };
@@ -0,0 +1,279 @@
1
+ import { ClientTargetUnsetError } from "./client-target.errors.mjs";
2
+ import { clients, wired } from "./tally-clients.layer.mjs";
3
+ import { ShortError } from "./tally.contract.mjs";
4
+ import { ActorAlreadyExistsError, CallerNotAllowedError, UnauthenticatedError } from "@akterjs/effect/contract/errors";
5
+ import { expect } from "@effect/vitest";
6
+ import { Array, Effect, Exit, Function, MutableRef, Option, Queue, Record, Schedule, Schema, Scope, Stream } from "effect";
7
+ import { SecureRandom } from "effect/crypto";
8
+ // src/client-contract.suite.ts
9
+ const none = 0;
10
+ const one = 1;
11
+ const two = 2;
12
+ const three = 3;
13
+ const four = 4;
14
+ const five = 5;
15
+ const eight = 8;
16
+ const nine = 9;
17
+ const pollTries = 250;
18
+ const abnormalClose = 4e3;
19
+ const dropped = "dropped by the client contract fixture";
20
+ const resubscribed = "250 millis";
21
+ const updateDeadline = "10 seconds";
22
+ const randomKey = Effect.sync(() => `tally-${SecureRandom.uuidV4Unsafe()}`);
23
+ const freshKeyOf = ({ freshKey }) => Option.getOrElse(Option.fromNullishOr(freshKey), () => randomKey);
24
+ const polled = (read, done) => Effect.filterOrFail(read, done, () => "not yet").pipe(Effect.retry({
25
+ schedule: Schedule.spaced("20 millis"),
26
+ times: pollTries
27
+ }), Effect.orDie);
28
+ const nextOf = (queue) => Effect.timeoutOrElse(Queue.take(queue), {
29
+ duration: updateDeadline,
30
+ orElse: () => Effect.die(`no live update arrived within ${updateDeadline}`)
31
+ });
32
+ const collected = (updates) => Effect.gen(function* collect() {
33
+ const queue = yield* Queue.unbounded();
34
+ yield* Effect.forkScoped(Effect.matchEffect(Stream.runForEach(updates, (update) => Queue.offer(queue, update)), {
35
+ onFailure: (failure) => Queue.fail(queue, failure),
36
+ onSuccess: () => Effect.void
37
+ }));
38
+ return queue;
39
+ });
40
+ const headOf = (updates) => Effect.flatMap(Stream.runHead(updates), Effect.fromOption);
41
+ const handle = ({ connect, target, wire }, headers, key) => Effect.map(connect({
42
+ headers,
43
+ url: target.url,
44
+ wire
45
+ }), (connected) => connected(key));
46
+ const reasonOf = (effect) => Effect.match(effect, {
47
+ onFailure: (failure) => failure.reason,
48
+ onSuccess: (succeeded) => ({ succeeded })
49
+ });
50
+ const created = Effect.fnUntraced(function* created(test) {
51
+ const key = yield* freshKeyOf(test.target);
52
+ const tally = yield* handle(test, test.target.callers.user, key);
53
+ yield* tally.create("ada");
54
+ return {
55
+ key,
56
+ tally
57
+ };
58
+ });
59
+ const creation = Effect.fnUntraced(function* creation(test) {
60
+ const { tally } = yield* created(test);
61
+ const again = yield* reasonOf(tally.create("bob"));
62
+ yield* tally.ensure("bob");
63
+ const owner = yield* tally.owner;
64
+ expect(again).toBeInstanceOf(ActorAlreadyExistsError);
65
+ expect(owner).toBe("ada");
66
+ });
67
+ const commands = Effect.fnUntraced(function* commands(test) {
68
+ const { tally } = yield* created(test);
69
+ const added = yield* tally.add(five);
70
+ const short = yield* reasonOf(tally.take(nine));
71
+ const taken = yield* tally.take(two);
72
+ expect([added, taken]).toStrictEqual([five, three]);
73
+ expect(short).toBeInstanceOf(ShortError);
74
+ expect(short).toStrictEqual(ShortError.make({ total: five }));
75
+ });
76
+ const reads = Effect.fnUntraced(function* reads(test) {
77
+ const { tally } = yield* created(test);
78
+ yield* tally.add(four);
79
+ const totals = yield* collected(tally.totals);
80
+ const [total, first, state] = yield* Effect.all([
81
+ tally.total,
82
+ nextOf(totals),
83
+ headOf(tally.state)
84
+ ]);
85
+ yield* tally.add(one);
86
+ const next = yield* nextOf(totals);
87
+ expect([
88
+ total,
89
+ first.value,
90
+ next.value
91
+ ]).toStrictEqual([
92
+ four,
93
+ four,
94
+ five
95
+ ]);
96
+ expect(state).toStrictEqual({
97
+ value: {
98
+ owner: "ada",
99
+ total: four
100
+ },
101
+ version: first.version
102
+ });
103
+ expect(next.version).toBeGreaterThan(first.version);
104
+ });
105
+ const readYourWrites = Effect.fnUntraced(function* readYourWrites(test) {
106
+ const { tally } = yield* created(test);
107
+ const seen = yield* Effect.forEach(Array.makeBy(five, Function.identity), () => Effect.andThen(tally.total, Effect.andThen(tally.add(one), tally.total)));
108
+ expect(seen).toStrictEqual([
109
+ one,
110
+ two,
111
+ three,
112
+ four,
113
+ five
114
+ ]);
115
+ });
116
+ const forkTargets = Effect.fnUntraced(function* forkTargets(test) {
117
+ const [first, second, taken] = yield* Effect.all([
118
+ freshKeyOf(test.target),
119
+ freshKeyOf(test.target),
120
+ freshKeyOf(test.target)
121
+ ]);
122
+ return {
123
+ first,
124
+ occupied: yield* handle(test, test.target.callers.user, taken),
125
+ second,
126
+ taken
127
+ };
128
+ });
129
+ const forking = Effect.fnUntraced(function* forking(test) {
130
+ const { tally } = yield* created(test);
131
+ const { first, occupied, second, taken } = yield* forkTargets(test);
132
+ yield* Effect.andThen(tally.add(three), test.wire.loseNextReply);
133
+ const child = yield* tally.fork(first);
134
+ const sibling = yield* Effect.andThen(tally.add(one), tally.fork(second));
135
+ yield* Effect.andThen(child.add(five), occupied.create("bob"));
136
+ const totals = Effect.all([
137
+ tally.total,
138
+ child.total,
139
+ sibling.total,
140
+ child.owner,
141
+ occupied.owner
142
+ ]);
143
+ const [refused, read] = yield* Effect.all([reasonOf(tally.fork(taken)), totals]);
144
+ expect(read).toStrictEqual([
145
+ four,
146
+ eight,
147
+ four,
148
+ "ada",
149
+ "bob"
150
+ ]);
151
+ expect(refused).toBeInstanceOf(ActorAlreadyExistsError);
152
+ });
153
+ const warming = Effect.fnUntraced(function* warming(test) {
154
+ const { tally } = yield* created(test);
155
+ const never = yield* Effect.flatMap(freshKeyOf(test.target), (key) => handle(test, test.target.callers.user, key));
156
+ const before = yield* headOf(tally.state);
157
+ yield* Effect.all([tally.warm, never.warm]);
158
+ const after = yield* headOf(tally.state);
159
+ yield* never.create("bob");
160
+ const owner = yield* never.owner;
161
+ expect([after, owner]).toStrictEqual([before, "bob"]);
162
+ });
163
+ const refusals = Effect.fnUntraced(function* refusals(test) {
164
+ const { key, tally } = yield* created(test);
165
+ const { stranger, unauthenticated } = test.target.callers;
166
+ const [robot, anyone] = yield* Effect.all([handle(test, stranger, key), handle(test, unauthenticated, key)]);
167
+ const refused = yield* reasonOf(robot.add(one));
168
+ const anonymous = yield* reasonOf(anyone.add(one));
169
+ const total = yield* tally.total;
170
+ expect(refused).toBeInstanceOf(CallerNotAllowedError);
171
+ expect(anonymous).toBeInstanceOf(UnauthenticatedError);
172
+ expect(total).toBe(none);
173
+ });
174
+ const outsiders = (headers) => Effect.fnUntraced(function* refuseOutsiders(test) {
175
+ const { key } = yield* created(test);
176
+ const outsider = yield* handle(test, headers, key);
177
+ const refused = yield* reasonOf(outsider.add(one));
178
+ const read = yield* reasonOf(outsider.total);
179
+ expect(refused).toBeInstanceOf(CallerNotAllowedError);
180
+ expect(read).toBeInstanceOf(CallerNotAllowedError);
181
+ });
182
+ const lostReply = Effect.fnUntraced(function* lostReply(test) {
183
+ const { tally } = yield* created(test);
184
+ yield* test.wire.loseNextReply;
185
+ const added = yield* tally.add(three);
186
+ const total = yield* tally.total;
187
+ expect([added, total]).toStrictEqual([three, three]);
188
+ });
189
+ const dropSockets = ({ wire }) => Effect.gen(function* dropEverySocket() {
190
+ const before = MutableRef.get(wire.opened);
191
+ yield* Effect.sync(() => {
192
+ for (const socket of wire.sockets) socket.close(abnormalClose, dropped);
193
+ });
194
+ yield* polled(Effect.sync(() => MutableRef.get(wire.opened)), (count) => count > before);
195
+ yield* Effect.sleep(resubscribed);
196
+ });
197
+ const reconnect = Effect.fnUntraced(function* reconnect(test) {
198
+ const { tally } = yield* created(test);
199
+ const totals = yield* collected(tally.totals);
200
+ const first = yield* nextOf(totals);
201
+ const next = yield* Effect.andThen(Effect.andThen(dropSockets(test), tally.add(two)), nextOf(totals));
202
+ yield* tally.add(one);
203
+ const last = yield* nextOf(totals);
204
+ expect([
205
+ first.value,
206
+ next.value,
207
+ last.value
208
+ ]).toStrictEqual([
209
+ none,
210
+ two,
211
+ three
212
+ ]);
213
+ expect(next.version).toBeGreaterThan(first.version);
214
+ expect(last.version).toBeGreaterThan(next.version);
215
+ });
216
+ const disposal = Effect.fnUntraced(function* disposal(test) {
217
+ const scope = yield* Scope.make();
218
+ const { tally } = yield* Scope.provide(created(test), scope);
219
+ const totals = yield* Scope.provide(collected(tally.totals), scope);
220
+ yield* nextOf(totals);
221
+ const open = test.wire.sockets.size;
222
+ yield* Scope.close(scope, Exit.void);
223
+ const left = yield* polled(Effect.sync(() => test.wire.sockets.size), (size) => size === none);
224
+ expect([open, left]).toStrictEqual([one, none]);
225
+ });
226
+ const titles = {
227
+ commands: "a command replies with its success or the contract's typed error",
228
+ creation: "create makes the actor once, and ensure attaches to it",
229
+ disposal: "disposing the client closes its live sockets",
230
+ foreign: "a caller from another organization or app is refused with CallerNotAllowedError",
231
+ forking: "a fork copies the actor at one cut into a new key, independent of its parent and siblings, once per fork id",
232
+ lostReply: "a command whose reply was lost is retried with its id and runs once",
233
+ readYourWrites: "a query right after the caller's own command reads that command's write",
234
+ reads: "queries and state read committed state, and live updates carry increasing versions",
235
+ reconnect: "a subscription that loses its socket reconnects and resumes without repeating an update",
236
+ refusals: "a caller the contract doesn't allow, or one without valid credentials, is refused and changes nothing",
237
+ warming: "warm opens an actor without changing it, and does nothing for a key never created"
238
+ };
239
+ const casesOf = (callers) => ({
240
+ commands,
241
+ creation,
242
+ disposal,
243
+ foreign: Option.match(Option.fromNullishOr(callers.foreign), {
244
+ onNone: () => () => Effect.die("this target declares no caller from another organization or app"),
245
+ onSome: outsiders
246
+ }),
247
+ forking,
248
+ lostReply,
249
+ readYourWrites,
250
+ reads,
251
+ reconnect,
252
+ refusals,
253
+ warming
254
+ });
255
+ const perTest = 6e4;
256
+ const isUnset = Schema.is(ClientTargetUnsetError);
257
+ const clientConformanceOf = ({ skip, target }) => (test) => {
258
+ for (const [client, connect] of clients) for (const name of Record.keys(titles)) {
259
+ const title = `${client}: ${titles[name]}`;
260
+ const run = ({ skip: skipCase }) => Effect.scoped(Effect.gen(function* runCase() {
261
+ const resolved = yield* target;
262
+ const wire = yield* wired;
263
+ yield* casesOf(resolved.callers)[name]({
264
+ connect,
265
+ target: resolved,
266
+ wire
267
+ });
268
+ })).pipe(Effect.catchIf(isUnset, ({ reason }) => Effect.sync(() => skipCase(reason))));
269
+ Option.match(Option.fromNullishOr(skip[name]), {
270
+ onNone: () => {
271
+ test.effect(title, run, perTest);
272
+ },
273
+ onSome: (reason) => {
274
+ test.effect.skip(`${title} (skipped: ${reason})`, run);
275
+ }
276
+ });
277
+ }
278
+ };
279
+ export { ClientTargetUnsetError, clientConformanceOf };
@@ -0,0 +1,8 @@
1
+ import { Schema } from "effect";
2
+ declare const ClientTargetUnsetError_base: Schema.Class<ClientTargetUnsetError, Schema.TaggedStruct<"ClientTargetUnsetError", {
3
+ readonly reason: Schema.String;
4
+ }>, import("effect/Cause").YieldableError & {
5
+ readonly brand: unique symbol;
6
+ }>;
7
+ export declare class ClientTargetUnsetError extends ClientTargetUnsetError_base {}
8
+ export {};
@@ -0,0 +1,4 @@
1
+ import { Schema } from "effect";
2
+ // src/client-target.errors.ts
3
+ var ClientTargetUnsetError = class extends Schema.TaggedError()("ClientTargetUnsetError", { reason: Schema.String }) {};
4
+ export { ClientTargetUnsetError };
@@ -0,0 +1,19 @@
1
+ import { guaranteeTitles } from "./guarantee-titles.pure.mjs";
2
+ import { Ledgers } from "./ledger/ledger.actor.mjs";
3
+ import { Vitest } from "@effect/vitest";
4
+ import { Effect, Layer, Scope } from "effect";
5
+ import { ActorHost } from "@akterjs/effect";
6
+ import { ActorRegistry } from "@akterjs/effect/contract/actor-registry";
7
+ type Storage<Failure> = Layer.Layer<ActorHost | ActorRegistry, Failure>;
8
+ type Engine<Failure, Services> = Effect.Effect<Storage<Failure>, Failure, Scope.Scope | Services>;
9
+ type GuaranteeName = keyof typeof guaranteeTitles;
10
+ interface Skipping<Failure, Services> {
11
+ readonly engine: Engine<Failure, Services>;
12
+ readonly hostTables?: string;
13
+ /** The Ledger implementation to run: the Effect SDK's by default, or the plain SDK's from `@akterjs/conformance/plain`. */
14
+ readonly ledgers?: Ledgers;
15
+ readonly skip: Readonly<Partial<Record<GuaranteeName, string>>>;
16
+ }
17
+ declare const conformanceOf: <Failure, Services>({ engine, hostTables, ledgers, skip }: Skipping<Failure, Services>) => ((test: Vitest.MethodsNonLive<Services>) => void);
18
+ declare const conformance: <Failure, Services>(engine: Engine<Failure, Services>) => ((test: Vitest.MethodsNonLive<Services>) => void);
19
+ export { type Engine, type GuaranteeName, type Ledgers, type Storage, conformance, conformanceOf };