abla/websocket/server

Generated from source.

Import with import "abla/websocket/server".

Source: abla/websocket/server/entry.ab

WebSocketServerOptions (class)

class WebSocketServerOptions(
    val maximumConnections: int = 4096,
    val maximumHeaderBytes: int = 16384,
    val maximumBodyBytes: int = 65536,
    val maximumMessageBytes: int = 1048576,
    val maximumPendingBytes: int = 4194304,
    val pingIntervalMilliseconds: int = 15000,
    val idleTimeoutMilliseconds: int = 45000,
    val handshakeTimeoutMilliseconds: int = 10000,
    val closeTimeoutMilliseconds: int = 2000,
    val drainTimeoutMilliseconds: int = 5000,
    // When true an upgrade request is surfaced as a request event and stays
    // pending until `accept` or `reject`, which permits asynchronous token or
    // ticket verification; a successful `accept` opens the connection
    // synchronously and no open event follows. Otherwise upgrades are accepted
    // immediately and surfaced as open events.
    val manualAdmission: bool = false,
    val readChunkBytes: int = 65536, // at most 65536
    val backlog: int = 1024,
    val reusePort: bool = false,
    val noDelay: bool = true,
    // Serve TLS on this port (`webSocketServerTls` in
    // `abla/websocket/server/tls`); null serves plain TCP.
    val tls: WebSocketServerTls? = null
)

Sets limits for connections, framing, pending output, and WebSocket lifecycle deadlines.

WebSocketServerTls (class)

class WebSocketServerTls(
    val context: int,
    val error: string,
    val handshakeTimeoutMilliseconds: int,
    val start: (int, int) -> int,
    val handshake: (int) -> int,
    val read: (int, var: SocketReceiveResult) -> void,
    val write: (int, string, int) -> int,
    val pending: (int) -> bool,
    val free: (int, bool) -> void,
    val retain: (int) -> bool,
    val release: (int) -> void
)

A TLS configuration ID and the nonblocking callbacks that drive its sessions. abla/websocket/server/tls creates the configuration from a certificate chain and key and sets error to "" on success. Sessions use integer handles. handshake returns 1 when done; handshake, read and write report a pending operation as webSocketServerTlsWantsRead or webSocketServerTlsWantsWrite, and failure as another negative value.

webSocketServerTlsWantsRead (val)

val webSocketServerTlsWantsRead

Sentinel indicating that a TLS operation must wait for the socket to become readable.

webSocketServerTlsWantsWrite (val)

val webSocketServerTlsWantsWrite

Sentinel indicating that a TLS operation must wait for the socket to become writable.

WebSocketServerEvent (class)

class WebSocketServerEvent(
    val kind: int,
    val id: int,
    val binary: bool,
    val payload: string,
    val request: HttpRequest?,
    val code: int,
    val reason: string
)

Holds a connection identifier and the request, message, or closure data for one server event.

WebSocketServerEvent.isRequest (method)

fun isRequest(): bool

Returns true for an upgrade request awaiting an admission decision.

WebSocketServerEvent.isOpen (method)

fun isOpen(): bool

Returns true for an event announcing an open WebSocket connection.

WebSocketServerEvent.isMessage (method)

fun isMessage(): bool

Returns true for an event containing a WebSocket message.

WebSocketServerEvent.isClose (method)

fun isClose(): bool

Returns true for an event announcing a closed WebSocket connection.

WebSocketServerEvent.isHttp (method)

fun isHttp(): bool

Returns true for a regular HTTP request event.

WebSocketServerEvent.path (extension fun)

fun WebSocketServerEvent.path(): string

Returns the request path or empty text if this event has no request.

WebSocketServerEvent.method (extension fun)

fun WebSocketServerEvent.method(): string

Returns the HTTP method or empty text if this event has no request.

WebSocketServerEvent.header (extension fun)

fun WebSocketServerEvent.header(name: string): string

Returns the named request header or empty text if absent.

WebSocketServerEvent.query (extension fun)

fun WebSocketServerEvent.query(name: string): string

Returns the percent-decoded query parameter or empty text if absent.

WebSocketServerEvent.body (extension fun)

fun WebSocketServerEvent.body(): string

Returns the request body or empty text if this event has no request.

WebSocketServerStats (class)

class WebSocketServerStats(
    var accepted: int,
    var rejected: int,
    var released: int,
    var messagesIn: int,
    var bytesIn: int,
    var framesOut: int,
    var bytesOut: int,
    var writeCalls: int,
    var backpressureCloses: int,
    var timeouts: int,
    // TLS handshakes that failed or timed out; each closed only its socket.
    var tlsHandshakeFailures: int = 0
)

Counts accepted, rejected, released, and processed WebSocket traffic and failures.

WebSocketServer (class)

resource class WebSocketServer(
    val listener: TcpListener,
    val poller: SocketPoller,
    val options: WebSocketServerOptions,
    val reader: SocketReceiveResult,
    val readCapacity: int,
    val slotsByDescriptor: array<int>,
    val descriptors: array<int>,
    val ids: array<int>,
    val states: array<int>,
    val inputs: array<string>,
    val outputs: array<string>,
    val outputOffsets: array<int>,
    val writeWatching: array<bool>,
    val dirty: array<bool>,
    val acceptKeys: array<string>,
    val fragmentOpcodes: array<int>,
    val fragmentPayloads: array<string>,
    val lastReceived: array<int>,
    val lastPinged: array<int>,
    val deadlines: array<int>,
    val surfaced: array<bool>,
    val closeCodes: array<int>,
    val closeReasons: array<string>,
    val peerClosed: array<bool>,
    val freeSlots: array<int>,
    var freeCount: int,
    val dirtySlots: array<int>,
    var dirtyCount: int,
    var events: array<WebSocketServerEvent>,
    var activeCount: int,
    var openConnections: int,
    var nextSerial: int,
    var lastSweepMilliseconds: int,
    var draining: bool,
    var drainDeadlineMilliseconds: int,
    var stopped: bool,
    var externalWakeups: int,
    val stats: WebSocketServerStats,
    val tls: WebSocketServerTls?,
    val tlsSessions: array<int>,
    val tlsHandshaking: array<bool>,
    val tlsFlags: array<int>,
    // Reads that cannot complete the frame being received wait in `tails[slot]`, unjoined, until `needs[slot]` bytes are held:
    // joining the whole buffer on every read made a large frame sent in small pieces cost time growing with the square of its size.
    val needs: array<int> = [],
    val tails: array<ByteBuffer> = []
)

Owns the listener, poller, TLS sessions, and state for each connection slot.

WebSocketServer.drop (method)

fun drop(): void

Frees TLS sessions and closes remaining client descriptors when the server is released.

webSocketServer (fun)

fun webSocketServer(
    address: Ipv4SocketAddress,
    options: WebSocketServerOptions = WebSocketServerOptions()
): WebSocketServer

Creates a WebSocket event server at IPv4 address with the supplied options, including backlog and port sharing. The returned server carries listener and poller state.

webSocketServerIpv6 (fun)

fun webSocketServerIpv6(
    address: Ipv6SocketAddress,
    options: WebSocketServerOptions = WebSocketServerOptions(),
    dualStack: bool = true
): WebSocketServer

Returns a server listening on the IPv6 address, with an invalid listener if setup fails.

webSocketServerReceive (fun)

fun webSocketServerReceive(
    descriptor: int,
    capacity: int,
    var result: SocketReceiveResult
): void

Reads once from a descriptor into the reusable result (linuxTcpReceiveDescriptor): status holds the byte count, zero at EOF or a negative errno (-11 when the socket would block).

webSocketServerJoin (fun)

trusted fun webSocketServerJoin(
    left: string,
    leftBegin: int,
    right: string
): string

Copies left[leftBegin..] followed by right into one flat string. Input buffers are kept contiguous rather than as concatenation ropes, so frame parsing indexes plain storage and a carried-over partial frame is copied exactly once.

webSocketServerUnmask (fun)

trusted fun webSocketServerUnmask(
    input: string,
    keyOffset: int,
    begin: int,
    length: int
): string

Unmasks length payload bytes starting at begin with the four-byte key stored at keyOffset, eight bytes per step.

webSocketServerFrameHeader (fun)

trusted fun webSocketServerFrameHeader(opcode: int, length: int): string

Builds the unmasked server frame header for a final frame.

WebSocketServer.slotOf (extension fun)

fun WebSocketServer.slotOf(id: int): int

Returns the active slot for a current connection identifier, or -1 for an unknown or stale identifier.

WebSocketServer.allocateSlot (extension fun)

fun WebSocketServer.allocateSlot(descriptor: int, now: int): int

Initializes and returns a slot for the accepted descriptor, or -1 if the server cannot admit it.

WebSocketServer.release (extension fun)

fun WebSocketServer.release(slot: int, code: int, reason: string): void

Releases the socket and slot. A connection the application has seen gets exactly one close event, whichever side or timer ended it.

WebSocketServer.markDirty (extension fun)

fun WebSocketServer.markDirty(slot: int): void

Schedules an active slot for output processing unless it is already scheduled.

WebSocketServer.enqueue (extension fun)

fun WebSocketServer.enqueue(slot: int, bytes: string): bool

Queues bytes for a valid slot and returns false if the pending-byte limit would be exceeded.

WebSocketServer.writeSlot (extension fun)

fun WebSocketServer.writeSlot(slot: int): void

Attempts to send the queued bytes and updates the slot when the socket blocks or fails.

WebSocketServer.flush (extension fun)

fun WebSocketServer.flush(): void

Writes every connection with queued frames. Called by step; call it directly after a simulation tick to put snapshots on the wire immediately.

WebSocketServer.startClose (extension fun)

fun WebSocketServer.startClose(slot: int, code: int, reason: string): void

Starts the close handshake for an open slot with the supplied close code and reason.

WebSocketServer.finishWithResponse (extension fun)

fun WebSocketServer.finishWithResponse(slot: int, response: string): void

Queues a final HTTP response and schedules the connection to close.

WebSocketServer.deliver (extension fun)

fun WebSocketServer.deliver(slot: int, opcode: int, payload: string): void

Emits a message event for an open connection or starts closing if a text payload contains invalid UTF-8.

WebSocketServer.processFrames (extension fun)

fun WebSocketServer.processFrames(slot: int, data: string, begin: int): int

Parses complete client frames from data starting at begin and returns the first unconsumed offset.

WebSocketServer.processRequest (extension fun)

fun WebSocketServer.processRequest(slot: int, data: string): int

Processes a buffered HTTP request and returns bytes consumed, or zero while more header or body input is needed.

WebSocketServer.processInput (extension fun)

fun WebSocketServer.processInput(slot: int, data: string): int

Processes complete request or frame bytes from an active slot and returns the byte count consumed.

WebSocketServer.readSlot (extension fun)

fun WebSocketServer.readSlot(slot: int): void

Reads from the active slot and dispatches complete input, stopping on would-block or closure.

WebSocketServer.tlsStart (extension fun)

fun WebSocketServer.tlsStart(slot: int): void

Starts TLS for the connection and releases the slot if the TLS adapter cannot create a session.

WebSocketServer.tlsSyncInterest (extension fun)

fun WebSocketServer.tlsSyncInterest(slot: int): void

Updates the poller interests required by the slot's pending TLS operations.

WebSocketServer.tlsHandshake (extension fun)

fun WebSocketServer.tlsHandshake(slot: int): void

Advances the TLS handshake or releases the slot if the adapter reports a fatal error.

WebSocketServer.tlsReceive (extension fun)

fun WebSocketServer.tlsReceive(slot: int, session: int): void

Reads one record into reader with the plain status convention: bytes, 0 at a close, -11 while nothing is readable, another negative on failure.

WebSocketServer.tlsPending (extension fun)

fun WebSocketServer.tlsPending(slot: int): bool

Returns true if the TLS adapter already has decrypted input ready for the slot.

WebSocketServer.tlsWriteSlot (extension fun)

fun WebSocketServer.tlsWriteSlot(slot: int): void

Writes queued output a record at a time until it is all written or TLS must wait; the completion bookkeeping matches writeSlot.

WebSocketServer.tlsReady (extension fun)

fun WebSocketServer.tlsReady(slot: int, readable: bool, writable: bool): void

Advances handshakes or application I/O according to the socket readiness flags.

WebSocketServer.acceptReady (extension fun)

fun WebSocketServer.acceptReady(): void

Accepts ready client descriptors until the listener drains or no more are available.

WebSocketServer.sweep (extension fun)

fun WebSocketServer.sweep(now: int): void

Processes expired timeouts, pending close deadlines, and scheduled pings.

WebSocketServer.step (extension fun)

fun WebSocketServer.step(timeoutMilliseconds: int = 0): int

Polls once for up to timeoutMilliseconds, processes readiness, runs the heartbeat/timeout sweep, and flushes queued output. Returns the number of readiness records handled. Pass 0 for a non-blocking poll.

WebSocketServer.takeEvents (extension fun)

fun WebSocketServer.takeEvents(): array<WebSocketServerEvent>

Returns and clears the queued events.

WebSocketServer.pendingEvents (extension fun)

fun WebSocketServer.pendingEvents(): int

Returns the number of queued application events.

WebSocketServer.admit (extension fun)

fun WebSocketServer.admit(slot: int): void

Accepts the pending upgrade at a valid slot and queues the switching-protocols response.

WebSocketServer.accept (extension fun)

fun WebSocketServer.accept(id: int): bool

Completes a pending upgrade (manual admission). Frames the client sent early are processed immediately.

WebSocketServer.reject (extension fun)

fun WebSocketServer.reject(id: int, status: int = 403, body: string = ""): bool

Refuses a pending upgrade or plain HTTP request with a status and body.

WebSocketServer.respond (extension fun)

fun WebSocketServer.respond(id: int, response: HttpResponse): bool

Answers a plain HTTP request event; the connection closes afterwards.

webSocketServerEncode (fun)

fun webSocketServerEncode(payload: string, binary: bool = false): string

Encodes one final unmasked frame. Reuse the result with sendEncoded or broadcastEncoded to frame a shared payload only once.

WebSocketServer.sendEncoded (extension fun)

fun WebSocketServer.sendEncoded(id: int, frame: string): bool

Queues an encoded frame and returns false if the connection is closed, unknown, or over its pending-byte limit.

WebSocketServer.send (extension fun)

fun WebSocketServer.send(id: int, payload: string, binary: bool = false): bool

Queues a text or binary frame and returns false if the connection is closed, unknown, or over its pending-byte limit.

WebSocketServer.sendText (extension fun)

fun WebSocketServer.sendText(id: int, payload: string): bool

Queues a text frame and returns false if the connection cannot accept it.

WebSocketServer.sendBinary (extension fun)

fun WebSocketServer.sendBinary(id: int, payload: string): bool

Queues a binary frame and returns false if the connection cannot accept it.

WebSocketServer.ping (extension fun)

fun WebSocketServer.ping(id: int, payload: string = ""): bool

Queues a ping and returns false if the connection cannot accept it or the payload exceeds 125 bytes.

WebSocketServer.broadcastEncoded (extension fun)

fun WebSocketServer.broadcastEncoded(frame: string): int

Queues a pre-encoded frame to every open connection; returns the number of connections that accepted it.

WebSocketServer.broadcast (extension fun)

fun WebSocketServer.broadcast(payload: string, binary: bool = false): int

Queues a text or binary message for every open connection and returns the number that accepted it.

WebSocketServer.close (extension fun)

fun WebSocketServer.close(id: int, code: int = 1000, reason: string = ""): bool

Starts the closing handshake. The close event follows once the peer answers or closeTimeoutMilliseconds elapses.

WebSocketServer.terminate (extension fun)

fun WebSocketServer.terminate(id: int, code: int = 1006, reason: string = ""): bool

Drops the socket immediately without a closing handshake.

WebSocketServer.isOpen (extension fun)

fun WebSocketServer.isOpen(id: int): bool

Returns true when the current connection identifier names an open WebSocket.

WebSocketServer.bufferedAmount (extension fun)

fun WebSocketServer.bufferedAmount(id: int): int

Bytes queued but not yet accepted by the kernel for this connection.

WebSocketServer.watchExternal (extension fun)

fun WebSocketServer.watchExternal(descriptor: int): bool

Adds another readiness source (for example an HttpAsyncClient poller) so a blocking step returns as soon as it has work. The server never reads it; the owner drives it after step returns.

WebSocketServer.unwatchExternal (extension fun)

fun WebSocketServer.unwatchExternal(descriptor: int): bool

Returns true if an external descriptor is successfully removed from the poller.

WebSocketServer.connectionCount (extension fun)

fun WebSocketServer.connectionCount(): int

Returns the number of active connection slots.

WebSocketServer.openCount (extension fun)

fun WebSocketServer.openCount(): int

Returns the number of admitted WebSocket connections that are still open.

WebSocketServer.localPort (extension fun)

fun WebSocketServer.localPort(): int

Returns the listener's bound port, or -1 if the lookup fails.

WebSocketServer.enableGracefulShutdown (extension fun)

fun WebSocketServer.enableGracefulShutdown(): bool

Returns true if the host installs TCP graceful-shutdown handling.

WebSocketServer.shutdownRequested (extension fun)

fun WebSocketServer.shutdownRequested(): bool

Returns true if the server is stopped or the host has requested TCP shutdown.

WebSocketServer.beginDrain (extension fun)

fun WebSocketServer.beginDrain(): void

Stops accepting new clients and starts the deadline for closing existing connections.

WebSocketServer.stop (extension fun)

fun WebSocketServer.stop(): void

Starts graceful draining of existing connections.

WebSocketServer.forceStop (extension fun)

fun WebSocketServer.forceStop(): void

Releases all active connection slots and stops the server.

WebSocketServer.drain (extension fun)

fun WebSocketServer.drain(): int

Sends 1001 close frames, waits up to drainTimeoutMilliseconds for peers to finish, then force-closes stragglers.

WebSocketServer.stopNow (extension fun)

fun WebSocketServer.stopNow(): void

Stops the server immediately and releases active connections.

Built from Abla v0.2.79 source ba5d6b7d. Examples and generated signatures follow that source revision.