|
| 1 | +import { soloListener } from './listener.ts'; |
| 2 | +import { objectNotifyAll, objectWait } from './notify.ts'; |
| 3 | +import { buildLinkQueue } from './queue.ts'; |
| 4 | + |
| 5 | +export type CallToken = Object; |
| 6 | + |
| 7 | +export type MuxTask<Out> = { token: CallToken } & ({ signal: AbortSignal } | { data: Out }); |
| 8 | + |
| 9 | +type InternalMuxTask<In, Out> = |
| 10 | + | { token: CallToken } & ( |
| 11 | + | { signal: AbortSignal; respond: (x: SimpleResponse<In>) => void } |
| 12 | + | { data: Out } |
| 13 | + ); |
| 14 | + |
| 15 | +export interface MuxSession<In, Out> { |
| 16 | + signal: AbortSignal; |
| 17 | + |
| 18 | + /** |
| 19 | + * Are there any active calls as part of this {@link MuxSession}? |
| 20 | + * The runner should probably not return if this is the case. |
| 21 | + */ |
| 22 | + hasActive(): boolean; |
| 23 | + |
| 24 | + /** |
| 25 | + * Synchronously return the next task. |
| 26 | + * This may return `undefined` even if the session is still active, check {@link hasActive}. |
| 27 | + */ |
| 28 | + nextTask(): MuxTask<Out> | undefined; |
| 29 | + |
| 30 | + /** |
| 31 | + * Wait for another task to become ready. |
| 32 | + */ |
| 33 | + waitForTask(): Promise<true>; |
| 34 | + |
| 35 | + /** |
| 36 | + * Process a message received for this {@link CallToken}. |
| 37 | + */ |
| 38 | + handle(token: CallToken, data: In): void; |
| 39 | + |
| 40 | + /** |
| 41 | + * Process a remote shutdown of this {@link CallToken}. |
| 42 | + */ |
| 43 | + stop(token: CallToken, error?: Error): void; |
| 44 | +} |
| 45 | + |
| 46 | +export type MuxFn<In, Out> = (session: MuxSession<In, Out>) => Promise<any>; |
| 47 | + |
| 48 | +type SimpleResponse<X> = { data?: X; error?: Error }; |
| 49 | + |
| 50 | +class MuxSessionImpl<In, Out> implements MuxSession<In, Out> { |
| 51 | + readonly controller = new AbortController(); |
| 52 | + public readonly signal = this.controller.signal; |
| 53 | + |
| 54 | + readonly active = new Map<CallToken, (x: SimpleResponse<In>) => void>(); |
| 55 | + |
| 56 | + constructor(private readonly tasks: InternalMuxTask<In, Out>[]) {} |
| 57 | + |
| 58 | + hasActive(): boolean { |
| 59 | + return this.active.size !== 0; |
| 60 | + } |
| 61 | + |
| 62 | + nextTask(): MuxTask<Out> | undefined { |
| 63 | + const t = this.tasks.shift(); |
| 64 | + if (!t) { |
| 65 | + return; |
| 66 | + } |
| 67 | + |
| 68 | + if ('respond' in t) { |
| 69 | + if (t.signal.aborted) { |
| 70 | + return this.nextTask(); |
| 71 | + } |
| 72 | + t.signal.addEventListener('abort', () => this.active.delete(t.token)); |
| 73 | + this.active.set(t.token, t.respond); |
| 74 | + return { token: t.token, signal: t.signal }; |
| 75 | + } else if (!this.active.has(t.token)) { |
| 76 | + // silently drop messages for already-dead calls |
| 77 | + return this.nextTask(); |
| 78 | + } |
| 79 | + |
| 80 | + return t; |
| 81 | + } |
| 82 | + |
| 83 | + async waitForTask(): Promise<true> { |
| 84 | + while (!this.tasks.length) { |
| 85 | + await objectWait(this.tasks); |
| 86 | + } |
| 87 | + return true; |
| 88 | + } |
| 89 | + |
| 90 | + handle(token: CallToken, data: In): void { |
| 91 | + const fn = this.active.get(token); |
| 92 | + fn?.({ data }); |
| 93 | + } |
| 94 | + |
| 95 | + stop(token: CallToken, error?: Error): void { |
| 96 | + const fn = this.active.get(token); |
| 97 | + fn?.({ error }); |
| 98 | + this.active.delete(token); |
| 99 | + } |
| 100 | +} |
| 101 | + |
| 102 | +export interface Call<In, Out> { |
| 103 | + /** |
| 104 | + * Listen to data from the other side. |
| 105 | + */ |
| 106 | + readonly gen: AsyncGenerator<In, Error | void, void>; |
| 107 | + |
| 108 | + /** |
| 109 | + * Send the packet. |
| 110 | + * This may queue the packet rather than send immediately. |
| 111 | + */ |
| 112 | + send(data: Out): void; |
| 113 | +} |
| 114 | + |
| 115 | +export type MuxCall<In, Out> = { |
| 116 | + call(signal: AbortSignal): Call<In, Out>; |
| 117 | + addListener(cb: (error: Error) => void, signal: AbortSignal): void; |
| 118 | +}; |
| 119 | + |
| 120 | +/** |
| 121 | + * Builds a {@link MuxCall}. |
| 122 | + */ |
| 123 | +export function buildMux<In, Out>(runner: MuxFn<In, Out>): MuxCall<In, Out> { |
| 124 | + let activeRunner: Promise<any> | undefined; |
| 125 | + const tasks: InternalMuxTask<In, Out>[] = []; |
| 126 | + |
| 127 | + const listener = soloListener<Error>(); |
| 128 | + |
| 129 | + const maybeStartRunner = () => { |
| 130 | + if (!tasks.length || activeRunner !== undefined) { |
| 131 | + return; |
| 132 | + } |
| 133 | + |
| 134 | + const session = new MuxSessionImpl(tasks); |
| 135 | + const response: { error?: Error } = {}; |
| 136 | + |
| 137 | + activeRunner = runner(session) |
| 138 | + .catch((error) => { |
| 139 | + response.error = error; |
| 140 | + listener.dispatch(error); |
| 141 | + }) |
| 142 | + .finally(() => { |
| 143 | + activeRunner = undefined; |
| 144 | + maybeStartRunner(); |
| 145 | + |
| 146 | + // kill all still-active because the runner shut down |
| 147 | + session.active.forEach((cb) => cb(response)); |
| 148 | + }); |
| 149 | + }; |
| 150 | + |
| 151 | + const call = (signal: AbortSignal): Call<In, Out> => { |
| 152 | + if (signal.aborted) { |
| 153 | + const gen = (async function* () { |
| 154 | + try { |
| 155 | + signal.throwIfAborted(); |
| 156 | + } catch (e: any) { |
| 157 | + return e instanceof Error ? e : new Error(e); |
| 158 | + } |
| 159 | + })(); |
| 160 | + return { send() {}, gen }; |
| 161 | + } |
| 162 | + |
| 163 | + const queue = buildLinkQueue<SimpleResponse<In>>(); |
| 164 | + const listener = queue.join(signal); |
| 165 | + |
| 166 | + const gen = (async function* () { |
| 167 | + for (;;) { |
| 168 | + const m = await listener.next(); |
| 169 | + if (m?.data !== undefined) { |
| 170 | + yield m?.data as In; |
| 171 | + } |
| 172 | + if (m?.error || m?.data === undefined) { |
| 173 | + return m?.error as Error | void; |
| 174 | + } |
| 175 | + } |
| 176 | + })(); |
| 177 | + |
| 178 | + // something object-like |
| 179 | + const token: CallToken = new Object(); |
| 180 | + tasks.push({ token, signal, respond: queue.push.bind(queue) }); |
| 181 | + objectNotifyAll(tasks); |
| 182 | + |
| 183 | + const send = (out: Out) => { |
| 184 | + if (!signal.aborted) { |
| 185 | + tasks.push({ token, data: out }); |
| 186 | + } |
| 187 | + }; |
| 188 | + |
| 189 | + maybeStartRunner(); |
| 190 | + |
| 191 | + return { gen, send }; |
| 192 | + }; |
| 193 | + |
| 194 | + return { call, addListener: listener.addListener }; |
| 195 | +} |
0 commit comments