# moonrockz/signalr/client

A typed SignalR client for native and js. It connects to a Moon-Lander hub or to
an ASP.NET Core hub. On js the same program runs in a browser, in Node.js and in
Bun.

```text
connect(url)  -> negotiate -> WebSocket -> handshake -> body runs
invoke / send / stream  ->  result / nothing / items
on(client method)       <-  call from the server
end of the body         ->  Close message -> disconnected
```

## Connect and call

`connect` starts the connection, runs the body with it and stops it. The
methods come from the contract values, so the arguments and the results have
their MoonBit types:

```mbt check
///|
let add : @signalr.HubMethod[(Int32, Int32), Int32] = @signalr.HubMethod::call(
  @signalr.MethodName::parse("add") catch {
    _ => panic()
  },
  @signalr.args2(@signalr.int(), @signalr.int()),
  @signalr.int(),
)

///|
let counter : @signalr.HubMethod[Int32, Int32] = @signalr.HubMethod::stream(
  @signalr.MethodName::parse("counter") catch {
    _ => panic()
  },
  @signalr.args1(@signalr.int()),
  @signalr.int(),
)

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

///|
async fn use_hub(url : String) -> Int32 {
  @client.connect(@client.HubUrl::parse(url), connection => {
    connection.on(receive_message, message => {
      let (user, text) = message
      println("\{user}: \{text}")
    })
    connection.stream(counter, 3, item => println("item \{item}"))
    connection.invoke(add, (2, 3))
  })
}

///|
test "the example has the types of the contract" {
  let run : async (String) -> Int32 = use_hub
  ignore(run)
}
```

| Call | Effect |
| --- | --- |
| `invoke` | Waits for the typed result. A Completion error raises `HubError` with the text of the server |
| `send` | Sends a non-blocking invocation and returns when it is written; the server sends no reply |
| `stream` | Runs a function for each typed item until the stream ends |
| `on` | Registers the handler of a client method |
| `stop` | Sends a Close message; open calls fail with `Disconnected` |

A call from the server for a method with no handler goes to
`on_unknown_method`, and the connection stays open.

## Failures

`HubUrl::parse` rejects a text with no `http` or `https` scheme, with no host or
with a fragment. A failed start raises `ClientError` with the failed step: `NegotiateFailed`,
`TooManyRedirects` (more than 100), `TransportFailed` or `HandshakeFailed`.
When the connection ends, each open call raises `Disconnected` with the error
text of the server and its reconnect hint, and `on_close` gets the same values.
The client does not reconnect by itself.

`connect` returns in about a second after its body, also when the server does not
answer. In Node.js and Bun the runtime then keeps the program alive until the server
answers the close of the WebSocket, as for each `WebSocket` there. End such a program
with `process.exit`.

## Options

```mbt check
///|
test "client options" {
  let options = @client.ClientOptions::new(
    access_token=() => Some(@signalr.AccessToken::parse("token-from-login")),
    peer=DotNet11,
    server_timeout=@signalr.TimeLimit::seconds(60),
    on_close=info => println("closed: \{info.error.unwrap_or("no error")}"),
  )
  ignore(options)
}
```

| Option | Default | Effect |
| --- | --- | --- |
| `access_token` | none | Gives the bearer token before each negotiate and each WebSocket start |
| `skip_negotiation` | off | Opens the WebSocket at once |
| `peer` | `DotNet10` | The server that you talk to; see "Cancellation" |
| `keep_alive` | 15 s | Sends a Ping when the client sent nothing for this time |
| `server_timeout` | 30 s | Ends the connection when the server sent nothing for this time |
| `handshake_timeout` | 15 s | Fails the start when the server sends no handshake response in this time |
| `clock` | the platform | The time of each limit; a test gives its own clock |

The token goes into the `Authorization` header of the negotiate request. For the
WebSocket it goes into the same header on native, in Node.js and in Bun. A
browser cannot set that header, so there the token goes into the `access_token`
query value, as the stock JavaScript client does.

## Cancellation

Cancel the task that runs `invoke` or `stream`. A cancelled stream always sends
a CancelInvocation. A cancelled `invoke` sends one only when `peer` is
`DotNet11` or `MoonLander`, because a .NET 10 server does not accept it. The
client ignores later replies.
