* ✨ feat(session): persist and synchronize read state * 🌐 fix(client): complete Japanese labels after base update * 📝 docs: refresh session read-state dependency graph * 🧪 test(web): align session menu and read-state snapshots * 🌐 fix(session): complete Japanese plugin metadata * 🧪 test(web): distinguish unread from pending user input * 🐛 修复会话阅读状态的故障隔离与生命周期 * 🐛 修复阅读状态依赖检查并补齐自动已读覆盖 * 🐛 恢复会话绿点并移除未读标题加粗 * ♻️ Keep shared session reading state in Host memory * 🌐 Complete reading-state metadata for supported locales * 📝 Refresh module graph after removing storage dependency * 🧹 Move storage dependency policy out of memory-only reading * 🐛 Wait for sidebar catalog before replay navigation * 🔧 Give Host TypeScript checks 8 GiB of heap * ✅ Align Host heap checks and Windows diagnostics * ♻️ Keep CI repairs outside the session reading PR * 🐛 Show failed unread turns with an error indicator * 🔧 Adjust npm layout budget for the reading package * 🧪 Scope projection stream assertions to observed units * 🧪 Scope permission and title assertions to their projections * ♻️ Simplify session reading updates to explicit positions * 🐛 Align session reading package with release version * 🧪 Load reading state in LiveShare viewer fixtures * 🧹 Remove persistence-only type link from memory PR * 🧪 Align context menu expectations with reading actions * 🐛 Sync reading package with the release version * 🧪 Include turn boundaries in session summary expectations * ♻️ Derive reading failure facts from Host events instead of a projection The reading service took each completion from the Agent turn-boundary projection, which forced a stateVersion bump and put that projection's whole internal state on the wire for every Session list row. The service now records `turn/end` itself, so `core/agent` and the persisted projection schema are untouched. History that ended before the service started raises no reminder, which keeps "existing history reads as read" without a startup scan. The failure flag therefore describes only turns this Host observed: marking a Session whose last turn failed before a restart shows the ordinary unread reminder. * 🐛 Preserve manual unread until explicit Session interaction * 🧪 Align cold Session reading snapshot with unloaded title * 🔖 chore(session): align session-read-state with 0.2.2-rc.2 Master moved the root and every released manifest to 0.2.2-rc.2, but the new dsh-session-read-state package still declared 0.2.2-rc.1, failing constraints, verify-version-sync, verify-npm-install-layout, and release:verify after the master merge. * ♻️ refactor(gateway): recognize Remote stream carrier loss by error code RemoteStream now decides whether a generation end or failure is a retryable carrier loss by the stable code 'gateway/carrier-lost' instead of `instanceof RemoteStreamCarrierError`. RemoteStreamCarrierError keeps working and carries that code, so existing callers are unchanged, while a Client feature package can return a coded Error from `ended` without importing the class. The new RemoteStreamCarrierFailure type describes such errors; terminal-controller classifies disconnects the same way. * ♻️ refactor(session): move Session reading into ui-session-status Fold the reading feature into the single package packages/client/ui-session-status and delete session-read-state. - Host face: SessionStatusService keeps in-memory reading records and serves the sessionStatus Remote namespace (mark, follow) with session-status/* error codes; its service key is registered only for Gateway discovery and is not declared on Context. - Client face: a package-internal reading model follows the Host stream through RemoteSnapshotStream; ctx.uiSession.sessionStatus folds the records into completionUnread and completionFailed and exposes mark and readingReady; main-view acknowledgement and the session-status/read-intent event live here. No reading service or type is exported. - verify-client-packages lets a packages/client feature package request packages/api rows through dsh.client.external; feature-to-feature requests stay rejected. - ui-workspace, ui-conversation, bundles, remotes, LiveShare, the client test runtime, docs, Agent Notes, and the upgrade guide follow. * ♻️ refactor(session): clear manual unread only when the main view switches to the Session Remove the session-status/read-intent event. ui-session-status now clears an existing manual unread mark when the main view switches to a different Session, including the first selection after a page load, once the reading baseline is ready and the body arrives. Window focus, visibility changes, a replaced binding for the same Session, and activity in the open Session preserve manual unread. ui-conversation returns to master (only the ui-session-status client tsconfig reference remains), and ui-workspace navigation no longer emits the event. Tests, the session-reading Web e2e case, READMEs, and the reading Agent Note follow the new rule. * 🐛 fix(session): address the Session status review findings - Open the reading stream only while ctx.remoteAccess allows sessionStatus/follow, so a LiveShare viewer opens no owner-only stream, keeps readingReady false, and logs no synchronization failure; access changes start or stop the stream. - Hide the unacknowledged completion of the Session the visible, focused main view retains; manual marks stay visible, completionFailed follows completionUnread, and the reminder returns on blur, hiding, or a switch. - Declare ctx.sessionStatus on Context and restore its SERVICE_PAGE and SERVICE_ROLES entries; the service and SessionRead* types document on docs/subsystems/web-client.md, which now owns the reading section with the failed field. - Document that a Host plugin reload can leave the Client with a terminal error until a page reload; drop the redundant types import and the unused publish() result. - Archived Sessions read as read and offer no reading mark in the row menu or the toggle-read shortcut. - session.toggleRead names the open dialog, open panel, or archived Session that blocks it instead of asking to select a Session. - isRemoteStreamCarrierFailure rejects a RemoteError from the Host even when it carries gateway/carrier-lost; the code is Client-local. - ./types is types-only like ui-trajectory, and files no longer ship lib/types JavaScript. * 🐛 fix(session): close the remaining Session status review gaps - The Gateway Client exports isRemoteStreamCarrierFailure, and the terminal view uses it, so a Host RemoteError carrying the carrier code shows as failed rather than disconnected. - Each access grant's reading stream carries a token: frames a revoked or superseded stream still delivers are discarded, and cleanup waits for disposal before leaving reading unavailable unless a newer grant is active. - The status table hides the viewed Session's natural reminder only while that Session is open; the panel case is a documented limitation. - The README limitation and the upgrade guide state that only the main-view switch rule, including a reload restore, clears manual unread automatically. - Add the missing blank line before the next heading in the web-client reading section. * ♻️ refactor(session): install reading under the Session status table - apply returns to master's form plus one line: UiSessionStatus is the root, published as the useSessionStatus source, and installReading() from the new src/client/read.ts follows Host reading records into it. UiSessionStatus takes master's three constructor parameters and creates its own SessionReadModel as the package-internal `reading` member; installSessionStatus is removed and acknowledge.ts stays a separate file. - The viewed Session's snapshot subscription republishes the table only when its openState changes, so streamed events do not rebuild it. - Remove the obsolete Dev Note sentence about failure outcomes. - session.toggleRead passes when the Peer may not mark reading, matching the row menu, and reports readingUnavailable only while unsynchronized. --------- Co-authored-by: imccyu <[email protected]> Co-authored-by: imccyu <[email protected]>
537 lines
20 KiB
TypeScript
537 lines
20 KiB
TypeScript
/** Client owner for the Gateway multiplexed Remote stream socket. */
|
|
import { RemoteError, remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol'
|
|
import type { ConnectionWebSocket } from '@deepseek-ai/dsh-client-connection/client'
|
|
|
|
import {
|
|
parseRemoteStreamServerMessage,
|
|
REMOTE_STREAM_MUX_PATH,
|
|
type RemoteStreamClientMessage,
|
|
type RemoteStreamServerMessage,
|
|
} from '../stream-protocol.ts'
|
|
import { Deque } from '@deepseek-ai/dsh-deque'
|
|
import { randomUUID } from '@deepseek-ai/dsh-util-crypto'
|
|
|
|
/**
|
|
* Retryable physical Remote stream carrier failure. {@link RemoteStream} reconnects on any error whose `code` is
|
|
* `gateway/carrier-lost`, so a domain `ended` callback may return a plain `Error` carrying that code. The code is
|
|
* produced only inside this Client process; a `RemoteError` returned by the Host never counts as a carrier loss.
|
|
*/
|
|
export interface RemoteStreamCarrierFailure extends Error {
|
|
/** Stable carrier-loss code; class identity is not part of the retry decision. */
|
|
readonly code: 'gateway/carrier-lost'
|
|
}
|
|
|
|
const REMOTE_STREAM_CARRIER_CODE: RemoteStreamCarrierFailure['code'] = 'gateway/carrier-lost'
|
|
|
|
/** Physical Remote stream socket failure that may be retried by a domain transport. */
|
|
export class RemoteStreamCarrierError extends Error implements RemoteStreamCarrierFailure {
|
|
readonly code: RemoteStreamCarrierFailure['code'] = REMOTE_STREAM_CARRIER_CODE
|
|
|
|
/**
|
|
* @param message - physical carrier failure description.
|
|
* @param options - optional causal error.
|
|
*/
|
|
constructor(message: string, options?: ErrorOptions) {
|
|
super(message, options)
|
|
this.name = 'RemoteStreamCarrierError'
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Whether a failure is a retryable carrier loss, judged by its `code` rather than its class. {@link RemoteStream} uses
|
|
* this test, and domains that classify their own failures, such as a disconnected view, reuse it.
|
|
* @param error - thrown or returned failure.
|
|
* @returns true for a locally produced `Error` whose `code` is `gateway/carrier-lost`; false for any `RemoteError`,
|
|
* which reached this Client from the Host and terminates the stream even when it carries that code.
|
|
*/
|
|
export function isRemoteStreamCarrierFailure(error: unknown): error is RemoteStreamCarrierFailure {
|
|
return error instanceof Error && remoteErrorOf(error) === undefined
|
|
&& 'code' in error && error.code === REMOTE_STREAM_CARRIER_CODE
|
|
}
|
|
|
|
interface SocketWaiter {
|
|
readonly revision: number
|
|
resolve(socket: ConnectionWebSocket): void
|
|
reject(error: unknown): void
|
|
}
|
|
|
|
interface UplinkPump {
|
|
/** Settles once the pump has stopped sending. */
|
|
readonly done: Promise<void>
|
|
/** Interrupt the pump, including a read blocked on the caller's iterator, and release the iterator. */
|
|
stop(): void
|
|
}
|
|
|
|
/** One open logical stream: its downlink frames and, once the `open` frame is out, its uplink pump. */
|
|
interface LogicalStream {
|
|
readonly inbox: StreamInbox
|
|
pump: UplinkPump | undefined
|
|
}
|
|
|
|
const UPLINK_DONE: IteratorReturnResult<undefined> = { value: undefined, done: true }
|
|
|
|
/**
|
|
* Keep one physical WebSocket and share it among independently cancellable
|
|
* Remote streams. A carrier that supplies an in-process stream opener never
|
|
* starts one.
|
|
*/
|
|
export class RemoteStreamMuxClient {
|
|
private socket: ConnectionWebSocket | undefined
|
|
private cancelCandidate: ((error: Error) => void) | undefined
|
|
private keepAlive: Promise<void> | undefined
|
|
private revision = 0
|
|
private readonly streams = new Map<string, LogicalStream>()
|
|
private readonly waiters = new Set<SocketWaiter>()
|
|
private readonly socketClosures = new Set<Promise<void>>()
|
|
private running = false
|
|
private disposed = false
|
|
private failure: RemoteStreamCarrierFailure | undefined
|
|
|
|
/**
|
|
* @param openSocket - selected authenticated carrier; omission uses the browser socket.
|
|
* @param waitForReconnect - answering Clients wait for Connection to replace a lost socket; passive Clients fail later opens immediately.
|
|
*/
|
|
constructor(
|
|
private readonly openSocket: (path: string) => ConnectionWebSocket = () => new WebSocket(remoteStreamUrl()),
|
|
private readonly waitForReconnect = false,
|
|
) {}
|
|
|
|
/** Ensure a physical attempt exists, following the current attempt once if needed. */
|
|
start(): void {
|
|
if (this.disposed) return
|
|
this.running = true
|
|
if (this.socket?.readyState === 1) return
|
|
const pending = this.keepAlive
|
|
if (pending === undefined) this.maintain()
|
|
else void pending.then(() => { this.maintain() })
|
|
}
|
|
|
|
/** Cancel the current socket or retry wait and start a fresh attempt immediately. */
|
|
reconnect(): void {
|
|
if (!this.running || this.disposed) return
|
|
const failure = new RemoteStreamCarrierError('api gateway: Remote stream reconnect requested')
|
|
const pending = this.keepAlive
|
|
this.revision++
|
|
this.failure = undefined
|
|
this.cancelCandidate?.(failure)
|
|
const socket = this.socket
|
|
if (socket !== undefined) {
|
|
this.socket = undefined
|
|
this.failAll(failure)
|
|
socket.close(4000, 'reconnect requested')
|
|
}
|
|
if (pending === undefined) this.maintain()
|
|
else void pending.then(() => { this.maintain() })
|
|
}
|
|
|
|
/**
|
|
* Open one logical stream on the persistent physical connection.
|
|
* After an established socket is lost, answering Clients wait for Connection
|
|
* to reconnect or for their signal to abort; passive Clients reject immediately.
|
|
* An initial socket failure rejects both modes.
|
|
* @param endpoint - Typert Remote stream endpoint.
|
|
* @param payload - endpoint request encoded on the wire.
|
|
* @param signal - cancellation for this logical stream.
|
|
* @param uplink - the Client's items: each is sent as an `item` frame, its end as `end`; its `return()`
|
|
* runs when the stream finishes, and its failure cancels the stream and fails the downlink.
|
|
* @returns Host items until completion, cancellation, or failure.
|
|
*/
|
|
async *open(
|
|
endpoint: string,
|
|
payload: unknown,
|
|
signal: AbortSignal,
|
|
uplink?: AsyncIterable<unknown>,
|
|
): AsyncGenerator {
|
|
signal.throwIfAborted()
|
|
const streamId = randomUUID()
|
|
const inbox = new StreamInbox()
|
|
const stream: LogicalStream = { inbox, pump: undefined }
|
|
let carrier: ConnectionWebSocket | undefined
|
|
let opened = false
|
|
let terminal = false
|
|
const abort = (): void => { inbox.fail(signal.reason) }
|
|
signal.addEventListener('abort', abort, { once: true })
|
|
try {
|
|
const socket = await this.waitForSocket(signal)
|
|
signal.throwIfAborted()
|
|
carrier = socket
|
|
this.streams.set(streamId, stream)
|
|
this.send(socket, { type: 'open', streamId, endpoint, payload })
|
|
opened = true
|
|
if (uplink !== undefined) stream.pump = this.pumpUplink(socket, streamId, uplink, signal, inbox)
|
|
while (true) {
|
|
const frame = await inbox.next()
|
|
signal.throwIfAborted()
|
|
if (frame.type === 'item') {
|
|
yield frame.value
|
|
continue
|
|
}
|
|
terminal = true
|
|
if (frame.type === 'error') {
|
|
throw new RemoteError(frame.error.code as never, frame.error.message, frame.error.details as never)
|
|
}
|
|
return
|
|
}
|
|
} finally {
|
|
signal.removeEventListener('abort', abort)
|
|
this.streams.delete(streamId)
|
|
stream.pump?.stop()
|
|
if (opened && !terminal && carrier?.readyState === 1) {
|
|
this.send(carrier, { type: 'cancel', streamId })
|
|
}
|
|
// The old generation's pump has stopped before a supervisor reopens the next one.
|
|
if (stream.pump !== undefined) await stream.pump.done
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Send the caller's uplink items on this generation's socket. `stop()`
|
|
* interrupts a pump blocked on `uplink.next()` and releases the iterator: a
|
|
* handle's queue closes at once, so `send()` throws from then on, and any
|
|
* other iterator's `return()` is invoked without being awaited because a
|
|
* generator blocked in `next()` only completes it once it yields.
|
|
*/
|
|
private pumpUplink(
|
|
socket: ConnectionWebSocket,
|
|
streamId: string,
|
|
uplink: AsyncIterable<unknown>,
|
|
signal: AbortSignal,
|
|
inbox: StreamInbox,
|
|
): UplinkPump {
|
|
let stopped: PromiseWithResolvers<IteratorReturnResult<undefined>> | undefined
|
|
const interruption: IteratorReturnResult<undefined> = { value: undefined, done: true }
|
|
const uplinkIterator = uplink[Symbol.asyncIterator]()
|
|
const state = { stopping: false, exhausted: false, released: false }
|
|
const release = (): void => {
|
|
if (state.released || state.exhausted) return
|
|
state.released = true
|
|
if (uplink instanceof ClientUplinkQueue) uplink.close()
|
|
void Promise.resolve().then(() => uplinkIterator.return?.()).catch(() => undefined)
|
|
}
|
|
const done = (async (): Promise<void> => {
|
|
try {
|
|
while (true) {
|
|
const stoppingBeforeRead = state.stopping
|
|
if (stoppingBeforeRead) return
|
|
// A stop promise belongs to one read, not the whole uplink history.
|
|
stopped = Promise.withResolvers<IteratorReturnResult<undefined>>()
|
|
const next = await Promise.race([uplinkIterator.next(), stopped.promise])
|
|
stopped = undefined
|
|
if (state.stopping || next === interruption || signal.aborted || this.socket !== socket) return
|
|
if (next.done === true) {
|
|
state.exhausted = true
|
|
break
|
|
}
|
|
this.send(socket, { type: 'item', streamId, value: next.value })
|
|
}
|
|
this.send(socket, { type: 'end', streamId })
|
|
} catch (error) {
|
|
inbox.fail(error)
|
|
} finally {
|
|
stopped = undefined
|
|
release()
|
|
}
|
|
})()
|
|
return {
|
|
done,
|
|
stop: () => {
|
|
if (state.stopping) return
|
|
state.stopping = true
|
|
stopped?.resolve(interruption)
|
|
release()
|
|
},
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Permanently stop the carrier, close the physical socket, and fail every
|
|
* active logical stream.
|
|
* @returns once the connection attempt and every physical socket have closed.
|
|
*/
|
|
async close(): Promise<void> {
|
|
if (!this.disposed) {
|
|
this.disposed = true
|
|
this.running = false
|
|
const error = new Error('api gateway: Remote stream client disposed')
|
|
this.failAll(error)
|
|
for (const waiter of [...this.waiters]) waiter.reject(error)
|
|
this.cancelCandidate?.(error)
|
|
const socket = this.socket
|
|
this.socket = undefined
|
|
socket?.close(1000, 'disposed')
|
|
}
|
|
await this.keepAlive
|
|
await Promise.all(this.socketClosures)
|
|
}
|
|
|
|
private async connect(): Promise<ConnectionWebSocket> {
|
|
const socket = this.openSocket(REMOTE_STREAM_MUX_PATH)
|
|
const closed = new Promise<void>((resolve) => { socket.addEventListener('close', () => { resolve() }, { once: true }) })
|
|
this.socketClosures.add(closed)
|
|
void closed.then(() => { this.socketClosures.delete(closed) })
|
|
const connecting = new Promise<ConnectionWebSocket>((resolve, reject) => {
|
|
let settled = false
|
|
const rejectCandidate = (error: Error): void => {
|
|
settled = true
|
|
socket.removeEventListener('open', opened)
|
|
socket.removeEventListener('message', received)
|
|
this.cancelCandidate = undefined
|
|
// Node ws emits error when a connecting socket is closed. Keep its
|
|
// error listener until close even after rejecting the attempt.
|
|
if (socket.readyState < 2) socket.close()
|
|
reject(error)
|
|
}
|
|
const opened = (): void => {
|
|
settled = true
|
|
this.cancelCandidate = undefined
|
|
this.socket = socket
|
|
for (const waiter of [...this.waiters]) waiter.resolve(socket)
|
|
resolve(socket)
|
|
}
|
|
const failed = (): void => {
|
|
if (!settled) {
|
|
rejectCandidate(new RemoteStreamCarrierError(
|
|
'api gateway: Remote stream WebSocket failed to open',
|
|
))
|
|
return
|
|
}
|
|
const error = new RemoteStreamCarrierError('api gateway: Remote stream WebSocket failed')
|
|
this.lost(socket, error)
|
|
if (socket.readyState < 2) socket.close()
|
|
}
|
|
const closed = (): void => {
|
|
socket.removeEventListener('open', opened)
|
|
socket.removeEventListener('error', failed)
|
|
socket.removeEventListener('message', received)
|
|
if (!settled) {
|
|
rejectCandidate(new RemoteStreamCarrierError(
|
|
'api gateway: Remote stream WebSocket closed before opening',
|
|
))
|
|
return
|
|
}
|
|
this.lost(socket)
|
|
}
|
|
const received = (event: { readonly data: unknown }): void => { this.receive(socket, event.data) }
|
|
this.cancelCandidate = rejectCandidate
|
|
socket.addEventListener('open', opened, { once: true })
|
|
socket.addEventListener('error', failed)
|
|
socket.addEventListener('message', received)
|
|
socket.addEventListener('close', closed, { once: true })
|
|
})
|
|
return connecting
|
|
}
|
|
|
|
private waitForSocket(signal: AbortSignal): Promise<ConnectionWebSocket> {
|
|
signal.throwIfAborted()
|
|
if (this.socket?.readyState === 1) return Promise.resolve(this.socket)
|
|
if (this.disposed) return Promise.reject(new Error('api gateway: Remote stream client disposed'))
|
|
if (!this.running) return Promise.reject(new Error('api gateway: Remote stream client not started'))
|
|
if (this.failure !== undefined) return Promise.reject(this.failure)
|
|
return new Promise((resolve, reject) => {
|
|
const aborted = (): void => { waiter.reject(signal.reason) }
|
|
const cleanup = (): void => {
|
|
this.waiters.delete(waiter)
|
|
signal.removeEventListener('abort', aborted)
|
|
}
|
|
const waiter: SocketWaiter = {
|
|
revision: this.revision,
|
|
resolve: (socket) => {
|
|
cleanup()
|
|
resolve(socket)
|
|
},
|
|
reject: (error) => {
|
|
cleanup()
|
|
// AbortSignal.reason belongs to the caller and may intentionally be a non-Error sentinel.
|
|
// oxlint-disable-next-line typescript/prefer-promise-reject-errors
|
|
reject(error)
|
|
},
|
|
}
|
|
this.waiters.add(waiter)
|
|
signal.addEventListener('abort', aborted, { once: true })
|
|
})
|
|
}
|
|
|
|
private receive(socket: ConnectionWebSocket, data: unknown): void {
|
|
if (socket !== this.socket) return
|
|
try {
|
|
if (typeof data !== 'string') throw new Error('api gateway: Remote stream WebSocket requires text messages')
|
|
const frame = parseRemoteStreamServerMessage(data)
|
|
const stream = this.streams.get(frame.streamId)
|
|
if (stream === undefined) return
|
|
stream.inbox.push(frame)
|
|
// A terminal frame ends the uplink now, not on the consumer's next read.
|
|
if (frame.type !== 'item') stream.pump?.stop()
|
|
} catch (error) {
|
|
const failure = new RemoteStreamCarrierError('api gateway: invalid Remote stream frame', { cause: error })
|
|
this.failAll(failure)
|
|
this.lost(socket, failure)
|
|
socket.close(4002, 'invalid Remote stream frame')
|
|
}
|
|
}
|
|
|
|
private lost(
|
|
socket: ConnectionWebSocket,
|
|
error: RemoteStreamCarrierError = new RemoteStreamCarrierError(
|
|
'api gateway: Remote stream WebSocket closed',
|
|
),
|
|
): void {
|
|
if (this.socket !== socket) return
|
|
this.socket = undefined
|
|
if (!this.waitForReconnect) this.failure = error
|
|
this.failAll(error)
|
|
if (!this.waitForReconnect) {
|
|
for (const waiter of [...this.waiters]) waiter.reject(error)
|
|
}
|
|
}
|
|
|
|
private maintain(): void {
|
|
if (!this.running || this.disposed) return
|
|
if (this.socket?.readyState === 1 || this.keepAlive !== undefined) return
|
|
const revision = this.revision
|
|
this.failure = undefined
|
|
const task = this.connect().then(
|
|
() => undefined,
|
|
(error: unknown) => {
|
|
if (!this.running) return
|
|
const failure = isRemoteStreamCarrierFailure(error) ? error
|
|
: new RemoteStreamCarrierError('api gateway: Remote stream WebSocket failed to open', { cause: error })
|
|
if (this.revision === revision) this.failure = failure
|
|
for (const waiter of [...this.waiters]) {
|
|
if (waiter.revision <= revision) waiter.reject(failure)
|
|
}
|
|
},
|
|
)
|
|
this.keepAlive = task
|
|
void task.then(() => {
|
|
this.keepAlive = undefined
|
|
})
|
|
}
|
|
|
|
private failAll(error: unknown): void {
|
|
for (const stream of this.streams.values()) {
|
|
stream.inbox.fail(error)
|
|
stream.pump?.stop()
|
|
}
|
|
}
|
|
|
|
private send(socket: ConnectionWebSocket, message: RemoteStreamClientMessage): void {
|
|
socket.send(JSON.stringify(message))
|
|
}
|
|
}
|
|
|
|
class StreamInbox {
|
|
private readonly frames = new Deque<RemoteStreamServerMessage>()
|
|
private wake: (() => void) | undefined
|
|
private failure: Error | undefined
|
|
|
|
push(frame: RemoteStreamServerMessage): void {
|
|
if (this.failure !== undefined) return
|
|
this.frames.pushBack(frame)
|
|
this.wake?.()
|
|
this.wake = undefined
|
|
}
|
|
|
|
fail(error: unknown): void {
|
|
if (this.failure !== undefined) return
|
|
this.failure = error instanceof Error ? error : new Error(String(error), { cause: error })
|
|
this.frames.clear()
|
|
this.wake?.()
|
|
this.wake = undefined
|
|
}
|
|
|
|
async next(): Promise<RemoteStreamServerMessage> {
|
|
while (this.frames.size === 0) {
|
|
if (this.failure !== undefined) throw this.failure
|
|
await new Promise<void>((resolve) => { this.wake = resolve })
|
|
}
|
|
return this.frames.popFront() as RemoteStreamServerMessage
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Uplink items a stream handle queues for its carrier: the mux pump or the
|
|
* in-process Host decoder iterates it as the stream's uplink. `end()` is the
|
|
* Client half-close; `close()` marks the stream terminated, after which
|
|
* `push()` throws. One consumer reads it, one read at a time.
|
|
*/
|
|
export class ClientUplinkQueue implements AsyncIterable<unknown>, AsyncIterator<unknown> {
|
|
private readonly items = new Deque<unknown>()
|
|
private ended = false
|
|
private closed = false
|
|
private wake: (() => void) | undefined
|
|
|
|
/** @param endpoint - canonical Remote endpoint named by failures. */
|
|
constructor(private readonly endpoint: string) {}
|
|
|
|
/**
|
|
* Queue one item for the carrier.
|
|
* @param item - item the Host validates against the method's uplink codec.
|
|
* @throws {Error} after `end()` or once the stream has terminated.
|
|
*/
|
|
push(item: unknown): void {
|
|
if (this.closed) throw new Error(`client api: ${this.endpoint} stream has terminated`)
|
|
if (this.ended) throw new Error(`client api: ${this.endpoint} uplink was ended`)
|
|
this.items.pushBack(item)
|
|
this.signal()
|
|
}
|
|
|
|
/** Half-close: the carrier reads the queued items, then `end`. Idempotent; ignored after termination. */
|
|
end(): void {
|
|
if (this.ended || this.closed) return
|
|
this.ended = true
|
|
this.signal()
|
|
}
|
|
|
|
/** The carrier stopped reading: the logical stream terminated or was disposed. Idempotent. */
|
|
close(): void {
|
|
if (this.closed) return
|
|
this.closed = true
|
|
this.items.clear()
|
|
this.signal()
|
|
}
|
|
|
|
[Symbol.asyncIterator](): AsyncIterator<unknown> {
|
|
return this
|
|
}
|
|
|
|
/**
|
|
* Take the next queued item, waiting for one; ends after `end()` or `close()`.
|
|
* @returns the next item, or the end of the uplink.
|
|
* @throws {Error} when a read is already pending.
|
|
*/
|
|
async next(): Promise<IteratorResult<unknown>> {
|
|
while (true) {
|
|
if (this.closed) return UPLINK_DONE
|
|
if (this.items.size > 0) return { value: this.items.popFront(), done: false }
|
|
if (this.ended) return UPLINK_DONE
|
|
if (this.wake !== undefined) throw new Error(`client api: ${this.endpoint} uplink has one pending read`)
|
|
await new Promise<void>((resolve) => { this.wake = resolve })
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The carrier is done with the uplink: close it.
|
|
* @returns the end of the uplink.
|
|
*/
|
|
return(): Promise<IteratorResult<unknown>> {
|
|
this.close()
|
|
return Promise.resolve(UPLINK_DONE)
|
|
}
|
|
|
|
private signal(): void {
|
|
const wake = this.wake
|
|
this.wake = undefined
|
|
wake?.()
|
|
}
|
|
}
|
|
|
|
function remoteStreamUrl(): string {
|
|
// The mux route is registered absolute; a page resolves its document-relative
|
|
// form against its own document base. A shell-owned Host on another origin
|
|
// supplies that base through the transport.
|
|
const globals = globalThis as { __DSH_TRANSPORT__?: { streamBaseUrl?: string } }
|
|
const url = new URL(REMOTE_STREAM_MUX_PATH.slice(1), globals.__DSH_TRANSPORT__?.streamBaseUrl ?? document.baseURI)
|
|
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
|
|
return url.href
|
|
}
|