- realtime.ts: the page's one Centrifuge client, setRealtimeAuth, onUserEvent for user:{me} events the chat does not handle
- chatEvents, chatFormat, chatText, chatUnread, format, media, tabs ported; copy passed in localized
- useChat over useState: channels with join and leave, DMs, member list, unread and mention counts, read marks, typing, presence, polling fallback
- ChatPanel, ChatHeader, ChatMessage, ChatDmList, ChatMemberPicker, ChatMentionPopup, ChatAvatar, ChatIcon, ChatNotices
- EN and PL strings
418 lines
14 KiB
TypeScript
418 lines
14 KiB
TypeScript
// The page's one Centrifuge client, ported from a Golem15 SPA's
|
|
// lib/realtime.ts. Chat, its satellite layers and any other page code
|
|
// (a presentations speaker view and phone remote, for example) subscribe
|
|
// through it, so a page never holds a second socket.
|
|
//
|
|
// Nuxt-free: the app (or the chat store, from $chatAuth) hands it the
|
|
// user's token through setRealtimeAuth. The connection token comes from
|
|
// GET /api/realtime/token with that bearer; one 401 renews the user's token
|
|
// through the refresh callback and retries.
|
|
import type { Centrifuge, Subscription } from 'centrifuge'
|
|
|
|
/** REALTIME_WS_PATH matches realtime.centrifugo.ws_url and the nginx `location = /ws` block. */
|
|
export const REALTIME_WS_PATH = '/ws'
|
|
|
|
/** TOKEN_PATH is the lighthouse connection-token route; the host decides who gets a token. */
|
|
export const TOKEN_PATH = '/api/realtime/token'
|
|
|
|
/**
|
|
* Token answers that mean "realtime is not for this session"; the client
|
|
* stops retrying. 503 is not one of them: the access guard answers 503 for a
|
|
* database hiccup too, and a token refresh (about hourly) that hit one would
|
|
* otherwise end the remote for the rest of the talk. A 503 is rethrown as an
|
|
* ordinary error, so the client retries with backoff.
|
|
*/
|
|
const UNAVAILABLE = new Set([401, 403, 404])
|
|
|
|
/** tokenFailureIsFinal reports whether a token-route status stops the client for good. */
|
|
export function tokenFailureIsFinal(status: number): boolean {
|
|
return UNAVAILABLE.has(status)
|
|
}
|
|
|
|
export type ConnectionState = 'connecting' | 'connected' | 'disconnected'
|
|
|
|
export interface ChannelHooks {
|
|
onPublication(data: unknown): void
|
|
onSubscribed?(): void
|
|
onConnection?(state: ConnectionState): void
|
|
onDenied?(code: number): void
|
|
onUnavailable?(): void
|
|
}
|
|
|
|
export interface ChannelHandle {
|
|
close(): void
|
|
resubscribe(): void
|
|
}
|
|
|
|
/** A token-route refusal: the HTTP status, 0 without a connection. */
|
|
export class RealtimeTokenError extends Error {
|
|
status: number
|
|
constructor(status: number, message: string) {
|
|
super(message)
|
|
this.name = 'RealtimeTokenError'
|
|
this.status = status
|
|
}
|
|
}
|
|
|
|
type TokenGetter = () => string | null | undefined
|
|
type TokenRefresher = () => Promise<string | null | undefined>
|
|
|
|
let authToken: TokenGetter | null = null
|
|
let authRefresh: TokenRefresher | null = null
|
|
|
|
/**
|
|
* setRealtimeAuth gives the client the user's token getter (the frontend
|
|
* JWT sent as the bearer of the token route) and, optionally, its renewal.
|
|
* The latest call wins.
|
|
*/
|
|
export function setRealtimeAuth(getToken: TokenGetter, refresh?: TokenRefresher) {
|
|
authToken = getToken
|
|
authRefresh = refresh ?? null
|
|
}
|
|
|
|
/** hasRealtimeAuth reports whether setRealtimeAuth ran. */
|
|
export function hasRealtimeAuth(): boolean {
|
|
return authToken !== null
|
|
}
|
|
|
|
function bearer(): string | null {
|
|
try {
|
|
return authToken?.() || null
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
async function tokenRequest(user: string | null): Promise<Response> {
|
|
const headers: Record<string, string> = { Accept: 'application/json' }
|
|
if (user) headers.Authorization = `Bearer ${user}`
|
|
try {
|
|
return await fetch(TOKEN_PATH, { method: 'GET', headers })
|
|
} catch {
|
|
throw new RealtimeTokenError(0, 'realtime: no connection')
|
|
}
|
|
}
|
|
|
|
/**
|
|
* fetchConnectionToken asks the token route for a Centrifugo connection
|
|
* token. A 401 with a user token renews it once through the refresh
|
|
* callback and retries. Refusals throw RealtimeTokenError with the status.
|
|
*/
|
|
export async function fetchConnectionToken(): Promise<string> {
|
|
const used = bearer()
|
|
let res = await tokenRequest(used)
|
|
if (res.status === 401 && used && authRefresh) {
|
|
let next: string | null = null
|
|
try {
|
|
next = (await authRefresh()) || null
|
|
} catch {
|
|
next = null
|
|
}
|
|
if (next) res = await tokenRequest(next)
|
|
}
|
|
if (!res.ok) throw new RealtimeTokenError(res.status, `realtime: token route answered ${res.status}`)
|
|
let got: unknown = null
|
|
try {
|
|
got = await res.json()
|
|
} catch {
|
|
got = null
|
|
}
|
|
const body = (got && typeof got === 'object' && 'data' in got ? (got as { data: unknown }).data : got) as { token?: unknown } | null
|
|
if (!body || typeof body.token !== 'string' || body.token === '') throw new Error('realtime: empty token')
|
|
return body.token
|
|
}
|
|
|
|
type UserEventHandler = (data: unknown) => void
|
|
const userEventHandlers = new Set<UserEventHandler>()
|
|
|
|
/**
|
|
* onUserEvent hears the publications on the user's own channel (user:{me})
|
|
* that the chat does not handle itself (for example video:* events of a
|
|
* call layer). The chat holds the one user:{me} subscription; a second
|
|
* layer must not subscribe to it. Returns the unlisten function.
|
|
*/
|
|
export function onUserEvent(handler: UserEventHandler): () => void {
|
|
userEventHandlers.add(handler)
|
|
return () => void userEventHandlers.delete(handler)
|
|
}
|
|
|
|
/** dispatchUserEvent hands one user:{me} publication to every onUserEvent handler. */
|
|
export function dispatchUserEvent(data: unknown) {
|
|
for (const h of [...userEventHandlers]) {
|
|
try {
|
|
h(data)
|
|
} catch (err) {
|
|
console.error('vue-chat-layer: a user event handler failed', err)
|
|
}
|
|
}
|
|
}
|
|
|
|
/** One subscribed connection in a channel's presence; user is the token subject. */
|
|
export interface PresenceClient {
|
|
client: string
|
|
user: number
|
|
}
|
|
|
|
/** Hooks of one subscribe() handle; every handle on a channel hears every event. */
|
|
export interface SubscribeHooks {
|
|
onPublication?(data: unknown): void
|
|
onSubscribed?(): void
|
|
onDenied?(code: number): void
|
|
onJoin?(who: PresenceClient): void
|
|
onLeave?(who: PresenceClient): void
|
|
}
|
|
|
|
/** wsURL is the WebSocket endpoint on the page's own host. */
|
|
export function wsURL(loc: Pick<Location, 'protocol' | 'host'> = window.location): string {
|
|
return `${loc.protocol === 'https:' ? 'wss' : 'ws'}://${loc.host}${REALTIME_WS_PATH}`
|
|
}
|
|
|
|
function connectionState(value: unknown): ConnectionState {
|
|
const s = String(value)
|
|
if (s === 'connected' || s === 'connecting') return s
|
|
return 'disconnected'
|
|
}
|
|
|
|
function presenceClient(info: { client?: unknown; user?: unknown } | null | undefined): PresenceClient | null {
|
|
if (!info || typeof info.client !== 'string') return null
|
|
const user = Number(info.user)
|
|
if (!Number.isInteger(user) || user <= 0) return null
|
|
return { client: info.client, user }
|
|
}
|
|
|
|
interface Entry {
|
|
sub: Subscription
|
|
hooks: Set<SubscribeHooks>
|
|
}
|
|
|
|
// The page's one client. Chat, the speaker view and the phone remote all
|
|
// subscribe through it, so the app never holds a second socket.
|
|
let centrifuge: Centrifuge | null = null
|
|
let connecting: Promise<Centrifuge> | null = null
|
|
let state: ConnectionState = 'disconnected'
|
|
let unavailable = false
|
|
/** Bumped by disconnect(): a client still loading for an older session is dropped. */
|
|
let epoch = 0
|
|
const entries = new Map<string, Entry>()
|
|
const connectionListeners = new Set<(s: ConnectionState) => void>()
|
|
const unavailableListeners = new Set<() => void>()
|
|
|
|
function setState(next: ConnectionState) {
|
|
state = next
|
|
for (const l of [...connectionListeners]) l(next)
|
|
}
|
|
|
|
function markUnavailable() {
|
|
unavailable = true
|
|
for (const l of [...unavailableListeners]) l()
|
|
}
|
|
|
|
/** realtimeState is the shared client's connection state. */
|
|
export function realtimeState(): ConnectionState {
|
|
return state
|
|
}
|
|
|
|
/** realtimeUnavailable reports a final token refusal for this session. */
|
|
export function realtimeUnavailable(): boolean {
|
|
return unavailable
|
|
}
|
|
|
|
/** onConnection listens to the shared client's state; returns the unlisten function. */
|
|
export function onConnection(listener: (s: ConnectionState) => void): () => void {
|
|
connectionListeners.add(listener)
|
|
return () => void connectionListeners.delete(listener)
|
|
}
|
|
|
|
/**
|
|
* onUnavailable listens for a final token refusal (401, 403, 404). A listener
|
|
* added after the refusal hears it at once, on a microtask.
|
|
*/
|
|
export function onUnavailable(listener: () => void): () => void {
|
|
unavailableListeners.add(listener)
|
|
if (unavailable) queueMicrotask(() => unavailableListeners.has(listener) && listener())
|
|
return () => void unavailableListeners.delete(listener)
|
|
}
|
|
|
|
/**
|
|
* connect returns the shared client, creating it on first use. The client
|
|
* package is loaded here, on demand, so no page that never subscribes pulls
|
|
* it in. The connection token is fetched (and refreshed) from the token
|
|
* route, never passed in statically.
|
|
*/
|
|
export function connect(): Promise<Centrifuge> {
|
|
if (centrifuge) {
|
|
if (state === 'disconnected' && !unavailable) centrifuge.connect()
|
|
return Promise.resolve(centrifuge)
|
|
}
|
|
if (connecting) return connecting
|
|
const mine = epoch
|
|
connecting = (async () => {
|
|
try {
|
|
const { Centrifuge, UnauthorizedError } = await import('centrifuge')
|
|
if (mine !== epoch) throw new Error('realtime: disconnected while loading')
|
|
const c = new Centrifuge(wsURL(), {
|
|
minReconnectDelay: 500,
|
|
maxReconnectDelay: 10000,
|
|
getToken: async () => {
|
|
try {
|
|
return await fetchConnectionToken()
|
|
} catch (err) {
|
|
if (err instanceof RealtimeTokenError && tokenFailureIsFinal(err.status)) {
|
|
markUnavailable()
|
|
throw new UnauthorizedError('realtime unavailable')
|
|
}
|
|
throw err
|
|
}
|
|
},
|
|
})
|
|
c.on('state', (ctx) => {
|
|
if (centrifuge === c) setState(connectionState(ctx.newState))
|
|
})
|
|
centrifuge = c
|
|
c.connect()
|
|
return c
|
|
} finally {
|
|
if (mine === epoch) connecting = null
|
|
}
|
|
})()
|
|
return connecting
|
|
}
|
|
|
|
function each(entry: Entry, call: (h: SubscribeHooks) => void) {
|
|
for (const h of [...entry.hooks]) call(h)
|
|
}
|
|
|
|
function attach(c: Centrifuge, channel: string, hooks: SubscribeHooks): Entry {
|
|
let entry = entries.get(channel)
|
|
if (!entry) {
|
|
const sub = c.getSubscription(channel) ?? c.newSubscription(channel)
|
|
const e: Entry = { sub, hooks: new Set() }
|
|
sub.on('publication', (ctx) => each(e, (h) => h.onPublication?.(ctx.data)))
|
|
sub.on('subscribed', () => each(e, (h) => h.onSubscribed?.()))
|
|
sub.on('unsubscribed', (ctx) => {
|
|
if (ctx.code >= 400) each(e, (h) => h.onDenied?.(ctx.code))
|
|
})
|
|
sub.on('join', (ctx) => {
|
|
const who = presenceClient(ctx.info)
|
|
if (who) each(e, (h) => h.onJoin?.(who))
|
|
})
|
|
sub.on('leave', (ctx) => {
|
|
const who = presenceClient(ctx.info)
|
|
if (who) each(e, (h) => h.onLeave?.(who))
|
|
})
|
|
entries.set(channel, e)
|
|
sub.subscribe()
|
|
entry = e
|
|
} else if (String(entry.sub.state) === 'subscribed') {
|
|
// A later handle on a live channel still gets its "subscribed" (gap fill, presence).
|
|
queueMicrotask(() => entry?.hooks.has(hooks) && hooks.onSubscribed?.())
|
|
}
|
|
entry.hooks.add(hooks)
|
|
return entry
|
|
}
|
|
|
|
function detach(channel: string, entry: Entry) {
|
|
entry.sub.removeAllListeners()
|
|
entry.sub.unsubscribe()
|
|
centrifuge?.removeSubscription(entry.sub)
|
|
entries.delete(channel)
|
|
}
|
|
|
|
/**
|
|
* subscribe joins a channel on the shared client. Handles on the same channel
|
|
* share one Subscription; the channel is left when its last handle closes,
|
|
* and the socket disconnects when no channel is left.
|
|
*/
|
|
export async function subscribe(channel: string, hooks: SubscribeHooks): Promise<ChannelHandle> {
|
|
const c = await connect()
|
|
const own: SubscribeHooks = { ...hooks }
|
|
const mine = epoch
|
|
attach(c, channel, own)
|
|
let closed = false
|
|
return {
|
|
close() {
|
|
if (closed) return
|
|
closed = true
|
|
const entry = entries.get(channel)
|
|
if (mine !== epoch || !entry || !entry.hooks.delete(own)) return
|
|
if (entry.hooks.size > 0) return
|
|
detach(channel, entry)
|
|
if (entries.size === 0 && centrifuge === c) c.disconnect()
|
|
},
|
|
resubscribe() {
|
|
if (closed || mine !== epoch) return
|
|
entries.get(channel)?.sub.subscribe()
|
|
},
|
|
}
|
|
}
|
|
|
|
/** presence lists the clients subscribed to a channel this page has joined; null when unavailable. */
|
|
export async function presence(channel: string): Promise<PresenceClient[] | null> {
|
|
const entry = entries.get(channel)
|
|
if (!entry) return null
|
|
try {
|
|
const got = await entry.sub.presence()
|
|
return Object.values(got.clients ?? {})
|
|
.map((info) => presenceClient(info))
|
|
.filter((p): p is PresenceClient => p !== null)
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
/**
|
|
* disconnect closes every channel and the socket and forgets the client (on
|
|
* logout): the next session gets a fresh client and a fresh token.
|
|
*/
|
|
export function disconnect() {
|
|
epoch++
|
|
connecting = null
|
|
for (const [channel, entry] of [...entries]) detach(channel, entry)
|
|
const c = centrifuge
|
|
centrifuge = null
|
|
unavailable = false
|
|
if (c) {
|
|
c.disconnect()
|
|
c.removeAllListeners()
|
|
}
|
|
if (state !== 'disconnected') setState('disconnected')
|
|
}
|
|
|
|
/**
|
|
* openChannel subscribes one channel for the presentations speaker view and
|
|
* phone remote, over the shared client. Its hooks also hear the client's
|
|
* connection state (at once when the socket is already up) and a final
|
|
* token refusal.
|
|
*/
|
|
export async function openChannel(channel: string, hooks: ChannelHooks): Promise<ChannelHandle> {
|
|
const offConnection = onConnection((s) => hooks.onConnection?.(s))
|
|
const offUnavailable = onUnavailable(() => hooks.onUnavailable?.())
|
|
let handle: ChannelHandle
|
|
try {
|
|
handle = await subscribe(channel, {
|
|
onPublication: (data) => hooks.onPublication(data),
|
|
onSubscribed: () => hooks.onSubscribed?.(),
|
|
onDenied: (code) => hooks.onDenied?.(code),
|
|
})
|
|
} catch (err) {
|
|
offConnection()
|
|
offUnavailable()
|
|
throw err
|
|
}
|
|
// A socket that was already up for another channel sends no new 'connected'.
|
|
if (state === 'connected') hooks.onConnection?.(state)
|
|
let closed = false
|
|
return {
|
|
close() {
|
|
if (closed) return
|
|
closed = true
|
|
offConnection()
|
|
offUnavailable()
|
|
handle.close()
|
|
},
|
|
resubscribe() {
|
|
if (!closed) handle.resubscribe()
|
|
},
|
|
}
|
|
}
|