Skip to content

Commit

Permalink
simplify errors
Browse files Browse the repository at this point in the history
  • Loading branch information
turbocrime committed Mar 4, 2025
1 parent dc05c10 commit 178b509
Showing 1 changed file with 11 additions and 27 deletions.
38 changes: 11 additions & 27 deletions packages/transport-chrome/src/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export class PortStreamSource implements UnderlyingDefaultSource<JsonValue> {
constructor(incoming: chrome.runtime.Port) {
this.disconnect = () => incoming.disconnect();

this.ac.signal.addEventListener('abort', this.onAbortDisconnect);
this.ac.signal.addEventListener('abort', this.onSignalDisconnect);

incoming.onDisconnect.addListener(() =>
this.ac.abort(ConnectError.from('Source disconnected', Code.Unavailable)),
Expand All @@ -27,15 +27,15 @@ export class PortStreamSource implements UnderlyingDefaultSource<JsonValue> {
? this.push(this.cont, item)
: this.ac.abort(
new ConnectError(
'PortStreamSource message before start',
'Stream item arrived before start',
Code.Unavailable,
undefined,
undefined,
item,
),
);

private onAbortDisconnect = () => {
private onSignalDisconnect = () => {
if (globalThis.__DEV__) {
console.debug('PortStreamSource signal', this.ac.signal.reason);
}
Expand Down Expand Up @@ -73,17 +73,11 @@ export class PortStreamSource implements UnderlyingDefaultSource<JsonValue> {
chunk.abort,
undefined,
// fallback error
ConnectError.from('PortStreamSource failed to deserialize abort reason', Code.Aborted),
ConnectError.from('Failed to deserialize abort reason'),
);
} else {
// should never happen
throw new ConnectError(
'PortStreamSource unexpected item',
Code.Unimplemented,
undefined,
undefined,
chunk,
);
throw new TypeError('Unexpected stream item', { cause: chunk });
}
} catch (e) {
// disconnect and fail with cause
Expand Down Expand Up @@ -113,22 +107,12 @@ export class PortStreamSink implements UnderlyingSink<JsonValue> {
outgoing.onDisconnect.removeListener(this.onDisconnectCancel);
// set up expectation that the counterpart will disconnect
const termination = shouldDisconnect(outgoing);
try {
// post the final message
outgoing.postMessage(item);
await termination;
} catch (cause) {
// in the failure case, we can't expect the counterpart to disconnect.
outgoing.disconnect();

throw new ConnectError(
'PortStreamSink termination failed',
Code.Canceled,
undefined,
undefined,
cause,
);
}
// post the final message
outgoing.postMessage(item);
await termination.finally(
// ensure port disconnected
() => outgoing.disconnect(),
);
};

this.ac.signal.addEventListener('abort', () => {
Expand Down

0 comments on commit 178b509

Please sign in to comment.