# Kokum ABI 1.12: persistent WebSocket service and client flow control

This is the implemented contract for the official native transport additions.
The listener, sockets, protocol parser, queues and byte limits live in Kokum's
native runtime. Kokum application code owns authentication and relay policy.
These APIs do not implement an Infinetus delivery protocol or certify a deployed
service. Existing `WSCLIENT`, its C specification layout and its default event
queue mode remain available.

## Execution and ownership

`WSSERVER` creates one runtime-owned resource and one native, nonblocking socket
reactor. The reactor never evaluates Kokum code or constructs Kokum values. The
creating runtime owner consumes events and authorizes connections through the
public builtins. A resource cannot be used from another runtime or an execution
context other than the currently entered context. Closing/releasing the resource
stops and joins its reactor and frees its native queues and sockets.

For a single server `.kapp` that also serves HTTP accounts, configure the headless
host's `service_startup_handler`, `service_tick_handler`,
`service_shutdown_handler` and `service_tick_ms`. Create the listener in startup,
keep its handle in that service VM's state, consume a bounded number of
`WSNEXT(server, 0)` events per tick, and call `WSCLOSE(server)` during shutdown.
Declare the event variable as `LOCAL event` (untyped), because `WSNEXT` can
return either a MAP or `NULL`; a `LOCAL event AS MAP` assignment rejects `NULL`.
These hooks execute on one dedicated service VM/thread. HTTP workers retain their
separate contexts and normal account routes. A `PUBLIC` variable in an HTTP
worker is not a shared relay registry. An ordinary console `Main` may also own a
server and poll it explicitly.

Socket I/O is nonblocking and bounded per reactor turn. The owner must still use
small message chunks, bounded tick work and bounded database queries. Large
Kokum arrays take time and heap space to construct. Slow peers do not occupy the
HTTP worker pool.

## Public functions

Names and option keys are case-insensitive. Unknown/duplicate option keys,
wrong types and values outside their ranges raise typed runtime errors. The
success value of an operation described below as `LOGICAL` is `.T.`; errors,
including queue pressure and stale connection IDs, must be handled with `TRY` /
`CATCH`. A peer may disconnect between a request event and authorization.

| Function | Result and meaning |
| --- | --- |
| `WSSERVER(options)` | Native server resource, usable in an untyped local or `ANY`; binds IPv4 loopback only. |
| `WSNEXT(server [, timeoutMs])` | Next event MAP, or `NULL` if none is available. Default wait is zero; permitted waits are 0–60000 ms. |
| `WSAUTHORIZE(server, id, identity, expiresAtMs [, subprotocol])` | Authorize a pending request before HTTP 101. Also renew an unexpired open connection with exactly the same identity and protocol. |
| `WSREJECT(server, id [, status])` | Reject a pending request with a metadata-only HTTP JSON response. Default 401; permitted explicit statuses: 400, 401, 403, 404, 429. |
| `WSSEND(server, id, bytes)` | Queue one binary message, an ARRAY of INTEGER octets 0–255. The complete input is validated before queuing. |
| `WSSENDTEXT(server, id, text)` | Queue one UTF-8 text message. Embedded NUL is preserved through counted-string APIs. |
| `WSCLOSE(server [, id [, code [, reason]]])` | With one argument, close the server resource. With an ID, start that connection's close handshake; default code 1000, empty reason. |
| `WSREVOKE(server, identity)` | INTEGER count of active/upgrading connections closed for that exact identity. Uses close code 1008 for open connections. |
| `WSINFO(server [, id])` | Global counters/limits, or state of one still-retained connection. No credentials or message payloads. |
| `WSFLOWCONTROL(client, receiveBytes, sendBytes [, reliable])` | Enable explicit byte budgets on a new disconnected `WSCLIENT` before its first `Connect`. Reliable defaults to `.T.`. |

A connection ID is a positive, monotonically allocated INTEGER local to its
server resource. It is not an account identifier, a secret, or a persistent post
identifier. A closed connection's native slot is retained until its terminal
notification can be queued, then may be reused under a new ID. `WSINFO(server,
id)` can therefore raise `KSV6005` after disconnect.

`identity` is a nonempty, valid UTF-8 string of at most 128 bytes with no embedded
NUL. Derive it from a verified session/account/device record. Do not copy an
identity claim from a subsequent message into this field. An application may
bind a canonical account/device/session key and keep associated metadata in its
service-owned registry. `WSREVOKE` performs exact equality, not prefix matching;
account-wide revocation of composite identities must enumerate the account's
active identities.

`expiresAtMs` is an INTEGER Unix timestamp in milliseconds. Every event's
`Timestamp` uses the same wall-clock unit. A short development lease can use
`request["Timestamp"] + 30000`, but production authorization must be capped by
the validated session's actual expiry. The native service rejects past or
excessively long leases, retains a monotonic deadline as well as wall-clock
expiry, checks expiry during frame processing and sending, and closes expired
connections with code 1008. Renewal cannot change identity or revive an expired
lease.

The optional chosen subprotocol must have been offered by the client. If the
listener requires a subprotocol, authorization must select that exact protocol;
omitting the argument selects the listener's configured protocol. With no
configured protocol, the default is no negotiated subprotocol.

`WSSEND`/`WSSENDTEXT` mean **accepted into a bounded local send queue**. They do not
mean the frame reached the peer, passed cryptographic checks, or was committed
to recipient SQLite. Application receipts, duplicate detection and retry/resume
state remain necessary. Closing, expiry, revocation or process shutdown can
cancel unsent frames. Expected `KSV6005` and `KSV6007` failures belong in the
service loop's exception handling, so a single peer's churn does not become an
uncaught service failure.

## Listener options

| Option | Default | Allowed range / meaning |
| --- | --- | --- |
| `Port` | 0 | 0–65535; zero requests an ephemeral port, returned by `WSINFO`. Production normally uses a fixed configured port. |
| `Path` | `/relay` | Exact request path, at most 256 bytes, starting `/`; query/fragment markers and whitespace are forbidden. |
| `Origin` | empty | If nonempty, require exact equality with the request Origin; at most 1024 bytes. |
| `Subprotocol` | empty | Required RFC token, at most 128 bytes; empty means no requirement. |
| `MaxConnections` | 32 | 1–64; bounds accepted sockets and pending handshakes. |
| `MaxEvents` | 128 | 1–4096; global queued events and per-connection queued send records. |
| `MaxMessageBytes` | 65536 | 1–16777216; bounds each data frame and the full fragmented data message. |
| `MaxConnectionBytes` | 1048576 | 16384–67108864; native input, fragment, pending-header and send allocations for a connection. |
| `MaxBufferedBytes` | 8388608 | 65536–268435456; shared native server/connection structures, all owned buffers and queued events/sends. |
| `HandshakeTimeoutMs` | 5000 | 100–30000; includes waiting for the application to authorize. |
| `IdleTimeoutMs` | 60000 | 100–3600000; maximum interval without incoming activity. |
| `PingIntervalMs` | 15000 | 0–3600000; zero disables periodic server pings. |
| `PingTimeoutMs` | 10000 | 100–3600000; unanswered nonce ping deadline. |
| `MaxAuthLifetimeMs` | 86400000 | 100–604800000; maximum future authorization lifetime. |

There is no wildcard bind address or public plaintext listener option. Bind is
always `127.0.0.1`. There is no compression or extension negotiation. Control
frames retain their RFC 125-byte limit even if `MaxMessageBytes` is smaller.

The constructor rejects inconsistent budgets. `MaxConnectionBytes` must cover
at least `2 * MaxMessageBytes + 8192 + 512`; the global budget must also cover the
connection workspace plus its fixed server/slot structures. Use the defaults
for a 64-KiB chunk profile unless measurements justify another configuration.
These minima permit one bounded assembly; they are not a promise that every
connection can simultaneously consume its full per-connection allowance. The
global budget is shared. Queue draining, per-account admission limits and
bounded application transfer concurrency remain necessary under contention.

## Events and authentication boundary

All events include `Event`, `ConnectionId`, `Timestamp`, `Identity` and
`ExpiresAt`. Request events have empty identity and zero expiry. Other events
snapshot the identity and lease bound to the connection at event creation.

| `Event` | Additional fields |
| --- | --- |
| `request` | `Path`, `Headers`, `RemoteAddress`. Header names are lower-case; values include the private authorization header for application validation. |
| `connected` | `Subprotocol`. Emitted after the accepted HTTP 101 response has been written. |
| `binary` | `Data` as ARRAY of INTEGER octets, and integer `Size`. |
| `text` | `Data` as a counted STRING, and integer UTF-8 byte `Size`. |
| `error` | `Code`, `Reason`; metadata-only terminal protocol/auth/transport failure, before the corresponding `closed` event. |
| `closed` | `Code`, `Reason`, `Clean`; `Clean` indicates that the peer's close frame was received, not delivery acknowledgment. |

The native handshake accepts only GET and HTTP/1.1 at the configured exact
path. Headers are bounded to 8192 bytes, 32 fields, 64-byte names and 2048-byte
values. It validates the version, canonical 16-byte WebSocket nonce, Upgrade /
Connection requirements, tokens, configured Origin and subprotocol. Duplicate
header names and prohibited control characters are rejected. A request with
`Content-Length` (including zero), `Transfer-Encoding`, bytes following the
header terminator in the same read, or payload observed while authorization is
pending is rejected before upgrade. Authentication is not deferred to a first
WebSocket message. The application must call `WSAUTHORIZE` or `WSREJECT`.

The binary/text parser requires masked client frames, checks RSV/opcode/control
rules and canonical lengths before large allocation, enforces aggregate
fragment limits, and validates UTF-8. Ping is answered automatically. Periodic
server pings use random nonces; only their matching pong clears the deadline.
The server never constructs a Kokum event for unauthenticated message bytes.

Do not log the full request event: it intentionally contains credentials for
authentication. Native diagnostics and HTTP rejections do not echo those
credentials or message bodies. `RemoteAddress` is the loopback frontend address;
it does not assert the original user's Internet address. Treat any forwarded
address header according to the separately configured frontend trust boundary.

Events accepted before expiry or revocation remain queued until consumed.
Their identity is authentic, but their application permission may no longer be
current. Recheck sender/recipient session status, relationship/block state and
object/removal/audience policy immediately before forwarding or releasing keys.
A transport lease is not an authorization to ignore later policy changes.

## Native memory and pressure

The server uses one ledger for fixed server/connection storage, input capacity,
fragment capacity, pending HTTP headers, event metadata/payload and send
metadata/wire bytes. In-flight sends remain charged until their allocation is
freed. A completed fragmented message transfers ownership of its existing
buffer into the event queue: it does not require a third full-message copy.
Native `WSSEND` marshals validated array bytes directly into the counted send
allocation.

When event capacity is exhausted, the reactor stops accepting further data
messages and reads. Accepted events are not silently evicted. Closed slots wait
for space to report terminal events. Send admission raises `KSV6007` when count,
connection or global bytes are full; callers must wait for progress, drain
events or cancel the transfer. Idle, ping, handshake and authorization deadlines
continue to apply to stalled connections. The module does not write payloads
to a database, a temporary file or an offline mailbox.

`WSINFO(server)` exposes `Port`, `Address`, `Path`, `Connections`, `PendingEvents`,
`BufferedBytes`, `PeakBufferedBytes`, `MaxBufferedBytes`, `AcceptedConnections`,
`AuthorizedConnections`, `RejectedConnections`, `ClosedConnections`,
`ReceivedMessages`, `QueuedMessages`, `ReceivedBytes`, `QueuedBytes`,
`PressureCount` and `DroppedEvents`. `DroppedEvents` is zero: ordinary pressure
does not evict events. Send counters describe queue acceptance, not delivery.
Per-connection information includes `ConnectionId`, `State`, `Identity`,
`ExpiresAt`, `BufferedBytes` and `QueuedSendBytes`.

These byte budgets describe native owned traffic buffers and reserved working
storage. They are not a bound on process RSS. Allocator metadata, bounded native
thread stacks, OS socket buffers, OpenSSL/provider state and the application's
own Kokum values are separate. A Kokum ARRAY stores INTEGER values, so an array
of 65536 octets consumes substantially more than 65536 bytes of application
heap. Do not retain unbounded event arrays in application maps. Keep file I/O
and encryption chunk sizes bounded and release processed values promptly.

## Reliable outbound client setup

`WSCLIENT` already creates a disconnected client. Do not add an `AutoConnect`
option; that key is not part of its existing MAP contract.

```kokum
LOCAL socket AS WEBSOCKET
socket = WSCLIENT("wss://infinetus.com/relay", { ;
    "VerifyTLS": .T., ;
    "MaxMessageBytes": 65536, ;
    "QueueLimit": 128, ;
    "Subprotocols": "ksn.e2e.v1" ;
})
WSFLOWCONTROL(socket, 4194304, 1048576, .T.)
socket.SetHeader("Origin", "https://infinetus.com")
socket.SetBearerToken(validatedSessionToken)
socket.Connect()
```

The URL/path in this example must be included in the actual application's route
contract before deployment. `validatedSessionToken` is the account session
credential obtained through the application's existing secure login flow.
TLS certificate and hostname verification remain enabled.

For configured maximum message size **M** and event-count limit **Q**:

- Reserved receive working space is `8*M + 524288 + 128*Q` bytes.
- The accepted receive budget must be at least `9*M + 524289 + 128*Q` bytes.
- The accepted send budget must be at least `2*M + 64` bytes.
- Each budget must be at most 268435456 bytes.

The receive reserve is a conservative portable upper bound for geometric
receive/fragment capacities, in-progress event and last-text copies, event
descriptors, and bounded HTTP/control work. The remaining bytes bound queued
payloads. The send ledger reserves `2*payloadLength + 64` per message to cover
its queued copy, metadata and in-flight masked wire frame. It retains that
charge until the send completes or is cancelled. This makes even the transient
native frame copy part of admission accounting.

Reliable mode pauses the native reader when event count or queued bytes are
full. `Receive`, `Drain` and explicit `ClearMessages` release queued storage and
wake it. It never evicts an accepted event due to ordinary capacity pressure;
`DroppedMessages` stays zero. `Close` and finalization also wake the reader.
Explicit close cancels unsent frames and unaccepted incoming work, preserves
already queued receive events, and never emits a data frame after its close
frame. `ClearMessages` is an explicit application discard operation, not a
transport receipt.

With reliable set to `.F.`, the opted-in client still enforces byte budgets and
uses its observable oldest-event eviction behavior. Without any
`WSFLOWCONTROL` call, the previous defaults and C `KokumWebSocketSpec` layout
remain in effect.

Flow control can only be configured before the first connection attempt. Once
it is enabled, URLs are limited to 4096 bytes, subprotocol lists to 1024 bytes,
and headers/query parameters to 32 entries with 64-byte names and 2048-byte
values. URL, protocol and authentication setters reject oversized input before
allocating encoded/copy buffers. `SendBinary` validates and copies directly into
the admitted queue allocation. In this opt-in mode, `SendText`, text events and
`LastMessage` also preserve counted UTF-8 text including embedded NUL; legacy
mode retains its previous string behavior. JSON serialization of application values is a
separate caller operation; use bounded binary envelopes for media transfer.

In this mode `socket.Snapshot()` additionally returns `reliable`,
`receiveBudgetBytes`, `receiveReservedBytes`, `receiveQueuedBytes`,
`sendBudgetBytes`, `sendBufferedBytes` and `pressureWaits`. Continue observing
`DroppedMessages`; a loss indication or connection interruption requires the
application's authenticated resynchronization/receipt protocol.

## HTTPS routing and the non-storage deployment claim

Terminate verified WSS at the service's established HTTPS frontend and forward
only the exact contracted relay path to the IPv4 loopback port. Keep the
existing account routes and gateway authorization boundary intact. The relay
path must forward WebSocket Upgrade/Connection semantics; an ordinary HTTP
status check does not demonstrate a working authenticated 101 upgrade.

The native listener rejects HTTP request bodies, but frontend controls must also
prevent buffering a body before it reaches that listener. The deployment must
reject pre-upgrade request bodies at the edge, disable proxy payload buffering,
disk caching/storage and request-body capture for the relay location, and test
its actual configuration. Native in-memory queues alone cannot establish a
host-wide promise about swap, dumps, hibernation, snapshots, access logs or
frontend temporary paths. Those remain explicit deployment acceptance checks.

Before enabling Infinetus content exchange, verify the exact public path with
a disposable authenticated session, real binary exchange, a slow/offline peer,
expiry/revocation, bounded pressure and concurrent account requests. Encrypted
content, acknowledgments/resume and database/file non-storage inspections are
application/deployment gates beyond this transport release.

## Errors and tests

Server failures use static codes/messages: `KSV6001` invalid argument,
`KSV6002` invalid/inconsistent option or flow setup, `KSV6003` listener setup,
`KSV6004` owner/closed resource, `KSV6005` stale/unavailable connection,
`KSV6006` invalid authorization expiry, `KSV6007` buffer pressure, and
`KSV6009` allocation/runtime failure. Existing client method errors keep their
`KWS` codes; send pressure is `KWS5007`.

`tests/abi112_ws/native_host.c` drives the public production dispatch APIs.
`wire_test.py` implements an independent standard-library Python RFC6455 peer.
It exercises pre-upgrade denial, the RFC nonce/accept vector, exact binary/text
bytes and fragmentation, frame/UTF-8/length rejection, Origin/subprotocol,
request body/pipeline rejection, lease/revocation, count and byte pressure,
small-budget fragment ownership transfer, context ownership, full-queue
cancellation/close ordering, option bounds, and native-resource cleanup.
The existing `run_kokum_027_websocket_test.py` separately retests legacy plain
WS and verified WSS behavior. See the test README for reproducible commands.

Protocol reference: [RFC 6455](https://www.rfc-editor.org/rfc/rfc6455.html).
