Awesome Go

ygo

CategoryDistributed Systems
SubcategoryDistributed Systems
Stars95

Pure Go port of the Yjs CRDT, wire-compatible with JavaScript yjs clients

About ygo

This large README is shown as a plain-text preview. Read the full README at the source

# Ygo

[![Listed in the Yjs docs](https://img.shields.io/badge/Yjs%20docs-listed%20port-7c3aed.svg)](https://docs.yjs.dev/ecosystem/ports-to-other-languages)
[![CI](https://github.com/Deln0r/ygo/actions/workflows/test.yml/badge.svg)](https://github.com/Deln0r/ygo/actions/workflows/test.yml)
[![Coverage](https://coveralls.io/repos/github/Deln0r/ygo/badge.svg?branch=main)](https://coveralls.io/github/Deln0r/ygo?branch=main)
[![Go Reference](https://pkg.go.dev/badge/github.com/Deln0r/ygo.svg)](https://pkg.go.dev/github.com/Deln0r/ygo)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![Go Version](https://img.shields.io/badge/go-1.23%2B-00ADD8.svg)](go.mod)
[![Yjs Protocol](https://img.shields.io/badge/Yjs%20protocol-V1%20%2B%20V2-7c3aed.svg)](https://github.com/yjs/yjs)
[![Live Demo](https://img.shields.io/badge/live%20demo-ygo.deln0r.com-22c55e.svg)](https://ygo.deln0r.com)
[![Codeberg Mirror](https://img.shields.io/badge/codeberg-mirror-2185d0?logo=codeberg&logoColor=white)](https://codeberg.org/Deln0r/ygo)

Pure-Go port of [Yjs](https://github.com/yjs/yjs), the CRDT framework for collaborative applications, listed on the [ports page](https://docs.yjs.dev/ecosystem/ports-to-other-languages) of the Yjs documentation.

Ygo speaks the **Yjs V1 and V2 wire formats** byte for byte, apart from whole-number floats set from Go and a lone surrogate in a V1 embed or format value (see [Strings and values](#strings-and-values)). The encoding is verified in both directions through **890 cross-language fixture scenarios** generated from `[email protected]`. The bundled WebSocket server speaks the `y-websocket` protocol: JavaScript clients using `y-websocket` connect to it directly, and the Go client connects to the reference `y-websocket` server. Since 1.37.0 the server also serves `@hocuspocus/provider` 2.15, 3.4 and 4.8, and the Go client connects to Hocuspocus servers of those versions (see [Hocuspocus setup](docs/yserve.md#coming-from-hocuspocus)). No CGO; `gomobile bind` produces an Android AAR (built in CI) and an iOS xcframework (built by hand).

## Highlights

- **Byte-level wire compatibility, verified in both directions.** 890 cross-language fixture scenarios (generated from `[email protected]`) cover the V1 and V2 update formats, snapshots, subdocuments, undo, observers, relative positions, GC, awareness, the sync protocol, and the Any values JavaScript has and Go does not (undefined, BigInt, -0), JS to Go and Go to JS, plus 56 lib0 primitive vectors. The suite runs in CI on every push to `main` and every pull request, so a regression in either direction fails the build. The exceptions are the Any values listed under [Strings and values](#strings-and-values).
- **Pure Go, no CGO.** The CRDT core, the sync client and the server compile with `CGO_ENABLED=0` for all 47 targets in `go tool dist list`, `js/wasm` and `wasip1/wasm` included. The core module needs Go 1.23. The SQLite-backed store in [`persist/sqlite`](persist/sqlite), and with it `yserve` and the mobile SDK, is a module of its own that needs Go 1.26, and builds only where `modernc.org/sqlite` does: not on wasm, AIX, DragonFly, illumos, Plan 9, Solaris, MIPS or big-endian ppc64 Linux, NetBSD other than amd64, or OpenBSD other than amd64 and arm64. Elsewhere, supply your own [`persist.Store`](persist) (it is a seven-method interface). `gomobile bind` produces an Android AAR (built in CI on every push to `main` and every pull request) and an iOS xcframework (built by hand on 2026-11-10) carrying a full mobile SDK: editable Text / Map, undo, cursors, and a built-in background sync client (WebSocket + reconnect), so a Swift / Kotlin app only renders UI. No V8, no embedded JavaScript engine, no Rust FFI bridge.
- **Embeddable sync client, offline-first.** The [`client`](client) package is a Go-native `y-websocket` provider, and with `Options.Hocuspocus` a Hocuspocus one: handshake, incremental updates, awareness, reconnect with backoff, and a liveness check that redials a connection which went silent. With a `LocalStore` it persists the document to disk (pure-Go SQLite), loads it before any network so the app works offline, and syncs edits made offline up on reconnect. The building block for bots, CLI tools, server-side agents, and the mobile SDK (`EnableOfflineStore`).
- **The Yjs shared types.** Map, Array, Text (rich-text formatting, Quill deltas, embeds), XML types, Awareness, UndoManager, Snapshots / time-travel, and Subdocuments. Not implemented: the legacy `XmlHook`, observers on `XmlFragment` and `XmlElement`, and `Text.ObserveDeep`.
- **Change observers.** `Map.Observe` / `Array.Observe` / `Text.Observe` deliver Quill-style deltas of exactly what changed; `ObserveDeep` bubbles events from nested types with their path. Semantic parity with yjs's YMapEvent / YArrayEvent / YTextEvent. On mobile, `ObserveChanges` hands a native editor the delta as JSON.
- **One update per transaction.** `Doc.OnUpdate` / `OnUpdateV2` hand you each committed transaction as an update holding just its changes, the bytes yjs emits on `doc.on('update')` (known exceptions in the status table), with the transaction's origin; an append costs under 30 bytes however long the history. `ApplyUpdateWithOrigin` tags a peer's update so an echo guard and the UndoManager can tell it apart, and `EncodeDiff` catches a peer up from its own clock.
- **Compact encoding.** Commit-time block squash collapses per-character edits into single items (about 1 byte per character in V1), and garbage collection frees deleted content at commit. On a 260k-edit real-world trace a document with a random client ID takes 311 KB in V1 and 160 KB in V2, the same as yjs: both draw 32-bit client IDs. With the same client ID, ygo and yjs produce documents of identical size in both formats.
- **Forward-looking wire handling.** ygo handles 53-bit client IDs throughout (byte-verified above 2^32), the confirmed wire-level change in the `yjs@14` release candidate, and decodes Skip structs in the update stream as no-op gaps (part of the wire format since yjs v13.5). Full attribution / IdMap support waits for the v14 format to stabilize.
- **Sync over HTTP too.** [`HTTPSyncHandler`](docs/yserve.md#sync-over-http) serves the server's own documents to clients that pull and push with plain requests (scripts, serverless functions, networks that drop WebSockets), next to the WebSocket clients of the same document: an HTTP write reaches them at once. Pulls are the bytes yjs's encoder writes (checked against yjs with `fetch` in CI), V1 or V2, with `ETag` / 304 polling; `client.HTTPSync` is the Go side.
- **Ready-to-run server: [yserve](docs/yserve.md).** A self-hosted Yjs server in one binary, with no Node and no Redis. `y-websocket` clients connect unchanged (CI runs y-websocket 2.1 and 3.1 against it), and SQLite persistence and periodic document versioning are built in. The document is the URL path, slashes included; behind a proxy that keeps a path prefix, pass it as `-path-prefix`. It also embeds as a plain `http.Handler` inside an existing Go backend.
- **Scales horizontally, as a library.** Several instances of the [`server`](server) package behind a load balancer converge on the same document through a pluggable [backplane](server/backplane): edits and live cursors both cross instances, so two users on different servers collaborate as if on one. An in-process hub ships in the core; an opt-in [NATS adapter](server/backplane/nats) (a separate module, so NATS stays out of the core's dependencies) spans machines, with a JetStream mode that resumes delivery across a broker reconnect or restart. Clustered instances share one `Store` and run the same ygo version. The `yserve` binary has no backplane option.
- **Federated transport over Matrix.** An opt-in [Matrix transport](integration/matrix) (a separate module, so mautrix stays out of a build that only wants the CRDT) turns an ordinary unencrypted Matrix room into the sync channel: peers publish updates as `dev.ygo.update` room events and merge what they read back, with no ygo server involved. A room is an append-only log with no ordering or exactly-once guarantee, which is exactly what Yjs updates tolerate. Room content is treated as untrusted — validated on both sides, decoded one event at a time so one bad event cannot break a whole page, encrypted rooms refused rather than silently written in the clear — though, as the module README spells out, Yjs updates do not authenticate deletes, so room membership is write access to the document. Exercised in CI against a real Dendrite on every push to `main` and every pull request. Its limits are documented rather than papered over.
- **EU-sovereign mirror** on [codeberg.org/Deln0r/ygo](https://codeberg.org/Deln0r/ygo), auto-synced from GitHub on every push for adopters who prefer or require EU-hosted code infrastructure.

**Live demo:** open [ygo.deln0r.com](https://ygo.deln0r.com) in two browser tabs and start typing. The page runs a stock `y-websocket` client in JavaScript against a pure-Go server.

## Quick start

```bash
go get github.com/Deln0r/ygo                  # Go 1.23 or later
go get github.com/Deln0r/ygo/persist/sqlite   # the SQLite store, a module of its own (Go 1.26)
```

```go
package main

import (
    "fmt"

    "github.com/Deln0r/ygo"
)

func main() {
    src := ygo.NewDoc()
    m := ygo.NewMap(src, "settings")

    txn := src.WriteTxn()
    m.Set(txn, "theme", "dark")
    m.Set(txn, "lang", "go")
    txn.Commit()

    // Encode the source doc's full state as wire bytes.
    update := ygo.EncodeStateAsUpdate(src)

    // Apply to a fresh peer doc — same bytes JS Yjs's Y.applyUpdate consumes.
    dst := ygo.NewDoc()
    if err := ygo.ApplyUpdate(dst, update); err != nil {
        panic(err)
    }

    dstMap := ygo.NewMap(dst, "settings")
    fmt.Println(dstMap.Get("theme")) // dark
}
```

For a collaborative server backend, see [yserve](docs/yserve.md), a stand-alone WebSocket server for `y-websocket` clients with SQLite persistence and document versioning, in one binary:

```bash
# CGO_ENABLED=0 makes the binary fully static on Linux
CGO_ENABLED=0 go install github.com/Deln0r/ygo/cmd/yserve@latest
yserve -addr :1234 -store data.db -version-interval 10m
```

### Sending each change

`Doc.OnUpdate` hands you every committed transaction as a V1 update holding exactly that transaction's changes, the bytes of yjs's `doc.on('update')`, except for the Any values listed under [Strings and values](#strings-and-values). Forward them to peers or append them to a log; an append costs a few bytes however long the document's history is. Apply what peers send with an origin, so the handler can tell their updates from yours:

```go
type peer struct{ id string }
from := &peer{id: "ws-1"}

d.OnUpdate(func(update []byte, origin any) {
    if origin == from {
        return // came from that peer, do not send it back
    }
    broadcast(update)
})

err := ygo.ApplyUpdateWithOrigin(d, received, from)
```

`OnUpdateV2` gives the V2 bytes, and `ApplyUpdateV2WithOrigin` applies V2 bytes with an origin. Handlers run at the end of the commit with the document lock held, in commit order; they must not open a transaction on the same document. To catch up a peer that has been away, send `ygo.EncodeDiff(d, peerStateVector)`: it starts exactly at the peer's clock, as `Y.encodeStateAsUpdate(doc, sv)` does, and like it appends the updates still waiting in the pending buffer for a missing dependency.

### Undo / Redo

Wrap any shared types in an `UndoManager` to get scoped, grouped Undo / Redo:

```go
d := ygo.NewDoc()
m := ygo.NewMap(d, "settings")

um := ygo.NewUndoManager(d, m) // watch m; defaults to local edits, 500ms grouping
defer um.Close()

txn := d.WriteTxn()
m.Set(txn, "theme", "dark")
txn.Commit()

um.Undo() // m no longer has "theme"
um.Redo() // "theme" == "dark" again
```

Only edits under the watched types made by a tracked origin are captured. The default tracks the nil origin, which local edits carry, but so does plain `ApplyUpdate`, exactly as in yjs: apply remote updates with `ygo.ApplyUpdateWithOrigin(d, update, origin)` to keep them out of the history, or track your own origin only (`um.AddTrackedOrigin(mine)`, `um.RemoveTrackedOrigin(nil)`). Rapid edits inside the capture-timeout window collapse into one undo step; call `um.StopCapturing()` to force a boundary. The semantics match `[email protected]`'s `UndoManager`, checked by cross-language conformance fixtures.

### Snapshots / time-travel

Capture a point in a document's history and reconstruct it later. The source doc must have GC disabled so deleted content is retained:

```go
d := ygo.NewDocWithOptions(ygo.Options{DisableGC: true})
txt := ygo.NewText(d, "t")

txn := d.WriteTxn()
txt.Insert(txn, 0, "world!")
txn.Commit()

snap := ygo.CreateSnapshot(d)         // mark this moment
saved := ygo.EncodeSnapshot(snap)     // persist it (byte-compatible with Y.encodeSnapshot)

txn = d.WriteTxn()
txt.Insert(txn, 0, "hello ")          // doc moves on
txn.Commit()

restored, _ := ygo.RestoreSnapshot(d, snap) // reconstruct the marked state
ygo.NewText(restored, "t").String()         // "world!"
```

The snapshot wire format (`EncodeSnapshot` / `DecodeSnapshot`) is byte-compatible with `[email protected]`'s `Y.encodeSnapshot`, verified by cross-language fixtures including multi-client delete-set ordering. `RestoreSnapshot` mirrors `Y.createDocFromSnapshot`.

### Subdocuments

Nest a `Y.Doc` inside a Map. The parent stores a reference (the subdoc's GUID); the subdocument's own content syncs as a separate update stream:

```go
d := ygo.NewDoc()
m := ygo.NewMap(d, "m")

txn := d.WriteTxn()
sub := m.SetDoc(txn, "child") // nest a new subdocument
txn.Commit()

// after syncing the parent to another replica:
got, ok := m.GetDoc(d, "child") // got.GUID() == sub.GUID()
```

The `ContentDoc` wire format (GUID + options) is byte-compatible with `[email protected]`, verified by cross-language fixtures. Lifecycle events are observable via `d.OnSubdocs` (added / removed / loaded GUIDs per transaction); `SetDocWithOptions(..., autoLoad)` and `subdoc.Load()` drive the loaded set, so a sync provider knows which nested documents to fetch. `Load` is reported with the next transaction on the parent, where yjs reports it at once.

### Strings and values

lib0 rejects strings that are not valid UTF-8, so ygo makes every string it is given valid at the call, before it becomes part of an item: each byte that does not start a valid UTF-8 sequence becomes U+FFFD, so UTF-16 indexes into the string you passed still point at the same places (values nested deeper than 1000 levels are not checked below that depth). An embed or format value that is not a plain value (strings, numbers, bools, nil, `[]byte`, `[]any`, `map[string]any`) is marshaled once, at the call, and stored as that JSON. A value passed to the API belongs to the document from then on: do not mutate it, or a value a read returns, after the call. Updates arriving with invalid UTF-8 are rejected (`ygo.ErrInvalidUTF8`); bytes an older release stored load as they were.

JavaScript's `undefined`, `BigInt` and `-0` keep their identity: they read as `ygo.Undefined{}`, `ygo.BigInt` and a `float64` negative zero, and are written as lib0 writes them, checked byte for byte against yjs in both directions. A BigInt set from Go reaches JavaScript as a BigInt, except in a V1 format attribute or embed: those are JSON, where a BigInt is a Number and loses digits beyond 2^53. Where ygo renders a value as JSON (gomobile), an undefined object entry is left out and an undefined array entry is null, as `JSON.stringify` does; a top-level undefined is null, -0 is 0, and a BigInt, where `JSON.stringify` throws, is a number. A format attribute whose value is `undefined` itself is a marker of its own and does what it does in yjs (an insert inheriting it clears it, a format request with it writes the marker but leaves the run's markers alone, the attributes in effect and `ToDelta` keep the key); `Text.InsertEmbed` refuses an undefined embed (`ygo.ErrUndefinedEmbed`, where yjs throws), and one a peer sent stays. V1, which is JSON, cannot carry either (yjs cannot write such a document in V1 at all): ygo writes null there, so a V1 reader, including the Go client's local log, gets null; `json.Marshal` of a delta writes null for `ygo.Undefined{}`.

V1 embeds and format values are written as `JSON.stringify` writes them, and a value stored as JSON (a struct, a `json.RawMessage`) is stored in that form.

An object read from a peer keeps its key order: when ygo writes the document again (the state a late joiner gets, a compaction, a V1/V2 conversion, a merge, a restored format value, undo), its keys go out in the order JavaScript holds them, array-index keys first. A Go map has no order, so an object built in Go, or read and set again (`Get` then `Set`, `ToDelta` into `ApplyDelta`), goes out with its array-index keys first, ascending, and the others sorted. A `__proto__` key read from a lib0 Any object stays a key, where yjs reading the same bytes sets the object's prototype instead (and keeps a second `__proto__` as a key once the first set the prototype to null). Updates holding arrays and objects nested deeper than 10000 levels are refused (`ygo.ErrNestedTooDeep`); yjs cannot read them either.

Two differences remain. A whole-number `float64` set from Go as a Map or Array value is written as a float64, where lib0 writes the same number as a varint. That is on purpose: a Go peer reads a varint back as an `int64`, so `float64(3)` would come back as `int64(3)`, while JavaScript peers read the number 3 either way. Embeds and format values follow lib0, and a Go peer still reads their numbers as `float64`. A lone surrogate escaped in the JSON of a V1 embed or format value (`"\ud800"`) reads as U+FFFD and is written back as that, where yjs keeps the escape; two keys that differ only in such a surrogate become one.

### Observing changes

Subscribe to a shared type to learn exactly what changed in each transaction, local or remote:

```go
m := ygo.NewMap(d, "settings")
unsub := m.Observe(func(e *ygo.MapEvent) {
    for key, change := range e.Keys {
        // change.Action is "add" / "update" / "delete"; change.OldValue
        // holds the prior value for update / delete.
        fmt.Printf("%s %s\n", change.Action, key)
    }
})
defer unsub()
```

`Array.Observe` and `Text.Observe` deliver a Quill-style delta (`{Insert, Delete, Retain}` ops; Text ops carry formatting attributes). `TextEvent.ReadDelta()` reads it as yjs's `event.delta` getter does, deleting the format markers it finds redundant in a transaction of its own, so a receiver that reads deltas ends where a yjs editor binding ends; the `Delta` field changes nothing. `Map.ObserveDeep` / `Array.ObserveDeep` fire for changes to nested types too, with each event's `Path` from the observed type to the change. The event semantics match `yjs`'s YMapEvent / YArrayEvent / YTextEvent, cross-checked against captured reference output.

## Status

**Stable CRDT core, with known gaps.** The CRDT engine, the V1 and V2 wire formats, and the type set above are validated bidirectionally against `[email protected]` and exercised in CI on every push to `main`. The public API is considered stable for the v1.x line; changes follow semantic versioning, with new functionality as minor releases and breaking changes deferred to a future major.

### Known gaps

- **Hocuspocus extensions.** Token refresh on an established server key (`onTokenSync`), server-initiated token requests and Redis cluster opcodes are not implemented. Close and reopen a key to change its token or scope; see [server setup](docs/yserve.md#coming-from-hocuspocus).

Frequently Asked Questions

What is ygo?

ygo is a Distributed Systems library for the Go programming language. Pure Go port of the Yjs CRDT, wire-compatible with JavaScript yjs clients

How do I install ygo?

Install ygo with the Go module system using `go get Deln0r/ygo`. Check the repository for the current installation instructions.

What category does ygo belong to?

ygo is listed under Distributed Systems, specifically Distributed Systems.

← Back to Distributed Systems