Documentation
¶
Overview ¶
Package protocol reads and writes the y-protocols messages Yjs peers exchange, for applications that carry them over a transport of their own: a WebRTC data channel, a message bus, a TCP socket, a test pipe. The server and client packages speak the same bytes over WebSocket.
There are three layers, each a function of bytes:
- Sync messages (y-protocols/sync): step 1 carries a state vector, step 2 the updates the other side lacks, update one live change. EncodeSyncStep1, EncodeSyncStep2, EncodeUpdate, ReadSync; and on a document, StartSync and HandleSync, which answer a step 1 and apply a step 2 or an update as y-protocols' readSyncMessage does.
- The y-websocket envelope: a message type before each message, so sync, awareness and auth share one connection. EncodeSyncMessage, EncodeAwareness, EncodeQueryAwareness, Read; y-protocols' auth dialect with EncodePermissionDenied and ReadPermissionDenied.
- Hocuspocus: a routing key (the document name, maybe followed by a NUL and a session ID) before each document message, its own auth dialect, CLOSE, and the acknowledgement of each update (SyncStatus).
A two-peer handshake over any message transport:
// A asks: here is what I have.
send(protocol.EncodeSyncMessage(protocol.StartSync(a)))
// B, for each message it receives from A:
m, _, err := protocol.Read(msg)
if err != nil {
return err // not a message: drop the connection
}
if m.Type == protocol.MessageSync {
reply, err := protocol.HandleSync(b, m.Sync, peerA)
if errors.Is(err, protocol.ErrApply) {
log.Print(err) // y-protocols logs these and goes on
} else if err != nil {
return err
}
if reply != nil {
send(protocol.EncodeSyncMessage(reply)) // B's step 2, to A
}
}
Example has this loop as a function that runs.
Both sides send a step 1, so each ends up with what the other has; after that, Doc.OnUpdate gives each local change to send as EncodeUpdate. OnUpdate runs with the document's write lock held: stage the bytes there and send them from another goroutine (examples/peer-sync shows how), or a peer that applies to the same document from its callback deadlocks.
One message at a time ¶
Read decodes one transport message: a WebSocket message, an HTTP body, a data-channel message. y-websocket and Hocuspocus give every message its own frame, and a type this package does not know (an application's own extension) keeps the rest of the bytes as its payload; nothing is read past it. Over a byte stream, which has no message boundaries, frame each message with WriteRecord and read it back with ReadRecord.
Updates are V1 ¶
Sync messages carry one V1 update (y-protocols applies them with Y.applyUpdate). Nothing checks that bytes handed to EncodeUpdate or EncodeSyncStep2 are one; ygo.ValidateUpdate does, for a caller that wants to.
Ownership ¶
Payloads returned by Read, ReadSync and the readers here are copies; the rest returned with them is a sub-slice of the input.
Example ¶
Two documents sync with y-protocols messages: each sends a step 1, each answers the other's with a step 2. Here the "transport" is a function call; it can be anything that carries a message.
package main
import (
"errors"
"fmt"
"log"
"github.com/Deln0r/ygo"
"github.com/Deln0r/ygo/protocol"
)
func main() {
a, b := ygo.NewDocWithOptions(ygo.Options{ClientID: 1}), ygo.NewDocWithOptions(ygo.Options{ClientID: 2})
write := func(d *ygo.Doc, s string) {
t := ygo.NewText(d, "notes")
txn := d.WriteTxn()
_ = t.Insert(txn, t.Length(), s)
txn.Commit()
}
write(a, "from a. ")
write(b, "from b. ")
// receive is what a peer does with each message from another: the loop
// in the package documentation. It returns the reply to send back.
receive := func(d *ygo.Doc, from string, msg []byte) ([]byte, error) {
m, _, err := protocol.Read(msg)
if err != nil {
return nil, err // not a message: drop the connection
}
if m.Type != protocol.MessageSync {
return nil, nil // awareness and the rest: not shown here
}
reply, err := protocol.HandleSync(d, m.Sync, from)
if errors.Is(err, protocol.ErrApply) {
log.Print(err) // y-protocols logs these and goes on
} else if err != nil {
return nil, err
}
if reply == nil {
return nil, nil
}
return protocol.EncodeSyncMessage(reply), nil
}
// a's step 1 goes to b, b's step 2 comes back to a; then the other way.
for _, p := range [][2]*ygo.Doc{{a, b}, {b, a}} {
step2, err := receive(p[1], "peer", protocol.EncodeSyncMessage(protocol.StartSync(p[0])))
if err != nil {
log.Fatal(err)
}
if _, err := receive(p[0], "peer", step2); err != nil {
log.Fatal(err)
}
}
read := func(d *ygo.Doc) string {
t := ygo.NewText(d, "notes") // before the read transaction: it takes the lock
r := d.ReadTxn()
defer r.Close()
return t.String()
}
fmt.Println(read(a) == read(b), len(read(a)))
}
Output: true 16
Index ¶
- Variables
- func DocumentName(key string) string
- func EncodeAwareness(update []byte) []byte
- func EncodeClose(reason string) []byte
- func EncodeCloseRequest() []byte
- func EncodeHocuspocusAuthenticated(scope string) []byte
- func EncodeHocuspocusPermissionDenied(reason string) []byte
- func EncodeHocuspocusToken(token string) []byte
- func EncodeHocuspocusTokenRequest() []byte
- func EncodePermissionDenied(reason string) []byte
- func EncodePing() []byte
- func EncodePong() []byte
- func EncodeQueryAwareness() []byte
- func EncodeSyncMessage(sync []byte) []byte
- func EncodeSyncStatus(applied bool) []byte
- func EncodeSyncStep1(stateVector []byte) []byte
- func EncodeSyncStep2(update []byte) []byte
- func EncodeUpdate(update []byte) []byte
- func HandleSync(d *ygo.Doc, m SyncMessage, origin any) (reply []byte, err error)
- func ReadClose(payload []byte) (reason string, err error)
- func ReadPermissionDenied(payload []byte) (reason string, err error)
- func ReadRecord(r RecordReader, limit int) ([]byte, error)
- func ReadRoutingKey(b []byte) (key string, rest []byte, err error)
- func ReadSyncStatus(payload []byte) (applied bool, err error)
- func StartSync(d *ygo.Doc) []byte
- func WithRoutingKey(key string, msg []byte) ([]byte, error)
- func WriteRecord(w io.Writer, msg []byte) error
- type HocuspocusAuth
- type HocuspocusAuthType
- type Message
- type MessageType
- type RecordReader
- type SyncMessage
- type SyncType
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrMalformed is returned for bytes that are not a message this // package reads: truncated, an unknown sync type, a step 1 without a // state vector. ErrMalformed = errors.New("protocol: malformed message") // ErrApply is returned by HandleSync when a well-formed step 2 or // update could not be applied; the apply error is wrapped too. ErrApply = errors.New("protocol: update not applied") )
var ErrInvalidKey = errors.New("protocol: routing key is not valid UTF-8")
ErrInvalidKey is returned by WithRoutingKey for a key that is not valid UTF-8.
var ErrTooLarge = errors.New("protocol: record too large")
ErrTooLarge is returned by ReadRecord for a record longer than its limit.
Functions ¶
func DocumentName ¶
DocumentName is the document a routing key names: the key up to its first NUL, as Hocuspocus' parseRoutingKey.
func EncodeAwareness ¶
EncodeAwareness puts an awareness update (ygo.Awareness's Encode or EncodeLive) in the y-websocket envelope.
func EncodeClose ¶
EncodeClose writes a server's CLOSE, in the envelope: the document was closed, and why. The reason is always written, empty or not, since a provider reads it.
func EncodeCloseRequest ¶
func EncodeCloseRequest() []byte
EncodeCloseRequest writes a provider's CLOSE, in the envelope: it asks the server to close the document, and carries nothing else.
func EncodeHocuspocusAuthenticated ¶
EncodeHocuspocusAuthenticated writes a server's acceptance with the scope granted, in the envelope.
func EncodeHocuspocusPermissionDenied ¶
EncodeHocuspocusPermissionDenied writes a server's refusal, in the envelope.
func EncodeHocuspocusToken ¶
EncodeHocuspocusToken writes a provider's token message, in the envelope (put the routing key before it). Hocuspocus providers 3 and 4 add their version after the token; servers do not read it.
func EncodeHocuspocusTokenRequest ¶
func EncodeHocuspocusTokenRequest() []byte
EncodeHocuspocusTokenRequest writes a server's request for the provider's token, in the envelope.
func EncodePermissionDenied ¶
EncodePermissionDenied writes y-protocols' auth message (the dialect of y-websocket servers), in the envelope.
func EncodePing ¶
func EncodePing() []byte
EncodePing and EncodePong write Hocuspocus' keep-alive messages. They belong to the connection, not a document: send them without a routing key.
func EncodeQueryAwareness ¶
func EncodeQueryAwareness() []byte
EncodeQueryAwareness writes a request for every known awareness state.
func EncodeSyncMessage ¶
EncodeSyncMessage puts a sync message in the y-websocket envelope.
func EncodeSyncStatus ¶
EncodeSyncStatus writes a server's acknowledgement of one update from the provider, in the envelope: applied, or refused (a read-only connection's update, or one a hook rejected).
func EncodeSyncStep1 ¶
EncodeSyncStep1 writes a step 1 carrying a V1 state vector (ygo.EncodeStateVector), as y-protocols' writeSyncStep1. It is the sync message alone: EncodeSyncMessage puts it in the y-websocket envelope.
func EncodeSyncStep2 ¶
EncodeSyncStep2 writes a step 2 carrying one V1 update, as y-protocols' writeSyncStep2.
func EncodeUpdate ¶
EncodeUpdate writes an update message carrying one V1 update, as y-protocols' writeUpdate.
func HandleSync ¶
HandleSync answers or applies one sync message on d, as y-protocols' readSyncMessage:
- a step 1 is answered with a step 2 (the reply, to send back) holding what the sender lacks, including the updates d holds pending, as Y.encodeStateAsUpdate;
- a step 2 or an update is applied with origin (Doc.OnUpdate observers see it); there is no reply.
A step 1 without a state vector, or with one that does not decode, is refused with ErrMalformed (y-protocols throws on it). An update that does not apply is returned as ErrApply wrapping the apply error; y-protocols logs those and goes on, and a caller that wants to do the same checks errors.Is(err, ErrApply). A panic in an observer is the observer's, not an error here.
Access control is the caller's: a read-only peer answers step 1 and does not call HandleSync for a step 2 or an update.
func ReadClose ¶
ReadClose reads the payload of a MessageClose: a server's carries a reason, a provider's none (reason "").
func ReadPermissionDenied ¶
ReadPermissionDenied reads the payload of a MessageAuth in y-protocols' dialect. The bytes do not say which dialect they are in: y-protocols' permission denied reads as a Hocuspocus token, and Hocuspocus' as an unknown y-protocols type. Read with the dialect of the server at the other end (ReadHocuspocusAuth for Hocuspocus).
func ReadRecord ¶
func ReadRecord(r RecordReader, limit int) ([]byte, error)
ReadRecord reads one record written by WriteRecord. A record longer than limit bytes is refused with ErrTooLarge before any of it is read. At the end of the stream between records it returns io.EOF; inside a record, io.ErrUnexpectedEOF.
func ReadRoutingKey ¶
ReadRoutingKey reads the routing key at the start of a Hocuspocus message and returns the message after it, a sub-slice of b, for Read.
func ReadSyncStatus ¶
ReadSyncStatus reads the payload of a MessageSyncStatus: whether the server applied the update it acknowledges. It reads the value as the provider does (a signed varint, applied when it is 1).
func StartSync ¶
StartSync is the step 1 a peer opens a sync with: d's state vector, the sync message alone (EncodeSyncMessage puts it in the y-websocket envelope).
func WithRoutingKey ¶
WithRoutingKey puts a Hocuspocus routing key before a message of the envelope: every message about a document starts with its key, so one connection carries several documents. The key is the document name, or the name, a NUL and a session ID when a provider opens the same document more than once; answer with the key as it came (DocumentName gives the name). Ping and Pong belong to the connection and take no key.
A key that is not valid UTF-8 is refused with ErrInvalidKey: lib0 throws on it, and a Hocuspocus peer closes the whole connection, every document on it, when a message does not parse. Replacing the bad bytes would name another document, so the key is not changed.
Types ¶
type HocuspocusAuth ¶
type HocuspocusAuth struct {
Type HocuspocusAuthType
// Value is the token, the reason or the scope.
Value string
// Request is set for a token message without a token: the server asks
// the provider for its token (again, when it has to be renewed).
Request bool
}
HocuspocusAuth is one Hocuspocus auth message.
func ReadHocuspocusAuth ¶
func ReadHocuspocusAuth(payload []byte) (HocuspocusAuth, error)
ReadHocuspocusAuth reads the payload of a MessageAuth in Hocuspocus' dialect. Bytes after the value (a provider's version) are not read.
type HocuspocusAuthType ¶
type HocuspocusAuthType uint64
HocuspocusAuthType is the tag of a Hocuspocus auth message, a varuint compared whole. Hocuspocus' numbering is not y-protocols': its 0 is a token, where y-protocols' 0 is permission denied.
const ( // HocuspocusToken carries a provider's token; with no token, it is the // server asking the provider for one (HocuspocusAuth.Request). HocuspocusToken HocuspocusAuthType = 0 // HocuspocusPermissionDenied carries the server's reason. HocuspocusPermissionDenied HocuspocusAuthType = 1 // HocuspocusAuthenticated carries the scope the server granted: // "read-write" or "readonly". HocuspocusAuthenticated HocuspocusAuthType = 2 )
type Message ¶
type Message struct {
Type MessageType
// Sync is the sync message of a MessageSync or MessageSyncReply.
Sync SyncMessage
// Payload is the awareness update of a MessageAwareness; for every
// other type but the sync ones, the bytes after the type, unread
// (an auth, close or sync-status message is read from it with this
// package's readers).
Payload []byte
}
Message is one message of the y-websocket envelope.
func Read ¶
Read reads one message of the y-websocket envelope from b, one transport message. It returns what follows a sync or awareness message, which y-websocket ignores; for any other type the rest is the payload, and nothing follows.
Example ¶
A message of a type the application defines rides in the same envelope: Read returns its type and the bytes after it.
package main
import (
"fmt"
"github.com/Deln0r/ygo/protocol"
)
func main() {
m, rest, err := protocol.Read([]byte{100, 'h', 'i'})
fmt.Println(m.Type, string(m.Payload), rest == nil, err)
}
Output: 100 hi true <nil>
type MessageType ¶
type MessageType uint64
MessageType is the tag before each message of the y-websocket envelope. It is a varuint on the wire and compared whole: a type past 255 is not its low byte.
const ( // MessageSync carries a sync message (step 1, step 2 or update). MessageSync MessageType = 0 // MessageAwareness carries an awareness update (ygo.Awareness). MessageAwareness MessageType = 1 // MessageAuth carries an auth message, in y-protocols' dialect // (ReadPermissionDenied) or Hocuspocus' (ReadHocuspocusAuth), // depending on the server. MessageAuth MessageType = 2 // MessageQueryAwareness asks for every known awareness state; it has // no payload. MessageQueryAwareness MessageType = 3 // MessageSyncReply is a sync message Hocuspocus servers send each // other (extension-redis); a server reads it as MessageSync, and // answers its step 1 without a step 1 of its own. Providers do not // read it: send them MessageSync. MessageSyncReply MessageType = 4 // MessageStateless carries an application string between a provider // and the server, either way. MessageStateless MessageType = 5 // MessageBroadcastStateless carries an application string between // Hocuspocus servers (extension-redis), for every connection to the // document. A server refuses it from a client: clients send // MessageStateless, and the server decides whether to broadcast. MessageBroadcastStateless MessageType = 6 // MessageClose closes one document of a multiplexed connection // (ReadClose). MessageClose MessageType = 7 // MessageSyncStatus acknowledges one update: applied or refused // (ReadSyncStatus). MessageSyncStatus MessageType = 8 // MessagePing and MessagePong keep a Hocuspocus connection alive; they // belong to the connection, so they have no routing key. MessagePing MessageType = 9 MessagePong MessageType = 10 )
type RecordReader ¶
type RecordReader interface {
io.Reader
io.ByteReader
}
RecordReader is what ReadRecord reads from; a *bufio.Reader is one.
type SyncMessage ¶
type SyncMessage struct {
Type SyncType
// Payload is the state vector of a step 1, the update of a step 2 or
// an update.
Payload []byte
}
SyncMessage is one sync message.