返回源码地图

packages/chord/src/contract.ts

v1.3.0 · 71023aec1546 · 22:契约、placement与兼容

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import { type Static, type TSchema, Type } from "typebox";
2import { Value } from "typebox/value";
3import { ChordError, invalid } from "./errors.ts";
4import { canonicalJson, fits, hash64 } from "./schema.ts";
5import type { Ctx, Exposed, Readable, RefBase, StateSource } from "./types.ts";
6
7const MEMBER = Symbol("chord.member");
8
9/** A method's arguments and result; `undefined`: it takes no arguments, or returns nothing (void). */
10export interface MethodSpec<
11 A extends TSchema | undefined = TSchema | undefined,
12 R extends TSchema | undefined = TSchema | undefined,
13> {
14 readonly [MEMBER]: "method";
15 readonly args: A;
16 readonly result: R;
17}
18
19export interface OpaqueSpec<T = unknown> {
20 readonly [MEMBER]: "opaque";
21 readonly id: string;
22 /** Type carrier only; never set. */
23 readonly type?: T;
24}
25
26/**
27 * A method. `method()`: no arguments (called as `ref.name(ctx)`, implemented as `(ctx) => …`) and no result.
28 * `method(args)`: no result, the handler returns nothing (void). `method(args, result)`, or `method(undefined, result)`
29 * for a method without arguments that returns something.
30 */
31export function method(): MethodSpec<undefined, undefined>;
32export function method<A extends TSchema>(args: A): MethodSpec<A, undefined>;
33export function method<A extends TSchema | undefined, R extends TSchema>(args: A, result: R): MethodSpec<A, R>;
34export function method(args?: TSchema, result?: TSchema): MethodSpec {
35 return { [MEMBER]: "method", args, result };
36}
37
38/** A native in-process object identified by `name@version` (local contracts only). */
39export const opaque = <T = unknown>(id: string): OpaqueSpec<T> => {
40 if (!/^[^@\s]+@\d+$/.test(id)) throw new TypeError(`opaque id must be name@version: ${id}`);
41 return { [MEMBER]: "opaque", id };
42};
43
44export interface VariantDef {
45 readonly state?: Readonly<Record<string, TSchema>>;
46 readonly methods?: Readonly<Record<string, MethodSpec>>;
47}
48
49/** Where objects of a remote type live: one named host. */
50export interface HostNamed {
51 readonly name: string;
52}
53
54/** Where objects of a remote type live: the host `prefix` + the input's string field `key` (`session:` + `session`). */
55export interface HostFamily<K extends string = string> {
56 readonly prefix: string;
57 readonly key: K;
58}
59
60/** A remote type's placement: data only, so a description carries it and every host can check it. */
61export type Placement = HostNamed | HostFamily;
62
63/** Objects of the type live on the host named `name` (`hostNamed("server")`). */
64export function hostNamed(name: string): HostNamed {
65 if (typeof name !== "string" || name === "") throw new TypeError("hostNamed needs a host name");
66 return { name };
67}
68
69/**
70 * Objects of the type live on `prefix` + the value of the input's string field `key`: `hostFamily("session:",
71 * "session")` puts `{ session: "S1", … }` on `session:S1`. The field is required and must be a non-empty string.
72 */
73export function hostFamily<const K extends string>(prefix: string, key: K): HostFamily<K> {
74 if (typeof prefix !== "string" || prefix === "") throw new TypeError("hostFamily needs a host-name prefix");
75 if (typeof key !== "string" || key === "") throw new TypeError("hostFamily needs an input field name");
76 return { prefix, key };
77}
78
79/** Required string fields of `I`: what a `hostFamily` may name. */
80type StringKeys<I> = { [K in keyof I]-?: I[K] extends string ? K : never }[keyof I] & string;
81/** The placements a remote type with input `I` may have. */
82export type PlacementFor<I> = HostNamed | HostFamily<StringKeys<I>>;
83
84/** The host an object of `placement` with this (normalized) input lives on. Throws `invalid/placement`. */
85export function resolveHost(typeName: string, placement: Placement, input: unknown): string {
86 if ("name" in placement) return placement.name;
87 const value =
88 input !== null && typeof input === "object" ? (input as Record<string, unknown>)[placement.key] : undefined;
89 if (typeof value !== "string" || value === "")
90 throw invalid("placement", `${typeName}: input field ${placement.key} names no host`);
91 return placement.prefix + value;
92}
93
94/** Whether the host named `hostName` may serve a type of `placement`. */
95export const placedOn = (placement: Placement, hostName: string): boolean =>
96 "name" in placement
97 ? placement.name === hostName
98 : hostName.startsWith(placement.prefix) && hostName.length > placement.prefix.length;
99
100export const placementText = (placement: Placement): string =>
101 "name" in placement ? placement.name : `${placement.prefix}<${placement.key}>`;
102
103export interface RemoteDef {
104 readonly version: number;
105 readonly input: TSchema;
106 /** Where its objects live: `hostNamed(…)` or `hostFamily(…)`. Part of the contract (and its fingerprint). */
107 readonly host: Placement;
108 readonly variants: Readonly<Record<string, VariantDef>>;
109}
110
111/** A local member: a method, an opaque native object, or a state member described by its schema. */
112export type LocalMember = MethodSpec | OpaqueSpec | TSchema;
113
114export interface LocalDef {
115 readonly version: number;
116 readonly input: TSchema;
117 readonly members?: Readonly<Record<string, LocalMember>>;
118}
119
120// A description travels as a reference's contract token (wire.ts), so it is declared once, as the schema that validates it.
121// `TSchema` is an empty interface: any object is one, which is all a peer's schema is checked for here.
122const SchemaObject = Type.Unsafe<TSchema>(Type.Object({}));
123
124const MemberDescriptionSchema = Type.Union([
125 // Absent `args`: the method takes none. Absent `result`: it returns nothing.
126 Type.Object({
127 kind: Type.Literal("method"),
128 args: Type.Optional(SchemaObject),
129 result: Type.Optional(SchemaObject),
130 }),
131 Type.Object({ kind: Type.Literal("state"), schema: SchemaObject }),
132 Type.Object({ kind: Type.Literal("opaque"), id: Type.String() }),
133]);
134export type MemberDescription = Static<typeof MemberDescriptionSchema>;
135
136/** Local contracts have one unnamed variant. */
137export const LOCAL_VARIANT = "";
138
139const PlacementSchema = Type.Union([
140 Type.Object({ name: Type.String({ minLength: 1 }) }, { additionalProperties: false }),
141 Type.Object(
142 { prefix: Type.String({ minLength: 1 }), key: Type.String({ minLength: 1 }) },
143 { additionalProperties: false },
144 ),
145]);
146
147export const DescriptionSchema = Type.Object({
148 name: Type.String({ minLength: 1 }),
149 scope: Type.Union([Type.Literal("remote"), Type.Literal("local")]),
150 version: Type.Integer(),
151 input: SchemaObject,
152 /** Remote types only (required there): where their objects live. */
153 host: Type.Optional(PlacementSchema),
154 variants: Type.Record(Type.String(), Type.Record(Type.String(), MemberDescriptionSchema)),
155});
156export type Description = Static<typeof DescriptionSchema>;
157
158interface ContractBase {
159 readonly name: string;
160 readonly version: number;
161 readonly input: TSchema;
162 readonly description: Description;
163 readonly fingerprint: string;
164}
165
166export interface RemoteContract<D extends RemoteDef = RemoteDef> extends ContractBase {
167 readonly scope: "remote";
168 readonly def: D;
169}
170
171export interface LocalContract<D extends LocalDef = LocalDef> extends ContractBase {
172 readonly scope: "local";
173 readonly def: D;
174}
175
176export type AnyContract = RemoteContract | LocalContract;
177
178/** Names a reference uses itself; members may not use them. */
179export const RESERVED_MEMBERS: ReadonlySet<string> = new Set([
180 "variant",
181 "status",
182 "ready",
183 "shape",
184 "error",
185 "onShape",
186 "onStatus",
187 "release",
188 "then",
189 "contract",
190]);
191
192function describeMember(name: string, member: unknown, scope: "remote" | "local"): MemberDescription {
193 if (RESERVED_MEMBERS.has(name)) throw new TypeError(`member name is reserved: ${name}`);
194 const brand = (member as { [MEMBER]?: string })[MEMBER];
195 if (brand === "method") {
196 const spec = member as MethodSpec;
197 return {
198 kind: "method",
199 ...(spec.args === undefined ? {} : { args: spec.args }),
200 ...(spec.result === undefined ? {} : { result: spec.result }),
201 };
202 }
203 if (brand === "opaque") {
204 if (scope === "remote") throw new TypeError(`remote contracts cannot expose opaque members: ${name}`);
205 return { kind: "opaque", id: (member as OpaqueSpec).id };
206 }
207 return { kind: "state", schema: member as TSchema };
208}
209
210function finish<C extends AnyContract>(contract: Omit<C, "fingerprint">): C {
211 return { ...contract, fingerprint: hash64(canonicalJson(contract.description)) } as C;
212}
213
214function checkHeader(name: string, version: number): void {
215 if (!name) throw new TypeError("contract name is empty");
216 if (!Number.isInteger(version) || version < 1) throw new TypeError(`contract version must be a positive integer`);
217}
218
219export function remote<const D extends RemoteDef>(
220 name: string,
221 def: D & { readonly host: PlacementFor<Static<D["input"]>> },
222): RemoteContract<D> {
223 checkHeader(name, def.version);
224 const placement = def.host as Placement | undefined;
225 if (placement === undefined || !Value.Check(PlacementSchema, placement))
226 throw new TypeError(`remote contract ${name} needs \`host\`: hostNamed(…) or hostFamily(…)`);
227 // A JSON copy: the description travels, and a placement object may carry nothing else.
228 const host: Placement =
229 "name" in placement ? { name: placement.name } : { prefix: placement.prefix, key: placement.key };
230 const variants: Record<string, Record<string, MemberDescription>> = {};
231 if (Object.keys(def.variants).length === 0) throw new TypeError(`remote contract ${name} has no variants`);
232 for (const [kind, variant] of Object.entries(def.variants)) {
233 const members: Record<string, MemberDescription> = {};
234 for (const [key, schema] of Object.entries(variant.state ?? {}))
235 members[key] = describeMember(key, schema, "remote");
236 for (const [key, spec] of Object.entries(variant.methods ?? {})) {
237 if (key in members) throw new TypeError(`member ${key} is both state and method in ${name}.${kind}`);
238 members[key] = describeMember(key, spec, "remote");
239 if (members[key].kind !== "method") throw new TypeError(`methods.${key} is not a method()`);
240 }
241 variants[kind] = members;
242 }
243 const description: Description = { name, scope: "remote", version: def.version, input: def.input, host, variants };
244 return finish<RemoteContract<D>>({
245 scope: "remote",
246 name,
247 version: def.version,
248 input: def.input,
249 def,
250 description,
251 });
252}
253
254export function local<const D extends LocalDef>(name: string, def: D): LocalContract<D> {
255 checkHeader(name, def.version);
256 const members: Record<string, MemberDescription> = {};
257 for (const [key, member] of Object.entries(def.members ?? {})) members[key] = describeMember(key, member, "local");
258 const description: Description = {
259 name,
260 scope: "local",
261 version: def.version,
262 input: def.input,
263 variants: { [LOCAL_VARIANT]: members },
264 };
265 return finish<LocalContract<D>>({ scope: "local", name, version: def.version, input: def.input, def, description });
266}
267
268/**
269 * A consumer token received over a link (only its description travels). Has no `def`, so it is only good for binding
270 * and validation, never for TypeScript types.
271 */
272export function contractFromDescription(description: Description): AnyContract {
273 const { name, scope, version, input, host } = description;
274 if (
275 typeof name !== "string" ||
276 (scope !== "remote" && scope !== "local") ||
277 !Number.isInteger(version) ||
278 (scope === "remote") !== (host !== undefined)
279 ) {
280 throw new ChordError("invalid", "malformed contract token", { reason: "token" });
281 }
282 const base = { name, version, input, description, fingerprint: hash64(canonicalJson(description)) };
283 return scope === "remote"
284 ? { ...base, scope, def: { version, input, host: host!, variants: {} } }
285 : { ...base, scope, def: { version, input } };
286}
287
288/** Returns why `provider` does not cover `consumer`, or undefined when it does. */
289export function coverage(provider: Description, consumer: Description): string | undefined {
290 if (provider.name !== consumer.name || provider.scope !== consumer.scope) return "different type";
291 if (!samePlacement(provider, consumer)) return "host";
292 if (!fits(consumer.input, provider.input)) return "input";
293 for (const [kind, consumerMembers] of Object.entries(consumer.variants)) {
294 const providerMembers = provider.variants[kind];
295 if (providerMembers === undefined) return `variant ${kind} missing`;
296 for (const [name, wanted] of Object.entries(consumerMembers)) {
297 const offered = providerMembers[name];
298 if (offered === undefined || offered.kind !== wanted.kind) return `${kind}.${name} missing or of another kind`;
299 if (offered.kind === "method" && wanted.kind === "method") {
300 // Both take arguments or neither does; a consumer that expects no result accepts any.
301 if ((wanted.args === undefined) !== (offered.args === undefined)) return `${kind}.${name} arguments`;
302 if (wanted.args !== undefined && offered.args !== undefined && !fits(wanted.args, offered.args))
303 return `${kind}.${name} arguments`;
304 if (wanted.result !== undefined && (offered.result === undefined || !fits(offered.result, wanted.result)))
305 return `${kind}.${name} result`;
306 } else if (offered.kind === "state" && wanted.kind === "state") {
307 if (!fits(offered.schema, wanted.schema)) return `${kind}.${name} state`;
308 } else if (offered.kind === "opaque" && wanted.kind === "opaque" && offered.id !== wanted.id) {
309 return `${kind}.${name} opaque ${offered.id} != ${wanted.id}`;
310 }
311 }
312 }
313 return undefined;
314}
315
316const samePlacement = (a: Description, b: Description): boolean =>
317 canonicalJson(a.host ?? null) === canonicalJson(b.host ?? null);
318const placementOf = (description: Description): string =>
319 description.host === undefined ? "(local)" : placementText(description.host);
320
321/** Maps the provider's current implementation to the view a consumer of an older contract version expects. */
322export type Adapter = (current: Record<string, unknown>) => Record<string, unknown>;
323export type Accepts = Readonly<Record<number, Adapter>>;
324
325/** How a consumer token binds to a provider: directly or through an `accepts` adapter. Throws contract_mismatch. */
326export function bind(provider: AnyContract, accepts: Accepts | undefined, consumer: AnyContract): Adapter | undefined {
327 if (provider.fingerprint === consumer.fingerprint) return undefined;
328 // A moved type is another type for its consumers: no adapter reaches across hosts.
329 if (!samePlacement(provider.description, consumer.description)) {
330 throw new ChordError(
331 "contract_mismatch",
332 `${provider.name} lives on ${placementOf(provider.description)}, the consumer expects ${placementOf(consumer.description)}`,
333 );
334 }
335 if (provider.version === consumer.version) {
336 const reason = coverage(provider.description, consumer.description);
337 if (reason === undefined) return undefined;
338 throw new ChordError(
339 "contract_mismatch",
340 `${provider.name}@${provider.version} does not cover the consumer's description (${reason}); forgotten version bump?`,
341 );
342 }
343 const adapter = accepts?.[consumer.version];
344 if (adapter === undefined) {
345 throw new ChordError(
346 "contract_mismatch",
347 `${provider.name}: provider version ${provider.version}, consumer version ${consumer.version}, no accepts adapter`,
348 );
349 }
350 return adapter;
351}
352
353// ─── Static types ────────────────────────────────────────────────────────────
354
355type Empty = Record<never, never>;
356type StateOf<V> = V extends { readonly state: infer S extends Readonly<Record<string, TSchema>> } ? S : Empty;
357type StaticOf<S> = S extends TSchema ? Static<S> : never;
358type MethodsOf<V> = V extends { readonly methods: infer M extends Readonly<Record<string, MethodSpec>> } ? M : Empty;
359
360/** What a handler returns: the result's value, or nothing for a void method. */
361type Returned<R> = [R] extends [TSchema] ? Static<R> | Promise<Static<R>> : void | Promise<void>;
362/** What a call resolves to. */
363type Resolved<R> = [R] extends [TSchema] ? Static<R> : undefined;
364
365/** A method's handler; `P` is the app's principal type (`ctx.principal`). */
366export type MethodImplementation<M, P = unknown> = M extends MethodSpec<infer A, infer R>
367 ? [A] extends [TSchema]
368 ? (args: Static<A>, ctx: Ctx<P>) => Returned<R>
369 : (ctx: Ctx<P>) => Returned<R>
370 : never;
371export type Call<M> = M extends MethodSpec<infer A, infer R>
372 ? [A] extends [TSchema]
373 ? (args: Static<A>, ctx?: Ctx) => Promise<Resolved<R>>
374 : (ctx?: Ctx) => Promise<Resolved<R>>
375 : never;
376
377/** Whether `contract`'s method `name` takes no arguments (it is called as `ref.name(ctx)`). */
378export function takesNoArgs(contract: AnyContract, name: string): boolean {
379 for (const members of Object.values(contract.description.variants)) {
380 const member = members[name];
381 if (member?.kind === "method") return member.args === undefined;
382 }
383 return false;
384}
385
386type VariantImplementation<K, V, P> = { readonly variant: K } & {
387 readonly [S in keyof StateOf<V>]: StateSource<StaticOf<StateOf<V>[S]>>;
388} & {
389 readonly [M in keyof MethodsOf<V>]: MethodImplementation<MethodsOf<V>[M], P>;
390};
391/**
392 * A reference in one variant: its state members are plain readables (a reference you hold has its state) and its
393 * methods calls. `variant` discriminates the union `Ref` is for a multi-variant type.
394 */
395type VariantRef<C extends AnyContract, K, V> = RefBase<C> & { readonly variant: K } & {
396 readonly [S in keyof StateOf<V>]: Readable<StaticOf<StateOf<V>[S]>>;
397} & {
398 readonly [M in keyof MethodsOf<V>]: Call<MethodsOf<V>[M]>;
399};
400
401type LocalImplementationMember<M, P> = M extends MethodSpec
402 ? MethodImplementation<M, P>
403 : M extends OpaqueSpec<infer T>
404 ? T | Exposed<T>
405 : M extends TSchema
406 ? StateSource<Static<M>>
407 : never;
408type LocalRefMember<M> = M extends MethodSpec
409 ? Call<M>
410 : M extends OpaqueSpec<infer T>
411 ? T | undefined
412 : M extends TSchema
413 ? Readable<Static<M>>
414 : never;
415type LocalMembers<D> = D extends { readonly members: infer M extends Readonly<Record<string, LocalMember>> }
416 ? M
417 : Empty;
418
419export type InputOf<C> = C extends { readonly def: { readonly input: infer I extends TSchema } } ? Static<I> : never;
420
421/** What a factory returns for contract C; its methods' `ctx.principal` is `P`. */
422export type ImplementationOf<C, P = unknown> = C extends RemoteContract<infer D>
423 ? { [K in keyof D["variants"]]: VariantImplementation<K, D["variants"][K], P> }[keyof D["variants"]]
424 : C extends LocalContract<infer D>
425 ? { readonly [K in keyof LocalMembers<D>]: LocalImplementationMember<LocalMembers<D>[K], P> } & Record<
426 string,
427 unknown
428 >
429 : never;
430
431/**
432 * What `get` returns for contract C. A remote type's reference is a union discriminated by `variant`: another variant's
433 * members are reachable only after narrowing (`if (ref.variant === "editor") ref.add(…)`). A local type's reference has
434 * its members.
435 */
436export type Ref<C extends AnyContract = AnyContract> = C extends RemoteContract<infer D>
437 ? { [K in keyof D["variants"]]: VariantRef<C, K, D["variants"][K]> }[keyof D["variants"]]
438 : C extends LocalContract<infer D>
439 ? RefBase<C> & { readonly [K in keyof LocalMembers<D>]: LocalRefMember<LocalMembers<D>[K]> }
440 : never;