Silk

silk/websocket_server

Profiles: aarch64-apple-darwin, aarch64-unknown-linux-gnu, aarch64-unknown-linux-gnu-no-libc, wasm32-unknown-unknown, x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-no-libc.

Bounded server WebSocket messages over one validated upgraded HTTP channel.

When to use

Use withServer after silk.websocket_upgrade.withUpgrade accepts a request and lends its exact buffered channel.

Details

The actor accepts final, unfragmented client frames with mandatory masking. It validates one complete event at a time and writes final unmasked server frames. The scoped session owns all frame ordering and closes the upgraded channel when its callback ends.

Gotchas

This actor does not implement continuation frames, extensions, compression, a listener, or TLS server acquisition. Unsupported fragmentation closes with code 1003 when a finite deadline permits that response.

Import as WebSocketServer with import silk.websocket_server as WebSocketServer.

Public declarations: 25.

Limits

pub struct Limits

Finite message and close-handshake limits for one server session.

Field maxMessageBytes

pub maxMessageBytes: usize

The maximum payload bytes in one Text or Binary frame.

Field maxCloseFrames

pub maxCloseFrames: usize

The maximum peer frames accepted by one finishClose call.

Field maxCloseBytes

pub maxCloseBytes: usize

The maximum aggregate peer frame bytes accepted by one finishClose call.

Associated function Limits.defaults

pub fn defaults() -> Limits

Returns limits for 65,536-byte messages, 32 close frames, and 65,536 close bytes.

Associated function Limits.make

pub fn make(maxMessageBytes: usize, maxCloseFrames: usize, maxCloseBytes: usize) -> silk/result.Result<silk/websocket_server.Limits, silk/websocket_server.WebSocketError>

Validates and returns finite positive session limits.

Implementation Copy for Limits

impl Copy for Limits

LimitKind

pub enum LimitKind

The finite limit or arithmetic rule that rejected session construction.

MessageBytes

MessageBytes = 0

The message-byte limit is zero.

CloseFrames

CloseFrames = 1

The close-frame limit is zero.

CloseBytes

CloseBytes = 2

The close-byte limit is zero.

Arithmetic

Arithmetic = 3

Checked size arithmetic cannot represent a required value.

State

pub enum State

The externally visible lifecycle state of one session.

Open

Open = 0

The session accepts message, control, and peer Close events.

CloseSent

CloseSent = 1

The server sent one Close and waits for the peer Close.

Closed

Closed = 2

The close handshake and terminal transport close completed.

Failed

Failed = 3

A preceding failure made all later frame operations unavailable.

Operation

pub enum Operation

The public operation associated with a state or transport failure.

ReadEvent

ReadEvent = 0

Read one peer event.

WriteText

WriteText = 1

Write one Text frame.

WriteBinary

WriteBinary = 2

Write one Binary frame.

WritePing

WritePing = 3

Write one Ping frame.

WritePong

WritePong = 4

Write one Pong frame.

SendClose

SendClose = 5

Send the local Close frame.

FinishClose

FinishClose = 6

Pump peer frames until the close handshake completes.

ProtocolReason

pub enum ProtocolReason

The peer frame rule that selected protocol Close code 1002.

MaskRequired

MaskRequired = 0

A client frame does not contain the required mask.

Rsv

Rsv = 1

One or more reserved bits are set.

ReservedOpcode

ReservedOpcode = 2

The opcode is reserved by the selected profile.

NonMinimalLength

NonMinimalLength = 3

An extended length uses a longer than necessary encoding.

LengthHighBit

LengthHighBit = 4

A 64-bit payload length has its most significant bit set.

ControlTooLarge

ControlTooLarge = 5

A control frame payload exceeds 125 bytes.

ControlFragmented

ControlFragmented = 6

A control frame clears FIN and therefore attempts illegal fragmentation.

ClosePayloadLength

ClosePayloadLength = 7

A Close frame payload has exactly one byte.

CloseCode

CloseCode = 8

A peer Close frame contains a disallowed status code.

Utf8Component

pub enum Utf8Component

The text value that failed complete UTF-8 validation.

Text

Text = 0

A Text message payload.

CloseReason

CloseReason = 1

A Close status reason.

CloseDataReason

pub enum CloseDataReason

The caller Close value rule that rejected construction.

Code

Code = 0

The status code is not permitted for a server Close frame.

ReasonTooLarge

ReasonTooLarge = 1

The UTF-8 reason contains more than 123 bytes.

CloseLimitKind

pub enum CloseLimitKind

The aggregate close-handshake budget that was exhausted.

Frames

Frames = 0

The peer frame-count budget.

Bytes

Bytes = 1

The aggregate peer wire-byte budget.

Failure

pub enum Failure

A copyable classification retained after the first terminal failure.

Protocol

Protocol = 0

Peer frame syntax violated the protocol.

Fragmentation

Fragmentation = 1

A continuation or nonfinal frame requested unsupported fragmentation.

Utf8

Utf8 = 2

Text or a Close reason was not UTF-8.

MessageLimit

MessageLimit = 3

A data payload exceeded the message policy.

BufferCapacity

BufferCapacity = 4

A legal data payload exceeded caller storage.

CloseLimit

CloseLimit = 5

A close-handshake aggregate budget was exhausted.

Truncated

Truncated = 6

The byte stream ended before a complete required frame.

Transport

Transport = 7

Buffered or terminal transport I/O failed.

WebSocketError

pub union WebSocketError

A typed WebSocket admission, frame, lifecycle, or transport failure.

InvalidLimits

WebSocketError.InvalidLimits { kind: LimitKind }: WebSocketError

Session construction rejected a zero finite limit.

Field kind

pub kind: LimitKind

The invalid public limit.

InvalidState

WebSocketError.InvalidState { operation: Operation, state: State }: WebSocketError

The operation is not available in the current lifecycle state.

Field operation

pub operation: Operation

The rejected operation.

Field state

pub state: State

The state that rejected the operation.

PreviousFailure

WebSocketError.PreviousFailure { failure: Failure }: WebSocketError

A preceding terminal failure prevents more frame I/O.

Field failure

pub failure: Failure

The retained copyable classification of the first failure.

BufferTooSmall

WebSocketError.BufferTooSmall { required: usize, capacity: usize }: WebSocketError

Caller storage cannot hold one otherwise legal complete data payload.

Field required

pub required: usize

The complete required payload capacity.

Field capacity

pub capacity: usize

The supplied output capacity.

MessageTooLarge

WebSocketError.MessageTooLarge { length: u64, allowed: usize }: WebSocketError

A peer or caller data payload exceeds the message policy.

Field length

pub length: u64

The rejected payload length before narrowing.

Field allowed

pub allowed: usize

The configured message-byte limit.

UnsupportedFragmentation

WebSocketError.UnsupportedFragmentation: WebSocketError

The frame requests continuation or fragmentation outside this profile.

ProtocolError

WebSocketError.ProtocolError { reason: ProtocolReason }: WebSocketError

Peer framing violates one exact RFC 6455 protocol rule.

Field reason

pub reason: ProtocolReason

The rule that rejected the frame.

InvalidCloseData

WebSocketError.InvalidCloseData { reason: CloseDataReason }: WebSocketError

Caller-supplied Close metadata is not valid for server output.

Field reason

pub reason: CloseDataReason

The rejected caller-data rule.

InvalidUtf8

WebSocketError.InvalidUtf8 { component: Utf8Component }: WebSocketError

A complete peer or caller text value is not UTF-8.

Field component

pub component: Utf8Component

The text value that failed validation.

CloseLimitExceeded

WebSocketError.CloseLimitExceeded { kind: CloseLimitKind, allowed: usize }: WebSocketError

One aggregate close-handshake budget is exhausted.

Field kind

pub kind: CloseLimitKind

The exhausted budget.

Field allowed

pub allowed: usize

The configured inclusive maximum.

Truncated

WebSocketError.Truncated: WebSocketError

The byte stream ended before a complete required frame.

Buffer

WebSocketError.Buffer { operation: Operation, frameAccepted: usize, error: BufferError }: WebSocketError

Buffered frame I/O failed with exact accepted-prefix coordinates.

Field operation

pub operation: Operation

The frame operation that failed.

Field frameAccepted

pub frameAccepted: usize

Bytes accepted from the complete frame before this buffered failure.

Field error

pub error: BufferError

The original buffered failure.

Transport

WebSocketError.Transport { operation: Operation, error: ByteIoError }: WebSocketError

Terminal channel close failed after one frame operation.

Field operation

pub operation: Operation

The frame operation that required terminal close.

Field error

pub error: ByteIoError

The original byte-I/O failure.

ControlPayload

pub struct ControlPayload

An owned Ping or Pong payload with at most 125 bytes.

Method ControlPayload.asSlice

pub fn asSlice<'payload>(self: &'payload ControlPayload) -> &'payload [u8]

Borrows the complete copied control payload.

CloseReason

pub struct CloseReason

An owned validated Close reason with at most 123 UTF-8 bytes.

Method CloseReason.asSlice

pub fn asSlice<'reason>(self: &'reason CloseReason) -> &'reason [u8]

Borrows the complete copied UTF-8 reason bytes.

CloseData

pub struct CloseData

Owned validated status and reason data for one server Close frame.

Associated function CloseData.make

pub fn make<'life0>(code: u16, reason: &'life0 [u8]) -> silk/result.Result<silk/websocket_server.CloseData, silk/websocket_server.WebSocketError>

Validates and copies one server Close status and UTF-8 reason.

Details

The operation rejects client-only code 1010, other disallowed codes, reasons above 123 bytes, and invalid UTF-8 before it publishes owned data.

Method CloseData.code

pub fn code<'life0>(self: &'life0 CloseData) -> u16

Returns the validated status code.

Method CloseData.reason

pub fn reason<'data>(self: &'data CloseData) -> &'data silk/websocket_server.CloseReason

Borrows the owned validated reason.

PeerCloseData

pub union PeerCloseData

Owned peer Close metadata without a synthetic no-status code.

Absent

PeerCloseData.Absent: PeerCloseData

The peer sent an empty Close payload.

Present

PeerCloseData.Present { code: u16, reason: CloseReason }: PeerCloseData

The peer sent one validated status and reason.

Field code

pub code: u16

The exact peer status code.

Field reason

pub reason: CloseReason

The copied validated peer reason.

Event

pub union Event

One completely validated peer frame event.

Text

Event.Text { count: usize }: Event

The caller output prefix contains one valid UTF-8 Text payload.

Field count

pub count: usize

The initialized payload prefix length.

Binary

Event.Binary { count: usize }: Event

The caller output prefix contains one Binary payload.

Field count

pub count: usize

The initialized payload prefix length.

Ping

Event.Ping { payload: ControlPayload }: Event

One Ping payload was copied after its automatic Pong flushed.

Field payload

pub payload: ControlPayload

The copied Ping payload.

Pong

Event.Pong { payload: ControlPayload }: Event

One Pong payload was copied without a hidden follow-up read.

Field payload

pub payload: ControlPayload

The copied Pong payload.

PeerClose

Event.PeerClose { data: PeerCloseData }: Event

The peer Close reply and terminal channel close completed.

Field data

pub data: PeerCloseData

The exact copied peer Close metadata.

ServerWebSocket

pub struct ServerWebSocket<'channel, 'transport, P>

One callback-scoped affine server WebSocket over the upgraded buffered channel.

Details

Callers receive this value only through withServer. A returned event never retains a mutable borrow into this value.

state

pub fn state<'channel, 'transport, P, 'life3>(socket: &'life3 silk/websocket_server.ServerWebSocket<'channel, 'transport, P>) -> State

Returns the current public lifecycle state without performing I/O.

readEvent

pub effect<'env> fn readEvent<'channel: 'env, 'transport: 'env, P: 'env, 'life3: 'env, 'life4: 'env, 'env>(socket: &'life3 mut silk/websocket_server.ServerWebSocket<'channel, 'transport, P>, output: &'life4 mut [u8], deadline: silk/option.Option<silk/system_clock.Instant>) -> Event ! WebSocketError ? &mut MonotonicClock where &mut P provides &ByteDuplex from &mut ByteDuplex, &mut P provides &ByteDuplex from &mut ByteDuplex | &mut MonotonicClock

Reads and validates exactly one peer event.

Details

Text and Binary bytes are written directly into output. If this operation fails after it modifies a prefix, that prefix is unusable. Ping is published only after its identical Pong response flushes. Pong is returned without a hidden follow-up read.

Gotchas

A legal data payload that exceeds output closes the session and returns BufferTooSmall without reading the payload. Fragmented messages are not supported.

writeText

pub effect<'env> fn writeText<'message: 'env, 'channel: 'env, 'transport: 'env, P: 'env, 'life4: 'env, 'env>(socket: &'life4 mut silk/websocket_server.ServerWebSocket<'channel, 'transport, P>, message: string<'message>, deadline: silk/option.Option<silk/system_clock.Instant>) -> () ! WebSocketError ? &mut MonotonicClock where &mut P provides &ByteDuplex from &mut ByteDuplex, &mut P provides &ByteDuplex from &mut ByteDuplex | &mut MonotonicClock

Writes and flushes one final unmasked Text frame.

writeBinary

pub effect<'env> fn writeBinary<'message: 'env, 'channel: 'env, 'transport: 'env, P: 'env, 'life4: 'env, 'env>(socket: &'life4 mut silk/websocket_server.ServerWebSocket<'channel, 'transport, P>, message: &'message [u8], deadline: silk/option.Option<silk/system_clock.Instant>) -> () ! WebSocketError ? &mut MonotonicClock where &mut P provides &ByteDuplex from &mut ByteDuplex, &mut P provides &ByteDuplex from &mut ByteDuplex | &mut MonotonicClock

Writes and flushes one final unmasked Binary frame.

writePing

pub effect<'env> fn writePing<'message: 'env, 'channel: 'env, 'transport: 'env, P: 'env, 'life4: 'env, 'env>(socket: &'life4 mut silk/websocket_server.ServerWebSocket<'channel, 'transport, P>, message: &'message [u8], deadline: silk/option.Option<silk/system_clock.Instant>) -> () ! WebSocketError ? &mut MonotonicClock where &mut P provides &ByteDuplex from &mut ByteDuplex, &mut P provides &ByteDuplex from &mut ByteDuplex | &mut MonotonicClock

Writes and flushes one final unmasked Ping frame with at most 125 payload bytes.

writePong

pub effect<'env> fn writePong<'message: 'env, 'channel: 'env, 'transport: 'env, P: 'env, 'life4: 'env, 'env>(socket: &'life4 mut silk/websocket_server.ServerWebSocket<'channel, 'transport, P>, message: &'message [u8], deadline: silk/option.Option<silk/system_clock.Instant>) -> () ! WebSocketError ? &mut MonotonicClock where &mut P provides &ByteDuplex from &mut ByteDuplex, &mut P provides &ByteDuplex from &mut ByteDuplex | &mut MonotonicClock

Writes and flushes one final unmasked Pong frame with at most 125 payload bytes.

sendClose

pub effect<'env> fn sendClose<'close: 'env, 'channel: 'env, 'transport: 'env, P: 'env, 'life4: 'env, 'env>(socket: &'life4 mut silk/websocket_server.ServerWebSocket<'channel, 'transport, P>, data: silk/option.Option<&'close silk/websocket_server.CloseData>, deadline: silk/option.Option<silk/system_clock.Instant>) -> () ! WebSocketError ? &mut MonotonicClock where &mut P provides &ByteDuplex from &mut ByteDuplex, &mut P provides &ByteDuplex from &mut ByteDuplex | &mut MonotonicClock

Sends and flushes the local Close frame once.

Details

Open sends the supplied validated status and reason, or an empty payload for None, then enters CloseSent. Repeated calls in CloseSent or Closed succeed locally without inspecting data or writing another byte.

finishClose

pub effect<'env> fn finishClose<'channel: 'env, 'transport: 'env, P: 'env, 'life3: 'env, 'env>(socket: &'life3 mut silk/websocket_server.ServerWebSocket<'channel, 'transport, P>, deadline: Instant) -> () ! WebSocketError ? &mut MonotonicClock where &mut P provides &ByteDuplex from &mut ByteDuplex, &mut P provides &ByteDuplex from &mut ByteDuplex | &mut MonotonicClock

Pumps a bounded peer close handshake until a valid peer Close arrives.

Details

The caller supplies one absolute deadline. The same mark is passed unchanged to every partial read, automatic Pong write, and flush and is checked before the first frame and between frames. Data frames are validated and discarded without publication; controls remain observable only through their required protocol effects.

Gotchas

This operation is available only after sendClose. Both configured aggregate limits include complete inbound wire bytes: header, extended length, mask, and payload.

withServer

pub effect<'env> fn withServer<'callback: 'env, 'channel: 'env, 'transport: 'channel + 'env, A, E, ?R, P: 'env, 'env>(channel: &'channel mut silk/buffered_duplex.BufferedDuplex<'transport, P>, limits: Limits, use: for<'call, 'channelView: 'call, 'transportView: 'channelView> once fn<'callback>(&'call mut silk/websocket_server.ServerWebSocket<'channelView, 'transportView, P>) -> once Effect<'call; A ! E ? R>) -> A ! E | WebSocketError ? R | &mut MonotonicClock where &mut P provides &ByteDuplex from &mut ByteDuplex, &mut P provides &ByteDuplex from &mut ByteDuplex | &mut MonotonicClock, R in Without<R, &ByteDuplex>

Lends one affine server WebSocket over the exact upgraded buffered channel.

Details

Positive limits are validated before the session performs I/O. The higher-ranked callback cannot retain the session or a channel view. Terminal release runs after callback success, typed failure, or structured cancellation and never replaces the protected outcome.

On this page

When to useDetailsGotchasLimitsField maxMessageBytesField maxCloseFramesField maxCloseBytesAssociated function Limits.defaultsAssociated function Limits.makeImplementation Copy for LimitsLimitKindMessageBytesCloseFramesCloseBytesArithmeticStateOpenCloseSentClosedFailedOperationReadEventWriteTextWriteBinaryWritePingWritePongSendCloseFinishCloseProtocolReasonMaskRequiredRsvReservedOpcodeNonMinimalLengthLengthHighBitControlTooLargeControlFragmentedClosePayloadLengthCloseCodeUtf8ComponentTextCloseReasonCloseDataReasonCodeReasonTooLargeCloseLimitKindFramesBytesFailureProtocolFragmentationUtf8MessageLimitBufferCapacityCloseLimitTruncatedTransportWebSocketErrorInvalidLimitsField kindInvalidStateField operationField statePreviousFailureField failureBufferTooSmallField requiredField capacityMessageTooLargeField lengthField allowedUnsupportedFragmentationProtocolErrorField reasonInvalidCloseDataField reasonInvalidUtf8Field componentCloseLimitExceededField kindField allowedTruncatedBufferField operationField frameAcceptedField errorTransportField operationField errorControlPayloadMethod ControlPayload.asSliceCloseReasonMethod CloseReason.asSliceCloseDataAssociated function CloseData.makeDetailsMethod CloseData.codeMethod CloseData.reasonPeerCloseDataAbsentPresentField codeField reasonEventTextField countBinaryField countPingField payloadPongField payloadPeerCloseField dataServerWebSocketDetailsstatereadEventDetailsGotchaswriteTextwriteBinarywritePingwritePongsendCloseDetailsfinishCloseDetailsGotchaswithServerDetails