@earendil-works/chord 0.0.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 (98) hide show
  1. package/README.md +205 -0
  2. package/dist/api.d.ts +15 -0
  3. package/dist/api.d.ts.map +1 -0
  4. package/dist/api.js +72 -0
  5. package/dist/api.js.map +1 -0
  6. package/dist/bundler.d.ts +6 -0
  7. package/dist/bundler.d.ts.map +1 -0
  8. package/dist/bundler.js +3 -0
  9. package/dist/bundler.js.map +1 -0
  10. package/dist/context/index.d.ts +24 -0
  11. package/dist/context/index.d.ts.map +1 -0
  12. package/dist/context/index.js +97 -0
  13. package/dist/context/index.js.map +1 -0
  14. package/dist/delta/index.d.ts +119 -0
  15. package/dist/delta/index.d.ts.map +1 -0
  16. package/dist/delta/index.js +1213 -0
  17. package/dist/delta/index.js.map +1 -0
  18. package/dist/facets/host.d.ts +12 -0
  19. package/dist/facets/host.d.ts.map +1 -0
  20. package/dist/facets/host.js +763 -0
  21. package/dist/facets/host.js.map +1 -0
  22. package/dist/facets/loader.d.ts +3 -0
  23. package/dist/facets/loader.d.ts.map +1 -0
  24. package/dist/facets/loader.js +5 -0
  25. package/dist/facets/loader.js.map +1 -0
  26. package/dist/index.d.ts +11 -0
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/index.js +10 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/json.d.ts +4 -0
  31. package/dist/json.d.ts.map +1 -0
  32. package/dist/json.js +57 -0
  33. package/dist/json.js.map +1 -0
  34. package/dist/node/bundle-loader.d.ts +30 -0
  35. package/dist/node/bundle-loader.d.ts.map +1 -0
  36. package/dist/node/bundle-loader.js +377 -0
  37. package/dist/node/bundle-loader.js.map +1 -0
  38. package/dist/node/bundle.d.ts +26 -0
  39. package/dist/node/bundle.d.ts.map +1 -0
  40. package/dist/node/bundle.js +183 -0
  41. package/dist/node/bundle.js.map +1 -0
  42. package/dist/node/manifest.d.ts +36 -0
  43. package/dist/node/manifest.d.ts.map +1 -0
  44. package/dist/node/manifest.js +6 -0
  45. package/dist/node/manifest.js.map +1 -0
  46. package/dist/node/package.d.ts +15 -0
  47. package/dist/node/package.d.ts.map +1 -0
  48. package/dist/node/package.js +199 -0
  49. package/dist/node/package.js.map +1 -0
  50. package/dist/node.d.ts +5 -0
  51. package/dist/node.d.ts.map +1 -0
  52. package/dist/node.js +3 -0
  53. package/dist/node.js.map +1 -0
  54. package/dist/services/consumer.d.ts +11 -0
  55. package/dist/services/consumer.d.ts.map +1 -0
  56. package/dist/services/consumer.js +537 -0
  57. package/dist/services/consumer.js.map +1 -0
  58. package/dist/services/errors.d.ts +8 -0
  59. package/dist/services/errors.d.ts.map +1 -0
  60. package/dist/services/errors.js +22 -0
  61. package/dist/services/errors.js.map +1 -0
  62. package/dist/services/handle.d.ts +15 -0
  63. package/dist/services/handle.d.ts.map +1 -0
  64. package/dist/services/handle.js +99 -0
  65. package/dist/services/handle.js.map +1 -0
  66. package/dist/services/instances.d.ts +25 -0
  67. package/dist/services/instances.d.ts.map +1 -0
  68. package/dist/services/instances.js +137 -0
  69. package/dist/services/instances.js.map +1 -0
  70. package/dist/services/loopback.d.ts +5 -0
  71. package/dist/services/loopback.d.ts.map +1 -0
  72. package/dist/services/loopback.js +15 -0
  73. package/dist/services/loopback.js.map +1 -0
  74. package/dist/services/provider.d.ts +37 -0
  75. package/dist/services/provider.d.ts.map +1 -0
  76. package/dist/services/provider.js +472 -0
  77. package/dist/services/provider.js.map +1 -0
  78. package/dist/services/state-codec.d.ts +15 -0
  79. package/dist/services/state-codec.d.ts.map +1 -0
  80. package/dist/services/state-codec.js +115 -0
  81. package/dist/services/state-codec.js.map +1 -0
  82. package/dist/services/state-internals.d.ts +11 -0
  83. package/dist/services/state-internals.d.ts.map +1 -0
  84. package/dist/services/state-internals.js +10 -0
  85. package/dist/services/state-internals.js.map +1 -0
  86. package/dist/services/state.d.ts +23 -0
  87. package/dist/services/state.d.ts.map +1 -0
  88. package/dist/services/state.js +124 -0
  89. package/dist/services/state.js.map +1 -0
  90. package/dist/services/wire.d.ts +60 -0
  91. package/dist/services/wire.d.ts.map +1 -0
  92. package/dist/services/wire.js +173 -0
  93. package/dist/services/wire.js.map +1 -0
  94. package/dist/types.d.ts +203 -0
  95. package/dist/types.d.ts.map +1 -0
  96. package/dist/types.js +2 -0
  97. package/dist/types.js.map +1 -0
  98. package/package.json +72 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src/services/provider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,OAAO,EACP,SAAS,EACT,qBAAqB,EACrB,OAAO,EACP,WAAW,EACX,qBAAqB,EAIrB,WAAW,EACX,qBAAqB,EACrB,mBAAmB,EAEnB,MAAM,aAAa,CAAC;AAmCrB,UAAU,yBAAyB;IAClC,QAAQ,CAAC,OAAO,EAAE;QAAE,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,CAAC;IACpE,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;CAC3B;AAYD,MAAM,MAAM,sBAAsB,GAAG,CACpC,cAAc,EAAE,MAAM,EACtB,MAAM,EAAE,qBAAqB,EAC7B,OAAO,EAAE,OAAO,KACZ,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAE1B,yFAAyF;AACzF,MAAM,WAAW,qBAAqB;IACrC,MAAM,CAAC,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,sBAAsB,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC,CAAC;IAC7G,OAAO,IAAI,IAAI,CAAC;CAChB;AAED,qBAAa,qBAAqB;;IAKjC,YAAY,OAAO,EAAE,SAAS,CAAC,yBAAyB,GAAG;QAAE,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC,EAAE,EAuBpF;IAED,IAAI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qB,GAAG,qBAAqB,CAoClG;AAED,wBAAgB,mCAAmC,CAAC,SAAS,EAAE,MAAM,EAAE,cAAc,EAAE,OAAO,GAAG,IAAI,CAEpG","sourcesContent":["import type {\n\tContext,\n\tJsonValue,\n\tRemoteServiceContract,\n\tService,\n\tServiceCall,\n\tServiceCatalogueEntry,\n\tServiceInstanceAddress,\n\tServiceInstanceSnapshot,\n\tServiceMemberSnapshot,\n\tServiceMode,\n\tServiceProviderUpdate,\n\tServiceSubscription,\n\tServiceSubscriptionSnapshot,\n} from \"../types.ts\";\nimport { RemoteServiceError } from \"./errors.ts\";\nimport { serviceDeliveryContext } from \"./state.ts\";\nimport { getReplicatedStateInternals, type ReplicatedStateInternals } from \"./state-internals.ts\";\nimport { decodeServiceControlCall } from \"./wire.ts\";\n\ntype RemoteMethod = (...args: unknown[]) => unknown;\n\ntype InstanceMember =\n\t| { readonly kind: \"method\"; readonly method: RemoteMethod }\n\t| { readonly kind: \"state\"; readonly state: ReplicatedStateInternals };\n\ntype ServiceMemberKind = InstanceMember[\"kind\"];\n\ninterface ClassifiedRemoteServiceImplementation {\n\treadonly implementation: object;\n\treadonly members: Map<string, InstanceMember>;\n}\n\ninterface ProviderInstance {\n\treadonly address?: ServiceInstanceAddress;\n\treadonly implementation: object;\n\treadonly members: ReadonlyMap<string, InstanceMember>;\n\treadonly removeMemberListeners: readonly (() => void)[];\n\tactive: boolean;\n}\n\ninterface ProviderSubscriber {\n\treadonly listener: (update: ServiceProviderUpdate, context: Context) => void;\n\treadonly buffer: { readonly update: ServiceProviderUpdate; readonly context: Context }[];\n\tactive: boolean;\n\tterminated: boolean;\n\tclosed: boolean;\n}\n\ninterface ServiceProviderDefinition {\n\treadonly service: { readonly id: string; readonly local?: boolean };\n\treadonly mode: ServiceMode;\n}\n\ninterface ServiceRegistration {\n\treadonly serviceId: string;\n\treadonly mode: ServiceMode;\n\tsingleton?: ProviderInstance;\n\tsingletonShape?: ReadonlyMap<string, ServiceMemberKind>;\n\treadonly instances: Map<string, ProviderInstance>;\n\treadonly generations: Map<string, number>;\n\treadonly subscribers: Set<ProviderSubscriber>;\n}\n\nexport type ServiceUpdatePublisher = (\n\tsubscriptionId: string,\n\tupdate: ServiceProviderUpdate,\n\tcontext: Context,\n) => void | Promise<void>;\n\n/** Hosts one provider for one remote consumer and owns that consumer's subscriptions. */\nexport interface RemoteServiceEndpoint {\n\tinvoke(call: ServiceCall, publish: ServiceUpdatePublisher, context: Context): Promise<JsonValue | undefined>;\n\tdispose(): void;\n}\n\nexport class RemoteServiceProvider {\n\treadonly #catalogue: readonly ServiceCatalogueEntry[];\n\treadonly #registrations = new Map<string, ServiceRegistration>();\n\t#disposed = false;\n\n\tconstructor(entries: readonly (ServiceProviderDefinition | { readonly id: string })[]) {\n\t\tconst definitions = entries.map(\n\t\t\t(entry): ServiceProviderDefinition => (\"service\" in entry ? entry : { service: entry, mode: \"singleton\" }),\n\t\t);\n\t\tfor (const { service } of definitions) {\n\t\t\tif (\"local\" in service && service.local === true) {\n\t\t\t\tthrow new TypeError(`Local service ${service.id} cannot be published remotely`);\n\t\t\t}\n\t\t}\n\t\tconst ids = definitions.map(({ service }) => service.id);\n\t\tif (new Set(ids).size !== ids.length) throw new TypeError(\"Remote service catalogue contains duplicate IDs\");\n\t\tthis.#catalogue = Object.freeze(\n\t\t\tdefinitions.map(({ service, mode }) => Object.freeze({ serviceId: service.id, mode })),\n\t\t);\n\t\tfor (const { service, mode } of definitions) {\n\t\t\tthis.#registrations.set(service.id, {\n\t\t\t\tserviceId: service.id,\n\t\t\t\tmode,\n\t\t\t\tinstances: new Map(),\n\t\t\t\tgenerations: new Map(),\n\t\t\t\tsubscribers: new Set(),\n\t\t\t});\n\t\t}\n\t}\n\n\tget catalogue(): readonly ServiceCatalogueEntry[] {\n\t\treturn this.#catalogue;\n\t}\n\n\tprovide<T>(service: Service<T>, implementation: NoInfer<RemoteServiceContract<T>>): void {\n\t\tthis.#assertActive();\n\t\tthis.#assertRemotable(service);\n\t\tthis.#assertAllowed(service.id);\n\t\tconst registration = this.#registration(service.id, \"singleton\");\n\t\tif (registration.singleton !== undefined) {\n\t\t\tthrow new RemoteServiceError(\"service_mode_mismatch\", `Remote service ${service.id} already has a provider`);\n\t\t}\n\t\tconst classified = classifyRemoteServiceImplementation(registration.serviceId, implementation);\n\t\tconst shape = serviceMemberShape(classified.members);\n\t\tthis.#assertSingletonShape(registration, shape);\n\t\tregistration.singleton = this.#createInstance(registration, classified, undefined);\n\t\tregistration.singletonShape = shape;\n\t}\n\n\t/** Disconnect one singleton while preserving active subscriptions and remote facades. */\n\twithdraw<T>(service: Service<T>): void {\n\t\tthis.#assertActive();\n\t\tthis.#assertRemotable(service);\n\t\tthis.#assertAllowed(service.id);\n\t\tconst registration = this.#registration(service.id, \"singleton\");\n\t\tconst previous = registration.singleton;\n\t\tif (previous === undefined) return;\n\t\tprevious.active = false;\n\t\tfor (const remove of previous.removeMemberListeners) remove();\n\t\tdelete registration.singleton;\n\t\tthis.#emit(registration, { type: \"unavailable\" });\n\t}\n\n\t/** Check a singleton replacement without changing the active provider. */\n\tvalidateReplacement<T>(service: Service<T>, implementation: NoInfer<RemoteServiceContract<T>>): void {\n\t\tthis.#assertActive();\n\t\tthis.#assertRemotable(service);\n\t\tthis.#assertAllowed(service.id);\n\t\tconst registration = this.#registration(service.id, \"singleton\");\n\t\tconst classified = classifyRemoteServiceImplementation(registration.serviceId, implementation);\n\t\tthis.#assertSingletonShape(registration, serviceMemberShape(classified.members));\n\t}\n\n\t/** Replace one singleton without making its stable remote facade unavailable. */\n\treplace<T>(service: Service<T>, implementation: NoInfer<RemoteServiceContract<T>>): void {\n\t\tthis.#assertActive();\n\t\tthis.#assertRemotable(service);\n\t\tthis.#assertAllowed(service.id);\n\t\tconst registration = this.#registration(service.id, \"singleton\");\n\t\tconst classified = classifyRemoteServiceImplementation(registration.serviceId, implementation);\n\t\tconst shape = serviceMemberShape(classified.members);\n\t\tthis.#assertSingletonShape(registration, shape);\n\t\tconst replacement = this.#createInstance(registration, classified, undefined);\n\t\tconst previous = registration.singleton;\n\t\tif (previous !== undefined) {\n\t\t\tprevious.active = false;\n\t\t\tfor (const remove of previous.removeMemberListeners) remove();\n\t\t}\n\t\tregistration.singleton = replacement;\n\t\tregistration.singletonShape = shape;\n\t\tthis.#emit(registration, { type: \"replaced\", snapshot: this.#snapshotInstance(replacement) });\n\t}\n\n\tuse<T>(service: Service<T>): T {\n\t\tthis.#assertActive();\n\t\tthis.#assertRemotable(service);\n\t\tthis.#assertAllowed(service.id);\n\t\tconst registration = this.#registrations.get(service.id);\n\t\tif (registration?.mode !== \"singleton\" || registration.singleton === undefined) {\n\t\t\tthrow new RemoteServiceError(\"service_not_found\", `Remote service ${service.id} has no local provider`);\n\t\t}\n\t\treturn registration.singleton.implementation as T;\n\t}\n\n\tspawn<T>(service: Service<T>, key: string, implementation: NoInfer<RemoteServiceContract<T>>): () => void {\n\t\tthis.#assertActive();\n\t\tthis.#assertRemotable(service);\n\t\tthis.#assertAllowed(service.id);\n\t\tif (key.length === 0) throw new TypeError(\"Remote service instance key must not be empty\");\n\t\tconst registration = this.#registration(service.id, \"keyed\");\n\t\tif (registration.instances.has(key)) {\n\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\"service_mode_mismatch\",\n\t\t\t\t`Remote service ${service.id} already has a live instance with key ${key}`,\n\t\t\t);\n\t\t}\n\t\tconst generation = (registration.generations.get(key) ?? 0) + 1;\n\t\tregistration.generations.set(key, generation);\n\t\tconst address = { key, generation } satisfies ServiceInstanceAddress;\n\t\tconst classified = classifyRemoteServiceImplementation(registration.serviceId, implementation);\n\t\tconst instance = this.#createInstance(registration, classified, address);\n\t\tregistration.instances.set(key, instance);\n\t\tthis.#emit(registration, { type: \"spawned\", instance: this.#snapshotInstance(instance) });\n\t\tlet closed = false;\n\t\treturn () => {\n\t\t\tif (closed) return;\n\t\t\tclosed = true;\n\t\t\tif (registration.instances.get(key) !== instance) return;\n\t\t\tinstance.active = false;\n\t\t\tfor (const remove of instance.removeMemberListeners) remove();\n\t\t\tregistration.instances.delete(key);\n\t\t\tthis.#emit(registration, { type: \"closed\", instance: address });\n\t\t};\n\t}\n\n\tasync invoke(call: ServiceCall, context: Context): Promise<JsonValue | undefined> {\n\t\tthis.#assertActive();\n\t\tthis.#assertAllowed(call.serviceId);\n\t\tconst registration = this.#registrations.get(call.serviceId);\n\t\tif (registration === undefined) {\n\t\t\tthrow new RemoteServiceError(\"service_not_found\", `Unknown remote service ${call.serviceId}`);\n\t\t}\n\t\tconst instance = this.#resolveInstance(registration, call.instance);\n\t\tconst member = instance.members.get(call.member);\n\t\tif (member === undefined) {\n\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\"service_member_not_found\",\n\t\t\t\t`Unknown remote service member ${call.serviceId}.${call.member}`,\n\t\t\t);\n\t\t}\n\t\tif (member.kind !== \"method\") {\n\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\"service_member_mismatch\",\n\t\t\t\t`Remote service member ${call.serviceId}.${call.member} is not a method`,\n\t\t\t);\n\t\t}\n\t\tconst result: unknown = await Reflect.apply(member.method, instance.implementation, [...call.args, context]);\n\t\treturn result as JsonValue | undefined;\n\t}\n\n\tsubscribe(\n\t\tserviceId: string,\n\t\tmode: ServiceMode,\n\t\tlistener: (update: ServiceProviderUpdate, context: Context) => void,\n\t): ServiceSubscription {\n\t\tthis.#assertActive();\n\t\tthis.#assertAllowed(serviceId);\n\t\tconst registration = this.#registration(serviceId, mode);\n\t\tif (registration.mode === \"singleton\" && registration.singleton === undefined) {\n\t\t\tthrow new RemoteServiceError(\"service_not_found\", `Remote service ${serviceId} has no provider`);\n\t\t}\n\t\tconst subscriber: ProviderSubscriber = {\n\t\t\tlistener,\n\t\t\tbuffer: [],\n\t\t\tactive: false,\n\t\t\tterminated: false,\n\t\t\tclosed: false,\n\t\t};\n\t\tthis.#publishPending(registration);\n\t\tregistration.subscribers.add(subscriber);\n\t\tconst snapshot = this.#snapshot(registration);\n\t\treturn {\n\t\t\tsnapshot,\n\t\t\tactivate: () => {\n\t\t\t\tif (subscriber.closed || subscriber.active) return;\n\t\t\t\tsubscriber.active = true;\n\t\t\t\tconst errors: unknown[] = [];\n\t\t\t\ttry {\n\t\t\t\t\tfor (const entry of subscriber.buffer.splice(0)) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tlistener(entry.update, entry.context);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\terrors.push(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tif (subscriber.terminated) subscriber.closed = true;\n\t\t\t\t}\n\t\t\t\tthrowCollectedErrors(errors, \"Failed to activate remote service subscription\");\n\t\t\t},\n\t\t\tclose: () => {\n\t\t\t\tif (subscriber.closed) return;\n\t\t\t\tsubscriber.closed = true;\n\t\t\t\tsubscriber.buffer.length = 0;\n\t\t\t\tregistration.subscribers.delete(subscriber);\n\t\t\t},\n\t\t};\n\t}\n\n\tdispose(): void {\n\t\tif (this.#disposed) return;\n\t\tthis.#disposed = true;\n\t\tconst errors: unknown[] = [];\n\t\tfor (const registration of this.#registrations.values()) {\n\t\t\tconst singleton = registration.singleton;\n\t\t\tif (singleton !== undefined) {\n\t\t\t\tsingleton.active = false;\n\t\t\t\tfor (const remove of singleton.removeMemberListeners) remove();\n\t\t\t\tdelete registration.singleton;\n\t\t\t\ttry {\n\t\t\t\t\tthis.#emit(registration, { type: \"unavailable\" });\n\t\t\t\t} catch (error) {\n\t\t\t\t\terrors.push(error);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const [key, instance] of [...registration.instances]) {\n\t\t\t\tinstance.active = false;\n\t\t\t\tfor (const remove of instance.removeMemberListeners) remove();\n\t\t\t\tregistration.instances.delete(key);\n\t\t\t\ttry {\n\t\t\t\t\tthis.#emit(registration, { type: \"closed\", instance: instance.address! });\n\t\t\t\t} catch (error) {\n\t\t\t\t\terrors.push(error);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const subscriber of registration.subscribers) {\n\t\t\t\tif (subscriber.active) {\n\t\t\t\t\tsubscriber.closed = true;\n\t\t\t\t\tsubscriber.buffer.length = 0;\n\t\t\t\t} else {\n\t\t\t\t\tsubscriber.terminated = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tregistration.subscribers.clear();\n\t\t}\n\t\tthis.#registrations.clear();\n\t\tif (errors.length === 1) throw errors[0];\n\t\tif (errors.length > 1) throw new AggregateError(errors, \"Failed to dispose remote service provider\");\n\t}\n\n\t#registration(serviceId: string, mode: ServiceMode): ServiceRegistration {\n\t\tconst registration = this.#registrations.get(serviceId);\n\t\tif (registration === undefined) {\n\t\t\tthrow new RemoteServiceError(\"service_not_found\", `Unknown remote service ${serviceId}`);\n\t\t}\n\t\tif (registration.mode !== mode) {\n\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\"service_mode_mismatch\",\n\t\t\t\t`Remote service ${serviceId} is ${registration.mode}, not ${mode}`,\n\t\t\t);\n\t\t}\n\t\treturn registration;\n\t}\n\n\t#createInstance(\n\t\tregistration: ServiceRegistration,\n\t\tclassified: ClassifiedRemoteServiceImplementation,\n\t\taddress: ServiceInstanceAddress | undefined,\n\t): ProviderInstance {\n\t\tconst removeMemberListeners: (() => void)[] = [];\n\t\tconst instance: ProviderInstance = {\n\t\t\t...(address === undefined ? {} : { address }),\n\t\t\timplementation: classified.implementation,\n\t\t\tmembers: classified.members,\n\t\t\tremoveMemberListeners,\n\t\t\tactive: true,\n\t\t};\n\t\tfor (const [name, member] of classified.members) {\n\t\t\tif (member.kind !== \"state\") continue;\n\t\t\tremoveMemberListeners.push(\n\t\t\t\tmember.state.subscribe((ops, sequence, context) => {\n\t\t\t\t\tif (!instance.active) return;\n\t\t\t\t\tthis.#emit(\n\t\t\t\t\t\tregistration,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"state\",\n\t\t\t\t\t\t\t...(address === undefined ? {} : { instance: address }),\n\t\t\t\t\t\t\tmember: name,\n\t\t\t\t\t\t\tsequence,\n\t\t\t\t\t\t\tops,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcontext,\n\t\t\t\t\t);\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\treturn instance;\n\t}\n\n\t#assertSingletonShape(registration: ServiceRegistration, replacement: ReadonlyMap<string, ServiceMemberKind>): void {\n\t\tconst current = registration.singletonShape;\n\t\tif (current === undefined || sameServiceMemberShape(current, replacement)) return;\n\t\tthrow new RemoteServiceError(\n\t\t\t\"service_member_mismatch\",\n\t\t\t`Remote service ${registration.serviceId} replacement must preserve its member shape`,\n\t\t);\n\t}\n\n\t#resolveInstance(registration: ServiceRegistration, address: ServiceInstanceAddress | undefined): ProviderInstance {\n\t\tif (registration.mode === \"singleton\") {\n\t\t\tif (address !== undefined) {\n\t\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\t\"service_mode_mismatch\",\n\t\t\t\t\t`Remote service ${registration.serviceId} is singleton`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (registration.singleton === undefined) {\n\t\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\t\"service_not_found\",\n\t\t\t\t\t`Remote service ${registration.serviceId} has no provider`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn registration.singleton;\n\t\t}\n\t\tif (address === undefined) {\n\t\t\tthrow new RemoteServiceError(\"service_mode_mismatch\", `Remote service ${registration.serviceId} is keyed`);\n\t\t}\n\t\tconst instance = registration.instances.get(address.key);\n\t\tif (instance === undefined) {\n\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\"service_instance_not_found\",\n\t\t\t\t`Remote service ${registration.serviceId} has no instance ${address.key}`,\n\t\t\t);\n\t\t}\n\t\tif (instance.address?.generation !== address.generation) {\n\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\"service_stale_instance\",\n\t\t\t\t`Remote service ${registration.serviceId} instance ${address.key} is stale`,\n\t\t\t);\n\t\t}\n\t\treturn instance;\n\t}\n\n\t#publishPending(registration: ServiceRegistration): void {\n\t\tconst context = serviceDeliveryContext();\n\t\tconst instances =\n\t\t\tregistration.mode === \"singleton\"\n\t\t\t\t? registration.singleton === undefined\n\t\t\t\t\t? []\n\t\t\t\t\t: [registration.singleton]\n\t\t\t\t: registration.instances.values();\n\t\tfor (const instance of instances) {\n\t\t\tfor (const member of instance.members.values()) {\n\t\t\t\tif (member.kind === \"state\") member.state.publish(context);\n\t\t\t}\n\t\t}\n\t}\n\n\t#snapshot(registration: ServiceRegistration): ServiceSubscriptionSnapshot {\n\t\tconst instances =\n\t\t\tregistration.mode === \"singleton\"\n\t\t\t\t? registration.singleton\n\t\t\t\t\t? [this.#snapshotInstance(registration.singleton)]\n\t\t\t\t\t: []\n\t\t\t\t: [...registration.instances.values()]\n\t\t\t\t\t\t.sort((left, right) => left.address!.key.localeCompare(right.address!.key))\n\t\t\t\t\t\t.map((instance) => this.#snapshotInstance(instance));\n\t\treturn { serviceId: registration.serviceId, mode: registration.mode, instances };\n\t}\n\n\t#snapshotInstance(instance: ProviderInstance): ServiceInstanceSnapshot {\n\t\tconst members: ServiceMemberSnapshot[] = [];\n\t\tfor (const [name, member] of instance.members) {\n\t\t\tif (member.kind === \"method\") {\n\t\t\t\tmembers.push({ name, kind: \"method\" });\n\t\t\t} else {\n\t\t\t\tmembers.push({\n\t\t\t\t\tname,\n\t\t\t\t\tkind: \"state\",\n\t\t\t\t\tsequence: member.state.sequence,\n\t\t\t\t\tops: [[\"r\", member.state.value as JsonValue]],\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\t...(instance.address === undefined ? {} : { instance: instance.address }),\n\t\t\tmembers,\n\t\t};\n\t}\n\n\t#emit(registration: ServiceRegistration, update: ServiceProviderUpdate, context?: Context): void {\n\t\tif (registration.subscribers.size === 0) return;\n\t\tconst deliveryContext = context ?? serviceDeliveryContext();\n\t\tconst errors: unknown[] = [];\n\t\tfor (const subscriber of registration.subscribers) {\n\t\t\tif (subscriber.closed) continue;\n\t\t\tconst entry = { update, context: deliveryContext };\n\t\t\tif (!subscriber.active) {\n\t\t\t\tsubscriber.buffer.push(entry);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tsubscriber.listener(entry.update, entry.context);\n\t\t\t} catch (error) {\n\t\t\t\terrors.push(error);\n\t\t\t}\n\t\t}\n\t\tthrowCollectedErrors(errors, `Failed to publish remote service ${registration.serviceId} update`);\n\t}\n\n\t#assertRemotable(service: { readonly id: string; readonly local: boolean }): void {\n\t\tif (service.local) throw new RemoteServiceError(\"service_not_allowed\", `Service ${service.id} is process-local`);\n\t}\n\n\t#assertAllowed(serviceId: string): void {\n\t\tif (!this.#registrations.has(serviceId)) {\n\t\t\tthrow new RemoteServiceError(\"service_not_allowed\", `Remote service ${serviceId} is not allowlisted`);\n\t\t}\n\t}\n\n\t#assertActive(): void {\n\t\tif (this.#disposed) throw new Error(\"Remote service provider is disposed\");\n\t}\n}\n\nexport function createRemoteServiceEndpoint(provider: RemoteServiceProvider): RemoteServiceEndpoint {\n\tconst subscriptions = new Map<string, ServiceSubscription>();\n\tlet disposed = false;\n\n\treturn {\n\t\tasync invoke(call, publish, context) {\n\t\t\tif (disposed) throw new Error(\"Remote service endpoint is disposed\");\n\t\t\tconst control = decodeServiceControlCall(call);\n\t\t\tif (control?.type === \"catalogue\") return provider.catalogue as unknown as JsonValue;\n\t\t\tif (control?.type === \"subscribe\") {\n\t\t\t\tif (subscriptions.has(control.subscriptionId)) {\n\t\t\t\t\tthrow new Error(\"Service subscription ID is already active\");\n\t\t\t\t}\n\t\t\t\tconst subscription = provider.subscribe(control.serviceId, control.mode, (update, updateContext) => {\n\t\t\t\t\tvoid Promise.resolve(publish(control.subscriptionId, update, updateContext)).catch(() => {});\n\t\t\t\t});\n\t\t\t\tsubscriptions.set(control.subscriptionId, subscription);\n\t\t\t\tsubscription.activate();\n\t\t\t\treturn subscription.snapshot as unknown as JsonValue;\n\t\t\t}\n\t\t\tif (control?.type === \"unsubscribe\") {\n\t\t\t\tconst subscription = subscriptions.get(control.subscriptionId);\n\t\t\t\tif (subscription === undefined) throw new Error(\"Service subscription was not found\");\n\t\t\t\tsubscription.close();\n\t\t\t\tsubscriptions.delete(control.subscriptionId);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn provider.invoke(call, context);\n\t\t},\n\t\tdispose() {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tfor (const subscription of subscriptions.values()) subscription.close();\n\t\t\tsubscriptions.clear();\n\t\t},\n\t};\n}\n\nexport function validateRemoteServiceImplementation(serviceId: string, implementation: unknown): void {\n\tvoid classifyRemoteServiceImplementation(serviceId, implementation);\n}\n\nfunction classifyRemoteServiceImplementation(\n\tserviceId: string,\n\timplementation: unknown,\n): ClassifiedRemoteServiceImplementation {\n\tif (typeof implementation !== \"object\" || implementation === null || Array.isArray(implementation)) {\n\t\tthrow new TypeError(`Remote service ${serviceId} implementation must be an object`);\n\t}\n\tconst members = new Map<string, InstanceMember>();\n\tfor (const name of Object.keys(implementation).sort()) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(implementation, name);\n\t\tif (descriptor === undefined || !(\"value\" in descriptor)) {\n\t\t\tthrow new TypeError(`Remote service member ${serviceId}.${name} must be a data property`);\n\t\t}\n\t\tif (typeof descriptor.value === \"function\") {\n\t\t\tmembers.set(name, { kind: \"method\", method: descriptor.value as RemoteMethod });\n\t\t\tcontinue;\n\t\t}\n\t\tconst state = getReplicatedStateInternals(descriptor.value);\n\t\tif (state !== undefined) {\n\t\t\tmembers.set(name, { kind: \"state\", state });\n\t\t\tcontinue;\n\t\t}\n\t\tthrow new TypeError(`Remote service member ${serviceId}.${name} is not remotely exposable`);\n\t}\n\tif (members.size === 0) throw new TypeError(`Remote service ${serviceId} has no members`);\n\treturn { implementation, members };\n}\n\nfunction throwCollectedErrors(errors: readonly unknown[], message: string): void {\n\tif (errors.length === 1) throw errors[0];\n\tif (errors.length > 1) throw new AggregateError(errors, message);\n}\n\nfunction serviceMemberShape(members: ReadonlyMap<string, InstanceMember>): ReadonlyMap<string, ServiceMemberKind> {\n\treturn new Map([...members].map(([name, member]) => [name, member.kind]));\n}\n\nfunction sameServiceMemberShape(\n\tleft: ReadonlyMap<string, ServiceMemberKind>,\n\tright: ReadonlyMap<string, ServiceMemberKind>,\n): boolean {\n\treturn left.size === right.size && [...left].every(([name, kind]) => right.get(name) === kind);\n}\n"]}
@@ -0,0 +1,472 @@
1
+ import { RemoteServiceError } from "./errors.js";
2
+ import { serviceDeliveryContext } from "./state.js";
3
+ import { getReplicatedStateInternals } from "./state-internals.js";
4
+ import { decodeServiceControlCall } from "./wire.js";
5
+ export class RemoteServiceProvider {
6
+ #catalogue;
7
+ #registrations = new Map();
8
+ #disposed = false;
9
+ constructor(entries) {
10
+ const definitions = entries.map((entry) => ("service" in entry ? entry : { service: entry, mode: "singleton" }));
11
+ for (const { service } of definitions) {
12
+ if ("local" in service && service.local === true) {
13
+ throw new TypeError(`Local service ${service.id} cannot be published remotely`);
14
+ }
15
+ }
16
+ const ids = definitions.map(({ service }) => service.id);
17
+ if (new Set(ids).size !== ids.length)
18
+ throw new TypeError("Remote service catalogue contains duplicate IDs");
19
+ this.#catalogue = Object.freeze(definitions.map(({ service, mode }) => Object.freeze({ serviceId: service.id, mode })));
20
+ for (const { service, mode } of definitions) {
21
+ this.#registrations.set(service.id, {
22
+ serviceId: service.id,
23
+ mode,
24
+ instances: new Map(),
25
+ generations: new Map(),
26
+ subscribers: new Set(),
27
+ });
28
+ }
29
+ }
30
+ get catalogue() {
31
+ return this.#catalogue;
32
+ }
33
+ provide(service, implementation) {
34
+ this.#assertActive();
35
+ this.#assertRemotable(service);
36
+ this.#assertAllowed(service.id);
37
+ const registration = this.#registration(service.id, "singleton");
38
+ if (registration.singleton !== undefined) {
39
+ throw new RemoteServiceError("service_mode_mismatch", `Remote service ${service.id} already has a provider`);
40
+ }
41
+ const classified = classifyRemoteServiceImplementation(registration.serviceId, implementation);
42
+ const shape = serviceMemberShape(classified.members);
43
+ this.#assertSingletonShape(registration, shape);
44
+ registration.singleton = this.#createInstance(registration, classified, undefined);
45
+ registration.singletonShape = shape;
46
+ }
47
+ /** Disconnect one singleton while preserving active subscriptions and remote facades. */
48
+ withdraw(service) {
49
+ this.#assertActive();
50
+ this.#assertRemotable(service);
51
+ this.#assertAllowed(service.id);
52
+ const registration = this.#registration(service.id, "singleton");
53
+ const previous = registration.singleton;
54
+ if (previous === undefined)
55
+ return;
56
+ previous.active = false;
57
+ for (const remove of previous.removeMemberListeners)
58
+ remove();
59
+ delete registration.singleton;
60
+ this.#emit(registration, { type: "unavailable" });
61
+ }
62
+ /** Check a singleton replacement without changing the active provider. */
63
+ validateReplacement(service, implementation) {
64
+ this.#assertActive();
65
+ this.#assertRemotable(service);
66
+ this.#assertAllowed(service.id);
67
+ const registration = this.#registration(service.id, "singleton");
68
+ const classified = classifyRemoteServiceImplementation(registration.serviceId, implementation);
69
+ this.#assertSingletonShape(registration, serviceMemberShape(classified.members));
70
+ }
71
+ /** Replace one singleton without making its stable remote facade unavailable. */
72
+ replace(service, implementation) {
73
+ this.#assertActive();
74
+ this.#assertRemotable(service);
75
+ this.#assertAllowed(service.id);
76
+ const registration = this.#registration(service.id, "singleton");
77
+ const classified = classifyRemoteServiceImplementation(registration.serviceId, implementation);
78
+ const shape = serviceMemberShape(classified.members);
79
+ this.#assertSingletonShape(registration, shape);
80
+ const replacement = this.#createInstance(registration, classified, undefined);
81
+ const previous = registration.singleton;
82
+ if (previous !== undefined) {
83
+ previous.active = false;
84
+ for (const remove of previous.removeMemberListeners)
85
+ remove();
86
+ }
87
+ registration.singleton = replacement;
88
+ registration.singletonShape = shape;
89
+ this.#emit(registration, { type: "replaced", snapshot: this.#snapshotInstance(replacement) });
90
+ }
91
+ use(service) {
92
+ this.#assertActive();
93
+ this.#assertRemotable(service);
94
+ this.#assertAllowed(service.id);
95
+ const registration = this.#registrations.get(service.id);
96
+ if (registration?.mode !== "singleton" || registration.singleton === undefined) {
97
+ throw new RemoteServiceError("service_not_found", `Remote service ${service.id} has no local provider`);
98
+ }
99
+ return registration.singleton.implementation;
100
+ }
101
+ spawn(service, key, implementation) {
102
+ this.#assertActive();
103
+ this.#assertRemotable(service);
104
+ this.#assertAllowed(service.id);
105
+ if (key.length === 0)
106
+ throw new TypeError("Remote service instance key must not be empty");
107
+ const registration = this.#registration(service.id, "keyed");
108
+ if (registration.instances.has(key)) {
109
+ throw new RemoteServiceError("service_mode_mismatch", `Remote service ${service.id} already has a live instance with key ${key}`);
110
+ }
111
+ const generation = (registration.generations.get(key) ?? 0) + 1;
112
+ registration.generations.set(key, generation);
113
+ const address = { key, generation };
114
+ const classified = classifyRemoteServiceImplementation(registration.serviceId, implementation);
115
+ const instance = this.#createInstance(registration, classified, address);
116
+ registration.instances.set(key, instance);
117
+ this.#emit(registration, { type: "spawned", instance: this.#snapshotInstance(instance) });
118
+ let closed = false;
119
+ return () => {
120
+ if (closed)
121
+ return;
122
+ closed = true;
123
+ if (registration.instances.get(key) !== instance)
124
+ return;
125
+ instance.active = false;
126
+ for (const remove of instance.removeMemberListeners)
127
+ remove();
128
+ registration.instances.delete(key);
129
+ this.#emit(registration, { type: "closed", instance: address });
130
+ };
131
+ }
132
+ async invoke(call, context) {
133
+ this.#assertActive();
134
+ this.#assertAllowed(call.serviceId);
135
+ const registration = this.#registrations.get(call.serviceId);
136
+ if (registration === undefined) {
137
+ throw new RemoteServiceError("service_not_found", `Unknown remote service ${call.serviceId}`);
138
+ }
139
+ const instance = this.#resolveInstance(registration, call.instance);
140
+ const member = instance.members.get(call.member);
141
+ if (member === undefined) {
142
+ throw new RemoteServiceError("service_member_not_found", `Unknown remote service member ${call.serviceId}.${call.member}`);
143
+ }
144
+ if (member.kind !== "method") {
145
+ throw new RemoteServiceError("service_member_mismatch", `Remote service member ${call.serviceId}.${call.member} is not a method`);
146
+ }
147
+ const result = await Reflect.apply(member.method, instance.implementation, [...call.args, context]);
148
+ return result;
149
+ }
150
+ subscribe(serviceId, mode, listener) {
151
+ this.#assertActive();
152
+ this.#assertAllowed(serviceId);
153
+ const registration = this.#registration(serviceId, mode);
154
+ if (registration.mode === "singleton" && registration.singleton === undefined) {
155
+ throw new RemoteServiceError("service_not_found", `Remote service ${serviceId} has no provider`);
156
+ }
157
+ const subscriber = {
158
+ listener,
159
+ buffer: [],
160
+ active: false,
161
+ terminated: false,
162
+ closed: false,
163
+ };
164
+ this.#publishPending(registration);
165
+ registration.subscribers.add(subscriber);
166
+ const snapshot = this.#snapshot(registration);
167
+ return {
168
+ snapshot,
169
+ activate: () => {
170
+ if (subscriber.closed || subscriber.active)
171
+ return;
172
+ subscriber.active = true;
173
+ const errors = [];
174
+ try {
175
+ for (const entry of subscriber.buffer.splice(0)) {
176
+ try {
177
+ listener(entry.update, entry.context);
178
+ }
179
+ catch (error) {
180
+ errors.push(error);
181
+ }
182
+ }
183
+ }
184
+ finally {
185
+ if (subscriber.terminated)
186
+ subscriber.closed = true;
187
+ }
188
+ throwCollectedErrors(errors, "Failed to activate remote service subscription");
189
+ },
190
+ close: () => {
191
+ if (subscriber.closed)
192
+ return;
193
+ subscriber.closed = true;
194
+ subscriber.buffer.length = 0;
195
+ registration.subscribers.delete(subscriber);
196
+ },
197
+ };
198
+ }
199
+ dispose() {
200
+ if (this.#disposed)
201
+ return;
202
+ this.#disposed = true;
203
+ const errors = [];
204
+ for (const registration of this.#registrations.values()) {
205
+ const singleton = registration.singleton;
206
+ if (singleton !== undefined) {
207
+ singleton.active = false;
208
+ for (const remove of singleton.removeMemberListeners)
209
+ remove();
210
+ delete registration.singleton;
211
+ try {
212
+ this.#emit(registration, { type: "unavailable" });
213
+ }
214
+ catch (error) {
215
+ errors.push(error);
216
+ }
217
+ }
218
+ for (const [key, instance] of [...registration.instances]) {
219
+ instance.active = false;
220
+ for (const remove of instance.removeMemberListeners)
221
+ remove();
222
+ registration.instances.delete(key);
223
+ try {
224
+ this.#emit(registration, { type: "closed", instance: instance.address });
225
+ }
226
+ catch (error) {
227
+ errors.push(error);
228
+ }
229
+ }
230
+ for (const subscriber of registration.subscribers) {
231
+ if (subscriber.active) {
232
+ subscriber.closed = true;
233
+ subscriber.buffer.length = 0;
234
+ }
235
+ else {
236
+ subscriber.terminated = true;
237
+ }
238
+ }
239
+ registration.subscribers.clear();
240
+ }
241
+ this.#registrations.clear();
242
+ if (errors.length === 1)
243
+ throw errors[0];
244
+ if (errors.length > 1)
245
+ throw new AggregateError(errors, "Failed to dispose remote service provider");
246
+ }
247
+ #registration(serviceId, mode) {
248
+ const registration = this.#registrations.get(serviceId);
249
+ if (registration === undefined) {
250
+ throw new RemoteServiceError("service_not_found", `Unknown remote service ${serviceId}`);
251
+ }
252
+ if (registration.mode !== mode) {
253
+ throw new RemoteServiceError("service_mode_mismatch", `Remote service ${serviceId} is ${registration.mode}, not ${mode}`);
254
+ }
255
+ return registration;
256
+ }
257
+ #createInstance(registration, classified, address) {
258
+ const removeMemberListeners = [];
259
+ const instance = {
260
+ ...(address === undefined ? {} : { address }),
261
+ implementation: classified.implementation,
262
+ members: classified.members,
263
+ removeMemberListeners,
264
+ active: true,
265
+ };
266
+ for (const [name, member] of classified.members) {
267
+ if (member.kind !== "state")
268
+ continue;
269
+ removeMemberListeners.push(member.state.subscribe((ops, sequence, context) => {
270
+ if (!instance.active)
271
+ return;
272
+ this.#emit(registration, {
273
+ type: "state",
274
+ ...(address === undefined ? {} : { instance: address }),
275
+ member: name,
276
+ sequence,
277
+ ops,
278
+ }, context);
279
+ }));
280
+ }
281
+ return instance;
282
+ }
283
+ #assertSingletonShape(registration, replacement) {
284
+ const current = registration.singletonShape;
285
+ if (current === undefined || sameServiceMemberShape(current, replacement))
286
+ return;
287
+ throw new RemoteServiceError("service_member_mismatch", `Remote service ${registration.serviceId} replacement must preserve its member shape`);
288
+ }
289
+ #resolveInstance(registration, address) {
290
+ if (registration.mode === "singleton") {
291
+ if (address !== undefined) {
292
+ throw new RemoteServiceError("service_mode_mismatch", `Remote service ${registration.serviceId} is singleton`);
293
+ }
294
+ if (registration.singleton === undefined) {
295
+ throw new RemoteServiceError("service_not_found", `Remote service ${registration.serviceId} has no provider`);
296
+ }
297
+ return registration.singleton;
298
+ }
299
+ if (address === undefined) {
300
+ throw new RemoteServiceError("service_mode_mismatch", `Remote service ${registration.serviceId} is keyed`);
301
+ }
302
+ const instance = registration.instances.get(address.key);
303
+ if (instance === undefined) {
304
+ throw new RemoteServiceError("service_instance_not_found", `Remote service ${registration.serviceId} has no instance ${address.key}`);
305
+ }
306
+ if (instance.address?.generation !== address.generation) {
307
+ throw new RemoteServiceError("service_stale_instance", `Remote service ${registration.serviceId} instance ${address.key} is stale`);
308
+ }
309
+ return instance;
310
+ }
311
+ #publishPending(registration) {
312
+ const context = serviceDeliveryContext();
313
+ const instances = registration.mode === "singleton"
314
+ ? registration.singleton === undefined
315
+ ? []
316
+ : [registration.singleton]
317
+ : registration.instances.values();
318
+ for (const instance of instances) {
319
+ for (const member of instance.members.values()) {
320
+ if (member.kind === "state")
321
+ member.state.publish(context);
322
+ }
323
+ }
324
+ }
325
+ #snapshot(registration) {
326
+ const instances = registration.mode === "singleton"
327
+ ? registration.singleton
328
+ ? [this.#snapshotInstance(registration.singleton)]
329
+ : []
330
+ : [...registration.instances.values()]
331
+ .sort((left, right) => left.address.key.localeCompare(right.address.key))
332
+ .map((instance) => this.#snapshotInstance(instance));
333
+ return { serviceId: registration.serviceId, mode: registration.mode, instances };
334
+ }
335
+ #snapshotInstance(instance) {
336
+ const members = [];
337
+ for (const [name, member] of instance.members) {
338
+ if (member.kind === "method") {
339
+ members.push({ name, kind: "method" });
340
+ }
341
+ else {
342
+ members.push({
343
+ name,
344
+ kind: "state",
345
+ sequence: member.state.sequence,
346
+ ops: [["r", member.state.value]],
347
+ });
348
+ }
349
+ }
350
+ return {
351
+ ...(instance.address === undefined ? {} : { instance: instance.address }),
352
+ members,
353
+ };
354
+ }
355
+ #emit(registration, update, context) {
356
+ if (registration.subscribers.size === 0)
357
+ return;
358
+ const deliveryContext = context ?? serviceDeliveryContext();
359
+ const errors = [];
360
+ for (const subscriber of registration.subscribers) {
361
+ if (subscriber.closed)
362
+ continue;
363
+ const entry = { update, context: deliveryContext };
364
+ if (!subscriber.active) {
365
+ subscriber.buffer.push(entry);
366
+ continue;
367
+ }
368
+ try {
369
+ subscriber.listener(entry.update, entry.context);
370
+ }
371
+ catch (error) {
372
+ errors.push(error);
373
+ }
374
+ }
375
+ throwCollectedErrors(errors, `Failed to publish remote service ${registration.serviceId} update`);
376
+ }
377
+ #assertRemotable(service) {
378
+ if (service.local)
379
+ throw new RemoteServiceError("service_not_allowed", `Service ${service.id} is process-local`);
380
+ }
381
+ #assertAllowed(serviceId) {
382
+ if (!this.#registrations.has(serviceId)) {
383
+ throw new RemoteServiceError("service_not_allowed", `Remote service ${serviceId} is not allowlisted`);
384
+ }
385
+ }
386
+ #assertActive() {
387
+ if (this.#disposed)
388
+ throw new Error("Remote service provider is disposed");
389
+ }
390
+ }
391
+ export function createRemoteServiceEndpoint(provider) {
392
+ const subscriptions = new Map();
393
+ let disposed = false;
394
+ return {
395
+ async invoke(call, publish, context) {
396
+ if (disposed)
397
+ throw new Error("Remote service endpoint is disposed");
398
+ const control = decodeServiceControlCall(call);
399
+ if (control?.type === "catalogue")
400
+ return provider.catalogue;
401
+ if (control?.type === "subscribe") {
402
+ if (subscriptions.has(control.subscriptionId)) {
403
+ throw new Error("Service subscription ID is already active");
404
+ }
405
+ const subscription = provider.subscribe(control.serviceId, control.mode, (update, updateContext) => {
406
+ void Promise.resolve(publish(control.subscriptionId, update, updateContext)).catch(() => { });
407
+ });
408
+ subscriptions.set(control.subscriptionId, subscription);
409
+ subscription.activate();
410
+ return subscription.snapshot;
411
+ }
412
+ if (control?.type === "unsubscribe") {
413
+ const subscription = subscriptions.get(control.subscriptionId);
414
+ if (subscription === undefined)
415
+ throw new Error("Service subscription was not found");
416
+ subscription.close();
417
+ subscriptions.delete(control.subscriptionId);
418
+ return undefined;
419
+ }
420
+ return provider.invoke(call, context);
421
+ },
422
+ dispose() {
423
+ if (disposed)
424
+ return;
425
+ disposed = true;
426
+ for (const subscription of subscriptions.values())
427
+ subscription.close();
428
+ subscriptions.clear();
429
+ },
430
+ };
431
+ }
432
+ export function validateRemoteServiceImplementation(serviceId, implementation) {
433
+ void classifyRemoteServiceImplementation(serviceId, implementation);
434
+ }
435
+ function classifyRemoteServiceImplementation(serviceId, implementation) {
436
+ if (typeof implementation !== "object" || implementation === null || Array.isArray(implementation)) {
437
+ throw new TypeError(`Remote service ${serviceId} implementation must be an object`);
438
+ }
439
+ const members = new Map();
440
+ for (const name of Object.keys(implementation).sort()) {
441
+ const descriptor = Object.getOwnPropertyDescriptor(implementation, name);
442
+ if (descriptor === undefined || !("value" in descriptor)) {
443
+ throw new TypeError(`Remote service member ${serviceId}.${name} must be a data property`);
444
+ }
445
+ if (typeof descriptor.value === "function") {
446
+ members.set(name, { kind: "method", method: descriptor.value });
447
+ continue;
448
+ }
449
+ const state = getReplicatedStateInternals(descriptor.value);
450
+ if (state !== undefined) {
451
+ members.set(name, { kind: "state", state });
452
+ continue;
453
+ }
454
+ throw new TypeError(`Remote service member ${serviceId}.${name} is not remotely exposable`);
455
+ }
456
+ if (members.size === 0)
457
+ throw new TypeError(`Remote service ${serviceId} has no members`);
458
+ return { implementation, members };
459
+ }
460
+ function throwCollectedErrors(errors, message) {
461
+ if (errors.length === 1)
462
+ throw errors[0];
463
+ if (errors.length > 1)
464
+ throw new AggregateError(errors, message);
465
+ }
466
+ function serviceMemberShape(members) {
467
+ return new Map([...members].map(([name, member]) => [name, member.kind]));
468
+ }
469
+ function sameServiceMemberShape(left, right) {
470
+ return left.size === right.size && [...left].every(([name, kind]) => right.get(name) === kind);
471
+ }
472
+ //# sourceMappingURL=provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.js","sourceRoot":"","sources":["../../src/services/provider.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,kBAAkB,EAAE,M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F,CAAC;IACD,IAAI,OAAO,CAAC,IAAI,KAAK,CAAC;QAAE,MAAM,IAAI,SAAS,CAAC,kBAAkB,SAAS,iBAAiB,CAAC,CAAC;IAC1F,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,CAAC;AAAA,CACnC;AAED,SAAS,oBAAoB,CAAC,MAA0B,EAAE,OAAe,EAAQ;IAChF,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,MAAM,MAAM,CAAC,CAAC,CAAC,CAAC;IACzC,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC;QAAE,MAAM,IAAI,cAAc,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAAA,CACjE;AAED,SAAS,kBAAkB,CAAC,OAA4C,EAA0C;IACjH,OAAO,IAAI,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAAA,CAC1E;AAED,SAAS,sBAAsB,CAC9B,IAA4C,EAC5C,KAA6C,EACnC;IACV,OAAO,IAAI,CAAC,IAAI,KAAK,KAAK,CAAC,IAAI,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,CAAC;AAAA,CAC/F","sourcesContent":["import type {\n\tContext,\n\tJsonValue,\n\tRemoteServiceContract,\n\tService,\n\tServiceCall,\n\tServiceCatalogueEntry,\n\tServiceInstanceAddress,\n\tServiceInstanceSnapshot,\n\tServiceMemberSnapshot,\n\tServiceMode,\n\tServiceProviderUpdate,\n\tServiceSubscription,\n\tServiceSubscriptionSnapshot,\n} from \"../types.ts\";\nimport { RemoteServiceError } from \"./errors.ts\";\nimport { serviceDeliveryContext } from \"./state.ts\";\nimport { getReplicatedStateInternals, type ReplicatedStateInternals } from \"./state-internals.ts\";\nimport { decodeServiceControlCall } from \"./wire.ts\";\n\ntype RemoteMethod = (...args: unknown[]) => unknown;\n\ntype InstanceMember =\n\t| { readonly kind: \"method\"; readonly method: RemoteMethod }\n\t| { readonly kind: \"state\"; readonly state: ReplicatedStateInternals };\n\ntype ServiceMemberKind = InstanceMember[\"kind\"];\n\ninterface ClassifiedRemoteServiceImplementation {\n\treadonly implementation: object;\n\treadonly members: Map<string, InstanceMember>;\n}\n\ninterface ProviderInstance {\n\treadonly address?: ServiceInstanceAddress;\n\treadonly implementation: object;\n\treadonly members: ReadonlyMap<string, InstanceMember>;\n\treadonly removeMemberListeners: readonly (() => void)[];\n\tactive: boolean;\n}\n\ninterface ProviderSubscriber {\n\treadonly listener: (update: ServiceProviderUpdate, context: Context) => void;\n\treadonly buffer: { readonly update: ServiceProviderUpdate; readonly context: Context }[];\n\tactive: boolean;\n\tterminated: boolean;\n\tclosed: boolean;\n}\n\ninterface ServiceProviderDefinition {\n\treadonly service: { readonly id: string; readonly local?: boolean };\n\treadonly mode: ServiceMode;\n}\n\ninterface ServiceRegistration {\n\treadonly serviceId: string;\n\treadonly mode: ServiceMode;\n\tsingleton?: ProviderInstance;\n\tsingletonShape?: ReadonlyMap<string, ServiceMemberKind>;\n\treadonly instances: Map<string, ProviderInstance>;\n\treadonly generations: Map<string, number>;\n\treadonly subscribers: Set<ProviderSubscriber>;\n}\n\nexport type ServiceUpdatePublisher = (\n\tsubscriptionId: string,\n\tupdate: ServiceProviderUpdate,\n\tcontext: Context,\n) => void | Promise<void>;\n\n/** Hosts one provider for one remote consumer and owns that consumer's subscriptions. */\nexport interface RemoteServiceEndpoint {\n\tinvoke(call: ServiceCall, publish: ServiceUpdatePublisher, context: Context): Promise<JsonValue | undefined>;\n\tdispose(): void;\n}\n\nexport class RemoteServiceProvider {\n\treadonly #catalogue: readonly ServiceCatalogueEntry[];\n\treadonly #registrations = new Map<string, ServiceRegistration>();\n\t#disposed = false;\n\n\tconstructor(entries: readonly (ServiceProviderDefinition | { readonly id: string })[]) {\n\t\tconst definitions = entries.map(\n\t\t\t(entry): ServiceProviderDefinition => (\"service\" in entry ? entry : { service: entry, mode: \"singleton\" }),\n\t\t);\n\t\tfor (const { service } of definitions) {\n\t\t\tif (\"local\" in service && service.local === true) {\n\t\t\t\tthrow new TypeError(`Local service ${service.id} cannot be published remotely`);\n\t\t\t}\n\t\t}\n\t\tconst ids = definitions.map(({ service }) => service.id);\n\t\tif (new Set(ids).size !== ids.length) throw new TypeError(\"Remote service catalogue contains duplicate IDs\");\n\t\tthis.#catalogue = Object.freeze(\n\t\t\tdefinitions.map(({ service, mode }) => Object.freeze({ serviceId: service.id, mode })),\n\t\t);\n\t\tfor (const { service, mode } of definitions) {\n\t\t\tthis.#registrations.set(service.id, {\n\t\t\t\tserviceId: service.id,\n\t\t\t\tmode,\n\t\t\t\tinstances: new Map(),\n\t\t\t\tgenerations: new Map(),\n\t\t\t\tsubscribers: new Set(),\n\t\t\t});\n\t\t}\n\t}\n\n\tget catalogue(): readonly ServiceCatalogueEntry[] {\n\t\treturn this.#catalogue;\n\t}\n\n\tprovide<T>(service: Service<T>, implementation: NoInfer<RemoteServiceContract<T>>): void {\n\t\tthis.#assertActive();\n\t\tthis.#assertRemotable(service);\n\t\tthis.#assertAllowed(service.id);\n\t\tconst registration = this.#registration(service.id, \"singleton\");\n\t\tif (registration.singleton !== undefined) {\n\t\t\tthrow new RemoteServiceError(\"service_mode_mismatch\", `Remote service ${service.id} already has a provider`);\n\t\t}\n\t\tconst classified = classifyRemoteServiceImplementation(registration.serviceId, implementation);\n\t\tconst shape = serviceMemberShape(classified.members);\n\t\tthis.#assertSingletonShape(registration, shape);\n\t\tregistration.singleton = this.#createInstance(registration, classified, undefined);\n\t\tregistration.singletonShape = shape;\n\t}\n\n\t/** Disconnect one singleton while preserving active subscriptions and remote facades. */\n\twithdraw<T>(service: Service<T>): void {\n\t\tthis.#assertActive();\n\t\tthis.#assertRemotable(service);\n\t\tthis.#assertAllowed(service.id);\n\t\tconst registration = this.#registration(service.id, \"singleton\");\n\t\tconst previous = registration.singleton;\n\t\tif (previous === undefined) return;\n\t\tprevious.active = false;\n\t\tfor (const remove of previous.removeMemberListeners) remove();\n\t\tdelete registration.singleton;\n\t\tthis.#emit(registration, { type: \"unavailable\" });\n\t}\n\n\t/** Check a singleton replacement without changing the active provider. */\n\tvalidateReplacement<T>(service: Service<T>, implementation: NoInfer<RemoteServiceContract<T>>): void {\n\t\tthis.#assertActive();\n\t\tthis.#assertRemotable(service);\n\t\tthis.#assertAllowed(service.id);\n\t\tconst registration = this.#registration(service.id, \"singleton\");\n\t\tconst classified = classifyRemoteServiceImplementation(registration.serviceId, implementation);\n\t\tthis.#assertSingletonShape(registration, serviceMemberShape(classified.members));\n\t}\n\n\t/** Replace one singleton without making its stable remote facade unavailable. */\n\treplace<T>(service: Service<T>, implementation: NoInfer<RemoteServiceContract<T>>): void {\n\t\tthis.#assertActive();\n\t\tthis.#assertRemotable(service);\n\t\tthis.#assertAllowed(service.id);\n\t\tconst registration = this.#registration(service.id, \"singleton\");\n\t\tconst classified = classifyRemoteServiceImplementation(registration.serviceId, implementation);\n\t\tconst shape = serviceMemberShape(classified.members);\n\t\tthis.#assertSingletonShape(registration, shape);\n\t\tconst replacement = this.#createInstance(registration, classified, undefined);\n\t\tconst previous = registration.singleton;\n\t\tif (previous !== undefined) {\n\t\t\tprevious.active = false;\n\t\t\tfor (const remove of previous.removeMemberListeners) remove();\n\t\t}\n\t\tregistration.singleton = replacement;\n\t\tregistration.singletonShape = shape;\n\t\tthis.#emit(registration, { type: \"replaced\", snapshot: this.#snapshotInstance(replacement) });\n\t}\n\n\tuse<T>(service: Service<T>): T {\n\t\tthis.#assertActive();\n\t\tthis.#assertRemotable(service);\n\t\tthis.#assertAllowed(service.id);\n\t\tconst registration = this.#registrations.get(service.id);\n\t\tif (registration?.mode !== \"singleton\" || registration.singleton === undefined) {\n\t\t\tthrow new RemoteServiceError(\"service_not_found\", `Remote service ${service.id} has no local provider`);\n\t\t}\n\t\treturn registration.singleton.implementation as T;\n\t}\n\n\tspawn<T>(service: Service<T>, key: string, implementation: NoInfer<RemoteServiceContract<T>>): () => void {\n\t\tthis.#assertActive();\n\t\tthis.#assertRemotable(service);\n\t\tthis.#assertAllowed(service.id);\n\t\tif (key.length === 0) throw new TypeError(\"Remote service instance key must not be empty\");\n\t\tconst registration = this.#registration(service.id, \"keyed\");\n\t\tif (registration.instances.has(key)) {\n\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\"service_mode_mismatch\",\n\t\t\t\t`Remote service ${service.id} already has a live instance with key ${key}`,\n\t\t\t);\n\t\t}\n\t\tconst generation = (registration.generations.get(key) ?? 0) + 1;\n\t\tregistration.generations.set(key, generation);\n\t\tconst address = { key, generation } satisfies ServiceInstanceAddress;\n\t\tconst classified = classifyRemoteServiceImplementation(registration.serviceId, implementation);\n\t\tconst instance = this.#createInstance(registration, classified, address);\n\t\tregistration.instances.set(key, instance);\n\t\tthis.#emit(registration, { type: \"spawned\", instance: this.#snapshotInstance(instance) });\n\t\tlet closed = false;\n\t\treturn () => {\n\t\t\tif (closed) return;\n\t\t\tclosed = true;\n\t\t\tif (registration.instances.get(key) !== instance) return;\n\t\t\tinstance.active = false;\n\t\t\tfor (const remove of instance.removeMemberListeners) remove();\n\t\t\tregistration.instances.delete(key);\n\t\t\tthis.#emit(registration, { type: \"closed\", instance: address });\n\t\t};\n\t}\n\n\tasync invoke(call: ServiceCall, context: Context): Promise<JsonValue | undefined> {\n\t\tthis.#assertActive();\n\t\tthis.#assertAllowed(call.serviceId);\n\t\tconst registration = this.#registrations.get(call.serviceId);\n\t\tif (registration === undefined) {\n\t\t\tthrow new RemoteServiceError(\"service_not_found\", `Unknown remote service ${call.serviceId}`);\n\t\t}\n\t\tconst instance = this.#resolveInstance(registration, call.instance);\n\t\tconst member = instance.members.get(call.member);\n\t\tif (member === undefined) {\n\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\"service_member_not_found\",\n\t\t\t\t`Unknown remote service member ${call.serviceId}.${call.member}`,\n\t\t\t);\n\t\t}\n\t\tif (member.kind !== \"method\") {\n\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\"service_member_mismatch\",\n\t\t\t\t`Remote service member ${call.serviceId}.${call.member} is not a method`,\n\t\t\t);\n\t\t}\n\t\tconst result: unknown = await Reflect.apply(member.method, instance.implementation, [...call.args, context]);\n\t\treturn result as JsonValue | undefined;\n\t}\n\n\tsubscribe(\n\t\tserviceId: string,\n\t\tmode: ServiceMode,\n\t\tlistener: (update: ServiceProviderUpdate, context: Context) => void,\n\t): ServiceSubscription {\n\t\tthis.#assertActive();\n\t\tthis.#assertAllowed(serviceId);\n\t\tconst registration = this.#registration(serviceId, mode);\n\t\tif (registration.mode === \"singleton\" && registration.singleton === undefined) {\n\t\t\tthrow new RemoteServiceError(\"service_not_found\", `Remote service ${serviceId} has no provider`);\n\t\t}\n\t\tconst subscriber: ProviderSubscriber = {\n\t\t\tlistener,\n\t\t\tbuffer: [],\n\t\t\tactive: false,\n\t\t\tterminated: false,\n\t\t\tclosed: false,\n\t\t};\n\t\tthis.#publishPending(registration);\n\t\tregistration.subscribers.add(subscriber);\n\t\tconst snapshot = this.#snapshot(registration);\n\t\treturn {\n\t\t\tsnapshot,\n\t\t\tactivate: () => {\n\t\t\t\tif (subscriber.closed || subscriber.active) return;\n\t\t\t\tsubscriber.active = true;\n\t\t\t\tconst errors: unknown[] = [];\n\t\t\t\ttry {\n\t\t\t\t\tfor (const entry of subscriber.buffer.splice(0)) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tlistener(entry.update, entry.context);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\terrors.push(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tif (subscriber.terminated) subscriber.closed = true;\n\t\t\t\t}\n\t\t\t\tthrowCollectedErrors(errors, \"Failed to activate remote service subscription\");\n\t\t\t},\n\t\t\tclose: () => {\n\t\t\t\tif (subscriber.closed) return;\n\t\t\t\tsubscriber.closed = true;\n\t\t\t\tsubscriber.buffer.length = 0;\n\t\t\t\tregistration.subscribers.delete(subscriber);\n\t\t\t},\n\t\t};\n\t}\n\n\tdispose(): void {\n\t\tif (this.#disposed) return;\n\t\tthis.#disposed = true;\n\t\tconst errors: unknown[] = [];\n\t\tfor (const registration of this.#registrations.values()) {\n\t\t\tconst singleton = registration.singleton;\n\t\t\tif (singleton !== undefined) {\n\t\t\t\tsingleton.active = false;\n\t\t\t\tfor (const remove of singleton.removeMemberListeners) remove();\n\t\t\t\tdelete registration.singleton;\n\t\t\t\ttry {\n\t\t\t\t\tthis.#emit(registration, { type: \"unavailable\" });\n\t\t\t\t} catch (error) {\n\t\t\t\t\terrors.push(error);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const [key, instance] of [...registration.instances]) {\n\t\t\t\tinstance.active = false;\n\t\t\t\tfor (const remove of instance.removeMemberListeners) remove();\n\t\t\t\tregistration.instances.delete(key);\n\t\t\t\ttry {\n\t\t\t\t\tthis.#emit(registration, { type: \"closed\", instance: instance.address! });\n\t\t\t\t} catch (error) {\n\t\t\t\t\terrors.push(error);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const subscriber of registration.subscribers) {\n\t\t\t\tif (subscriber.active) {\n\t\t\t\t\tsubscriber.closed = true;\n\t\t\t\t\tsubscriber.buffer.length = 0;\n\t\t\t\t} else {\n\t\t\t\t\tsubscriber.terminated = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tregistration.subscribers.clear();\n\t\t}\n\t\tthis.#registrations.clear();\n\t\tif (errors.length === 1) throw errors[0];\n\t\tif (errors.length > 1) throw new AggregateError(errors, \"Failed to dispose remote service provider\");\n\t}\n\n\t#registration(serviceId: string, mode: ServiceMode): ServiceRegistration {\n\t\tconst registration = this.#registrations.get(serviceId);\n\t\tif (registration === undefined) {\n\t\t\tthrow new RemoteServiceError(\"service_not_found\", `Unknown remote service ${serviceId}`);\n\t\t}\n\t\tif (registration.mode !== mode) {\n\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\"service_mode_mismatch\",\n\t\t\t\t`Remote service ${serviceId} is ${registration.mode}, not ${mode}`,\n\t\t\t);\n\t\t}\n\t\treturn registration;\n\t}\n\n\t#createInstance(\n\t\tregistration: ServiceRegistration,\n\t\tclassified: ClassifiedRemoteServiceImplementation,\n\t\taddress: ServiceInstanceAddress | undefined,\n\t): ProviderInstance {\n\t\tconst removeMemberListeners: (() => void)[] = [];\n\t\tconst instance: ProviderInstance = {\n\t\t\t...(address === undefined ? {} : { address }),\n\t\t\timplementation: classified.implementation,\n\t\t\tmembers: classified.members,\n\t\t\tremoveMemberListeners,\n\t\t\tactive: true,\n\t\t};\n\t\tfor (const [name, member] of classified.members) {\n\t\t\tif (member.kind !== \"state\") continue;\n\t\t\tremoveMemberListeners.push(\n\t\t\t\tmember.state.subscribe((ops, sequence, context) => {\n\t\t\t\t\tif (!instance.active) return;\n\t\t\t\t\tthis.#emit(\n\t\t\t\t\t\tregistration,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"state\",\n\t\t\t\t\t\t\t...(address === undefined ? {} : { instance: address }),\n\t\t\t\t\t\t\tmember: name,\n\t\t\t\t\t\t\tsequence,\n\t\t\t\t\t\t\tops,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcontext,\n\t\t\t\t\t);\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\treturn instance;\n\t}\n\n\t#assertSingletonShape(registration: ServiceRegistration, replacement: ReadonlyMap<string, ServiceMemberKind>): void {\n\t\tconst current = registration.singletonShape;\n\t\tif (current === undefined || sameServiceMemberShape(current, replacement)) return;\n\t\tthrow new RemoteServiceError(\n\t\t\t\"service_member_mismatch\",\n\t\t\t`Remote service ${registration.serviceId} replacement must preserve its member shape`,\n\t\t);\n\t}\n\n\t#resolveInstance(registration: ServiceRegistration, address: ServiceInstanceAddress | undefined): ProviderInstance {\n\t\tif (registration.mode === \"singleton\") {\n\t\t\tif (address !== undefined) {\n\t\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\t\"service_mode_mismatch\",\n\t\t\t\t\t`Remote service ${registration.serviceId} is singleton`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (registration.singleton === undefined) {\n\t\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\t\"service_not_found\",\n\t\t\t\t\t`Remote service ${registration.serviceId} has no provider`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn registration.singleton;\n\t\t}\n\t\tif (address === undefined) {\n\t\t\tthrow new RemoteServiceError(\"service_mode_mismatch\", `Remote service ${registration.serviceId} is keyed`);\n\t\t}\n\t\tconst instance = registration.instances.get(address.key);\n\t\tif (instance === undefined) {\n\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\"service_instance_not_found\",\n\t\t\t\t`Remote service ${registration.serviceId} has no instance ${address.key}`,\n\t\t\t);\n\t\t}\n\t\tif (instance.address?.generation !== address.generation) {\n\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\"service_stale_instance\",\n\t\t\t\t`Remote service ${registration.serviceId} instance ${address.key} is stale`,\n\t\t\t);\n\t\t}\n\t\treturn instance;\n\t}\n\n\t#publishPending(registration: ServiceRegistration): void {\n\t\tconst context = serviceDeliveryContext();\n\t\tconst instances =\n\t\t\tregistration.mode === \"singleton\"\n\t\t\t\t? registration.singleton === undefined\n\t\t\t\t\t? []\n\t\t\t\t\t: [registration.singleton]\n\t\t\t\t: registration.instances.values();\n\t\tfor (const instance of instances) {\n\t\t\tfor (const member of instance.members.values()) {\n\t\t\t\tif (member.kind === \"state\") member.state.publish(context);\n\t\t\t}\n\t\t}\n\t}\n\n\t#snapshot(registration: ServiceRegistration): ServiceSubscriptionSnapshot {\n\t\tconst instances =\n\t\t\tregistration.mode === \"singleton\"\n\t\t\t\t? registration.singleton\n\t\t\t\t\t? [this.#snapshotInstance(registration.singleton)]\n\t\t\t\t\t: []\n\t\t\t\t: [...registration.instances.values()]\n\t\t\t\t\t\t.sort((left, right) => left.address!.key.localeCompare(right.address!.key))\n\t\t\t\t\t\t.map((instance) => this.#snapshotInstance(instance));\n\t\treturn { serviceId: registration.serviceId, mode: registration.mode, instances };\n\t}\n\n\t#snapshotInstance(instance: ProviderInstance): ServiceInstanceSnapshot {\n\t\tconst members: ServiceMemberSnapshot[] = [];\n\t\tfor (const [name, member] of instance.members) {\n\t\t\tif (member.kind === \"method\") {\n\t\t\t\tmembers.push({ name, kind: \"method\" });\n\t\t\t} else {\n\t\t\t\tmembers.push({\n\t\t\t\t\tname,\n\t\t\t\t\tkind: \"state\",\n\t\t\t\t\tsequence: member.state.sequence,\n\t\t\t\t\tops: [[\"r\", member.state.value as JsonValue]],\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\t...(instance.address === undefined ? {} : { instance: instance.address }),\n\t\t\tmembers,\n\t\t};\n\t}\n\n\t#emit(registration: ServiceRegistration, update: ServiceProviderUpdate, context?: Context): void {\n\t\tif (registration.subscribers.size === 0) return;\n\t\tconst deliveryContext = context ?? serviceDeliveryContext();\n\t\tconst errors: unknown[] = [];\n\t\tfor (const subscriber of registration.subscribers) {\n\t\t\tif (subscriber.closed) continue;\n\t\t\tconst entry = { update, context: deliveryContext };\n\t\t\tif (!subscriber.active) {\n\t\t\t\tsubscriber.buffer.push(entry);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tsubscriber.listener(entry.update, entry.context);\n\t\t\t} catch (error) {\n\t\t\t\terrors.push(error);\n\t\t\t}\n\t\t}\n\t\tthrowCollectedErrors(errors, `Failed to publish remote service ${registration.serviceId} update`);\n\t}\n\n\t#assertRemotable(service: { readonly id: string; readonly local: boolean }): void {\n\t\tif (service.local) throw new RemoteServiceError(\"service_not_allowed\", `Service ${service.id} is process-local`);\n\t}\n\n\t#assertAllowed(serviceId: string): void {\n\t\tif (!this.#registrations.has(serviceId)) {\n\t\t\tthrow new RemoteServiceError(\"service_not_allowed\", `Remote service ${serviceId} is not allowlisted`);\n\t\t}\n\t}\n\n\t#assertActive(): void {\n\t\tif (this.#disposed) throw new Error(\"Remote service provider is disposed\");\n\t}\n}\n\nexport function createRemoteServiceEndpoint(provider: RemoteServiceProvider): RemoteServiceEndpoint {\n\tconst subscriptions = new Map<string, ServiceSubscription>();\n\tlet disposed = false;\n\n\treturn {\n\t\tasync invoke(call, publish, context) {\n\t\t\tif (disposed) throw new Error(\"Remote service endpoint is disposed\");\n\t\t\tconst control = decodeServiceControlCall(call);\n\t\t\tif (control?.type === \"catalogue\") return provider.catalogue as unknown as JsonValue;\n\t\t\tif (control?.type === \"subscribe\") {\n\t\t\t\tif (subscriptions.has(control.subscriptionId)) {\n\t\t\t\t\tthrow new Error(\"Service subscription ID is already active\");\n\t\t\t\t}\n\t\t\t\tconst subscription = provider.subscribe(control.serviceId, control.mode, (update, updateContext) => {\n\t\t\t\t\tvoid Promise.resolve(publish(control.subscriptionId, update, updateContext)).catch(() => {});\n\t\t\t\t});\n\t\t\t\tsubscriptions.set(control.subscriptionId, subscription);\n\t\t\t\tsubscription.activate();\n\t\t\t\treturn subscription.snapshot as unknown as JsonValue;\n\t\t\t}\n\t\t\tif (control?.type === \"unsubscribe\") {\n\t\t\t\tconst subscription = subscriptions.get(control.subscriptionId);\n\t\t\t\tif (subscription === undefined) throw new Error(\"Service subscription was not found\");\n\t\t\t\tsubscription.close();\n\t\t\t\tsubscriptions.delete(control.subscriptionId);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn provider.invoke(call, context);\n\t\t},\n\t\tdispose() {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\tfor (const subscription of subscriptions.values()) subscription.close();\n\t\t\tsubscriptions.clear();\n\t\t},\n\t};\n}\n\nexport function validateRemoteServiceImplementation(serviceId: string, implementation: unknown): void {\n\tvoid classifyRemoteServiceImplementation(serviceId, implementation);\n}\n\nfunction classifyRemoteServiceImplementation(\n\tserviceId: string,\n\timplementation: unknown,\n): ClassifiedRemoteServiceImplementation {\n\tif (typeof implementation !== \"object\" || implementation === null || Array.isArray(implementation)) {\n\t\tthrow new TypeError(`Remote service ${serviceId} implementation must be an object`);\n\t}\n\tconst members = new Map<string, InstanceMember>();\n\tfor (const name of Object.keys(implementation).sort()) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(implementation, name);\n\t\tif (descriptor === undefined || !(\"value\" in descriptor)) {\n\t\t\tthrow new TypeError(`Remote service member ${serviceId}.${name} must be a data property`);\n\t\t}\n\t\tif (typeof descriptor.value === \"function\") {\n\t\t\tmembers.set(name, { kind: \"method\", method: descriptor.value as RemoteMethod });\n\t\t\tcontinue;\n\t\t}\n\t\tconst state = getReplicatedStateInternals(descriptor.value);\n\t\tif (state !== undefined) {\n\t\t\tmembers.set(name, { kind: \"state\", state });\n\t\t\tcontinue;\n\t\t}\n\t\tthrow new TypeError(`Remote service member ${serviceId}.${name} is not remotely exposable`);\n\t}\n\tif (members.size === 0) throw new TypeError(`Remote service ${serviceId} has no members`);\n\treturn { implementation, members };\n}\n\nfunction throwCollectedErrors(errors: readonly unknown[], message: string): void {\n\tif (errors.length === 1) throw errors[0];\n\tif (errors.length > 1) throw new AggregateError(errors, message);\n}\n\nfunction serviceMemberShape(members: ReadonlyMap<string, InstanceMember>): ReadonlyMap<string, ServiceMemberKind> {\n\treturn new Map([...members].map(([name, member]) => [name, member.kind]));\n}\n\nfunction sameServiceMemberShape(\n\tleft: ReadonlyMap<string, ServiceMemberKind>,\n\tright: ReadonlyMap<string, ServiceMemberKind>,\n): boolean {\n\treturn left.size === right.size && [...left].every(([name, kind]) => right.get(name) === kind);\n}\n"]}
@@ -0,0 +1,15 @@
1
+ import type { ServiceProviderUpdate, ServiceSubscriptionSnapshot } from "../types.ts";
2
+ import type { WireServiceProviderUpdate, WireServiceSubscriptionSnapshot } from "./wire.ts";
3
+ /** Stateful operation encoders for every replicated state in one service subscription. */
4
+ export interface ServiceStateEncoder {
5
+ encodeSnapshot(snapshot: ServiceSubscriptionSnapshot): WireServiceSubscriptionSnapshot;
6
+ encodeUpdate(update: ServiceProviderUpdate): WireServiceProviderUpdate;
7
+ }
8
+ /** Stateful operation decoders for every replicated state in one service subscription. */
9
+ export interface ServiceStateDecoder {
10
+ decodeSnapshot(snapshot: WireServiceSubscriptionSnapshot): ServiceSubscriptionSnapshot;
11
+ decodeUpdate(update: WireServiceProviderUpdate): ServiceProviderUpdate;
12
+ }
13
+ export declare function createServiceStateEncoder(): ServiceStateEncoder;
14
+ export declare function createServiceStateDecoder(): ServiceStateDecoder;
15
+ //# sourceMappingURL=state-codec.d.ts.map