moon-lander-hubs

    Typed SignalR hubs for the Moon-Lander framework: handlers, addressing, groups and hosting

    Download zip
    Author
    Version
    0.13.0
    License
    Apache-2.0
    Last updated
    10 hours ago
    Downloads
    8

    #moonrockz/moon-lander-hubs

    Typed SignalR hubs for Moon-Lander: the handlers of a contract, the addressing of connections, groups and users, and a hub server inside a host. The clients are the stock SignalR clients (@microsoft/signalr, .NET) and moonrockz/signalr/client.

    New to hubs? Build a chat with the SignalR guides. This page is the reference.

    The wire protocol, the codecs and the server are in moonrockz/signalr, which imports no Moon-Lander module. This module adds the framework part. It is not affiliated with Microsoft.

    client --sendMessage--> server session --> handler --> Target::OthersInGroup(room) | groups actor: members of the room | other client <--receiveMessage-- outgoing queue of each member

    PackageTargetsContents
    moonrockz/moon-lander-hubswasm, wasm-gc, js, nativeHandler binding, Target, HubContext, Membership, Recorder
    moonrockz/moon-lander-hubs/runtimenative, wasmHubRuntime: the groups actor and the link to a server
    moonrockz/moon-lander-hubs/hostingnative, wasmhub_service: a hub server in a host

    #A chat hub

    The contract holds the typed methods of both directions. The handlers get typed arguments, not JSON:

    ///|
    let post : @signalr.HubMethod[(String, String), Unit] = @signalr.HubMethod::call(
    @signalr.MethodName::parse("post") catch {
    _ => panic()
    },
    @signalr.args2(@signalr.string(), @signalr.string()),
    @signalr.unit(),
    )

    ///|
    let enter : @signalr.HubMethod[String, Unit] = @signalr.HubMethod::call(
    @signalr.MethodName::parse("enter") catch {
    _ => panic()
    },
    @signalr.args1(@signalr.string()),
    @signalr.unit(),
    )

    ///|
    let posted : @signalr.ClientMethod[(String, String)] = @signalr.ClientMethod::new(
    @signalr.MethodName::parse("posted") catch {
    _ => panic()
    },
    @signalr.args2(@signalr.string(), @signalr.string()),
    )

    ///|
    fn chat_room_hub() -> @hubs.Hub raise {
    let contract = @signalr.HubContract::new(@signalr.HubName::parse("chat"))
    .server(post)
    .server(enter)
    .client(posted)
    @hubs.bind(contract)
    .on(enter, (context, room) => {
    context
    .groups()
    .add(context.connection_id(), @signalr.GroupName::parse(room))
    })
    .on(
    post,
    (context, arguments) => {
    let (room, text) = arguments
    guard context.user_id() is Some(user) else {
    raise @signalr.HubError("sign in first")
    }
    context
    .clients()
    .others_in_group(@signalr.GroupName::parse(room))
    .send(posted, (user.to_string(), text))
    },
    policy=identity => identity.user_id() is Some(_),
    )
    .build()
    }

    ///|
    test "each hub method has a handler" {
    assert_eq(chat_room_hub().contract().hub_methods().length(), 2)
    }

    build raises BindError::MissingHandlers with each hub method that has no handler, so a hub with a gap does not start.

    #Test a handler

    A Recorder gives a context that records the targets, the calls and the group changes. The test has no connection and no actor:

    ///|
    async test "a post goes to the others in the room" {
    let recorder = @hubs.Recorder::new()
    let context = recorder.context(
    @signalr.ConnectionId::parse("A"),
    identity=@signalr.Identity::user(@signalr.UserId::parse("ana")),
    )
    chat_room_hub().invoke(context, call_of("post", ["room1", "hi"])) |> ignore
    assert_eq(recorder.sent()[0].target, OthersInGroup(room1, a))
    }

    Recorder::new(results=...) gives the replies of a client to clients().caller().invoke(...). The pure value Membership resolves a target to its connections, so a test also checks the addressing with no event loop.

    #Addressing

    CallTarget
    clients().all()Each connection
    clients().caller()The connection of the current call; it also has invoke for a typed result
    clients().others()Each connection except the caller
    clients().client(id), .any().clients(ids)These connections
    clients().any().all_except(ids)Each connection except these
    clients().group(g), .any().groups(gs)The connections of one or more groups
    clients().any().group_except(g, ids), .others_in_group(g)A group except some connections, or except the caller
    clients().user(u), .any().users(us)Each connection of one or more users

    A connection gets one call one time, also when it is in two of the groups. It leaves its groups when it ends. A reconnect is a new connection with no groups.

    #Order, limits and errors

    • The connect handler runs before the first hub method of a connection, and the disconnect handler runs one time after the connection ended, with the cause.
    • The calls of one connection run in the order of arrival, one at a time. A stream to the client frees its place when it starts. ServerOptions sets a higher limit with parallel_calls.
    • Each connection has a bounded queue of outgoing calls. When it is full, the hub ends that connection with the cause SlowClient and goes on with the others.
    • A handler that raises HubError sends its text to the caller. Another error sends a generic text, unless detailed_errors is on.
    • Arguments that do not decode give an error with the method and the argument, and the handler does not run.

    #Run a hub

    moonrockz/moon-lander-hubs/hosting runs a hub server in a host, with an authenticator, method policies and a graceful stop. A program with no host uses HubRuntime::start and HubRuntime::service of the runtime package with a Server of moonrockz/signalr/server.

    BindError

    A fault in the binding of a hub.

    BindError::equal

    fn BindError::equal(BindError, BindError) -> Bool
    automatically derived

    BindError::message

    fn BindError::message(self : BindError) -> String

    Text for people that describes the fault.

    BindError::not_equal

    fn BindError::not_equal(x : BindError, y : BindError) -> Bool
    automatically derived

    BindError::to_repr

    automatically derived

    ClientCallError

    pub(all) suberror ClientCallError {
    Disconnected(
    ConnectionId
    )
    ClientFailed(String)
    } derive(Eq,
    Debug
    )

    A failure of a call to one client that waits for a result.

    ClientCallError::equal

    automatically derived

    ClientCallError::not_equal

    fn ClientCallError::not_equal(x : ClientCallError, y : ClientCallError) -> Bool
    automatically derived

    ClientCallError::to_repr

    automatically derived

    Backend

    pub struct Backend {
    // private fields
    }

    The operations behind a hub context. The hub runtime and Recorder each give one; a program does not need to make one.

    CallerClients

    pub struct CallerClients {
    // private fields
    }

    The clients that a handler can call. It adds the targets that depend on the connection of the current call.

    CallerClients::all

    Every connection.

    CallerClients::any

    The targets that do not depend on the current call.

    CallerClients::caller

    The connection of the current call.

    CallerClients::client

    One connection.

    CallerClients::group

    The connections of a group.

    CallerClients::others

    Every connection except the one of the current call.

    CallerClients::others_in_group

    The connections of a group except the one of the current call.

    CallerClients::user

    The connections of a user.

    ClientProxy

    pub struct ClientProxy {
    // private fields
    }

    A target with the operation that sends to it.

    ClientProxy::send

    async fn[A] ClientProxy::send(self : ClientProxy, method_ :
    ClientMethod
    [A], arguments : A) -> Unit

    Call the client method method_ with arguments on each connection of the target, with no result. Two sends of one handler reach a connection in their order.

    ClientProxy::target

    fn ClientProxy::target(self : ClientProxy) -> Target

    The target.

    Clients

    pub struct Clients {
    // private fields
    }

    The clients of a hub: each method gives one target.

    Clients::all

    fn Clients::all(self : Clients) -> ClientProxy

    Every connection.

    Clients::all_except

    Every connection except ids.

    Clients::client

    One connection.

    Clients::clients

    The connections ids.

    Clients::group

    The connections of a group.

    Clients::group_except

    The connections of a group except ids.

    Clients::groups

    The connections of one or more groups. A connection in two of them gets the call one time.

    Clients::new

    fn Clients::new(backend : Backend) -> Clients

    The clients of backend. The runtime gives this value for sends from outside a hub method.

    Clients::target

    fn Clients::target(self : Clients, target : Target) -> ClientProxy

    The clients of any target.

    Clients::user

    The connections of a user.

    Clients::users

    The connections of one or more users.

    GroupChange

    A change of a group that a handler made.

    GroupChange::equal

    fn GroupChange::equal(GroupChange, GroupChange) -> Bool
    automatically derived

    GroupChange::not_equal

    fn GroupChange::not_equal(x : GroupChange, y : GroupChange) -> Bool
    automatically derived

    GroupChange::to_repr

    automatically derived

    GroupManager

    pub struct GroupManager {
    // private fields
    }

    The groups of a hub.

    GroupManager::add

    Add a connection to a group. After the return, a send to the group reaches the connection. A connection that ended is not added.

    GroupManager::new

    fn GroupManager::new(backend : Backend) -> GroupManager

    The groups of backend.

    GroupManager::remove

    Remove a connection from a group. When it is not in the group, this has no effect.

    Hub

    pub struct Hub {
    // private fields
    }

    A hub: a contract with one handler for each hub method (design CON-1).

    Hub::connected

    async fn Hub::connected(self : Hub, context : HubContext) -> Unit

    Run the connect handler.

    Hub::contract

    The contract of the hub.

    Hub::disconnected

    async fn Hub::disconnected(self : Hub, context : HubContext, cause :
    DisconnectCause
    ) -> Unit

    Run the disconnect handler.

    Hub::invoke

    async fn Hub::invoke(self : Hub, context : HubContext, call :
    Call
    ) ->
    HubValue
    ?

    Run the handler of a call with one result. Gives the result, or None for a method with no result.

    Hub::stream

    async fn Hub::stream(self : Hub, context : HubContext, call :
    Call
    , emit : async (
    HubValue
    ) -> Unit) -> Unit

    Run the handler of a streaming call, which sends each item with emit.

    HubBuilder

    pub struct HubBuilder {
    // private fields
    }

    A hub in construction: a contract and the handlers that are bound so far. Each call gives a new value.

    HubBuilder::build

    fn HubBuilder::build(self : HubBuilder) -> Hub raise BindError

    The hub. A hub method of the contract with no handler raises MissingHandlers with each such name.

    HubBuilder::on

    fn[A, R] HubBuilder::on(self : HubBuilder, method_ :
    HubMethod
    [A, R], handler : async (HubContext, A) -> R, policy? : (
    Identity
    ) -> Bool) -> HubBuilder raise BindError

    Bind the handler of a hub method with one result. The handler gets the typed arguments. policy gets the identity of the caller; when it gives false, the handler does not run and the caller gets an error.

    HubBuilder::on_connected

    fn HubBuilder::on_connected(self : HubBuilder, handler : async (HubContext) -> Unit) -> HubBuilder

    The handler that runs after the handshake and before the first hub method of a connection. An error refuses the connection.

    HubBuilder::on_disconnected

    fn HubBuilder::on_disconnected(self : HubBuilder, handler : async (HubContext,
    DisconnectCause
    ) -> Unit) -> HubBuilder

    The handler that runs one time after a connection ended, with the cause.

    HubBuilder::on_stream

    fn[A, R] HubBuilder::on_stream(self : HubBuilder, method_ :
    HubMethod
    [A, R], handler : async (HubContext, A, async (R) -> Unit) -> Unit, policy? : (
    Identity
    ) -> Bool) -> HubBuilder raise BindError

    Bind the handler of a streaming hub method. The handler sends each item with its third argument, which waits when the client reads slowly. When the client cancels the stream, the task of the handler is cancelled.

    HubContext

    pub struct HubContext {
    // private fields
    }

    What a handler knows and can do: the connection of the current call, its identity, the clients and the groups.

    HubContext::clients

    fn HubContext::clients(self : HubContext) -> CallerClients

    The clients of the hub.

    HubContext::connection_id

    The connection of the current call.

    HubContext::groups

    fn HubContext::groups(self : HubContext) -> GroupManager

    The groups of the hub.

    HubContext::identity

    Who the connection belongs to.

    HubContext::new

    A context for a call of the connection connection_id with the upload streams uploads.

    HubContext::read_upload

    async fn[T] HubContext::read_upload(self : HubContext, stream :
    StreamId
    , item :
    Codec
    [T]) -> T?

    The next item of an upload stream, or None at its end. A stream that the client ends with an error raises HubError with that text.

    HubContext::uploads

    fn HubContext::uploads(self : HubContext) -> ReadOnlyArray[
    StreamId
    ]

    The upload streams of the current call, in the order of the client.

    HubContext::user_id

    The user ID of the identity, or None for an anonymous connection.

    Membership

    pub struct Membership {
    // private fields
    }

    The open connections of a hub with their users and groups. The value is immutable and does no I/O, so a test checks the addressing with no actor. A group exists while it has a connection.

    Membership::connect

    Add an open connection with the user of its identity.

    Membership::connection_count

    fn Membership::connection_count(self : Membership) -> Int

    The number of open connections.

    Membership::disconnect

    Remove a connection that ended. It leaves all its groups.

    Membership::empty

    fn Membership::empty() -> Membership

    No connections.

    Membership::group_count

    fn Membership::group_count(self : Membership) -> Int

    The number of groups. Each has one connection or more.

    Membership::join

    Add an open connection to a group. A connection that is not open is not added, because it can never leave.

    Membership::leave

    Remove a connection from a group. When it is not in the group, this has no effect.

    Membership::resolve

    The open connections of a target, each one time.

    Recorder

    pub struct Recorder {
    // private fields
    }

    A hub context for a unit test of a handler. It records the calls to clients and the group changes, with no connection, no actor and no event loop.

    Recorder::context

    The context for a call of connection_id.

    Recorder::group_changes

    fn Recorder::group_changes(self : Recorder) -> Array[GroupChange]

    The group changes, in order.

    Recorder::new

    A recorder. results are the replies of the client to each call that waits for a result, in order; when no reply is left, the connection has ended. uploads are the items of the upload streams of the call.

    Recorder::sent

    fn Recorder::sent(self : Recorder) -> Array[Sent]

    The calls to clients, in order.

    Sent

    A call to clients that a handler sent.

    Sent::equal

    fn Sent::equal(Sent, Sent) -> Bool
    automatically derived

    Sent::not_equal

    fn Sent::not_equal(x : Sent, y : Sent) -> Bool
    automatically derived

    Sent::to_repr

    automatically derived

    SingleClient

    pub struct SingleClient {
    // private fields
    }

    One connection, which can also give a result.

    SingleClient::invoke

    async fn[A, R] SingleClient::invoke(self : SingleClient, call :
    ClientCall
    [A, R], arguments : A) -> R

    Call the client method call and wait for its typed result. A client error raises ClientFailed; a connection that ends first raises Disconnected.

    SingleClient::send

    async fn[A] SingleClient::send(self : SingleClient, method_ :
    ClientMethod
    [A], arguments : A) -> Unit

    Call the client method method_ with no result.

    SingleClient::target

    fn SingleClient::target(self : SingleClient) -> Target

    The target of the connection.

    Target

    The connections that get a call from the hub. A target is a plain value, so a test can compare it (signalr-hubs, "Addressing").

    Target::equal

    fn Target::equal(Target, Target) -> Bool
    automatically derived

    Target::not_equal

    fn Target::not_equal(x : Target, y : Target) -> Bool
    automatically derived

    Target::to_repr

    automatically derived

    bind

    Start to bind the handlers of contract.