Hcs.Event_source

hcs · API reference

High-level reconnecting SSE client.

This module wraps Sse_client with a background fiber, reconnect loop, Last-Event-ID tracking, server-provided retry handling, backoff, a status model, and an Eio.Stream of events. It is the preferred SSE client API for normal application use.

Reconnecting Server-Sent Events client.

Event_source is the high-level SSE client. It starts a background fiber, reconnects on transient connection failures, tracks Last-Event-ID, honors server-provided retry: values, exposes connection status, and pushes events into an Eio.Stream.

Example:

let source = Hcs.Event_source.start ~sw ~net ~clock url in
Hcs.Event_source.on_status source (function
  | Hcs.Event_source.Connected -> traceln "connected"
  | Reconnecting { delay; _ } -> traceln "reconnecting in %.1fs" delay
  | _ -> ());
let ev = Eio.Stream.take (Hcs.Event_source.events source) in
print_endline ev.Hcs.Sse_client.data
type status = 
  | Connecting
  | Connected
  | Reconnecting of {
    delay : float;
    attempt : int;
  }
  | Closed (* Lifecycle status. *)
type config = {
  sse : Sse_client.config;
  default_retry : float;
  max_retry : float;
  backoff : int -> float;
  max_reconnect_attempts : int option;
}

Reconnect and low-level SSE configuration. Delays are seconds.

val default_backoff : int -> float

Exponential backoff with jitter.

val default_config : config
val with_sse_config : Sse_client.config -> config -> config
val with_default_retry : float -> config -> config
val with_max_retry : float -> config -> config
val with_backoff : (int -> float) -> config -> config
val with_max_reconnect_attempts : int -> config -> config
val with_unlimited_reconnects : config -> config

Configuration helpers.

type t

Running event source.

val start : 
  sw:Eio.Switch.t ->
  net:_ Eio.Net.t ->
  clock:_ Eio.Time.clock ->
  ?config:config ->
  Uri.t ->
  t

Start the reconnect loop under sw.

val events : t -> Sse_client.event Eio.Stream.t

Stream of received events.

val status : t -> status

Current lifecycle status.

val on_status : t -> (status -> unit) -> unit

Register a callback invoked on future status changes.

val close : t -> unit

Stop reconnecting and close the current connection if any.