Skip to content

Commit

Permalink
sketch of a messagePortRef-based disconnect/reconnect for messagechannel
Browse files Browse the repository at this point in the history
  • Loading branch information
pvh committed Jul 25, 2024
1 parent a7038c9 commit e68e8fb
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export interface PortRefEvents {

export interface MessagePortRef extends EventEmitter<PortRefEvents> {
start(): void
stop(): void
postMessage(message: any, transferable?: Transferable[]): void
isAlive(): boolean
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,33 @@ export class StrongMessagePortRef
extends EventEmitter<PortRefEvents>
implements MessagePortRef
{
isDisconnected: boolean = false

constructor(private port: MessagePort) {
port.addEventListener("message", event => {
this.emit("message", event)
if (!this.isDisconnected) {
this.emit("message", event)
}
})

super()
}

postMessage(message: any, transfer: Transferable[]): void {
this.port.postMessage(message, transfer)
if (!this.isDisconnected) {
this.port.postMessage(message, transfer)
}
}

start(): void {
this.isDisconnected = false
this.port.start()
}

stop() {
this.isDisconnected = true
}

isAlive(): boolean {
/* c8 ignore next */
return true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ export class WeakMessagePortRef
this.weakRef = new WeakRef<MessagePort>(port)

port.addEventListener("message", event => {
this.emit("message", event)
if (!this.isDisconnected) {
this.emit("message", event)
}
})
}

Expand All @@ -27,6 +29,10 @@ export class WeakMessagePortRef
return
}

if (this.isDisconnected) {
return
}

try {
port.postMessage(message, transfer)
} catch (err) {
Expand All @@ -42,13 +48,19 @@ export class WeakMessagePortRef
return
}

this.isDisconnected = false

try {
port.start()
} catch (err) {
this.disconnnect()
}
}

stop() {
this.isDisconnected = true
}

private disconnnect() {
if (!this.isDisconnected) {
this.emit("close")
Expand Down
4 changes: 2 additions & 2 deletions packages/automerge-repo-network-messagechannel/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export class MessageChannelNetworkAdapter extends NetworkAdapter {
log("messageport connecting")
this.peerId = peerId
this.peerMetadata = peerMetadata

this.messagePortRef.start()
this.messagePortRef.addListener(
"message",
Expand Down Expand Up @@ -153,8 +154,7 @@ export class MessageChannelNetworkAdapter extends NetworkAdapter {
}

disconnect() {
// TODO
throw new Error("Unimplemented: leave on MessagePortNetworkAdapter")
this.messagePortRef.stop()
}
}

Expand Down

0 comments on commit e68e8fb

Please sign in to comment.