Skip to main content

broadcast

Function broadcast 

Source
pub fn broadcast(
    ctx: &Ctx,
    channel: &str,
    message: &str,
) -> impl Future<Output = Result<()>> + Send + use<>
Expand description

Sends message (an HTML fragment or JSON text) to every browser connected to channel.

Returns once the channel’s OcreChannel object has sent it. Build HTML messages with prepend, append, update, remove, or an element with an id that replaces the page element with that id; several can go in one message. Works from handlers and jobs. The returned future is Send, so axum handlers can await it.

Every failure is logged as [ocre realtime] broadcast to <channel> failed: ... and returned; callers that treat updates as best effort (the generated controllers do) can ignore it with .ok().

Free plan: each call is one Durable Object request (100,000 a day), even when the channel has no subscribers, and one subrequest of the current request; the messages to browsers are free.

§Errors

  • Error::Internal when channel is not a valid name (1 to MAX_CHANNEL_LEN ASCII letters, digits, _, -, . or :).
  • Error::Internal when the CHANNELS Durable Object binding is missing; the message names the cloudflare.config.ts entries to add.
  • Error::Internal when the channel object cannot be reached (e.g. the free-plan quota is exhausted) or answers with a non-200 status.

§Examples

use axum::extract::{Path, State};
use ocre::{Ctx, Result, realtime};

async fn destroy(State(ctx): State<Ctx>, Path(id): Path<i64>) -> Result<()> {
    // ... delete the post, then remove its row from every open index page:
    realtime::broadcast(&ctx, "posts", &realtime::remove(&format!("post_{id}"))).await.ok();
    Ok(())
}