Skip to content

Commit

Permalink
Merge pull request #140 from UCLA-IRL/varun/reconnect
Browse files Browse the repository at this point in the history
backend: auto reconnect
  • Loading branch information
pulsejet authored Oct 7, 2024
2 parents 7364eb4 + 2423c69 commit 2dd54b5
Showing 1 changed file with 29 additions and 3 deletions.
32 changes: 29 additions & 3 deletions src/backend/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ export async function disconnect() {
return
}

connection.face?.removeEventListener('down', reconnect)

connState.value = 'DISCONNECTING'
if (connection.config.kind !== 'peerJs') {
await checkPrefixRegistration(true)
Expand Down Expand Up @@ -88,16 +90,40 @@ export async function connect(config: connections.Config) {
connState.value = 'DISCONNECTED'
return
}
connection.face!.addEventListener('down', () => {
disconnect()
})

// Reconnect and initialize when ws breaks, but keep the
// face around. This means the application does not see any change.
connection.face?.addEventListener('down', reconnect)

workspace?.fireUpdate()
connState.value = 'CONNECTED'

toast.success('Connected to forwarder successfully!')
}

async function reconnect() {
toast.promise(
new Promise<void>((resolve, reject) => {
connection?.face?.addEventListener(
'up',
async () => {
resolve()

// The sleep here is needed otherwise prefix registration fails
setTimeout(() => checkPrefixRegistration(false), 500)
},
{ once: true },
)
connection?.face?.addEventListener('close', () => reject(), { once: true })
}),
{
loading: 'Disconnected from forwarding, attempting to reconnect ...',
success: () => 'Reconnected to forwarder!',
error: 'Failed to reconnect to forwarder',
},
)
}

// ============= Bootstrapping =============

export async function bootstrapWorkspace(opts: {
Expand Down

0 comments on commit 2dd54b5

Please sign in to comment.