@intellectual-frontiers/integrations 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +8 -2
  3. package/dist/governance/exchange.d.ts +224 -0
  4. package/dist/governance/exchange.js +86 -0
  5. package/dist/governance/ids.d.ts +61 -0
  6. package/dist/governance/ids.js +53 -0
  7. package/dist/governance/mod.d.ts +11 -0
  8. package/dist/governance/mod.js +12 -0
  9. package/dist/governance/observe.d.ts +172 -0
  10. package/dist/governance/observe.js +139 -0
  11. package/dist/logical/conformance.d.ts +44 -0
  12. package/dist/logical/conformance.js +108 -0
  13. package/dist/logical/constraints.d.ts +86 -0
  14. package/dist/logical/constraints.js +112 -0
  15. package/dist/logical/exchange.d.ts +98 -0
  16. package/dist/logical/exchange.js +135 -0
  17. package/dist/logical/ledger.d.ts +94 -0
  18. package/dist/logical/ledger.js +90 -0
  19. package/dist/logical/mapping.d.ts +64 -0
  20. package/dist/logical/mapping.js +99 -0
  21. package/dist/logical/mod.d.ts +18 -0
  22. package/dist/logical/mod.js +19 -0
  23. package/dist/logical/observe.d.ts +222 -0
  24. package/dist/logical/observe.js +156 -0
  25. package/dist/logical/plugin.d.ts +91 -0
  26. package/dist/logical/plugin.js +53 -0
  27. package/dist/logical/ports.d.ts +102 -0
  28. package/dist/logical/ports.js +31 -0
  29. package/dist/logical/registry.d.ts +72 -0
  30. package/dist/logical/registry.js +81 -0
  31. package/dist/logical/tree.d.ts +91 -0
  32. package/dist/logical/tree.js +114 -0
  33. package/dist/mod.d.ts +15 -0
  34. package/dist/mod.js +16 -0
  35. package/dist/physical/http/mod.d.ts +54 -0
  36. package/dist/physical/http/mod.js +114 -0
  37. package/dist/physical/transport/mod.d.ts +79 -0
  38. package/dist/physical/transport/mod.js +61 -0
  39. package/dist/surfaces/headless/mod.d.ts +46 -0
  40. package/dist/surfaces/headless/mod.js +258 -0
  41. package/package.json +67 -4
  42. package/src/governance/exchange.ts +220 -0
  43. package/src/governance/ids.ts +92 -0
  44. package/src/governance/mod.ts +12 -0
  45. package/src/governance/observe.ts +226 -0
  46. package/src/logical/conformance.ts +113 -0
  47. package/src/logical/constraints.ts +154 -0
  48. package/src/logical/exchange.ts +184 -0
  49. package/src/logical/ledger.ts +123 -0
  50. package/src/logical/mapping.ts +114 -0
  51. package/src/logical/mod.ts +19 -0
  52. package/src/logical/observe.ts +314 -0
  53. package/src/logical/plugin.ts +102 -0
  54. package/src/logical/ports.ts +89 -0
  55. package/src/logical/registry.ts +93 -0
  56. package/src/logical/tree.ts +153 -0
  57. package/src/mod.ts +16 -0
  58. package/src/physical/http/mod.ts +134 -0
  59. package/src/physical/transport/mod.ts +85 -0
  60. package/src/surfaces/headless/mod.ts +293 -0
@@ -0,0 +1,113 @@
1
+ // Spec: 0008-integrations-plugins FR-005, FR-006, FR-007, FR-008
2
+ /**
3
+ * The conformance suites of the extension points (commons integrations 0008-integrations-plugins): what every connector and every standards plugin must satisfy,
4
+ * as pure functions from the extension and its fixtures to findings. A plugin package runs them in its own tests and asserts that the findings are empty.
5
+ *
6
+ * @remarks
7
+ * The suites use no test framework: a finding is data (`ConformanceFinding`) with the extension's id, so that a registry can refuse an extension that does not conform.
8
+ *
9
+ * @module
10
+ */
11
+ import { isDenied, type Instant } from "@intellectual-frontiers/integrations/governance";
12
+ import { governanceProblems } from "@intellectual-frontiers/integrations/governance";
13
+ import type { Finding } from "./constraints.ts";
14
+ import type { Connector, Observation, PostureResult, PostureStatus } from "./observe.ts";
15
+ import type { StandardsPlugin } from "./plugin.ts";
16
+ import type { ReadPort } from "./ports.ts";
17
+ import { valuesOf, type Interchange } from "./tree.ts";
18
+
19
+ /** What a suite found wrong. */
20
+ export type ConformanceFinding = { readonly extension: string; readonly rule: string; readonly message: string };
21
+
22
+ /** A recorded run of a connector: the port it reads, the moment, and what is expected of the result. */
23
+ export type ConnectorFixture = {
24
+ readonly name: string;
25
+ readonly port: ReadPort;
26
+ readonly now: Instant;
27
+ readonly expect: {
28
+ readonly account?: string;
29
+ readonly posture?: Readonly<Record<string, string | number | boolean>>;
30
+ readonly labels?: Readonly<Record<string, number>>;
31
+ readonly policies?: Readonly<Record<string, PostureStatus>>;
32
+ };
33
+ };
34
+
35
+ const bad = (extension: string, rule: string, message: string): ConformanceFinding => ({ extension, rule, message });
36
+
37
+ function deniedProps(c: Connector, o: Observation): readonly string[] {
38
+ const out: string[] = [];
39
+ for (const r of o.records ?? []) for (const k of Object.keys(r.props)) if (isDenied(c.governance.denylist, k)) out.push(`${r.label}.${k}`);
40
+ return out;
41
+ }
42
+
43
+ /** The conformance of a connector over its fixtures: sound governance, a description that agrees with it, at least one fixture, a probe that answers, an observation that names the connector, keeps no denied field, is the same when observed twice, and meets each fixture's expectations. */
44
+ export async function conformConnector(c: Connector, fixtures: readonly ConnectorFixture[]): Promise<readonly ConformanceFinding[]> {
45
+ const id = c.governance.id;
46
+ const out: ConformanceFinding[] = [];
47
+ for (const p of governanceProblems(c.governance)) out.push(bad(id, `governance/${p.kind}`, "the governance of the connector has a problem"));
48
+ const d = c.describe();
49
+ if (d.id !== id || d.class !== c.governance.class || !d.readOnly) out.push(bad(id, "describe/disagrees", "describe does not say what the governance says"));
50
+ if (c.governance.contract.writes !== "never") out.push(bad(id, "contract/writes", "the contract does not say never"));
51
+ if (fixtures.length === 0) out.push(bad(id, "fixtures/none", "a connector has at least one fixture"));
52
+ for (const f of fixtures) {
53
+ const where = `${id}:${f.name}`;
54
+ const probe = await c.probe({ port: f.port, now: f.now });
55
+ if (probe.kind === "err") out.push(bad(where, "probe/fails", `the probe failed: ${probe.error.kind}`));
56
+ const first = await c.observe({ port: f.port, now: f.now });
57
+ if (first.kind === "err") {
58
+ out.push(bad(where, "observe/fails", `observe failed: ${first.error.kind}`));
59
+ continue;
60
+ }
61
+ const o = first.value;
62
+ if (o.provider !== id) out.push(bad(where, "observe/provider", "the observation does not name the connector as its provider"));
63
+ for (const k of deniedProps(c, o)) out.push(bad(where, "observe/denied-field", `a denied field was kept: ${k}`));
64
+ const second = await c.observe({ port: f.port, now: f.now });
65
+ if (second.kind === "err" || JSON.stringify(second.value) !== JSON.stringify(o)) out.push(bad(where, "observe/not-repeatable", "observing twice over the same answers gives two observations"));
66
+ if (f.expect.account !== undefined && o.account !== f.expect.account) out.push(bad(where, "expect/account", "the account is not the expected one"));
67
+ for (const [k, v] of Object.entries(f.expect.posture ?? {})) if (o.posture[k] !== v) out.push(bad(where, "expect/posture", `the fact ${k} is not as expected`));
68
+ for (const [label, n] of Object.entries(f.expect.labels ?? {})) if ((o.records ?? []).filter((r) => r.label === label).length !== n) out.push(bad(where, "expect/labels", `the number of records labelled ${label} is not ${n}`));
69
+ const results: readonly PostureResult[] = c.check(o, f.now);
70
+ for (const [pid, status] of Object.entries(f.expect.policies ?? {})) if (results.find((r) => r.id === pid)?.status !== status) out.push(bad(where, "expect/policy", `the policy ${pid} is not ${status}`));
71
+ }
72
+ return out;
73
+ }
74
+
75
+ /** The values of a tree that a text must not hold. */
76
+ const leaks = (text: string, tree: Interchange): boolean => valuesOf(tree).some((v) => v.length >= 4 && text.includes(v));
77
+
78
+ /** What a plugin is checked with: texts of its syntax that parse, from the issuer's published examples or generated, never real data. */
79
+ export type PluginSamples = { readonly valid: readonly string[]; readonly garbage: readonly string[] };
80
+
81
+ /** The conformance of a standards plugin: its codec parses each valid sample, serializes it and reads the result back to the same tree (round trip); it fails each garbage text as a syntax error that holds no part of the text; and its standards are registered with a licence that has terms. */
82
+ export function conformPlugin(p: StandardsPlugin, samples: PluginSamples): readonly ConformanceFinding[] {
83
+ const out: ConformanceFinding[] = [];
84
+ if (samples.valid.length === 0) out.push(bad(p.id, "samples/none", "a plugin has at least one valid sample"));
85
+ for (const [i, text] of samples.valid.entries()) {
86
+ const where = `${p.id}:valid[${i}]`;
87
+ const parsed = p.codec.parse(text);
88
+ if (parsed.kind === "err") {
89
+ out.push(bad(where, "codec/parse", `a valid sample does not parse: ${parsed.error.code}`));
90
+ continue;
91
+ }
92
+ const written = p.codec.serialize(parsed.value);
93
+ if (written.kind === "err") {
94
+ out.push(bad(where, "codec/serialize", `the tree does not serialize: ${written.error.code}`));
95
+ continue;
96
+ }
97
+ const again = p.codec.parse(written.value);
98
+ if (again.kind === "err" || JSON.stringify(again.value) !== JSON.stringify(parsed.value)) out.push(bad(where, "codec/round-trip", "parse, serialize and parse again gives another tree"));
99
+ }
100
+ for (const [i, text] of samples.garbage.entries()) {
101
+ const where = `${p.id}:garbage[${i}]`;
102
+ const parsed = p.codec.parse(text);
103
+ if (parsed.kind === "ok") out.push(bad(where, "codec/accepts-garbage", "a text that is not of the syntax parses"));
104
+ else if (text.length >= 4 && JSON.stringify(parsed.error).includes(text)) out.push(bad(where, "codec/echoes-input", "the error repeats the text it refused"));
105
+ }
106
+ for (const s of p.standards) if (s.license.terms.trim() === "") out.push(bad(`${p.id}:${s.urn}`, "standard/no-terms", "a standard has the terms of its licence"));
107
+ return out;
108
+ }
109
+
110
+ /** The findings of a validation, with none of their messages holding a value of the payload: the check a plugin's validation must pass. */
111
+ export function findingsHoldNoValue(fs: readonly Finding[], tree: Interchange): boolean {
112
+ return fs.every((f) => !leaks(`${f.message} ${f.path}`, tree));
113
+ }
@@ -0,0 +1,154 @@
1
+ // Spec: 0006-integrations-exchange FR-004, FR-005, FR-006, FR-007
2
+ /**
3
+ * Schema and Profile as typed constraints over the abstract tree, and validation (commons integrations 0006-integrations-exchange): a schema says which paths a
4
+ * transaction has and how many times, a profile adds constraints to a schema, a terminology says which codes a binding allows, and validation gives findings at the level
5
+ * where each was found (syntax, schema, profile, terminology, business rule).
6
+ *
7
+ * @remarks
8
+ * A finding has a level, a severity, a path, a code and a message made of the code and the path: it never holds a value of the payload, so that findings may be logged
9
+ * (commons integrations 0003-integrations-logical FR-003). A business rule is a function of the tree that returns findings, supplied by an agreement.
10
+ *
11
+ * @module
12
+ */
13
+ import { absurd, type Result } from "@intellectual-frontiers/core";
14
+ import type { BindingStrength, Ref, StandardUrn } from "@intellectual-frontiers/integrations/governance";
15
+ import { entries, occurrences, pathsOf, type Transaction } from "./tree.ts";
16
+
17
+ /** Where a finding was found. */
18
+ export type FindingLevel = "syntax" | "schema" | "profile" | "terminology" | "business-rule";
19
+
20
+ /** How bad a finding is. */
21
+ export type Severity = "error" | "warning" | "information";
22
+
23
+ /** What a finding says. */
24
+ export type FindingCode =
25
+ | "syntax-error"
26
+ | "unknown-path"
27
+ | "cardinality-min"
28
+ | "cardinality-max"
29
+ | "value-pattern"
30
+ | "value-fixed"
31
+ | "code-not-in-terminology"
32
+ | "terminology-unavailable"
33
+ | "business-rule"
34
+ | "unmapped-source-field"
35
+ | "lossy-mapping"
36
+ | "mapping-target-conflict";
37
+
38
+ const FINDING_CODE_TABLE: Readonly<Record<FindingCode, true>> = {
39
+ "syntax-error": true,
40
+ "unknown-path": true,
41
+ "cardinality-min": true,
42
+ "cardinality-max": true,
43
+ "value-pattern": true,
44
+ "value-fixed": true,
45
+ "code-not-in-terminology": true,
46
+ "terminology-unavailable": true,
47
+ "business-rule": true,
48
+ "unmapped-source-field": true,
49
+ "lossy-mapping": true,
50
+ "mapping-target-conflict": true,
51
+ };
52
+
53
+ /** Every finding code, as a closed list of strings a consumer may carry as data; the compiler holds it complete against `FindingCode`. */
54
+ export const FINDING_CODES: readonly FindingCode[] = Object.keys(FINDING_CODE_TABLE).filter((k): k is FindingCode => Object.hasOwn(FINDING_CODE_TABLE, k));
55
+
56
+ /** Every level of a finding. */
57
+ export const FINDING_LEVELS: readonly FindingLevel[] = ["syntax", "schema", "profile", "terminology", "business-rule"];
58
+
59
+ /** A finding: never a value of the payload. */
60
+ export type Finding = { readonly level: FindingLevel; readonly severity: Severity; readonly code: FindingCode; readonly path: string; readonly message: string };
61
+
62
+ /** A finding from its parts, its message made of the code and the path. */
63
+ export const finding = (level: FindingLevel, severity: Severity, code: FindingCode, path: string, note = ""): Finding => ({ level, severity, code, path, message: `${code} at ${path}${note === "" ? "" : `: ${note}`}` });
64
+
65
+ /** What a path of a schema must be. */
66
+ export type Constraint =
67
+ | { readonly kind: "cardinality"; readonly path: string; readonly min: number; readonly max: number | "*" }
68
+ | { readonly kind: "pattern"; readonly path: string; readonly regex: string }
69
+ | { readonly kind: "fixed"; readonly path: string; readonly value: string }
70
+ | { readonly kind: "binding"; readonly path: string; readonly terminology: Ref<"terminology">; readonly strength: BindingStrength };
71
+
72
+ /** A schema: the paths a kind of transaction has, with their constraints. A path with no constraint is allowed; a path not listed (and not below a listed one) is unknown. */
73
+ export type Schema = { readonly id: Ref<"schema">; readonly transaction: string; readonly paths: readonly string[]; readonly constraints: readonly Constraint[] };
74
+
75
+ /** A profile: more constraints on a schema. */
76
+ export type Profile = { readonly id: Ref<"profile">; readonly schema: Ref<"schema">; readonly constraints: readonly Constraint[] };
77
+
78
+ /** A code system or value set, as the codes it holds. Loaded from data the user supplies or the issuer publishes; the library embeds none. */
79
+ export type Terminology = { readonly id: Ref<"terminology">; readonly codes: ReadonlySet<string> };
80
+
81
+ /** Terminologies by urn. */
82
+ export type Terminologies = ReadonlyMap<StandardUrn, Terminology>;
83
+
84
+ /** A rule of business: a function of a transaction that gives findings (never of values). */
85
+ export type BusinessRule = (t: Transaction) => readonly Finding[];
86
+
87
+ function severityOf(strength: BindingStrength): Severity | undefined {
88
+ switch (strength) {
89
+ case "required":
90
+ return "error";
91
+ case "extensible":
92
+ return "warning";
93
+ case "preferred":
94
+ return "information";
95
+ case "example":
96
+ return undefined;
97
+ default:
98
+ return absurd(strength);
99
+ }
100
+ }
101
+
102
+ function checkConstraint(c: Constraint, level: "schema" | "profile", t: Transaction, terms: Terminologies): readonly Finding[] {
103
+ const out: Finding[] = [];
104
+ switch (c.kind) {
105
+ case "cardinality":
106
+ for (const [parent, n] of occurrences(t, c.path)) {
107
+ if (n < c.min) out.push(finding(level, "error", "cardinality-min", parent === t.id ? c.path : `${parent}.${c.path.slice(c.path.lastIndexOf(".") + 1)}`, `${n} of at least ${c.min}`));
108
+ if (c.max !== "*" && n > c.max) out.push(finding(level, "error", "cardinality-max", parent === t.id ? c.path : `${parent}.${c.path.slice(c.path.lastIndexOf(".") + 1)}`, `${n} of at most ${c.max}`));
109
+ }
110
+ return out;
111
+ case "pattern": {
112
+ const re = new RegExp(c.regex);
113
+ for (const e of entries(t)) if (e.path === c.path && !re.test(e.value)) out.push(finding(level, "error", "value-pattern", e.at, "does not match the pattern"));
114
+ return out;
115
+ }
116
+ case "fixed":
117
+ for (const e of entries(t)) if (e.path === c.path && e.value !== c.value) out.push(finding(level, "error", "value-fixed", e.at, "is not the fixed value"));
118
+ return out;
119
+ case "binding": {
120
+ const severity = severityOf(c.strength);
121
+ if (severity === undefined) return out;
122
+ const terminology = terms.get(c.terminology.urn);
123
+ for (const e of entries(t)) {
124
+ if (e.path !== c.path) continue;
125
+ if (terminology === undefined) out.push(finding("terminology", "warning", "terminology-unavailable", e.at, "the terminology was not loaded"));
126
+ else if (!terminology.codes.has(e.value)) out.push(finding("terminology", severity, "code-not-in-terminology", e.at, "the code is not in the bound terminology"));
127
+ }
128
+ return out;
129
+ }
130
+ default:
131
+ return absurd(c);
132
+ }
133
+ }
134
+
135
+ /** Every finding of a transaction against a schema, a profile where given, the terminologies loaded, and the rules of business supplied, in that order of level. Total and pure. */
136
+ export function validate(t: Transaction, schema: Schema, options: { readonly profile?: Profile; readonly terminologies?: Terminologies; readonly rules?: readonly BusinessRule[] } = {}): readonly Finding[] {
137
+ const terms = options.terminologies ?? new Map();
138
+ const out: Finding[] = [];
139
+ if (t.id !== schema.transaction) out.push(finding("schema", "error", "unknown-path", t.id, "the transaction is not the schema's"));
140
+ const known = new Set(schema.paths);
141
+ for (const p of pathsOf(t)) {
142
+ if (!known.has(p) && ![...known].some((k) => k !== t.id && p.startsWith(`${k}.`))) out.push(finding("schema", "error", "unknown-path", p));
143
+ }
144
+ for (const c of schema.constraints) out.push(...checkConstraint(c, "schema", t, terms));
145
+ if (options.profile !== undefined) for (const c of options.profile.constraints) out.push(...checkConstraint(c, "profile", t, terms));
146
+ for (const r of options.rules ?? []) out.push(...r(t));
147
+ return out;
148
+ }
149
+
150
+ /** Whether the findings hold an error. */
151
+ export const hasErrors = (fs: readonly Finding[]): boolean => fs.some((f) => f.severity === "error");
152
+
153
+ /** A result of a step that may give findings: the value, or the findings that stopped it. */
154
+ export type Checked<T> = Result<T, readonly Finding[]>;
@@ -0,0 +1,184 @@
1
+ // Spec: 0006-integrations-exchange FR-010, FR-011, FR-012
2
+ /**
3
+ * Acknowledgements, outcomes and the exchange state machine (commons integrations 0006-integrations-exchange): the typed acknowledgements of the standards
4
+ * (X12 TA1 and 999, HL7 ACK, FHIR OperationOutcome) reduced to one status, and the life of a message as a total transition function of a state and an event.
5
+ *
6
+ * @module
7
+ */
8
+ import { absurd, err, ok, type Result } from "@intellectual-frontiers/core";
9
+ import type { Instant } from "@intellectual-frontiers/integrations/governance";
10
+ import type { Finding } from "./constraints.ts";
11
+
12
+ /** What an acknowledgement says of what it acknowledges. */
13
+ export type AckStatus = "accepted" | "accepted-with-errors" | "rejected";
14
+
15
+ /** The codes of an HL7 v2 acknowledgement: application (AA, AE, AR) and commit (CA, CE, CR). */
16
+ export type Hl7AckCode = "AA" | "AE" | "AR" | "CA" | "CE" | "CR";
17
+
18
+ /** An acknowledgement or an outcome, by standard. It carries codes and counts and the findings (which hold no value), never a payload. */
19
+ export type Acknowledgement =
20
+ | { readonly kind: "x12-ta1"; readonly control: string; readonly status: AckStatus; readonly note: string }
21
+ | { readonly kind: "x12-999"; readonly control: string; readonly groupControl: string; readonly status: AckStatus; readonly errors: number }
22
+ | { readonly kind: "hl7-ack"; readonly control: string; readonly code: Hl7AckCode }
23
+ | { readonly kind: "fhir-operation-outcome"; readonly issues: readonly Finding[] };
24
+
25
+ /** What an acknowledgement comes to. */
26
+ export function statusOf(a: Acknowledgement): AckStatus {
27
+ switch (a.kind) {
28
+ case "x12-ta1":
29
+ case "x12-999":
30
+ return a.status;
31
+ case "hl7-ack":
32
+ switch (a.code) {
33
+ case "AA":
34
+ case "CA":
35
+ return "accepted";
36
+ case "AE":
37
+ case "CE":
38
+ return "accepted-with-errors";
39
+ case "AR":
40
+ case "CR":
41
+ return "rejected";
42
+ default:
43
+ return absurd(a.code);
44
+ }
45
+ case "fhir-operation-outcome":
46
+ return a.issues.some((i) => i.severity === "error") ? "rejected" : a.issues.some((i) => i.severity === "warning") ? "accepted-with-errors" : "accepted";
47
+ default:
48
+ return absurd(a);
49
+ }
50
+ }
51
+
52
+ const ACK_KIND_TABLE: Readonly<Record<Acknowledgement["kind"], true>> = { "x12-ta1": true, "x12-999": true, "hl7-ack": true, "fhir-operation-outcome": true };
53
+
54
+ /** Every kind of acknowledgement, as a closed list of strings a consumer may carry as data. */
55
+ export const ACK_KINDS: readonly Acknowledgement["kind"][] = Object.keys(ACK_KIND_TABLE).filter((k): k is Acknowledgement["kind"] => Object.hasOwn(ACK_KIND_TABLE, k));
56
+
57
+ /** Every acknowledgement status. */
58
+ export const ACK_STATUSES: readonly AckStatus[] = ["accepted", "accepted-with-errors", "rejected"];
59
+
60
+ /** Every reason a message is rejected: the partner said no (`nack`), or it was invalid on receipt (`invalid`). */
61
+ export const REJECTION_KINDS: readonly (Extract<ExchangeState, { kind: "rejected" }>["reason"])[] = ["nack", "invalid"];
62
+
63
+ /** Where a message is in its life. */
64
+ export type ExchangeState =
65
+ | { readonly kind: "pending" }
66
+ | { readonly kind: "sent"; readonly attempt: number; readonly at: Instant }
67
+ | { readonly kind: "received"; readonly at: Instant }
68
+ | { readonly kind: "retrying"; readonly attempt: number }
69
+ | { readonly kind: "acknowledged"; readonly status: "accepted" | "accepted-with-errors" }
70
+ | { readonly kind: "rejected"; readonly reason: "nack" | "invalid" }
71
+ | { readonly kind: "abandoned"; readonly attempts: number };
72
+
73
+ /** What happens to a message. */
74
+ export type ExchangeEvent =
75
+ | { readonly kind: "send"; readonly at: Instant }
76
+ | { readonly kind: "receive"; readonly at: Instant }
77
+ | { readonly kind: "ack"; readonly status: AckStatus }
78
+ | { readonly kind: "timeout" }
79
+ | { readonly kind: "retry"; readonly at: Instant }
80
+ | { readonly kind: "invalid" };
81
+
82
+ /** What the agreement allows. */
83
+ export type TransitionPolicy = { readonly maxAttempts: number };
84
+
85
+ /** An event that does not fit the state it came in. */
86
+ export type TransitionError = { readonly kind: "illegal"; readonly from: ExchangeState["kind"]; readonly event: ExchangeEvent["kind"] };
87
+
88
+ const illegal = (from: ExchangeState, event: ExchangeEvent): Result<ExchangeState, TransitionError> => err({ kind: "illegal", from: from.kind, event: event.kind });
89
+
90
+ function acked(status: AckStatus): ExchangeState {
91
+ switch (status) {
92
+ case "accepted":
93
+ case "accepted-with-errors":
94
+ return { kind: "acknowledged", status };
95
+ case "rejected":
96
+ return { kind: "rejected", reason: "nack" };
97
+ default:
98
+ return absurd(status);
99
+ }
100
+ }
101
+
102
+ /** The next state: total over every state and every event, an illegal pair giving an error and never throwing. */
103
+ export function transition(state: ExchangeState, event: ExchangeEvent, policy: TransitionPolicy): Result<ExchangeState, TransitionError> {
104
+ switch (state.kind) {
105
+ case "pending":
106
+ switch (event.kind) {
107
+ case "send":
108
+ return ok({ kind: "sent", attempt: 1, at: event.at });
109
+ case "receive":
110
+ return ok({ kind: "received", at: event.at });
111
+ case "ack":
112
+ case "timeout":
113
+ case "retry":
114
+ case "invalid":
115
+ return illegal(state, event);
116
+ default:
117
+ return absurd(event);
118
+ }
119
+ case "sent":
120
+ switch (event.kind) {
121
+ case "ack":
122
+ return ok(acked(event.status));
123
+ case "timeout":
124
+ return ok(state.attempt < policy.maxAttempts ? { kind: "retrying", attempt: state.attempt } : { kind: "abandoned", attempts: state.attempt });
125
+ case "send":
126
+ case "receive":
127
+ case "retry":
128
+ case "invalid":
129
+ return illegal(state, event);
130
+ default:
131
+ return absurd(event);
132
+ }
133
+ case "retrying":
134
+ switch (event.kind) {
135
+ case "retry":
136
+ return ok({ kind: "sent", attempt: state.attempt + 1, at: event.at });
137
+ case "send":
138
+ case "receive":
139
+ case "ack":
140
+ case "timeout":
141
+ case "invalid":
142
+ return illegal(state, event);
143
+ default:
144
+ return absurd(event);
145
+ }
146
+ case "received":
147
+ switch (event.kind) {
148
+ case "ack":
149
+ return ok(acked(event.status));
150
+ case "invalid":
151
+ return ok({ kind: "rejected", reason: "invalid" });
152
+ case "send":
153
+ case "receive":
154
+ case "timeout":
155
+ case "retry":
156
+ return illegal(state, event);
157
+ default:
158
+ return absurd(event);
159
+ }
160
+ case "acknowledged":
161
+ case "rejected":
162
+ case "abandoned":
163
+ return illegal(state, event);
164
+ default:
165
+ return absurd(state);
166
+ }
167
+ }
168
+
169
+ /** Whether a state is final: nothing follows it. */
170
+ export function isFinal(s: ExchangeState): boolean {
171
+ switch (s.kind) {
172
+ case "acknowledged":
173
+ case "rejected":
174
+ case "abandoned":
175
+ return true;
176
+ case "pending":
177
+ case "sent":
178
+ case "received":
179
+ case "retrying":
180
+ return false;
181
+ default:
182
+ return absurd(s);
183
+ }
184
+ }
@@ -0,0 +1,123 @@
1
+ // Spec: 0006-integrations-exchange FR-013, FR-014, FR-015
2
+ /**
3
+ * The ledger port of exchange (commons integrations 0006-integrations-exchange): a typed record of functions, each returning a `Result`, with which a consumer keeps the trail of a
4
+ * load without the library knowing where it is kept (a database, a file, memory). It appends stage events, checks the intake of a content by its hash, and records the outcome of a
5
+ * validation or an acknowledgement by code. A stage is an opaque branded text: the consumer's code list of stages lives with the consumer, not here. An event never carries a payload
6
+ * value: its fields are identifiers, a code, an instant and a digest, each made by a smart constructor that admits no free text.
7
+ *
8
+ * @module
9
+ */
10
+ import { err, ok, type Brand, type Result } from "@intellectual-frontiers/core";
11
+ import { brand, type IdError, type Instant, type Sha256 } from "@intellectual-frontiers/integrations/governance";
12
+
13
+ /** The identity of one load, as the consumer names it. */
14
+ export type LoadId = Brand<string, "LoadId">;
15
+ /** A stage of the consumer's pipeline, an opaque code such as `RECEIVED` or `VALIDATED`. */
16
+ export type Stage = Brand<string, "Stage">;
17
+ /** A code that says why, or what came of a check: lower-case words joined by dashes. */
18
+ export type OutcomeCode = Brand<string, "OutcomeCode">;
19
+ /** The key that names the same item across loads (a message id, a control number): what two contents of one item share. */
20
+ export type ItemKey = Brand<string, "ItemKey">;
21
+
22
+ const make = <B extends string>(what: B, pattern: RegExp, expected: string, text: string): Result<Brand<string, B>, IdError> => (pattern.test(text) ? ok(brand<B>(text)) : err({ kind: "id", what, expected }));
23
+
24
+ /** A load id: letters, digits and `. _ : -`, up to 128. Free text is refused, and the refusal does not repeat it. */
25
+ export const parseLoadId = (t: string): Result<LoadId, IdError> => make("LoadId", /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/, "letters, digits and . _ : -, up to 128", t);
26
+ /** A stage: upper-case words joined by underscores. */
27
+ export const parseStage = (t: string): Result<Stage, IdError> => make("Stage", /^[A-Z][A-Z0-9_]{1,31}$/, "upper-case words joined by underscores", t);
28
+ /** An outcome or reason code. */
29
+ export const parseOutcomeCode = (t: string): Result<OutcomeCode, IdError> => make("OutcomeCode", /^[a-z0-9][a-z0-9-]{0,63}$/, "lower-case words joined by dashes", t);
30
+ /** An item key. */
31
+ export const parseItemKey = (t: string): Result<ItemKey, IdError> => make("ItemKey", /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/, "letters, digits and . _ : -, up to 128", t);
32
+
33
+ /** One event of a load: a stage reached, with a reason code and a digest where there are any. Never a payload value. */
34
+ export type LedgerEvent = { readonly loadId: LoadId; readonly stage: Stage; readonly reasonCode?: OutcomeCode; readonly at: Instant; readonly contentHash?: Sha256 };
35
+
36
+ /** What a content is, on intake. */
37
+ export type IntakeRequest = { readonly loadId: LoadId; readonly itemKey: ItemKey; readonly contentHash: Sha256; readonly at: Instant };
38
+
39
+ /** What the ledger says of a content on intake: never seen; the same content seen before (in the load named); or another content of the same item (in the load named). */
40
+ export type Intake = { readonly kind: "first-seen" } | { readonly kind: "duplicate"; readonly of: LoadId } | { readonly kind: "conflict"; readonly with: LoadId };
41
+
42
+ /** Which check an outcome is of. */
43
+ export type OutcomeKind = "validation" | "acknowledgement";
44
+
45
+ /** The outcome of a check, by code. */
46
+ export type OutcomeRecord = { readonly loadId: LoadId; readonly kind: OutcomeKind; readonly code: OutcomeCode; readonly at: Instant };
47
+
48
+ /** Why the ledger could not answer. */
49
+ export type LedgerError = { readonly kind: "unavailable" } | { readonly kind: "unknown-load"; readonly loadId: LoadId };
50
+
51
+ /** The ledger port. */
52
+ export type LedgerPort = {
53
+ readonly append: (event: LedgerEvent) => Promise<Result<void, LedgerError>>;
54
+ readonly intake: (request: IntakeRequest) => Promise<Result<Intake, LedgerError>>;
55
+ readonly outcome: (record: OutcomeRecord) => Promise<Result<void, LedgerError>>;
56
+ readonly events: (loadId: LoadId) => Promise<Result<readonly LedgerEvent[], LedgerError>>;
57
+ readonly outcomes: (loadId: LoadId) => Promise<Result<readonly OutcomeRecord[], LedgerError>>;
58
+ };
59
+
60
+ /** A ledger in memory. */
61
+ export function memoryLedger(): LedgerPort {
62
+ const events = new Map<LoadId, LedgerEvent[]>();
63
+ const outcomes = new Map<LoadId, OutcomeRecord[]>();
64
+ const byHash = new Map<Sha256, LoadId>();
65
+ const byItem = new Map<ItemKey, { readonly hash: Sha256; readonly loadId: LoadId }>();
66
+ return {
67
+ append: (e) => {
68
+ events.set(e.loadId, [...(events.get(e.loadId) ?? []), e]);
69
+ return Promise.resolve(ok(undefined));
70
+ },
71
+ intake: (r) => {
72
+ const same = byHash.get(r.contentHash);
73
+ if (same !== undefined) return Promise.resolve(ok({ kind: "duplicate", of: same }));
74
+ const item = byItem.get(r.itemKey);
75
+ if (item !== undefined) return Promise.resolve(ok({ kind: "conflict", with: item.loadId }));
76
+ byHash.set(r.contentHash, r.loadId);
77
+ byItem.set(r.itemKey, { hash: r.contentHash, loadId: r.loadId });
78
+ return Promise.resolve(ok({ kind: "first-seen" }));
79
+ },
80
+ outcome: (o) => {
81
+ if (!events.has(o.loadId)) return Promise.resolve(err({ kind: "unknown-load", loadId: o.loadId }));
82
+ outcomes.set(o.loadId, [...(outcomes.get(o.loadId) ?? []), o]);
83
+ return Promise.resolve(ok(undefined));
84
+ },
85
+ events: (id) => Promise.resolve(ok(events.get(id) ?? [])),
86
+ outcomes: (id) => Promise.resolve(events.has(id) ? ok(outcomes.get(id) ?? []) : err({ kind: "unknown-load", loadId: id })),
87
+ };
88
+ }
89
+
90
+ /** What a ledger conformance finds wrong. */
91
+ export type LedgerFinding = { readonly rule: string; readonly message: string };
92
+
93
+ /**
94
+ * The conformance suite of a ledger: `make` gives a fresh, empty ledger each time. It finds a ledger that does not keep events in the order appended, that does not tell first-seen from
95
+ * duplicate from conflict, that accepts an outcome for a load it has no event of, or that does not keep outcomes. Any implementation (memory, a database) runs it.
96
+ */
97
+ export async function conformLedger(make: () => LedgerPort, ids: { readonly load: (n: number) => LoadId; readonly stage: (name: string) => Stage; readonly code: (name: string) => OutcomeCode; readonly key: (n: number) => ItemKey; readonly hash: (n: number) => Sha256; readonly at: Instant }): Promise<readonly LedgerFinding[]> {
98
+ const out: LedgerFinding[] = [];
99
+ const bad = (rule: string, message: string): void => void out.push({ rule, message });
100
+ const l = make();
101
+ const a = ids.load(1);
102
+ const b = ids.load(2);
103
+ const c = ids.load(3);
104
+ await l.append({ loadId: a, stage: ids.stage("RECEIVED"), at: ids.at });
105
+ await l.append({ loadId: a, stage: ids.stage("PARSED"), reasonCode: ids.code("ok"), at: ids.at, contentHash: ids.hash(1) });
106
+ const evs = await l.events(a);
107
+ if (evs.kind !== "ok" || evs.value.map((e) => e.stage).join(",") !== "RECEIVED,PARSED") bad("ledger/order", "events are not kept in the order appended");
108
+ const first = await l.intake({ loadId: a, itemKey: ids.key(1), contentHash: ids.hash(1), at: ids.at });
109
+ if (first.kind !== "ok" || first.value.kind !== "first-seen") bad("ledger/first-seen", "a content never seen is not first-seen");
110
+ const dup = await l.intake({ loadId: b, itemKey: ids.key(2), contentHash: ids.hash(1), at: ids.at });
111
+ if (dup.kind !== "ok" || dup.value.kind !== "duplicate" || dup.value.of !== a) bad("ledger/duplicate", "the same content is not a duplicate of the load that had it");
112
+ const conflict = await l.intake({ loadId: c, itemKey: ids.key(1), contentHash: ids.hash(3), at: ids.at });
113
+ if (conflict.kind !== "ok" || conflict.value.kind !== "conflict" || conflict.value.with !== a) bad("ledger/conflict", "another content of the same item is not a conflict");
114
+ const unknown = await l.outcome({ loadId: ids.load(99), kind: "validation", code: ids.code("none"), at: ids.at });
115
+ if (unknown.kind !== "err" || unknown.error.kind !== "unknown-load") bad("ledger/unknown-load", "an outcome for a load with no event is accepted");
116
+ await l.outcome({ loadId: a, kind: "validation", code: ids.code("cardinality-min"), at: ids.at });
117
+ const os = await l.outcomes(a);
118
+ if (os.kind !== "ok" || os.value.length !== 1 || os.value[0]?.code !== "cardinality-min") bad("ledger/outcomes", "an outcome recorded is not read back");
119
+ const other = make();
120
+ const fresh = await other.intake({ loadId: a, itemKey: ids.key(1), contentHash: ids.hash(1), at: ids.at });
121
+ if (fresh.kind !== "ok" || fresh.value.kind !== "first-seen") bad("ledger/fresh", "a fresh ledger remembers another's contents");
122
+ return out;
123
+ }