HTTP cancellation and WebSockets
Unreleased preview.3 candidate. These APIs are absent from the published preview.2 download. Its HTTP reference keeps the released contract. Candidate SDK packaging and native desktop journeys have their own qualification gates; this page does not publish a new download.
Use HttpService for a request/response. Use WebSocket when both sides need to
send messages on one connection. Both use task.spawn and the existing LUI
scheduler; application code does not create threads or pump a message loop.
Cancel one action
Section titled “Cancel one action”Create a token with HttpService:CreateCancellationToken(), pass it in request
options, and retain it with the action’s Cancel button or owner. Cancel is
idempotent. A cancelled token stays cancelled; create another for another action.
local Http = app:GetService('HttpService')local Token = Http:CreateCancellationToken()task.spawn(function() local Ok, Response = pcall(function() return Http:RequestAsync({Url = 'https://example.com/', CancellationToken = Token}) end) if Ok then print('[LUI:Example] HTTP status', Response.StatusCode) else print('[LUI:Example] Request failed or was cancelled') endend)-- From the action's Cancel callback: Token:Cancel()This needs network.client and host permission for the destination. HTTPS validates
certificates; do not disable verification to make an example connect. The optional
JsonClient’s RequestAsync accepts the same token. Cancellation affects only
requests or WebSocket work that intentionally shares the token. The existing
CancelAll() still cancels earlier HTTP requests runtime-wide; later requests
survive. Foreign tokens are refused and at most128 live tokens may be retained.
Expected network failures are catchable. HTTP error statuses are received
responses: inspect Response.Success and StatusCode. A failed connection,
timeout or cancellation throws instead. Do not treat all failures as invalid JSON
or print a private response body into framework diagnostics.
Send and receive a real message
Section titled “Send and receive a real message”Copy Examples/websocket-echo from the prepared candidate SDK to a sibling project.
It has no optional dependencies. Use lui check, then:
lui run --mode headless --grant network.client,network.server --http-origin http://127.0.0.1:18083 --diagnostics developmentPort18083 must be free. This complete entry file runs both sides, verifies an actual echo and closes the server. It does not report success from connection alone.
--!strict-- Finite client/server journey; port18083 is declared in the example's host policy.local Server = app:GetService('HttpServerService'):CreateServer({Port = 18083})Server:RouteWebSocket('/echo', function(Socket) local Ok = pcall(function() local Message = Socket:ReceiveAsync() if Message then Socket:SendAsync(Message.Data, Message.Binary) end Socket:Close() Socket:ReceiveAsync() end) if not Ok then Socket:Cancel() endend)Server:Start()task.spawn(function() local Socket: WebSocket? = nil local Ok = pcall(function() local Connected = app:GetService('WebSocketService'):ConnectAsync('ws://127.0.0.1:18083/echo') Socket = Connected Connected:SendAsync('Hello from the public SDK') local Message = Connected:ReceiveAsync() assert(Message and not Message.Binary and Message.Data == 'Hello from the public SDK') Connected:Close(); assert(Connected:ReceiveAsync() == nil) end) if Socket then Socket:Cancel() end Server:Close() assert(Ok, '[LUI:Echo] JourneyFailed') print('[LUI:Echo] Real client/server WebSocket echo passed')end)ConnectAsync, SendAsync and ReceiveAsync yield; call them in scheduled tasks
or a hosted route handler, which is already scheduled. network.client permits
outbound connections; network.server permits hosted routes. Existing address and
port restrictions still apply. A WebSocket route shares its HTTP listener and is
registered before Start. Native upgrade validation completes before its handler
owns the socket. An optional Authorize callback must return true. It runs as a
scheduled hosted task and may yield on supported scheduler operations within the
shared request deadline. Failure refuses the upgrade without exposing callback
error text.
Received messages are readonly {Data: string, Binary: boolean} values. Strings
send text by default; buffers send binary. An optional Binary boolean overrides
that choice. Text must be valid UTF-8. Data received before your first receive
waits in a bounded inbox, in order. Only one receive can be outstanding per socket.
Close() starts a graceful handshake; accepted sends may finish within its
deadline. Continue receiving to observe an orderly close as nil. Cancel() aborts
immediately and is useful during owner teardown. Both are idempotent. State is
Connecting/Open/Closing/Closed. CloseCode and CloseReason describe the peer;
messages and reasons are untrusted application data.
Defaults and optional controls
Section titled “Defaults and optional controls”| Control | Default | Maximum |
|---|---|---|
| ConnectTimeoutMs | 10,000ms | 60,000ms |
| CloseTimeoutMs | 5,000ms | 10,000ms |
| MaxMessageBytes / MaxFrameBytes | 1MiB each | Host ceilings, at most1MiB each |
| MaxQueuedBytes | 4MiB per direction | Host ceiling, at most4MiB |
| MaxQueuedMessages | 16 per direction | Host ceiling, at most16 |
| IdleTimeoutMs / PingIntervalMs | 0, disabled | 600,000ms |
| PongTimeoutMs | 10,000ms | 60,000ms |
Smaller options narrow the host’s ceilings. Protocols selects offered subprotocols; Headers and Origin supply application handshake data. CancellationToken scopes connection work. Hosted options additionally accept Origins and Authorize. An Origin-bearing request is rejected unless its Origin is explicitly listed; originless native clients remain allowed. Origin policy is not authentication. Use Authorize for application authorization. There are eight retained socket handles per runtime, including closed handles until released by the VM. Drop obsolete references; closing does not force GC. Payload reservations are bounded separately from total OS/TLS or VM memory.
Saturated queues reject work; messages are not silently replaced. An inbox flood closes the connection. A successful send means the complete frame was written, not that a peer processed it. Outbound fragmentation, compression, automatic reconnect, HTTP/2/3 upgrades and browser transports are outside this profile. The app chooses retry, credentials, JSON schema and reconnection policy.
Availability and deeper host controls
Section titled “Availability and deeper host controls”Windows/Linux native protocol, client/server, denial, cancellation, quotas and headless journeys have integration tests. Desktop UI, physical input and a packaged SDK recipient are distinct checks. Unsupported browser hosts refuse these native services; raw backend objects never enter Luau.
Ordinary app authors use the services and declared grants above. Native embedders
may additionally narrow exact origins, resolved public addresses, concurrency and
reservation budgets through versioned LuiHttp.h/LuiWebSocket.h APIs. Those are
host/framework integration controls, not extra setup every Luau application needs.
Candidate API signatures and option records
HttpService
Section titled “HttpService”export type HttpService = { read RequestAsync: (Self: HttpService, Options: HttpRequestOptions) -> HttpResponse, read GetAsync: (Self: HttpService, Url: string) -> HttpResponse, read CancelAll: (Self: HttpService) -> (), read CreateCancellationToken: (Self: HttpService) -> HttpCancellationToken,}HttpRequestOptions
Section titled “HttpRequestOptions”export type HttpRequestOptions = { Url: string, Method: string?, Headers: {HttpHeader}?, Body: (string | buffer)?, TimeoutMs: number?, MaxResponseBytes: number?, CancellationToken: HttpCancellationToken?,}HttpCancellationToken
Section titled “HttpCancellationToken”export type HttpCancellationToken = { read IsCanceled: boolean, read Cancel: (Self: HttpCancellationToken) -> (),}HttpServer
Section titled “HttpServer”export type HttpServer = { read Port: number, read IsListening: boolean, read BoundEndpoints: {NetworkEndpoint}, read RouteWebSocket: (Self: HttpServer, Path: string, Handler: (Socket: WebSocket, Request: HttpRequest) -> (), Options: WebSocketServerOptions?) -> (), read Route: (Self: HttpServer, Method: string, Path: string, Handler: (Request: HttpRequest) -> HttpReplyOptions) -> (), read Start: (Self: HttpServer) -> (), read Close: (Self: HttpServer) -> (),}WebSocketService
Section titled “WebSocketService”export type WebSocketService = { read ConnectAsync: (Self: WebSocketService, Url: string, Options: WebSocketOptions?) -> WebSocket,}WebSocket
Section titled “WebSocket”export type WebSocket = { read State: "Connecting" | "Open" | "Closing" | "Closed", read Subprotocol: string, read CloseCode: number?, read CloseReason: string, read SendAsync: (Self: WebSocket, Data: string | buffer, Binary: boolean?) -> (), read ReceiveAsync: (Self: WebSocket) -> WebSocketMessage?, read Close: (Self: WebSocket, Code: number?, Reason: string?) -> (), read Cancel: (Self: WebSocket) -> (),}WebSocketMessage
Section titled “WebSocketMessage”export type WebSocketMessage = { read Data: string, read Binary: boolean,}WebSocketOptions
Section titled “WebSocketOptions”export type WebSocketOptions = { ConnectTimeoutMs: number?, CloseTimeoutMs: number?, IdleTimeoutMs: number?, PingIntervalMs: number?, PongTimeoutMs: number?, MaxMessageBytes: number?, MaxFrameBytes: number?, MaxQueuedBytes: number?, MaxQueuedMessages: number?, Origin: string?, Protocols: {string}?, Headers: {HttpHeader}?, CancellationToken: HttpCancellationToken?,}WebSocketServerOptions
Section titled “WebSocketServerOptions”export type WebSocketServerOptions = { MaxMessageBytes: number?, MaxFrameBytes: number?, MaxQueuedBytes: number?, MaxQueuedMessages: number?, CloseTimeoutMs: number?, IdleTimeoutMs: number?, PingIntervalMs: number?, PongTimeoutMs: number?, Protocols: {string}?, Origins: {string}?, Authorize: ((Request: HttpRequest) -> boolean)?,}