SPB Git

Repository Public

sessions.ts 4.1 KB 62 lines typescript

1import { all, get, now, run } from "../db";2import { newToken, RelayRefused, tokenId, type StreamRow } from "./access";3import { limits } from "./config";4import { event } from "./events";5import type { Relay } from "./relays";67// StreamSessionManager — one session per player. A session is what a playback address designates; it lives as long as8// the player keeps asking for the stream and is closed after a period of silence, by the player, or by sign-out.910export interface Session { id: string; relay_id: string; stream_id: number; channel_id: string; auth: string; ip: string | null; user_agent: string | null; created_at: number; expires_at: number; last_seen_at: number; ended_at: number | null; end_reason: string | null; bytes_out: number; requests: number }11const MAX_AGE = 12 * 3600_000;12/** Silence after which a session is considered gone. */13export const idleMs = () => Math.max(45, limits().idleSec * 2) * 1000;14export const openSessions = () => all<Session>("SELECT * FROM relay_sessions WHERE ended_at IS NULL ORDER BY created_at");1516export function open(relay: Relay, row: StreamRow, auth: string, meta: { ip: string; userAgent: string | null }): { token: string; id: string } {17  const l = limits();18  expire();19  if (get<{ n: number }>("SELECT COUNT(*) n FROM relay_sessions WHERE ended_at IS NULL")!.n >= l.maxSessions) throw new RelayRefused(`Nombre maximal de lecteurs simultanés atteint (${l.maxSessions})`, 503);20  const token = newToken(); const id = tokenId(token);21  run("INSERT INTO relay_sessions(id, relay_id, stream_id, channel_id, auth, ip, user_agent, created_at, expires_at, last_seen_at) VALUES(?,?,?,?,?,?,?,?,?,?)",22    id, relay.id, row.id, row.channel_id, auth, meta.ip, meta.userAgent?.slice(0, 200) ?? null, now(), now() + MAX_AGE, now());23  event("info", "session", `Lecteur connecté à « ${row.channel_name} »`, relay.id);24  return { token, id };25}2627export function lookup(token: string): Session | null {28  const s = get<Session>("SELECT * FROM relay_sessions WHERE id = ?", tokenId(token));29  return s && !s.ended_at && s.expires_at > now() ? s : null;30}3132// Counters are accumulated in memory and written every few seconds: a segment request must not cost a database write.33type G = typeof globalThis & { __sptvRelayAcc?: Map<string, { bytes: number; requests: number; seen: number }>; __sptvRelayFlush?: ReturnType<typeof setInterval> };34const acc = () => ((globalThis as G).__sptvRelayAcc ??= new Map());35export function touch(id: string, bytes: number) {36  const a = acc().get(id) ?? { bytes: 0, requests: 0, seen: 0 }; a.bytes += bytes; if (!bytes) a.requests += 1; a.seen = now(); acc().set(id, a);37  const g = globalThis as G;38  if (!g.__sptvRelayFlush) { g.__sptvRelayFlush = setInterval(flush, 3000); g.__sptvRelayFlush.unref(); }39}40export function flush() {41  for (const [id, a] of acc()) run("UPDATE relay_sessions SET bytes_out = bytes_out + ?, requests = requests + ?, last_seen_at = MAX(last_seen_at, ?) WHERE id = ?", a.bytes, a.requests, a.seen, id);42  acc().clear();43}4445export function close(id: string, reason: string): boolean {46  flush();47  const done = run("UPDATE relay_sessions SET ended_at = ?, end_reason = ? WHERE id = ? AND ended_at IS NULL", now(), reason, id).changes > 0;48  if (done) { const s = get<Session>("SELECT * FROM relay_sessions WHERE id = ?", id)!; event("info", "session", `Lecteur déconnecté (${reason}) après ${Math.round((s.last_seen_at - s.created_at) / 1000)} s`, s.relay_id); }49  return done;50}51/** Closes the sessions that stopped asking for data, and those opened with a sign-in that no longer exists. */52export function expire(): number {53  const t = now(); let n = 0;54  for (const s of openSessions()) {55    const reason = s.expires_at < t ? "durée maximale" : t - s.last_seen_at > idleMs() ? "inactivité" : null;56    if (reason && close(s.id, reason)) n++;57  }58  run("DELETE FROM relay_sessions WHERE ended_at IS NOT NULL AND ended_at < ?", t - 14 * 86400_000);59  return n;60}61export const closeForAuth = (auth: string, reason: string) => { for (const s of all<Session>("SELECT * FROM relay_sessions WHERE auth = ? AND ended_at IS NULL", auth)) close(s.id, reason); };62
Files main
Menu

Theme