March Docs

Bastion.Channel

lib/channel.march — Bastion.Channel: connection type and helpers for channel handlers.

Channel handlers are ordinary March modules that implement three functions:

fn join(conn, topic, params_json) : Result(ChannelConn, String)
fn handle_in(conn, event, payload_json) : ChannelConn
fn handle_out(conn, event, payload_json) : Result(ChannelConn, String)

A ChannelConn flows through every callback, carrying user-set assigns, the joined topic, the connection's unique ID, and a push function for sending server-initiated messages back to this client.

── Minimal channel handler ───────────────────────────────────────────────────

mod MyApp.RoomChannel do
  import Bastion.Channel

  fn join(conn, topic, _params) do
    let room_id = String.replace_prefix(topic, "room:", "")
    conn
    |> Channel.assign("room_id", room_id)
    |> Ok()
  end

  fn handle_in(conn, "message:new", payload_json) do
    Bastion.PubSub.broadcast(Channel.topic(conn), "message:new", payload_json)
    conn
  end
  fn handle_in(conn, _event, _payload) do conn end

  fn handle_out(conn, _event, _payload) do Ok(conn) end
end

Types

typeChannelConnChannelConn = {#

Functions

fnassignassign(cc : ChannelConn, key : String, value : String) : ChannelConn#

Store a string key/value in the channel connection assigns.

Replaces any existing value with the same key.

    conn |> Channel.assign("room_id", "42")
         |> Channel.assign("role", "moderator")
fnbroadcast_frombroadcast_from(cc : ChannelConn, topic_ : String, event : String, payload_json : String)#

Broadcast an event to all subscribers of a topic, excluding this connection.

Shorthand for `Bastion.PubSub.broadcast_from/4` using this conn's ID.

    conn |> Channel.broadcast_from("room:42", "typing:start", "{}")
fnconn_idconn_id(cc : ChannelConn) : String do cc.conn_id end#

Return the unique connection ID used to identify this socket in PubSub.

fnget_assignget_assign(cc : ChannelConn, key : String) : Option(String)#

Look up an assign by key. Returns Some(value) or None.

    Channel.get_assign(conn, "room_id")   -- Some("42") or None
fnnew_connnew_conn(topic : String, conn_id : String, push_fn : String -> String -> ()) : ChannelConn#

Build a new ChannelConn. Called by Bastion.ChannelServer when a join is accepted; user code does not normally need to call this directly.

fnpushpush(cc : ChannelConn, event : String, payload_json : String)#

Push an event directly to this connection's client.

Use in handle_in to reply to only the sender, rather than broadcasting to
all topic subscribers.

    conn |> Channel.push("error", "{\"code\":\"not_found\"}")
fnsub_idsub_id(cc : ChannelConn, topic_ : String) : String#

Return the subscription ID used when registering with PubSub for a topic. Format: "conn:<conn_id>:<topic>"

fntopictopic(cc : ChannelConn) : String do cc.topic end#

Return the joined topic string (e.g. \