Bindings
realtime
Live connections on channels, held by Zeroko.
json
"bindings": { "LIVE": "realtime" }js
// In fetch: turn this request into a live connection on some channels.
if (url.pathname === "/live") {
const user = await authenticate(request) // your check
return env.LIVE.subscribe([`room:${room}`], { meta: { user } })
}
await env.LIVE.publish(`room:${room}`, { text: "hello" }) // {delivered: n}; objects go as JSON
await env.LIVE.send(connectionId, "only you") // true if connected
await env.LIVE.connections(`room:${room}`) // [{connection, meta}], up to 1000Clients
Clients connect with Server-Sent Events (server to client) or a WebSocket (both ways); the same route serves both:
js
const events = new EventSource("/live?room=1")
const socket = new WebSocket("wss://chat.example.com/live?room=1")Zeroko holds the connections, not the service: its process may stop between messages and they stay open.
Messages
WebSocket messages call the service's message(event, env, ctx), one at a
time per connection:
js
export default {
async fetch(request, env) { /* … */ },
async message(event, env) {
if (event.type === "message")
await env.LIVE.publish(event.channels[0], { from: event.meta.user, text: event.data })
},
}The event is {type: "message", connection, channels, meta, data}, and
{type: "close", …} when a connection closes, WebSocket or Server-Sent
Events. meta is what the service passed to subscribe.
Limits
Messages are text, up to 1 MB; up to 32 channels per connection; a connection that falls 256 messages behind is dropped.
From the API
http
POST /api/services/<name>/realtime/publish {"channel": "...", "data": ...}