ASP.NET Core SignalR hub protocol, payload codecs, server and client for MoonBit
| Package | Targets | Contents |
|---|---|---|
| moonrockz/signalr | wasm, wasm-gc, js, native | Domain types, HubValue, Codec[T], hub messages, JSON reader and writer, framing, handshake, negotiate payloads, the protocol state machine, HubMethod, ClientMethod, HubContract |
| moonrockz/signalr/server | native, wasm | The hub server: negotiate, the WebSocket transport, keep-alive, timeouts, the message size limit and the graceful drain |
| moonrockz/signalr/client | native, js | The typed client; see its guide |
| Type | Rules |
|---|---|
| HubName | ASCII letter first, then letters, digits, - and _; 1 to 128 characters |
| MethodName | 1 to 128 characters, no control or space characters |
| InvocationId, StreamId | 1 to 128 characters, no control characters |
| ConnectionId, ConnectionToken | 1 to 256 characters, no control or space characters |
| UserId, GroupName | 1 to 256 characters, no control characters |
| EndpointPath | / first, nonempty segments of ASCII letters, digits, -, ., _ and ~ |
///|
test "parse identifiers and match a failure by its rule" {
let path = @signalr.EndpointPath::parse("/chat")
assert_eq(path.negotiate(), "/chat/negotiate")
let rule = try {
ignore(@signalr.EndpointPath::parse("chat"))
None
} catch {
InvalidIdentifier(rule~, ..) => Some(rule)
}
assert_true(rule is Some(NoLeadingSlash))
}///|
test "a connection token is redacted" {
let token = @signalr.ConnectionToken::parse("x7Kq2")
assert_eq("token \{token}", "token [REDACTED]")
assert_eq(token.expose(), "x7Kq2")
}///|
test "a map keeps its key order and rejects a duplicate key" {
let map = @signalr.HubMap::empty().add("b", Int(1L)).add("a", Int(2L))
assert_eq(map.keys(), ["b", "a"])
let duplicate = try {
ignore(map.add("b", Null))
false
} catch {
DuplicateKey(key~) => key == "b"
_ => false
}
assert_true(duplicate)
}| Value | Default | Explicit choice |
|---|---|---|
| Record property names | camelCase (user_name gives userName, URLValue gives urlValue); only ASCII letters change | field(..., property="name") |
| Enums | numbers (enumeration, or enum_numbers with an EnumMapping) | text (enum_names with an EnumMapping) |
| Bytes | Base64 text in JSON | |
| Timestamps | ISO 8601 text in JSON | |
| 64-bit integers | numbers from -(2^53 - 1) to 2^53 - 1 (int64, uint64) | text (int64_as_text, uint64_as_text) |
///|
test "decode a domain type through its smart constructor" {
let user : @signalr.Codec[@signalr.UserId] = @signalr.string().parse(
@signalr.UserId::parse,
id => id.to_string(),
)
let args = @signalr.tuple2(user, @signalr.string())
let (id, text) = args.decode(
@signalr.HubValue::array([String("ana"), String("hi")]),
)
assert_eq(id.to_string(), "ana")
assert_eq(text, "hi")
let path = try {
ignore(
args.decode(
@signalr.HubValue::array([String(""), String("hi")]),
path=@signalr.Path::named("arguments"),
),
)
""
} catch {
Rejected(path~, ..) => path.to_string()
_ => "other error"
}
assert_eq(path, "arguments[0]")
}///|
struct Reading {
sensor_name : String
level : Int32
taken_at : @signalr.Timestamp
}
///|
test "a record codec writes camelCase properties" {
let codec = @signalr.record3(
(sensor_name, level, taken_at) => { sensor_name, level, taken_at, },
@signalr.field("sensor_name", @signalr.string(), r => r.sensor_name),
@signalr.field("level", @signalr.int(), r => r.level),
@signalr.field("taken_at", @signalr.timestamp(), r => r.taken_at),
)
let reading = {
sensor_name: "north",
level: 3,
taken_at: @signalr.Timestamp::parse("2026-12-01T10:15:00Z"),
}
guard codec.encode(reading) is Map(map) else { fail("expected an object") }
assert_eq(map.keys(), ["sensorName", "level", "takenAt"])
let back = codec.decode(Map(map))
assert_eq(back.sensor_name, "north")
assert_eq(back.level, 3)
}///|
test "64-bit integers stay in the safe range unless they are text" {
let outside = try {
ignore(@signalr.int64().encode(9007199254740992L))
""
} catch {
IntegerOutOfRange(min~, max~, ..) => "\{min} to \{max}"
_ => "other error"
}
assert_eq(outside, "-9007199254740991 to 9007199254740991")
assert_eq(
@signalr.int64_as_text().encode(9007199254740992L),
String("9007199254740992"),
)
} text in local call / cancel / item / completion
| |
v v
+--------------------------------------------+
| ProtocolState (framing buffer, handshake, |
| open calls, open streams, used IDs) |
+--------------------------------------------+
| | |
Send(text) Dispatch(call) Completed / ItemReceived / Closed///|
test "invoke a hub method through the in-memory pair" {
let add : @signalr.HubMethod[(Int32, Int32), Int32] = @signalr.HubMethod::call(
@signalr.MethodName::parse("add"),
@signalr.args2(@signalr.int(), @signalr.int()),
@signalr.int(),
)
let contract = @signalr.HubContract::new(@signalr.HubName::parse("calc")).server(
add,
)
let (pair, _) = @signalr.MemoryPair::connect()
// The client calls add(2, 3).
let (pair, _, events) = pair.client_call(
Blocking,
add.name(),
add.arguments().encode((2, 3)),
)
guard events is [{ role: Server, output: Dispatch(call), }] else {
fail("expected one call on the server")
}
guard contract.check_call(call) is Ok(_) else {
fail("expected a known method")
}
guard call.invocation_id is Some(id) else { fail("expected an ID") }
// The hub decodes the arguments and sends the result.
let (a, b) = add.arguments().decode(call.arguments)
let (_, events) = pair.on_server(state => {
state.complete(id, Result(add.result().encode(a + b)))
})
guard events is [{ role: Client, output: Completed(_, Result(value)), }] else {
fail("expected the result on the client")
}
assert_eq(add.result().decode(value), 5)
}POST /calc/negotiate?negotiateVersion=1 -> connectionId, connectionToken, WebSockets
GET /calc?id=<connectionToken> (upgrade) -> WebSocket, then the handshake///|
async fn main {
let add : @signalr.HubMethod[(Int32, Int32), Int32] = @signalr.HubMethod::call(
@signalr.MethodName::parse("add"),
@signalr.args2(@signalr.int(), @signalr.int()),
@signalr.int(),
)
let contract = @signalr.HubContract::new(@signalr.HubName::parse("calc")).server(
add,
)
let service = @server.HubService::new(contract, invoke=(_, call) => {
let (a, b) = add.arguments().decode(call.arguments)
Some(add.result().encode(a + b))
})
let options = @server.ServerOptions::new(
@signalr.EndpointPath::parse("/calc"),
)
let server = @server.Server::bind(
@server.BindAddress::parse("127.0.0.1:5000"),
options,
service,
)
server.run()
}| Option | Default | Effect |
|---|---|---|
| keep_alive | 15 s | Send a Ping when the server sent nothing for this time |
| client_timeout | 30 s | Close a connection that sent nothing for this time |
| handshake_timeout | 15 s | Close a WebSocket with no complete handshake in this time |
| negotiate_timeout | 15 s | Remove a negotiated connection that gets no WebSocket in this time |
| max_message_size | 32768 bytes | Close a connection that sends a larger hub message |
| outgoing_messages | 128 | End a connection with the cause SlowClient when this many calls to the client wait |
| parallel_calls | 1 | The calls of one connection that run at the same time; a stream to the client frees its place when it starts |
| max_connections | 1000 | The TCP connections at the same time; more wait |
| clock | the platform | The time of each limit; a test gives its own clock |
| detailed_errors | off | Put the error text in Completion errors |
{ "net": { "bind": ["127.0.0.1:5187"] } }moon build tests/signalr-calc-server --target wasm
moonrun --policy policy.json \
_build/wasm/debug/build/moonrockz/moon-lander-tests/signalr-calc-server/signalr-calc-server.wasm \
127.0.0.1:5187pub suberror CodecError {
TypeMismatch(path~ : Path, expected~ : ValueKind, found~ : ValueKind)
LengthMismatch(path~ : Path, expected~ : Int, found~ : Int)
MissingProperty(path~ : Path, name~ : String)
NotAnInteger(path~ : Path, value~ : Double)
IntegerOutOfRange(path~ : Path, value~ : String, min~ : String, max~ : String)
NotFinite(path~ : Path, value~ : Double)
UnknownEnumValue(path~ : Path, value~ : String)
InvalidText(path~ : Path, format~ : TextFormat, text~ : String)
NullInOption(path~ : Path)
Rejected(path~ : Path, cause~ : Error)
} derive(Debug)pub suberror ContractError {
DuplicateHubMethod(MethodName)
DuplicateClientMethod(MethodName)
} derive(Eq, Debug)pub suberror IdentifierError {
InvalidIdentifier(kind~ : IdentifierKind, text~ : String, rule~ : IdentifierRule)
} derive(Eq, Debug)pub suberror ProtocolError {
InvalidJson(detail~ : String)
NotAnObject
MissingField(field~ : String)
WrongFieldType(field~ : String, expected~ : String)
UnknownField(field~ : String)
UnsupportedMessageType(message_type~ : Int)
BadIdentifier(field~ : String, error~ : IdentifierError)
NumberOutOfRange(text~ : String)
ResultAndError(invocation_id~ : InvocationId)
InvocationIdInUse(invocation_id~ : InvocationId)
StreamIdInUse(stream_id~ : StreamId)
UnknownInvocation(invocation_id~ : InvocationId)
StreamItemForInvocation(invocation_id~ : InvocationId)
ResultAfterStreamItems(invocation_id~ : InvocationId)
MessageBeforeHandshake
UnexpectedMessage(message_type~ : Int)
MessageTooLarge(limit~ : Int, size~ : Int)
} derive(Debug)impl Eq for ProtocolErrorpub suberror TimestampError {
InvalidTimestamp(input~ : String, rule~ : TimestampRule)
} derive(Eq, Debug)pub suberror UsageError {
NotOpen
UnknownCall(invocation_id~ : InvocationId)
NotAStream(invocation_id~ : InvocationId)
ResultForStream(invocation_id~ : InvocationId)
UnknownInvocation(invocation_id~ : InvocationId)
UnknownStream(stream_id~ : StreamId)
StreamFromServer
} derive(Eq, Debug)pub struct AccessToken {
// private fields
}impl Eq for AccessTokenimpl Show for AccessTokenimpl Debug for AccessTokenpub struct Arguments[A] {
// private fields
}fn[A] Arguments::decode(self : Arguments[A], values : ReadOnlyArray[HubValue]) -> A raise CodecErrorpub(all) struct AvailableTransport {
transport : TransportKind
formats : ReadOnlyArray[TransferFormat]
} derive(Eq, Debug)pub(all) struct Call {
invocation_id : InvocationId?
kind : CallKind
target : MethodName
arguments : ReadOnlyArray[HubValue]
stream_ids : ReadOnlyArray[StreamId]
headers : Headers
} derive(Eq, Debug)pub(all) struct CancelInvocation {
invocation_id : InvocationId
headers : Headers
} derive(Eq, Debug)pub struct ClientCall[A, R] {
// private fields
}fn[A, R] ClientCall::new(name : MethodName, arguments : Arguments[A], result : Codec[R]) -> ClientCall[A, R]pub struct ClientMethod[A] {
// private fields
}pub struct Clock {
// private fields
}pub struct Codec[T] {
// private fields
}fn[T] Codec::new(encode~ : (T, Path) -> HubValue raise CodecError, decode~ : (HubValue, Path) -> T raise CodecError) -> Codec[T]pub(all) struct Completion {
invocation_id : InvocationId
outcome : Outcome
headers : Headers
} derive(Eq, Debug)impl Show for ConnectionIdpub struct ConnectionToken {
// private fields
}impl Eq for ConnectionTokenimpl Hash for ConnectionTokenimpl Show for ConnectionTokenimpl Debug for ConnectionTokenimpl Show for EndpointPathpub struct EnumMapping[T, W] {
// private fields
}fn[T : Eq, W : Eq + Show] EnumMapping::new(cases : ArrayView[(T, W)]) -> EnumMapping[T, W] raise EnumMappingErrorpub struct Field[R, F] {
// private fields
}pub struct FrameBuffer {
// private fields
}impl Eq for FrameBufferimpl Debug for FrameBufferpub struct HubContract {
// private fields
}fn[A] HubContract::client(self : HubContract, method_ : ClientMethod[A]) -> HubContract raise ContractErrorfn[A, R] HubContract::client_call(self : HubContract, call : ClientCall[A, R]) -> HubContract raise ContractErrorfn[A, R] HubContract::server(self : HubContract, method_ : HubMethod[A, R]) -> HubContract raise ContractErrorpub(all) enum HubMessage {
Invocation(Invocation)
StreamItem(StreamItem)
Completion(Completion)
StreamInvocation(StreamInvocation)
CancelInvocation(CancelInvocation)
Ping
Close(Close)
} derive(Eq, Debug)pub struct HubMethod[A, R] {
// private fields
}fn[A, R] HubMethod::call(name : MethodName, arguments : Arguments[A], result : Codec[R]) -> HubMethod[A, R]pub(all) struct Invocation {
invocation_id : InvocationId?
target : MethodName
arguments : ReadOnlyArray[HubValue]
stream_ids : ReadOnlyArray[StreamId]
headers : Headers
} derive(Eq, Debug)impl Show for InvocationIdpub(all) struct Invoked {
invocation_id : InvocationId?
stream_ids : ReadOnlyArray[StreamId]
} derive(Eq, Debug)pub struct MemoryPair {
// private fields
}fn MemoryPair::client_call(self : MemoryPair, mode : CallMode, target : MethodName, arguments : ArrayView[HubValue], uploads? : Int) -> (MemoryPair, Invoked, Array[Event]) raise UsageErrorfn MemoryPair::on_client(self : MemoryPair, step : (ProtocolState) -> (ProtocolState, Array[Output]) raise) -> (MemoryPair, Array[Event]) raisefn MemoryPair::on_server(self : MemoryPair, step : (ProtocolState) -> (ProtocolState, Array[Output]) raise) -> (MemoryPair, Array[Event]) raiseimpl Show for MethodNamepub(all) enum NegotiateResponse {
Connection(NegotiatedConnection)
Redirect(url~ : String, access_token~ : AccessToken?)
Refused(String)
} derive(Eq, Debug)pub(all) struct NegotiatedConnection {
connection_id : ConnectionId
token : NegotiatedToken
transports : ReadOnlyArray[AvailableTransport]
} derive(Eq, Debug)pub(all) enum Output {
Send(String)
HandshakeCompleted
HandshakeFailed(String)
Dispatch(Call)
ItemReceived(InvocationId, HubValue)
Completed(InvocationId, Outcome)
UploadItem(StreamId, HubValue)
UploadEnded(StreamId, String?)
CancelRequested(InvocationId)
CloseReceived(Close)
Violation(ProtocolError)
Closed
} derive(Eq, Debug)pub struct ProtocolState {
// private fields
}fn ProtocolState::call(self : ProtocolState, mode : CallMode, target : MethodName, arguments : ArrayView[HubValue], uploads? : Int, headers? : Headers) -> (ProtocolState, Invoked, Array[Output]) raise UsageErrorfn ProtocolState::cancel(self : ProtocolState, invocation_id : InvocationId) -> (ProtocolState, Array[Output]) raise UsageErrorfn ProtocolState::close(self : ProtocolState, error? : String, allow_reconnect? : Bool) -> (ProtocolState, Array[Output])fn ProtocolState::complete(self : ProtocolState, invocation_id : InvocationId, outcome : Outcome) -> (ProtocolState, Array[Output]) raise UsageErrorfn ProtocolState::end_upload(self : ProtocolState, stream_id : StreamId, error? : String) -> (ProtocolState, Array[Output]) raise UsageErrorfn ProtocolState::receive(self : ProtocolState, text : StringView) -> (ProtocolState, Array[Output])fn ProtocolState::send_item(self : ProtocolState, invocation_id : InvocationId, item : HubValue) -> (ProtocolState, Array[Output]) raise UsageErrorfn ProtocolState::upload_item(self : ProtocolState, stream_id : StreamId, item : HubValue) -> (ProtocolState, Array[Output]) raise UsageErrorpub(all) struct StreamInvocation {
invocation_id : InvocationId
target : MethodName
arguments : ReadOnlyArray[HubValue]
stream_ids : ReadOnlyArray[StreamId]
headers : Headers
} derive(Eq, Debug)pub(all) struct StreamItem {
invocation_id : InvocationId
item : HubValue
headers : Headers
} derive(Eq, Debug)pub(all) enum TimestampRule {
Syntax
FieldOutOfRange(TimestampField)
TooPrecise
InvalidNanoseconds(Int)
OutOfRange
} derive(Eq, Debug)let access_token_length_limit : Intfn camel_case(name : String) -> Stringfn frame(text : StringView) -> Stringlet id_length_limit : Intlet max_safe_integer : Int64let name_length_limit : Intlet record_separator : Charfn redact_target(target : String) -> String