santoku-websocket
View on LuaRocksone WebSocket API over a pluggable transport, with native, OpenResty and browser backends
santoku-websocket is one WebSocket API for every runtime santoku runs on. Its plain-Lua core takes a transport backend: require("santoku.websocket")(backend). The core adds callbacks, text and binary sends, queueing until open, and reconnect with backoff.
Details
- The core takes a transport backend the way santoku-http takes a socket backend.
- santoku-socket's santoku.socket.websocket is the native backend.
- santoku-resty's santoku.resty.websocket is the OpenResty client and server.
- santoku-web's santoku.web.websocket is the browser's backend.
- Code written against the core runs on each of them.
- Under OpenResty a conn is a cosocket. Only code in the request that opened or accepted the conn can send on it, and the shared-room card shows the pattern for that.
Connect, send and close
connect(url, opts, done) returns a connection at once. It calls done(true, conn) when the handshake completes, or done(false, err).
local arr = require("santoku.array")
local backend = {
connect = function (url, opts, done)
return done(true, {
send = function (data, binary)
opts.message(data, binary and "binary" or "text")
return true
end,
close = function (code, reason)
opts.closed(code, reason)
return true
end,
})
end,
}
local ws = require("santoku.websocket")(backend)
local got = {}
local conn = ws.connect("ws://example.test/echo", {
message = function (data, kind) arr.push(got, kind .. " " .. #data .. " bytes") end,
closed = function (code, reason) arr.push(got, "closed " .. code .. " " .. reason) end,
}, function (ok) print("open:", ok) end)
print("send:", conn.send("hello"))
print("send:", conn.send("\1\2\3", "binary"))
conn.close(1000, "done")
for i = 1, #got do
print(got[i])
end
return #got
Details
- conn.send(data, kind) takes kind "text" (the default) or "binary". It returns true, or false and a reason.
- Sends made before open queue, and they go out in order once the connection opens.
- Messages arrive as opts.message(data, kind), and the end of the connection as opts.closed(code, reason).
- conn.ping(data) sends a ping. It returns false, "closed" when the conn isn't open or the backend has no ping, as in the browser.
- conn.close(code, reason) starts the closing handshake.
- On the native backend nothing arrives until you call conn.wait(fn, ms) or conn.step(ms): https://santoku.dev/santoku-socket#santoku-socket--the-websocket-client
- This example runs the core over a small inline backend that echoes every send.
Reconnect with backoff
opts.reconnect = true, or a table { retries, backoff_ms }, makes the core retry a failed or dropped connection. Sends made meanwhile queue until the connection is back.
local tries = 0
local backend = {
runtime = {
spawn = function (fn)
return fn()
end,
sleep = function (ms)
print("retry after", ms, "ms")
end,
},
connect = function (url, opts, done)
tries = tries + 1
if tries < 3 then
return done(false, "refused")
end
return done(true, {
send = function () return true end,
close = function () return true end,
})
end,
}
local ws = require("santoku.websocket")(backend)
ws.connect("ws://example.test/", {
reconnect = { retries = 3, backoff_ms = 250 },
retrying = function (attempt, code, reason) print("attempt", attempt, code, reason) end,
}, function (ok) print("open:", ok, "after", tries, "tries") end)
return tries
Details
- The defaults are 3 retries and 1000 ms, and the wait grows with each attempt.
- opts.retrying(attempt, code, reason) reports each retry.
- opts.error(reason) reports each failed reconnect attempt after the first open.
- Retrying needs a backend with a runtime. Each retry is a task that sleeps the backoff, then reconnects.
- The browser, OpenResty and native backends carry santoku.web.async, santoku.resty.async and santoku.system.async.
- This example's backend refuses twice, and its runtime runs the retry at once instead of waiting.
A backend per runtime
Pick the backend for where the code runs: native with santoku-socket, OpenResty with santoku-resty, or the browser with santoku-web. Keep the one line for your runtime.
local ws = require("santoku.websocket")(require("santoku.socket.websocket"))
local ws = require("santoku.websocket")(require("santoku.resty.websocket"))
local ws = require("santoku.websocket")(require("santoku.web.websocket"))
ws.connect("wss://example.com/feed", {
protocols = { "chat" },
message = function (data, kind) print(kind, data) end,
closed = function (code, reason) print("closed", code, reason) end,
}, function (ok, conn)
if ok then
conn.send("hello")
end
end)
Details
- Native code drives its own loop. The native conn adds step(ms) and wait(fn, ms) from santoku.socket.websocket, and it has TLS options (verify, cafile, sslname).
- Under OpenResty the backend runs the receive loop in a light thread. Callbacks thus fire while your handler sleeps or does other cosocket work.
- In the browser the backend sets binaryType to arraybuffer, so binary messages arrive as Lua strings.
- Browsers can't set request headers, so opts.headers fails there.
A server under OpenResty
accept(opts, done) upgrades the current request and gives the same conn and events as connect, so one handler serves both sides of a test. Only the OpenResty backend can accept.
location = /echo {
content_by_lua_block {
local ws = require("santoku.websocket")(require("santoku.resty.websocket"))
local conn
ws.accept({
message = function (data, kind) conn.send(data, kind) end,
}, function (ok, c) conn = c end)
}
}
Details
- On the native and browser backends accept raises "websocket: this backend can't accept connections".
- done runs in the request's own coroutine. accept then spawns the receive loop as a light thread and returns.
- The request stays open until that thread ends.
- The conn's close sends the close frame with your code.
The backend interface
A backend is a table with connect(url, opts, done), plus runtime for reconnect and accept(opts, done) for a server. The first two examples on this page are complete backends.
local backend = {
connect = function (url, opts, done) end,
accept = function (opts, done) end,
runtime = require("santoku.system.async"),
}
Details
- connect calls done(true, t) or done(false, err).
- connect reports traffic through opts.message(data, kind), opts.closed(code, reason), opts.ping and opts.pong.
- The transport t has send(data, binary), close(code, reason) and optionally ping(data).
- Fields such as protocol, headers, tls, step and wait pass through to the conn that the core returns.
Examples
Projects that toku init creates with this rock. The examples page shows their files.
- A WebSocket echo server: An OpenResty server that echoes WebSocket messages, with a spec that talks to it from a native client.
toku init --example websocket my-websocket