@dim24/servin 0.2.1 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +757 -78
- package/package.json +1 -1
- package/src/server.js +36 -9
- package/src/tree.js +576 -16
- package/src/websocket.js +332 -6
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
`servin` lets you build HTTP APIs, static websites, HTML pages, Server-Sent Events (SSE), and WebSockets using plain JavaScript functions and nested object trees. Instead of manually wiring string paths, `(req, res)` handlers, and `next()` middleware chains, you express your backend as a clean JavaScript object hierarchy while `servin` handles routing, parameter type coercion, self-invalidating caching, session persistence, rate limiting, and zero-build frontend client generation automatically.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
[see the real example usage here](https://github.com/harakun24/webserver-example)
|
|
8
8
|
|
|
9
9
|
## Table of Contents
|
|
10
10
|
|
|
@@ -505,7 +505,7 @@ const updated = await api.tasks.$id.patch(1, { done: true });
|
|
|
505
505
|
await api.tasks.$id.delete(1);
|
|
506
506
|
```
|
|
507
507
|
|
|
508
|
-
### 4.3 Step 3: Consuming SSE Streams
|
|
508
|
+
### 4.3 Step 3: Consuming SSE Streams
|
|
509
509
|
|
|
510
510
|
`/@client.js` also translates Server-Sent Events and WebSockets into standard JavaScript `for await...of` async iterators:
|
|
511
511
|
|
|
@@ -516,14 +516,764 @@ import { api } from "/@client.js";
|
|
|
516
516
|
for await (const tick of api.clock.get()) {
|
|
517
517
|
console.log("Server tick:", tick);
|
|
518
518
|
}
|
|
519
|
+
```
|
|
520
|
+
|
|
521
|
+
---
|
|
522
|
+
|
|
523
|
+
# Servin WebSocket Guide
|
|
524
|
+
|
|
525
|
+
`servin` provides a declarative, integrated directly into your domain routing tree (`api.<route>.ws`) and virtual ESM client (`/@client.js`). It is designed to work cleanly alongside standard HTTP routes, sessions, and route guards while supporting per-socket state, rooms, targeted socket filtering, payload/rate/backpressure guards, action validation, optional room state with sequence tracking (`seq`), ring-buffer replay on reconnect, and explicit client sync/refresh/resync controls.
|
|
526
|
+
|
|
527
|
+
## Feature Overview & Scope
|
|
528
|
+
|
|
529
|
+
### Included in the Final WebSocket API
|
|
530
|
+
|
|
531
|
+
- **Declarative `open`, `actions`, and `close` blocks:** Separates connection lifecycle hooks from named client-callable actions.
|
|
532
|
+
|
|
533
|
+
- **Per-socket context (`socket.state`):** Mutable state attached to a single socket instance across `open`, `actions`, and `close`.
|
|
534
|
+
|
|
535
|
+
- **Direct connection data (`api.<route>.ws({ ... })`):** Passes initial connection data directly as an object without wrapping it in `{ query: { ... } }`, mapped automatically to the WebSocket upgrade URL.
|
|
536
|
+
|
|
537
|
+
- **Built-in rooms & broadcasting (`join`, `leave`, `to(room).broadcast(...)`):** Groups sockets into channels and broadcasts events with optional exclusions (such as `except: socket`).
|
|
538
|
+
|
|
539
|
+
- **Targeted socket filtering (`sockets.where(predicate).send(...)`):** Filters active sockets dynamically by predicate and sends targeted messages without manual loops or room-wide broadcasts.
|
|
540
|
+
|
|
541
|
+
- **Guards & action validation:** Enforces payload size limits (`maxPayloadBytes`), inbound message rate limits (`maxEventsPerSec`), outbound backpressure limits (`maxBufferedBytes`), and per-action `validate` hooks.
|
|
542
|
+
|
|
543
|
+
- **Optional room state & `commit`:** Maintains shared state per room when `state(socket, req)` is defined, incrementing a monotonic `seq` counter on every `commit` and storing entries in a bounded ring buffer.
|
|
544
|
+
|
|
545
|
+
- **Automatic sequence sync, ring-buffer replay & snapshot fallback:** Tracks mutation sequence numbers, replays missed patches upon reconnect via `__lastSeq`, and falls back to a full snapshot when `__lastSeq` falls outside the ring buffer window.
|
|
546
|
+
|
|
547
|
+
- **Standalone client `.sync(callback)`:** Delivers synchronized state and metadata to user-managed client code without coupling the framework to DOM elements or rendering libraries.
|
|
548
|
+
|
|
549
|
+
- **Connection & sync controls (`ws.refresh(...)` and `ws.resync(...)`):** `ws.refresh(nextData)` closes and reopens the connection (optionally updating connection data), while `ws.resync(room)` requests a fresh full snapshot without closing the active socket.
|
|
550
|
+
|
|
551
|
+
## Guide
|
|
552
|
+
|
|
553
|
+
### Step 1: Basic Connection (`open`, `actions`, `close`, `.on()`, and `.emit()`)
|
|
554
|
+
|
|
555
|
+
Start with a minimal WebSocket endpoint on a route node (for example, `api.chat.ws`) and connect from the browser using `api.chat.ws()`.
|
|
556
|
+
|
|
557
|
+
#### Server
|
|
558
|
+
|
|
559
|
+
```
|
|
560
|
+
import { serve } from './server.js';
|
|
561
|
+
|
|
562
|
+
await serve({
|
|
563
|
+
port: 3000,
|
|
564
|
+
api: {
|
|
565
|
+
chat: {
|
|
566
|
+
ws: {
|
|
567
|
+
//handle when client connect
|
|
568
|
+
open(socket) {
|
|
569
|
+
socket.send({ event: 'welcome', message: 'Connected to chat' });
|
|
570
|
+
},
|
|
571
|
+
//list all events
|
|
572
|
+
actions: {
|
|
573
|
+
//each event
|
|
574
|
+
ping(payload, socket) {
|
|
575
|
+
//send back to the client
|
|
576
|
+
socket.send({
|
|
577
|
+
event: 'pong',
|
|
578
|
+
payload: data,
|
|
579
|
+
sentAt: payload?.sentAt ?? null,
|
|
580
|
+
serverTime: Date.now()
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
},
|
|
584
|
+
close() {
|
|
585
|
+
// Clean up any non-room resources tied to this connection
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
});
|
|
591
|
+
|
|
592
|
+
```
|
|
519
593
|
|
|
520
|
-
|
|
521
|
-
const room = api.chat.$room.ws("general");
|
|
522
|
-
room.send({ text: "Hello everyone!" });
|
|
594
|
+
#### Client (`/@client.js`)
|
|
523
595
|
|
|
524
|
-
|
|
525
|
-
|
|
596
|
+
```
|
|
597
|
+
import { api } from '/@client.js';
|
|
598
|
+
|
|
599
|
+
const ws = api.chat.ws();
|
|
600
|
+
|
|
601
|
+
ws
|
|
602
|
+
.on('open', ({ reconnected }) => {
|
|
603
|
+
console.log(reconnected ? 'Reconnected to chat' : 'Connected to chat');
|
|
604
|
+
//emit an event
|
|
605
|
+
ws.emit('ping', { data:"hello" });
|
|
606
|
+
})
|
|
607
|
+
.on('event', (data) => {
|
|
608
|
+
console.log('Received from server:', data);
|
|
609
|
+
})
|
|
610
|
+
.on('close', ({ code, reason, manual }) => {
|
|
611
|
+
console.log('Socket closed:', { code, reason, manual });
|
|
612
|
+
});
|
|
613
|
+
|
|
614
|
+
```
|
|
615
|
+
|
|
616
|
+
#### How It Works
|
|
617
|
+
|
|
618
|
+
- Defining `ws` as an object inside an API node compiles a route with verb `WS` at that node's path (`/chat`).
|
|
619
|
+
|
|
620
|
+
- On the client, `ws.emit(actionName, payload)` serializes `{ type: 'action', name, payload }` and dispatches the matching handler in `actions`.
|
|
621
|
+
|
|
622
|
+
- Server-sent targeted events (`socket.send(...)`) arrive on the client under the `'event'` listener.
|
|
623
|
+
|
|
624
|
+
### Step 2: Direct Connection Data & Per-Socket State (`socket.state`)
|
|
625
|
+
|
|
626
|
+
Pass initial connection data directly to `api.<route>.ws({ ... })` without a `{ query: { ... } }` wrapper. On the server, read those values from `req.data` and store connection-specific properties on `socket.state`.
|
|
627
|
+
|
|
628
|
+
#### Server
|
|
629
|
+
|
|
630
|
+
```
|
|
631
|
+
api: {
|
|
632
|
+
presence: {
|
|
633
|
+
ws: {
|
|
634
|
+
open(socket, req) {
|
|
635
|
+
socket.state = {
|
|
636
|
+
userId: req.data.userId || 'anonymous',
|
|
637
|
+
role: req.data.role || 'member',
|
|
638
|
+
room: req.data.room || 'lobby'
|
|
639
|
+
};
|
|
640
|
+
|
|
641
|
+
socket.join(socket.state.room);
|
|
642
|
+
socket.send({
|
|
643
|
+
event: 'session_ready',
|
|
644
|
+
state: socket.state
|
|
645
|
+
});
|
|
646
|
+
},
|
|
647
|
+
|
|
648
|
+
actions: {
|
|
649
|
+
updateRole(payload, socket) {
|
|
650
|
+
if (!payload?.role) return;
|
|
651
|
+
socket.state.role = String(payload.role);
|
|
652
|
+
socket.send({
|
|
653
|
+
event: 'role_updated',
|
|
654
|
+
role: socket.state.role
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
},
|
|
658
|
+
|
|
659
|
+
close(socket) {
|
|
660
|
+
if (socket.state?.room) {
|
|
661
|
+
socket.leave(socket.state.room);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
}
|
|
526
666
|
}
|
|
667
|
+
|
|
668
|
+
```
|
|
669
|
+
|
|
670
|
+
#### Client
|
|
671
|
+
|
|
672
|
+
```
|
|
673
|
+
import { api } from '/@client.js';
|
|
674
|
+
|
|
675
|
+
const ws = api.presence.ws({
|
|
676
|
+
userId: 'usr_42',
|
|
677
|
+
role: 'member',
|
|
678
|
+
room: 'lobby'
|
|
679
|
+
});
|
|
680
|
+
|
|
681
|
+
ws
|
|
682
|
+
.on('open', () => {
|
|
683
|
+
ws.emit('updateRole', { role: 'editor' });
|
|
684
|
+
})
|
|
685
|
+
.on('event', (msg) => {
|
|
686
|
+
console.log('Presence event:', msg);
|
|
687
|
+
});
|
|
688
|
+
|
|
689
|
+
```
|
|
690
|
+
|
|
691
|
+
#### How It Works
|
|
692
|
+
|
|
693
|
+
- `api.presence.ws({ userId: 'usr_42', room: 'lobby' })` encodes top-level keys directly onto the WebSocket handshake URL query string.
|
|
694
|
+
|
|
695
|
+
- `req.data` exposes those connection parameters (excluding internal `__lastSeq`) cleanly in `open` and `state`.
|
|
696
|
+
|
|
697
|
+
- `socket.state` is a plain object scoped to a single socket connection, making it safe for per-user attributes like `userId`, `role`, or active `room`.
|
|
698
|
+
|
|
699
|
+
### Step 3: Rooms & Broadcasting (`join`, `leave`, `to(room).broadcast`)
|
|
700
|
+
|
|
701
|
+
Group sockets into rooms using `socket.join(room)` and `socket.leave(room)`, and publish updates to room members via `socket.to(room).broadcast(data, options)`.
|
|
702
|
+
|
|
703
|
+
#### Server
|
|
704
|
+
|
|
705
|
+
```
|
|
706
|
+
api: {
|
|
707
|
+
rooms: {
|
|
708
|
+
ws: {
|
|
709
|
+
open(socket, req) {
|
|
710
|
+
const room = req.data.room || 'general';
|
|
711
|
+
const user = req.data.user || 'guest';
|
|
712
|
+
|
|
713
|
+
socket.state = { room, user };
|
|
714
|
+
socket.join(room);
|
|
715
|
+
|
|
716
|
+
socket.to(room).broadcast(
|
|
717
|
+
{ data:here },
|
|
718
|
+
{ except: socket } //if you need to excluded
|
|
719
|
+
);
|
|
720
|
+
},
|
|
721
|
+
|
|
722
|
+
actions: {
|
|
723
|
+
switchRoom(payload, socket) {
|
|
724
|
+
const nextRoom = String(payload?.room || '').trim();
|
|
725
|
+
if (!nextRoom) return;
|
|
726
|
+
|
|
727
|
+
const prevRoom = socket.state.room;
|
|
728
|
+
if (prevRoom) {
|
|
729
|
+
socket.leave(prevRoom);
|
|
730
|
+
socket.to(prevRoom).broadcast(
|
|
731
|
+
{ type: 'member_left', user: socket.state.user, to: nextRoom },
|
|
732
|
+
{ except: socket }
|
|
733
|
+
);
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
socket.state.room = nextRoom;
|
|
737
|
+
socket.join(nextRoom);
|
|
738
|
+
socket.to(nextRoom).broadcast(
|
|
739
|
+
{ type: 'member_joined', user: socket.state.user, from: prevRoom },
|
|
740
|
+
{ except: socket }
|
|
741
|
+
);
|
|
742
|
+
},
|
|
743
|
+
|
|
744
|
+
say(payload, socket) {
|
|
745
|
+
const { room, user } = socket.state;
|
|
746
|
+
if (!room) return;
|
|
747
|
+
|
|
748
|
+
socket.to(room).broadcast(
|
|
749
|
+
{ type: 'message', from: user, text: String(payload?.text ?? '') },
|
|
750
|
+
{ except: socket }
|
|
751
|
+
);
|
|
752
|
+
}
|
|
753
|
+
},
|
|
754
|
+
|
|
755
|
+
close(socket) {
|
|
756
|
+
const { room, user } = socket.state || {};
|
|
757
|
+
if (room) {
|
|
758
|
+
socket.leave(room);
|
|
759
|
+
socket.to(room).broadcast(
|
|
760
|
+
{ type: 'member_left', user },
|
|
761
|
+
{ except: socket }
|
|
762
|
+
);
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
```
|
|
770
|
+
|
|
771
|
+
#### Client
|
|
772
|
+
|
|
773
|
+
```
|
|
774
|
+
import { api } from '/@client.js';
|
|
775
|
+
|
|
776
|
+
const ws = api.rooms.ws({ room: 'general', user: 'maya' });
|
|
777
|
+
|
|
778
|
+
ws
|
|
779
|
+
.on('broadcast', ({ room, payload }) => {
|
|
780
|
+
console.log(`[${room}]`, payload);
|
|
781
|
+
})
|
|
782
|
+
.on('open', () => {
|
|
783
|
+
ws.emit('say', { text: 'Hello room!' });
|
|
784
|
+
ws.emit('switchRoom', { room: 'engineering' });
|
|
785
|
+
});
|
|
786
|
+
|
|
787
|
+
```
|
|
788
|
+
|
|
789
|
+
#### How It Works
|
|
790
|
+
|
|
791
|
+
- `socket.to(room).broadcast(data, { except })` sends a `'broadcast'` envelope `{ type: 'broadcast', room, payload }` to open sockets subscribed to `room`.
|
|
792
|
+
|
|
793
|
+
- Passing `{ except: socket }` prevents echoing a peer's own action back to the sender. By default, `except` excludes the acting `socket`.
|
|
794
|
+
|
|
795
|
+
- Always call `socket.leave(room)` when switching rooms or in `close` so room memberships stay accurate.
|
|
796
|
+
|
|
797
|
+
### Step 4: Targeted Socket Filtering (`sockets.where(...)`)
|
|
798
|
+
|
|
799
|
+
When you need to reach a subset of active connections based on dynamic attributes (such as role, workspace, or tenant) rather than an entire room, use `sockets.where(predicate).send(data)` from the action helpers object.
|
|
800
|
+
|
|
801
|
+
#### Server
|
|
802
|
+
|
|
803
|
+
```
|
|
804
|
+
api: {
|
|
805
|
+
support: {
|
|
806
|
+
ws: {
|
|
807
|
+
open(socket, req) {
|
|
808
|
+
socket.state = {
|
|
809
|
+
userId: req.data.userId || 'guest',
|
|
810
|
+
role: req.data.role || 'customer',
|
|
811
|
+
tier: req.data.tier || 'standard'
|
|
812
|
+
};
|
|
813
|
+
},
|
|
814
|
+
|
|
815
|
+
actions: {
|
|
816
|
+
escalate(payload, socket, { sockets }) {
|
|
817
|
+
const target = sockets.where(
|
|
818
|
+
(peer) =>
|
|
819
|
+
peer !== socket &&
|
|
820
|
+
peer.state?.role === 'agent' &&
|
|
821
|
+
peer.state?.tier === 'enterprise'
|
|
822
|
+
);
|
|
823
|
+
|
|
824
|
+
target.send({
|
|
825
|
+
type: 'escalation',
|
|
826
|
+
from: socket.state.userId,
|
|
827
|
+
issue: String(payload?.issue ?? '')
|
|
828
|
+
});
|
|
829
|
+
|
|
830
|
+
socket.send({
|
|
831
|
+
type: 'escalation_ack',
|
|
832
|
+
notifiedAgents: target.count
|
|
833
|
+
});
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
```
|
|
841
|
+
|
|
842
|
+
#### Client
|
|
843
|
+
|
|
844
|
+
```
|
|
845
|
+
import { api } from '/@client.js';
|
|
846
|
+
|
|
847
|
+
const ws = api.support.ws({
|
|
848
|
+
userId: 'cust_99',
|
|
849
|
+
role: 'customer',
|
|
850
|
+
tier: 'enterprise'
|
|
851
|
+
});
|
|
852
|
+
|
|
853
|
+
ws
|
|
854
|
+
.on('event', (msg) => {
|
|
855
|
+
if (msg.type === 'escalation_ack') {
|
|
856
|
+
console.log(`Notified ${msg.notifiedAgents} enterprise agents`);
|
|
857
|
+
}
|
|
858
|
+
if (msg.type === 'escalation') {
|
|
859
|
+
console.log('Incoming escalation:', msg);
|
|
860
|
+
}
|
|
861
|
+
})
|
|
862
|
+
.on('open', () => {
|
|
863
|
+
ws.emit('escalate', { issue: 'Production webhook timeout' });
|
|
864
|
+
});
|
|
865
|
+
|
|
866
|
+
```
|
|
867
|
+
|
|
868
|
+
#### How It Works
|
|
869
|
+
|
|
870
|
+
- `sockets.where(predicate)` evaluates `predicate(peerSocket)` across active sockets and returns `{ sockets, count, send(data) }`.
|
|
871
|
+
|
|
872
|
+
- Calling `.send(data)` delivers `{ type: 'event', payload: data }` to every matched socket.
|
|
873
|
+
|
|
874
|
+
- Because `socket.state` is checked inside the predicate, filtering reflects live state changes made during the session.
|
|
875
|
+
|
|
876
|
+
### Step 5: Guards, Backpressure & Action Validation
|
|
877
|
+
|
|
878
|
+
Protect your endpoint against oversized frames, message floods, slow consumers, and malformed action payloads using route-level guard options and action `{ validate, run }` definitions.
|
|
879
|
+
|
|
880
|
+
#### Server
|
|
881
|
+
|
|
882
|
+
```
|
|
883
|
+
api: {
|
|
884
|
+
tasks: {
|
|
885
|
+
ws: {
|
|
886
|
+
maxPayloadBytes: 16384, // Reject incoming frames larger than 16 KB
|
|
887
|
+
maxEventsPerSec: 20, // Cap inbound messages per socket per second
|
|
888
|
+
maxBufferedBytes: 131072, // Close slow sockets exceeding 128 KB outbound buffer
|
|
889
|
+
|
|
890
|
+
open(socket, req) {
|
|
891
|
+
socket.state = {
|
|
892
|
+
room: req.data.room || 'sprint-1',
|
|
893
|
+
actor: req.data.actor || 'member'
|
|
894
|
+
};
|
|
895
|
+
socket.join(socket.state.room);
|
|
896
|
+
},
|
|
897
|
+
|
|
898
|
+
actions: {
|
|
899
|
+
addTask: {
|
|
900
|
+
validate(payload) {
|
|
901
|
+
const title = String(payload?.title ?? '').trim();
|
|
902
|
+
if (!title) {
|
|
903
|
+
throw new Error('VALIDATION_TITLE_REQUIRED');
|
|
904
|
+
}
|
|
905
|
+
if (title.length > 120) {
|
|
906
|
+
throw new Error('VALIDATION_TITLE_TOO_LONG');
|
|
907
|
+
}
|
|
908
|
+
return { title };
|
|
909
|
+
},
|
|
910
|
+
|
|
911
|
+
run(cleanPayload, socket, { commit }) {
|
|
912
|
+
const { room, actor } = socket.state;
|
|
913
|
+
commit(room, { op: 'add_task', actor }, (draft) => {
|
|
914
|
+
draft.tasks = draft.tasks || [];
|
|
915
|
+
draft.tasks.push({
|
|
916
|
+
id: `${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
|
|
917
|
+
title: cleanPayload.title,
|
|
918
|
+
completed: false
|
|
919
|
+
});
|
|
920
|
+
});
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
```
|
|
929
|
+
|
|
930
|
+
#### Client
|
|
931
|
+
|
|
932
|
+
```
|
|
933
|
+
import { api } from '/@client.js';
|
|
934
|
+
|
|
935
|
+
const ws = api.tasks.ws({ room: 'sprint-1', actor: 'alex' });
|
|
936
|
+
|
|
937
|
+
ws
|
|
938
|
+
.on('error', (err) => {
|
|
939
|
+
console.error('Server rejected request:', err);
|
|
940
|
+
})
|
|
941
|
+
.on('open', () => {
|
|
942
|
+
// Triggers validation error -> sent back via 'error' event
|
|
943
|
+
ws.emit('addTask', { title: ' ' });
|
|
944
|
+
|
|
945
|
+
// Passes validation -> mutates room state via commit
|
|
946
|
+
ws.emit('addTask', { title: 'Ship WebSocket guide' });
|
|
947
|
+
});
|
|
948
|
+
|
|
949
|
+
```
|
|
950
|
+
|
|
951
|
+
#### How It Works
|
|
952
|
+
|
|
953
|
+
- `maxPayloadBytes` checks incoming WebSocket frame payload length before parsing.
|
|
954
|
+
|
|
955
|
+
- `maxEventsPerSec` tracks a 1-second window per socket and emits `{ type: 'error', message: 'RATE_LIMIT_EXCEEDED' }` when exceeded.
|
|
956
|
+
|
|
957
|
+
- `maxBufferedBytes` monitors `socket.bufferedAmount` (`tcpSocket.writableLength`) before writing outbound frames, closing sockets that fall too far behind.
|
|
958
|
+
|
|
959
|
+
- When an action is defined as `{ validate, run }`, `validate` runs first; if it throws, `run` is skipped and `{ type: 'error', action, message }` is sent back to the caller socket.
|
|
960
|
+
|
|
961
|
+
### Step 6: Room State, `commit`, `seq`, Ring Buffer Replay & `.sync(...)`
|
|
962
|
+
|
|
963
|
+
Add a `state(socket, req)` hook to enable room-level synchronized state. Every `commit(room, meta, mutator)` mutates the room state in place, increments `seq`, records the update in a bounded ring buffer (`sync.bufferSize`), and pushes state updates to room subscribers.
|
|
964
|
+
|
|
965
|
+
#### Server
|
|
966
|
+
|
|
967
|
+
```
|
|
968
|
+
api: {
|
|
969
|
+
board: {
|
|
970
|
+
ws: {
|
|
971
|
+
sync: {
|
|
972
|
+
bufferSize: 100
|
|
973
|
+
},
|
|
974
|
+
|
|
975
|
+
state(socket, req) {
|
|
976
|
+
const room = req.data.room || 'default-board';
|
|
977
|
+
return {
|
|
978
|
+
room,
|
|
979
|
+
items: []
|
|
980
|
+
};
|
|
981
|
+
},
|
|
982
|
+
|
|
983
|
+
open(socket, req) {
|
|
984
|
+
const room = req.data.room || 'default-board';
|
|
985
|
+
socket.state = {
|
|
986
|
+
room,
|
|
987
|
+
user: req.data.user || 'guest'
|
|
988
|
+
};
|
|
989
|
+
if (!socket.rooms.has(room)) {
|
|
990
|
+
socket.join(room);
|
|
991
|
+
}
|
|
992
|
+
},
|
|
993
|
+
|
|
994
|
+
actions: {
|
|
995
|
+
toggleItem: {
|
|
996
|
+
validate(payload) {
|
|
997
|
+
const id = String(payload?.id ?? '').trim();
|
|
998
|
+
if (!id) throw new Error('ITEM_ID_REQUIRED');
|
|
999
|
+
return { id };
|
|
1000
|
+
},
|
|
1001
|
+
run({ id }, socket, { commit }) {
|
|
1002
|
+
const { room, user } = socket.state;
|
|
1003
|
+
commit(room, { op: 'toggle_item', by: user, id }, (draft) => {
|
|
1004
|
+
const item = draft.items.find((entry) => entry.id === id);
|
|
1005
|
+
if (item) {
|
|
1006
|
+
item.done = !item.done;
|
|
1007
|
+
}
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
1010
|
+
},
|
|
1011
|
+
|
|
1012
|
+
createItem: {
|
|
1013
|
+
validate(payload) {
|
|
1014
|
+
const label = String(payload?.label ?? '').trim();
|
|
1015
|
+
if (!label) throw new Error('LABEL_REQUIRED');
|
|
1016
|
+
return { label };
|
|
1017
|
+
},
|
|
1018
|
+
run({ label }, socket, { commit }) {
|
|
1019
|
+
const { room, user } = socket.state;
|
|
1020
|
+
commit(room, { op: 'create_item', by: user }, (draft) => {
|
|
1021
|
+
draft.items.push({
|
|
1022
|
+
id: `item_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
|
|
1023
|
+
label,
|
|
1024
|
+
done: false
|
|
1025
|
+
});
|
|
1026
|
+
});
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
```
|
|
1035
|
+
|
|
1036
|
+
#### Client
|
|
1037
|
+
|
|
1038
|
+
```
|
|
1039
|
+
import { api } from '/@client.js';
|
|
1040
|
+
|
|
1041
|
+
let latestBoardState = null;
|
|
1042
|
+
|
|
1043
|
+
const ws = api.board.ws({
|
|
1044
|
+
room: 'default-board',
|
|
1045
|
+
user: 'maya'
|
|
1046
|
+
});
|
|
1047
|
+
|
|
1048
|
+
ws.sync((state, meta) => {
|
|
1049
|
+
// Store and render state in your own application layer
|
|
1050
|
+
latestBoardState = state;
|
|
1051
|
+
console.log('State synced:', {
|
|
1052
|
+
seq: meta.seq,
|
|
1053
|
+
room: meta.room,
|
|
1054
|
+
fullSnapshot: meta.fullSnapshot,
|
|
1055
|
+
replayed: meta.replayed,
|
|
1056
|
+
meta: meta.meta ?? null
|
|
1057
|
+
});
|
|
1058
|
+
renderBoardView(latestBoardState);
|
|
1059
|
+
});
|
|
1060
|
+
|
|
1061
|
+
```
|
|
1062
|
+
|
|
1063
|
+
#### How It Works
|
|
1064
|
+
|
|
1065
|
+
- On initial connection (when `__lastSeq` is `0`), the server sends a `sync_snapshot` (`fullSnapshot: true, replayed: false`) with the current `seq` and `state`.
|
|
1066
|
+
|
|
1067
|
+
- On `commit`, the server increments `seq`, pushes `{ seq, meta, state }` into the room's ring buffer, and sends `sync_patch` (`fullSnapshot: false, replayed: false`) to members of that room.
|
|
1068
|
+
|
|
1069
|
+
- On automatic reconnect, the client appends `__lastSeq=<lastSeq>` to the WebSocket URL:
|
|
1070
|
+
- If `lastSeq` is within the ring buffer range, missed entries are replayed in order with `replayed: true`.
|
|
1071
|
+
|
|
1072
|
+
- If `lastSeq` is too old or outside the ring buffer range, the server falls back to sending a `sync_snapshot` (`fullSnapshot: true`).
|
|
1073
|
+
|
|
1074
|
+
- `.sync(callback)` is standalone: if a snapshot has already arrived when `.sync` is attached, `callback` is immediately invoked with the current state so late subscribers stay up to date.
|
|
1075
|
+
|
|
1076
|
+
### Step 7: Refreshing Connections & Manual Resync (`ws.refresh(...)` & `ws.resync(...)`)
|
|
1077
|
+
|
|
1078
|
+
Use `ws.refresh(nextData)` when you want to close and reopen the socket—such as moving to another room or changing connection parameters—and `ws.resync(room)` when you want a fresh snapshot without closing the active connection.
|
|
1079
|
+
|
|
1080
|
+
#### Client
|
|
1081
|
+
|
|
1082
|
+
```
|
|
1083
|
+
import { api } from '/@client.js';
|
|
1084
|
+
|
|
1085
|
+
const ws = api.board.ws({
|
|
1086
|
+
room: 'sprint-1',
|
|
1087
|
+
user: 'maya'
|
|
1088
|
+
});
|
|
1089
|
+
|
|
1090
|
+
ws.sync((state, meta) => {
|
|
1091
|
+
console.log(`Room ${meta.room} @ seq ${meta.seq}`, state);
|
|
1092
|
+
});
|
|
1093
|
+
|
|
1094
|
+
// Close and reopen the connection with updated connection data (no { query: ... } wrapper)
|
|
1095
|
+
function moveToSprint(nextRoom) {
|
|
1096
|
+
ws.refresh({ room: nextRoom });
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
// Request a full state snapshot while keeping the current WebSocket open
|
|
1100
|
+
function requestFreshSnapshot() {
|
|
1101
|
+
ws.resync('sprint-2');
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
```
|
|
1105
|
+
|
|
1106
|
+
#### How It Works
|
|
1107
|
+
|
|
1108
|
+
- `ws.refresh(nextData)` merges any provided `nextData` object into the connection data, resets `lastSeq` to `0`, closes the existing socket cleanly, and opens a new connection with the updated URL.
|
|
1109
|
+
|
|
1110
|
+
- `ws.resync(room)` sends `{ type: 'resync', room }` over the open socket, prompting the server to send a `sync_snapshot` for the target room.
|
|
1111
|
+
|
|
1112
|
+
### Step 8: Complete End-to-End Example
|
|
1113
|
+
|
|
1114
|
+
Below is a complete, self-contained example combining direct connection data, `socket.state`, rooms & `broadcast`, `sockets.where(...)`, guards & `validate`, room state + `commit` + `seq` replay, `.sync(...)`, `.refresh(...)`, and `.resync(...)`.
|
|
1115
|
+
|
|
1116
|
+
#### Server (`server.js` entry)
|
|
1117
|
+
|
|
1118
|
+
```
|
|
1119
|
+
import { serve } from './server.js';
|
|
1120
|
+
|
|
1121
|
+
await serve({
|
|
1122
|
+
port: 3000,
|
|
1123
|
+
api: {
|
|
1124
|
+
workspace: {
|
|
1125
|
+
ws: {
|
|
1126
|
+
maxPayloadBytes: 32768,
|
|
1127
|
+
maxEventsPerSec: 25,
|
|
1128
|
+
maxBufferedBytes: 262144,
|
|
1129
|
+
sync: {
|
|
1130
|
+
bufferSize: 100
|
|
1131
|
+
},
|
|
1132
|
+
|
|
1133
|
+
state(socket, req) {
|
|
1134
|
+
const room = req.data.room || 'general';
|
|
1135
|
+
return {
|
|
1136
|
+
room,
|
|
1137
|
+
notes: []
|
|
1138
|
+
};
|
|
1139
|
+
},
|
|
1140
|
+
|
|
1141
|
+
open(socket, req) {
|
|
1142
|
+
const room = req.data.room || 'general';
|
|
1143
|
+
const user = req.data.user || 'guest';
|
|
1144
|
+
const role = req.data.role || 'member';
|
|
1145
|
+
|
|
1146
|
+
socket.state = { room, user, role };
|
|
1147
|
+
if (!socket.rooms.has(room)) {
|
|
1148
|
+
socket.join(room);
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
socket.to(room).broadcast(
|
|
1152
|
+
{ event: 'presence', status: 'online', user },
|
|
1153
|
+
{ except: socket }
|
|
1154
|
+
);
|
|
1155
|
+
},
|
|
1156
|
+
|
|
1157
|
+
actions: {
|
|
1158
|
+
addNote: {
|
|
1159
|
+
validate(payload) {
|
|
1160
|
+
const text = String(payload?.text ?? '').trim();
|
|
1161
|
+
if (!text) throw new Error('NOTE_TEXT_REQUIRED');
|
|
1162
|
+
return { text };
|
|
1163
|
+
},
|
|
1164
|
+
run({ text }, socket, { commit }) {
|
|
1165
|
+
const { room, user } = socket.state;
|
|
1166
|
+
commit(room, { op: 'add_note', author: user }, (draft) => {
|
|
1167
|
+
draft.notes.push({
|
|
1168
|
+
id: `${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
|
1169
|
+
author: user,
|
|
1170
|
+
text
|
|
1171
|
+
});
|
|
1172
|
+
});
|
|
1173
|
+
}
|
|
1174
|
+
},
|
|
1175
|
+
|
|
1176
|
+
removeNote: {
|
|
1177
|
+
validate(payload) {
|
|
1178
|
+
const id = String(payload?.id ?? '').trim();
|
|
1179
|
+
if (!id) throw new Error('NOTE_ID_REQUIRED');
|
|
1180
|
+
return { id };
|
|
1181
|
+
},
|
|
1182
|
+
run({ id }, socket, { commit }) {
|
|
1183
|
+
const { room, user } = socket.state;
|
|
1184
|
+
commit(room, { op: 'remove_note', actor: user, id }, (draft) => {
|
|
1185
|
+
draft.notes = draft.notes.filter((note) => note.id !== id);
|
|
1186
|
+
});
|
|
1187
|
+
}
|
|
1188
|
+
},
|
|
1189
|
+
|
|
1190
|
+
pingRole: {
|
|
1191
|
+
validate(payload) {
|
|
1192
|
+
const role = String(payload?.role ?? '').trim();
|
|
1193
|
+
if (!role) throw new Error('TARGET_ROLE_REQUIRED');
|
|
1194
|
+
return {
|
|
1195
|
+
role,
|
|
1196
|
+
message: String(payload?.message ?? '')
|
|
1197
|
+
};
|
|
1198
|
+
},
|
|
1199
|
+
run({ role, message }, socket, { sockets }) {
|
|
1200
|
+
sockets
|
|
1201
|
+
.where((peer) => peer !== socket && peer.state?.role === role)
|
|
1202
|
+
.send({
|
|
1203
|
+
event: 'role_ping',
|
|
1204
|
+
from: socket.state.user,
|
|
1205
|
+
message
|
|
1206
|
+
});
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
},
|
|
1210
|
+
|
|
1211
|
+
close(socket) {
|
|
1212
|
+
const { room, user } = socket.state || {};
|
|
1213
|
+
if (room) {
|
|
1214
|
+
socket.leave(room);
|
|
1215
|
+
socket.to(room).broadcast(
|
|
1216
|
+
{ event: 'presence', status: 'offline', user },
|
|
1217
|
+
{ except: socket }
|
|
1218
|
+
);
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
});
|
|
1225
|
+
|
|
1226
|
+
```
|
|
1227
|
+
|
|
1228
|
+
#### Client (`client.js`)
|
|
1229
|
+
|
|
1230
|
+
```
|
|
1231
|
+
import { api } from '/@client.js';
|
|
1232
|
+
|
|
1233
|
+
let workspaceState = null;
|
|
1234
|
+
|
|
1235
|
+
const ws = api.workspace.ws({
|
|
1236
|
+
room: 'general',
|
|
1237
|
+
user: 'maya',
|
|
1238
|
+
role: 'lead'
|
|
1239
|
+
});
|
|
1240
|
+
|
|
1241
|
+
ws
|
|
1242
|
+
.on('open', ({ reconnected }) => {
|
|
1243
|
+
console.log(reconnected ? 'Reconnected to workspace' : 'Connected to workspace');
|
|
1244
|
+
})
|
|
1245
|
+
.on('broadcast', ({ room, payload }) => {
|
|
1246
|
+
console.log(`Broadcast in ${room}:`, payload);
|
|
1247
|
+
})
|
|
1248
|
+
.on('event', (payload) => {
|
|
1249
|
+
console.log('Targeted event:', payload);
|
|
1250
|
+
})
|
|
1251
|
+
.on('error', (err) => {
|
|
1252
|
+
console.error('WS error:', err);
|
|
1253
|
+
})
|
|
1254
|
+
.sync((state, meta) => {
|
|
1255
|
+
workspaceState = state;
|
|
1256
|
+
console.log('Synced state:', {
|
|
1257
|
+
seq: meta.seq,
|
|
1258
|
+
room: meta.room,
|
|
1259
|
+
fullSnapshot: meta.fullSnapshot,
|
|
1260
|
+
replayed: meta.replayed,
|
|
1261
|
+
notesCount: workspaceState?.notes?.length ?? 0
|
|
1262
|
+
});
|
|
1263
|
+
});
|
|
1264
|
+
|
|
1265
|
+
// Add a note to the current room state
|
|
1266
|
+
ws.emit('addNote', { text: 'Kickoff sync notes' });
|
|
1267
|
+
|
|
1268
|
+
// Send a targeted message only to other connected sockets with role 'lead'
|
|
1269
|
+
ws.emit('pingRole', { role: 'lead', message: 'Check latest notes' });
|
|
1270
|
+
|
|
1271
|
+
// Switch room with a fresh connection and updated connection data
|
|
1272
|
+
ws.refresh({ room: 'planning' });
|
|
1273
|
+
|
|
1274
|
+
// Request a full snapshot without closing the connection
|
|
1275
|
+
ws.resync('planning');
|
|
1276
|
+
|
|
527
1277
|
```
|
|
528
1278
|
|
|
529
1279
|
---
|
|
@@ -1390,76 +2140,6 @@ const exportsApi = {
|
|
|
1390
2140
|
|
|
1391
2141
|
---
|
|
1392
2142
|
|
|
1393
|
-
## 11. Linear WebSockets & Pub/Sub
|
|
1394
|
-
|
|
1395
|
-
### 11.1 Step 1: Minimal Echo WebSocket (`ws` & `for await`)
|
|
1396
|
-
|
|
1397
|
-
Add a `ws(socket)` method anywhere in your tree and iterate over incoming messages linearly with `for await`:
|
|
1398
|
-
|
|
1399
|
-
```javascript
|
|
1400
|
-
const echo = {
|
|
1401
|
-
// WS /echo
|
|
1402
|
-
async ws(socket) {
|
|
1403
|
-
socket.send({ status: "connected" });
|
|
1404
|
-
|
|
1405
|
-
for await (const msg of socket) {
|
|
1406
|
-
socket.send({ echoed: msg });
|
|
1407
|
-
}
|
|
1408
|
-
},
|
|
1409
|
-
};
|
|
1410
|
-
```
|
|
1411
|
-
|
|
1412
|
-
### 11.2 Step 2: Rooms & Pub/Sub Broadcasting (`socket.join`, `wire.publish`)
|
|
1413
|
-
|
|
1414
|
-
Subscribe sockets to named topics and broadcast messages from either WebSocket handlers or HTTP routes:
|
|
1415
|
-
|
|
1416
|
-
```javascript
|
|
1417
|
-
const chat = {
|
|
1418
|
-
$room: {
|
|
1419
|
-
// WS /chat/:room
|
|
1420
|
-
async ws(room, socket) {
|
|
1421
|
-
socket.join(`room:${room}`);
|
|
1422
|
-
socket.broadcast(`room:${room}`, { event: "joined" });
|
|
1423
|
-
|
|
1424
|
-
for await (const msg of socket) {
|
|
1425
|
-
wire.publish(`room:${room}`, { text: msg.text });
|
|
1426
|
-
}
|
|
1427
|
-
},
|
|
1428
|
-
},
|
|
1429
|
-
|
|
1430
|
-
// Any HTTP route can also publish to WebSocket subscribers!
|
|
1431
|
-
announce: {
|
|
1432
|
-
post({ room, text }) {
|
|
1433
|
-
wire.publish(`room:${room}`, { announcement: text });
|
|
1434
|
-
return { sent: true };
|
|
1435
|
-
},
|
|
1436
|
-
},
|
|
1437
|
-
};
|
|
1438
|
-
```
|
|
1439
|
-
|
|
1440
|
-
### 11.3 Step 3: Guarded WebSockets & `wsConfig`
|
|
1441
|
-
|
|
1442
|
-
Combine `guard()`, `param()`, and `wsConfig` (`heartbeat`, `maxPayload`, `binary`) on the same branch:
|
|
1443
|
-
|
|
1444
|
-
```javascript
|
|
1445
|
-
const liveStream = guard(requireAuth, {
|
|
1446
|
-
wsConfig: {
|
|
1447
|
-
maxPayload: "256kb",
|
|
1448
|
-
heartbeat: "30s",
|
|
1449
|
-
},
|
|
1450
|
-
$channelId: param("int", {
|
|
1451
|
-
async ws(channelId, socket) {
|
|
1452
|
-
socket.join(`ch:${channelId}`);
|
|
1453
|
-
for await (const msg of socket) {
|
|
1454
|
-
socket.broadcast(`ch:${channelId}`, msg);
|
|
1455
|
-
}
|
|
1456
|
-
},
|
|
1457
|
-
}),
|
|
1458
|
-
});
|
|
1459
|
-
```
|
|
1460
|
-
|
|
1461
|
-
---
|
|
1462
|
-
|
|
1463
2143
|
## 12. Streaming File Uploads (`wire.multipart` & `rawBody`)
|
|
1464
2144
|
|
|
1465
2145
|
**1. Streaming `multipart/form-data` without buffering in RAM:**
|
|
@@ -1613,7 +2293,6 @@ await replay(
|
|
|
1613
2293
|
| `wire.multipart(opts)` | `(opts?) => AsyncGenerator` | Iterates streaming `multipart/form-data` fields and files sequentially. |
|
|
1614
2294
|
| `wire.session` | `Proxy \| null` | Lazy encrypted session object (`.rotate()`, `.bind(userId)`, or `wire.session = null`). |
|
|
1615
2295
|
| `wire.sessions` | `{ list, revokeOthers }` | Multi-device session listing and remote session revocation helpers. |
|
|
1616
|
-
| `wire.publish(topic, data)` | `(string, any) => void` | Broadcasts a message to all WebSocket clients subscribed to `topic`. |
|
|
1617
2296
|
| `wire.cost(points)` | `(number) => void` | Adjusts rate-limit quota consumption for the current request. |
|
|
1618
2297
|
| `wire.log.debug(msg, meta)` | `(string, any?) => void` | Buffers a debug log entry emitted only on unhandled errors. |
|
|
1619
2298
|
| `wire.mark(label)` | `(string) => () => number` | Starts a performance timer; calling the returned function records `Server-Timing`. |
|