// SPDX-License-Identifier: AGPL-3.0-or-later package collab import ( "encoding/binary" "errors" "slices" ) // The y-websocket wire format (y-protocols sync and awareness, lib0 encoding): // // [varuint messageType] ... // sync: [varuint step] [varUint8Array payload] // awareness: [varUint8Array update] const ( msgSync = 0 msgAwareness = 1 msgQueryAwareness = 3 syncStep1 = 0 // payload: the sender's state vector syncStep2 = 1 // payload: an update with what the receiver is missing syncUpdate = 2 // payload: an incremental update ) var errMalformed = errors.New("malformed message") type decoder struct{ buf []byte } func (d *decoder) uint() (uint64, error) { v, n := binary.Uvarint(d.buf) if n <= 0 { return 0, errMalformed } d.buf = d.buf[n:] return v, nil } func (d *decoder) bytes() ([]byte, error) { n, err := d.uint() if err != nil || uint64(len(d.buf)) < n { return nil, errMalformed } b := d.buf[:n] d.buf = d.buf[n:] return b, nil } func appendUint(b []byte, v uint64) []byte { return binary.AppendUvarint(b, v) } func appendBytes(b, v []byte) []byte { return append(appendUint(b, uint64(len(v))), v...) } func syncMessage(step uint64, payload []byte) []byte { b := make([]byte, 0, len(payload)+8) return appendBytes(appendUint(appendUint(b, msgSync), step), payload) } func awarenessMessage(update []byte) []byte { return appendBytes(appendUint(make([]byte, 0, len(update)+8), msgAwareness), update) } // awarenessState is one client's entry in an awareness update. type awarenessState struct { clock uint64 state string // JSON; "null" means the client left } // decodeAwareness reads [varuint n] then n × [varuint clientID][varuint clock][varString state]. func decodeAwareness(update []byte) (map[uint64]awarenessState, error) { d := decoder{update} n, err := d.uint() if err != nil || n > 1<<16 { return nil, errMalformed } out := make(map[uint64]awarenessState, n) for range n { id, err := d.uint() if err != nil { return nil, err } clock, err := d.uint() if err != nil { return nil, err } state, err := d.bytes() if err != nil { return nil, err } out[id] = awarenessState{clock: clock, state: string(state)} } return out, nil } func encodeAwareness(states map[uint64]awarenessState) []byte { b := appendUint(nil, uint64(len(states))) ids := make([]uint64, 0, len(states)) for id := range states { ids = append(ids, id) } slices.Sort(ids) for _, id := range ids { s := states[id] b = appendBytes(appendUint(appendUint(b, id), s.clock), []byte(s.state)) } return b }