SPB Git

Repository Public

push.ts 3.1 KB 95 lines typescript

1// Notifications de changement d'état (RFC 8620 §7.3) par EventSource, avec reconnexion à délai croissant.2import type { StateChange } from "./types"34export type PushStatus = "connecting" | "open" | "retrying" | "closed"56export interface PushOptions {7  url: string8  onChange: (change: StateChange) => void9  onStatus?: (status: PushStatus, attempt: number) => void10  /** appelé après une reconnexion réussie : des changements ont pu être manqués pendant la coupure */11  onReconnect?: () => void12  /** appelé quand plusieurs tentatives échouent : l'appelant vérifie si la session est encore valide */13  onTrouble?: () => void14}1516export const backoffDelay = (attempt: number, rand = Math.random()): number => Math.round(Math.min(30_000, 1000 * 2 ** Math.min(attempt, 5)) * (0.75 + rand * 0.5))1718export class PushConnection {19  private es: EventSource | null = null20  private timer: ReturnType<typeof setTimeout> | undefined21  private attempt = 022  private stopped = false23  private everOpened = false24  private lastEvent = 025  private watchdog: ReturnType<typeof setInterval> | undefined2627  constructor(private opts: PushOptions) {}2829  start() {30    this.stopped = false31    this.open()32    // Le serveur envoie un « ping » toutes les 30 s : sans rien depuis 90 s, la connexion est morte sans l'avoir dit.33    this.watchdog = setInterval(() => {34      if (this.es && this.es.readyState === EventSource.OPEN && Date.now() - this.lastEvent > 90_000) this.retry()35    }, 30_000)36  }3738  stop() {39    this.stopped = true40    clearTimeout(this.timer)41    clearInterval(this.watchdog)42    this.es?.close()43    this.es = null44    this.opts.onStatus?.("closed", 0)45  }4647  /** Reconnexion immédiate (retour du réseau, onglet de nouveau visible). */48  kick() {49    if (this.stopped) return50    if (this.es && this.es.readyState === EventSource.OPEN) return51    clearTimeout(this.timer)52    this.attempt = 053    this.open()54  }5556  private open() {57    this.es?.close()58    this.opts.onStatus?.(this.attempt ? "retrying" : "connecting", this.attempt)59    const es = new EventSource(this.opts.url)60    this.es = es61    es.onopen = () => {62      const wasRetry = this.everOpened63      this.everOpened = true64      this.attempt = 065      this.lastEvent = Date.now()66      this.opts.onStatus?.("open", 0)67      if (wasRetry) this.opts.onReconnect?.()68    }69    es.addEventListener("state", (ev) => {70      this.lastEvent = Date.now()71      try {72        const data = JSON.parse((ev as MessageEvent<string>).data) as StateChange73        if (data && typeof data.changed === "object") this.opts.onChange(data)74      } catch {75        /* événement illisible : ignoré */76      }77    })78    es.addEventListener("ping", () => {79      this.lastEvent = Date.now()80    })81    es.onerror = () => this.retry()82  }8384  private retry() {85    if (this.stopped) return86    this.es?.close()87    this.es = null88    this.attempt++89    if (this.attempt === 3) this.opts.onTrouble?.()90    this.opts.onStatus?.("retrying", this.attempt)91    clearTimeout(this.timer)92    this.timer = setTimeout(() => this.open(), backoffDelay(this.attempt))93  }94}95
Files main
Menu

Theme