Files

104 lines
2.7 KiB
TypeScript

import type { ConnectionState } from "convex/browser"
/** The part of `ConvexReactClient` connectivity needs. */
export type ConnectionClient = {
connectionState(): ConnectionState
subscribeToConnectionState(cb: (state: ConnectionState) => void): () => void
}
/** A platform reachability signal, such as `navigator.onLine` on web. */
export type PlatformNetwork = {
isOnline(): boolean
subscribe(onChange: () => void): () => void
}
/** Shaped for `useSyncExternalStore`; the snapshot is true while offline. */
export type ConnectivityStore = {
subscribe(onChange: () => void): () => void
getSnapshot(): boolean
}
/** How long the socket may stay down before the app counts as offline. */
const DISCONNECT_GRACE_MS = 5_000
const stores = new WeakMap<ConnectionClient, ConnectivityStore>()
/**
* Returns the shared offline store for a Convex client. The app is offline
* when the platform reports no network, or when the server socket has stayed
* closed past a short grace period (server down, requests timing out). It
* comes back online as soon as the socket reconnects.
*/
export function connectivityStore(
client: ConnectionClient,
network?: PlatformNetwork
): ConnectivityStore {
let store = stores.get(client)
if (!store) {
store = createConnectivityStore(client, network)
stores.set(client, store)
}
return store
}
function createConnectivityStore(
client: ConnectionClient,
network: PlatformNetwork | undefined
): ConnectivityStore {
const listeners = new Set<() => void>()
let offline = false
let graceTimer: ReturnType<typeof setTimeout> | undefined
let stop: (() => void) | undefined
function setOffline(next: boolean) {
if (next === offline) return
offline = next
for (const listener of listeners) listener()
}
function clearGrace() {
clearTimeout(graceTimer)
graceTimer = undefined
}
function update() {
if (network && !network.isOnline()) {
clearGrace()
setOffline(true)
} else if (client.connectionState().isWebSocketConnected) {
clearGrace()
setOffline(false)
} else if (!offline && graceTimer === undefined) {
graceTimer = setTimeout(() => {
graceTimer = undefined
setOffline(true)
}, DISCONNECT_GRACE_MS)
}
}
function start() {
const stopClient = client.subscribeToConnectionState(update)
const stopNetwork = network?.subscribe(update)
update()
return () => {
stopClient()
stopNetwork?.()
clearGrace()
}
}
return {
subscribe(onChange) {
listeners.add(onChange)
stop ??= start()
return () => {
listeners.delete(onChange)
if (listeners.size > 0) return
stop?.()
stop = undefined
}
},
getSnapshot: () => offline,
}
}