File size: 14,332 Bytes
51c026d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 | import {
createServiceCatalogueCall,
createServiceStateDecoder,
createServiceSubscribeCall,
createServiceUnsubscribeCall,
type JsonValue,
parseServiceCall,
parseServiceCatalogue,
parseWireServiceProviderUpdate,
parseWireServiceSubscriptionSnapshot,
type RemoteServiceTransport,
type ServiceCall,
type ServiceCatalogueEntry,
type ServiceMode,
type ServiceProviderUpdate,
type ServiceStateDecoder,
type ServiceSubscriptionSnapshot,
} from "@earendil-works/chord";
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
import {
type AttachmentEnvelope,
encodeClientMessage,
isServerId,
ProtocolValidationError,
type ResponseEnvelope,
type RpcTarget,
type ServerHello,
type ServiceEventEnvelope,
type SessionTarget,
} from "@earendil-works/pi-protocol";
import { Connection } from "./connection.ts";
import { ClientDisposedError, DisconnectedError, ServerError, toError } from "./errors.ts";
import { createPromiseResolvers } from "./promise.ts";
import type {
AttachmentChangeListener,
ClientOptions,
ConnectionState,
ConnectionStateChange,
ServiceSubscription,
Unsubscribe,
} from "./types.ts";
type ServiceResult = JsonValue | undefined;
interface PendingRequest {
resolve(result: ServiceResult): void;
reject(error: Error): void;
cleanup(): void;
}
interface ActiveServiceListener {
readonly target: RpcTarget;
readonly listener: (update: ServiceProviderUpdate) => void | Promise<void>;
readonly decoder: ServiceStateDecoder;
readonly queuedWireUpdates: JsonValue[];
readonly queued: ServiceProviderUpdate[];
deliveryTail: Promise<void>;
hydrated: boolean;
ready: boolean;
}
export class Client {
readonly #options: ClientOptions;
readonly #connection: Connection;
readonly #pendingRequests = new Map<string, PendingRequest>();
readonly #connectionStateListeners = new Set<(change: ConnectionStateChange) => void>();
readonly #attachmentListeners = new Set<AttachmentChangeListener>();
readonly #serviceListeners = new Map<string, ActiveServiceListener>();
#requestSequence = 0;
#serviceSubscriptionSequence = 0;
#hello: ServerHello | undefined;
#attachment: SessionTarget | undefined;
#disposed = false;
#disposePromise: Promise<void> | undefined;
constructor(options: ClientOptions) {
if (!isServerId(options.serverId)) {
throw new TypeError("serverId must be a canonical lowercase UUIDv4");
}
this.#options = options;
this.#connection = new Connection({
transportFactory: options.transportFactory,
serverId: options.serverId,
maxFrameLength: options.maxFrameLength,
onHandshake: (hello) => {
this.#hello = hello;
},
onMessage: (message) => this.#handleMessage(message),
onStateChange: (change) => this.#handleConnectionStateChange(change),
});
}
get disposed(): boolean {
return this.#disposed;
}
get connectionState(): ConnectionState {
return this.#connection.state;
}
get connected(): boolean {
return this.#connection.state === "connected";
}
get serverId(): string {
return this.#options.serverId;
}
get hello(): ServerHello | undefined {
return this.#hello;
}
get attachment(): SessionTarget | undefined {
return this.#attachment;
}
static async connect(options: ClientOptions): Promise<Client> {
const client = new Client(options);
try {
await client.connect();
return client;
} catch (error) {
await client.dispose();
throw error;
}
}
connect(): Promise<ServerHello> {
if (this.#disposed) return Promise.reject(new ClientDisposedError());
this.#hello = undefined;
return this.#connection.connect();
}
reconnect(): Promise<ServerHello> {
return this.connect();
}
disconnect(reason = "Client disconnected"): void {
this.#connection.disconnect(reason);
}
onConnectionStateChange(listener: (change: ConnectionStateChange) => void): Unsubscribe {
this.#assertNotDisposed();
this.#connectionStateListeners.add(listener);
return () => this.#connectionStateListeners.delete(listener);
}
onAttachmentChange(listener: AttachmentChangeListener): Unsubscribe {
this.#assertNotDisposed();
this.#attachmentListeners.add(listener);
return () => this.#attachmentListeners.delete(listener);
}
/** Invoke one low-level protocol call against an explicit routed target. */
request(target: RpcTarget, call: ServiceCall, signal?: AbortSignal): Promise<ServiceResult> {
return this.#request(target, call, signal);
}
async serviceCatalogue(target: RpcTarget, signal?: AbortSignal): Promise<readonly ServiceCatalogueEntry[]> {
const result = await this.#request(target, createServiceCatalogueCall(), signal);
try {
return parseServiceCatalogue(result);
} catch (error) {
const validationError = new ProtocolValidationError(
error instanceof Error ? error.message : "Invalid service catalogue",
);
this.#connection.fail(validationError);
throw validationError;
}
}
async subscribeService(
target: RpcTarget,
serviceId: string,
mode: ServiceMode,
listener: (update: ServiceProviderUpdate) => void | Promise<void>,
signal?: AbortSignal,
): Promise<ServiceSubscription> {
const subscriptionId = `service-${++this.#serviceSubscriptionSequence}`;
const active: ActiveServiceListener = {
target,
listener,
decoder: createServiceStateDecoder(),
queuedWireUpdates: [],
queued: [],
deliveryTail: Promise.resolve(),
hydrated: false,
ready: false,
};
this.#serviceListeners.set(subscriptionId, active);
let snapshot: ServiceSubscriptionSnapshot;
try {
snapshot = await this.#request(
target,
createServiceSubscribeCall(subscriptionId, serviceId, mode),
signal,
(result) => {
const decoded = active.decoder.decodeSnapshot(parseWireServiceSubscriptionSnapshot(result));
active.hydrated = true;
for (const update of active.queuedWireUpdates.splice(0)) {
active.queued.push(active.decoder.decodeUpdate(parseWireServiceProviderUpdate(update)));
}
return decoded;
},
);
} catch (error) {
if (this.#serviceListeners.get(subscriptionId) === active) this.#serviceListeners.delete(subscriptionId);
throw error;
}
if (this.#serviceListeners.get(subscriptionId) !== active) throw new DisconnectedError();
let disposed = false;
return {
id: subscriptionId,
target,
snapshot,
start: () => {
if (disposed || active.ready) return;
active.ready = true;
for (const update of active.queued.splice(0)) this.#deliverServiceUpdate(active, update);
},
dispose: async () => {
if (disposed) return;
disposed = true;
if (this.#serviceListeners.get(subscriptionId) === active) this.#serviceListeners.delete(subscriptionId);
try {
if (this.connected && this.#targetIsCurrent(target)) {
await this.#request(target, createServiceUnsubscribeCall(subscriptionId));
}
await active.deliveryTail;
} finally {
active.queuedWireUpdates.length = 0;
active.queued.length = 0;
}
},
};
}
#request<T = ServiceResult>(
target: RpcTarget,
call: ServiceCall,
signal?: AbortSignal,
transform?: (result: ServiceResult) => T,
): Promise<T> {
if (this.#disposed) return Promise.reject(new ClientDisposedError());
if (!this.connected) return Promise.reject(new DisconnectedError());
if (signal?.aborted) return Promise.reject(abortError(signal));
const id = `request-${++this.#requestSequence}`;
const { promise, resolve, reject } = createPromiseResolvers<T>();
let sent = false;
let aborted = false;
let onAbort: (() => void) | undefined;
const sendCancel = (): void => {
if (!sent || !this.connected) return;
try {
this.#connection.send(
encodeClientMessage({ type: "cancel", id, target }, { maxFrameLength: this.#connection.maxFrameLength }),
);
} catch (error) {
this.#connection.fail(toError(error));
}
};
if (signal !== undefined) {
onAbort = () => {
if (aborted) return;
aborted = true;
reject(abortError(signal));
sendCancel();
};
signal.addEventListener("abort", onAbort, { once: true });
}
this.#pendingRequests.set(id, {
resolve: (result) => {
try {
resolve(transform === undefined ? (result as T) : transform(result));
} catch (error) {
const validationError = new ProtocolValidationError(
error instanceof Error ? error.message : "Invalid service operation stream",
);
this.#connection.fail(validationError);
reject(validationError);
}
},
reject,
cleanup: () => {
if (signal !== undefined && onAbort !== undefined) signal.removeEventListener("abort", onAbort);
},
});
let frame: Uint8Array;
try {
frame = encodeClientMessage(
{ type: "request", id, target, call: parseServiceCall(call) as unknown as JsonValue },
{ maxFrameLength: this.#connection.maxFrameLength },
);
} catch (error) {
this.#takePendingRequest(id)?.reject(toError(error));
return promise;
}
this.#connection.send(frame);
sent = true;
if (aborted) sendCancel();
return promise;
}
#handleMessage(message: ResponseEnvelope | ServiceEventEnvelope | AttachmentEnvelope): void {
if (message.type === "attachment") {
if (message.attachment !== null && message.attachment.serverId !== this.#options.serverId) {
this.#connection.fail(new ProtocolValidationError("Attachment update belongs to another server"));
return;
}
this.#setAttachment(message.attachment ?? undefined);
return;
}
if (message.type === "service_update") {
const active = this.#serviceListeners.get(message.subscriptionId);
if (active === undefined) return;
if (!active.hydrated) {
active.queuedWireUpdates.push(message.update);
return;
}
let update: ServiceProviderUpdate;
try {
update = active.decoder.decodeUpdate(parseWireServiceProviderUpdate(message.update));
} catch (error) {
this.#connection.fail(
new ProtocolValidationError(error instanceof Error ? error.message : "Invalid service operation stream"),
);
return;
}
if (active.ready) this.#deliverServiceUpdate(active, update);
else active.queued.push(update);
return;
}
const pending = this.#takePendingRequest(message.id);
if (!pending) {
this.#connection.fail(new ProtocolValidationError("Response has no matching request"));
return;
}
if (!message.ok) {
pending.reject(new ServerError(message.error));
return;
}
pending.resolve(message.result);
}
#handleConnectionStateChange(change: ConnectionStateChange): void {
if (change.state === "disconnected") {
this.#hello = undefined;
this.#setAttachment(undefined);
this.#rejectPendingRequests(change.error ?? new DisconnectedError());
this.#serviceListeners.clear();
}
for (const listener of this.#connectionStateListeners) {
try {
listener(change);
} catch (error) {
this.#reportListenerError(error);
}
}
}
#takePendingRequest(id: string): PendingRequest | undefined {
const request = this.#pendingRequests.get(id);
if (request) {
this.#pendingRequests.delete(id);
request.cleanup();
}
return request;
}
#rejectPendingRequests(error: Error): void {
const requests = [...this.#pendingRequests.values()];
this.#pendingRequests.clear();
for (const request of requests) {
request.cleanup();
request.reject(error);
}
}
dispose(): Promise<void> {
if (this.#disposePromise) return this.#disposePromise;
this.#disposed = true;
this.#disposePromise = Promise.resolve();
const error = new ClientDisposedError();
this.#rejectPendingRequests(error);
this.#connection.disconnect(error);
this.#hello = undefined;
this.#setAttachment(undefined);
this.#connectionStateListeners.clear();
this.#attachmentListeners.clear();
this.#serviceListeners.clear();
return this.#disposePromise;
}
[Symbol.asyncDispose](): Promise<void> {
return this.dispose();
}
#setAttachment(attachment: SessionTarget | undefined): void {
const previous = this.#attachment;
if (
previous?.serverId === attachment?.serverId &&
previous?.sessionId === attachment?.sessionId &&
previous?.attachmentId === attachment?.attachmentId
) {
return;
}
this.#attachment = attachment;
for (const listener of this.#attachmentListeners) {
try {
listener(attachment);
} catch (error) {
this.#reportListenerError(error);
}
}
}
#deliverServiceUpdate(active: ActiveServiceListener, update: ServiceProviderUpdate): void {
active.deliveryTail = active.deliveryTail
.then(() => active.listener(update))
.catch((error: unknown) => this.#reportListenerError(error));
}
#targetIsCurrent(target: RpcTarget): boolean {
if (!("sessionId" in target)) return this.#hello?.serverId === target.serverId;
const attachment = this.#attachment;
return (
attachment?.serverId === target.serverId &&
attachment.sessionId === target.sessionId &&
attachment.attachmentId === target.attachmentId
);
}
#assertNotDisposed(): void {
if (this.#disposed) throw new ClientDisposedError();
}
#reportListenerError(error: unknown): void {
if (!this.#options.onListenerError) return;
try {
this.#options.onListenerError(toError(error));
} catch {
// Diagnostics cannot affect protocol or transport state.
}
}
}
/** Adapts a lazily resolved routed client target to a Chord service transport. */
export function createClientServiceTransport(
client: Client,
getTarget: () => RpcTarget | undefined,
): RemoteServiceTransport {
const target = (): RpcTarget => {
const resolved = getTarget();
if (resolved === undefined) throw new Error("Remote service target is unavailable");
return resolved;
};
return {
invoke: async (call, context) => client.request(target(), call, context.abortSignal),
async subscribe(serviceId, mode, listener, context) {
const subscription = await client.subscribeService(
target(),
serviceId,
mode,
(update) => listener(update, BACKGROUND_CONTEXT),
context.abortSignal,
);
return {
snapshot: subscription.snapshot,
activate: () => subscription.start(),
close: () => subscription.dispose(),
};
},
};
}
function abortError(signal: AbortSignal): Error {
const reason: unknown = signal.reason;
return reason instanceof Error ? reason : new DOMException("The operation was aborted", "AbortError");
}
|