Documentation
¶
Overview ¶
Package crdt provides the shared contracts and protocol capability discovery used by this module's state-based CRDT implementations.
Applications normally use a concrete data type from a subpackage, such as counter for G-Counters and PN-Counters, set for add-wins OR-Sets, or clock for hybrid logical clocks. This root package contains the common CRDT, delta, snapshot, and mutation-tag contracts those implementations share.
The framed protocol table is intentionally closed. Use ProtocolPolicy during authenticated connection setup to advertise only the state and delta frame types a replication group has agreed to exchange. Every implemented protocol pair is stable; matching TypeIDs alone still do not authenticate a peer.
For installation, examples, and package-level guidance, see the module README at https://github.com/darkinno/crdt.
Example (LwwRegister) ¶
package main
import (
"fmt"
"github.com/DarkInno/crdt/register"
)
func main() {
writer, err := register.NewLWW("writer")
if err != nil {
panic(err)
}
reader, err := register.NewLWW("reader")
if err != nil {
panic(err)
}
if err := writer.Set([]byte("healthy")); err != nil {
panic(err)
}
if err := reader.Merge(writer); err != nil {
panic(err)
}
value, ok := reader.Get()
fmt.Println(ok, string(value))
}
Output: true healthy
Example (LwwSet) ¶
package main
import (
"fmt"
"github.com/DarkInno/crdt/lww"
)
func main() {
writer, err := lww.NewSet[string]("writer")
if err != nil {
panic(err)
}
reader, err := lww.NewSet[string]("reader")
if err != nil {
panic(err)
}
if err := writer.Add("on-call"); err != nil {
panic(err)
}
if err := reader.Merge(writer); err != nil {
panic(err)
}
fmt.Println(reader.Contains("on-call"))
}
Output: true
Example (MaxRegister) ¶
package main
import (
"fmt"
"github.com/DarkInno/crdt/register"
)
func main() {
local := register.NewMax()
remote := register.NewMax()
if err := local.Set(8); err != nil {
panic(err)
}
if err := remote.Set(13); err != nil {
panic(err)
}
if err := local.Merge(remote); err != nil {
panic(err)
}
value, ok := local.Get()
fmt.Println(ok, value)
}
Output: true 13
Index ¶
- Constants
- func IsExperimentalFrame(typeID uint64) booldeprecated
- func MarshalDiagnosticJSON(summary StateSnapshot) ([]byte, error)
- func MarshalStateJSON(value StateReporter) ([]byte, error)
- func WrapError(code ErrorCode, operation string, cause error) error
- type CRDT
- type DeltaCapable
- type Error
- type ErrorCode
- type FrameType
- type FrameTypeRegistration
- type ProtocolPolicy
- type ReplicationProfile
- type StateReporter
- type StateSnapshot
- type Tag
Examples ¶
Constants ¶
const ( TypeIDGCounterState uint64 = 1 TypeIDGCounterDelta uint64 = 3 SemanticsVersionGCounter uint64 = 1 TypeIDORSetState uint64 = 2 TypeIDORSetDelta uint64 = 4 SemanticsVersionORSet uint64 = 1 TypeIDPNCounterState uint64 = 5 TypeIDPNCounterDelta uint64 = 6 SemanticsVersionPNCounter uint64 = 1 TypeIDLWWSetState uint64 = 7 TypeIDLWWSetDelta uint64 = 8 SemanticsVersionLWWSet uint64 = 1 TypeIDLWWMapState uint64 = 9 TypeIDLWWMapDelta uint64 = 10 SemanticsVersionLWWMap uint64 = 1 TypeIDRGAState uint64 = 11 TypeIDRGADelta uint64 = 12 SemanticsVersionRGA uint64 = 1 TypeIDGSetState uint64 = 13 TypeIDGSetDelta uint64 = 14 SemanticsVersionGSet uint64 = 1 TypeIDMVRegisterState uint64 = 15 TypeIDMVRegisterDelta uint64 = 16 SemanticsVersionMVRegister uint64 = 1 TypeIDORTreeState uint64 = 17 TypeIDORTreeDelta uint64 = 18 SemanticsVersionORTree uint64 = 1 TypeIDRGARunState uint64 = 19 TypeIDRGARunDelta uint64 = 20 SemanticsVersionRGARun uint64 = 2 TypeIDListRGAState uint64 = 21 TypeIDListRGADelta uint64 = 22 SemanticsVersionListRGA uint64 = 1 TypeIDRichTextState uint64 = 23 TypeIDRichTextDelta uint64 = 24 SemanticsVersionRichText uint64 = 1 TypeIDMoveRGAState uint64 = 25 TypeIDMoveRGADelta uint64 = 26 SemanticsVersionMoveRGA uint64 = 2 TypeIDRGAPackedState uint64 = 29 TypeIDRGAPackedDelta uint64 = 30 SemanticsVersionRGAPacked uint64 = 3 TypeIDDocumentTreeState uint64 = 31 TypeIDDocumentTreeDelta uint64 = 32 SemanticsVersionDocumentTree uint64 = 2 )
Stable frame type assignments. Values are part of the v1 wire contract and must never be reused for a different payload shape. The source of truth is docs/protocol/type-ids.json.
Variables ¶
This section is empty.
Functions ¶
func IsExperimentalFrame
deprecated
IsExperimentalFrame reports whether typeID belongs to an experimental protocol. No implemented protocol is experimental; reserved and unknown IDs also return false. It remains for source compatibility with earlier policy negotiation code.
Deprecated: every implemented frame type is stable.
func MarshalDiagnosticJSON ¶ added in v1.0.5
func MarshalDiagnosticJSON(summary StateSnapshot) ([]byte, error)
MarshalDiagnosticJSON encodes a caller-provided diagnostic summary. It is useful for CRDT delta log views that use the same schema as StateSnapshot. The summary must not contain application values or replication state.
func MarshalStateJSON ¶ added in v1.0.5
func MarshalStateJSON(value StateReporter) ([]byte, error)
MarshalStateJSON returns a compact JSON diagnostic summary for value.
This helper is intended for structured logs and human inspection. It does not encode CRDT state, deltas, or opaque application values, so its output cannot reconstruct a replica and must not be used as a wire format.
Types ¶
type CRDT ¶
type CRDT[T any] interface { Merge(other T) error State() StateSnapshot }
CRDT is the common contract for state-based CRDTs.
For every concrete state type T, Merge must be commutative, associative, and idempotent. If Merge returns an error, it must leave the receiver unchanged.
type DeltaCapable ¶
DeltaCapable is implemented by a state-based CRDT that accepts a concrete, type-safe delta D. Delta mutators return D directly; the library does not maintain an implicitly acknowledged delta buffer.
type Error ¶ added in v1.0.25
Error adds an operation and a stable code to a cause. Operation must be a constant diagnostic name such as "durable.new_handler"; do not put peer IDs, group IDs, endpoints, credentials, payloads, or other untrusted data in it.
Error unwraps to Cause, so existing errors.Is and errors.As checks continue to work when a package adopts structured errors at a public boundary.
type ErrorCode ¶ added in v1.0.25
type ErrorCode string
ErrorCode classifies a failure without requiring callers to parse an error message. Codes describe a stable operational category, not a wire protocol result or application authorization policy.
const ( // ErrorCodeUnknown is returned when an error has no CRDT structured wrapper. ErrorCodeUnknown ErrorCode = "unknown" // ErrorCodeInvalidConfig identifies missing, malformed, or unsafe local // configuration before an operation begins. ErrorCodeInvalidConfig ErrorCode = "invalid_config" // ErrorCodeInvalidInput identifies rejected untrusted or malformed input. ErrorCodeInvalidInput ErrorCode = "invalid_input" ErrorCodeUnauthorized ErrorCode = "unauthorized" // ErrorCodeConflict identifies an incompatible retry or concurrent binding. ErrorCodeConflict ErrorCode = "conflict" // ErrorCodeResourceLimit identifies a configured capacity or size bound. ErrorCodeResourceLimit ErrorCode = "resource_limit" ErrorCodeUnavailable ErrorCode = "unavailable" )
func ErrorCodeOf ¶ added in v1.0.25
ErrorCodeOf returns the outermost structured error code in err's tree, or ErrorCodeUnknown when no structured wrapper is present.
type FrameType ¶
FrameType describes one fully implemented framed CRDT protocol. The type table is deliberately closed: reserving an ID alone must not make a payload eligible for batching or recovery before its concrete codec is available.
func DefaultRGAFrameType ¶ added in v1.0.19
func DefaultRGAFrameType() FrameType
DefaultRGAFrameType returns the compact run-v2 protocol for new RGA replication groups. Legacy scalar RGA v1 frames remain a separately selected stable migration contract.
func FrameTypeForDelta ¶
FrameTypeForDelta returns the supported protocol associated with deltaID.
func FrameTypeForState ¶
FrameTypeForState returns the supported protocol associated with stateID.
type FrameTypeRegistration ¶ added in v1.0.25
FrameTypeRegistration identifies one implemented state/delta protocol pair. It is diagnostic and negotiation metadata only: applications must still bind an authenticated manifest, authorization policy, and resource limits before accepting a frame.
func FrameTypeRegistrationForID ¶ added in v1.0.25
func FrameTypeRegistrationForID(typeID uint64) (FrameTypeRegistration, bool)
FrameTypeRegistrationForID returns the implemented registration containing typeID as either its state or delta frame ID. Reserved and unknown IDs return false. It performs no policy, manifest, or authentication decision.
func RegisteredFrameTypes ¶ added in v1.0.25
func RegisteredFrameTypes() []FrameTypeRegistration
RegisteredFrameTypes returns a copy of every implemented protocol registration in stable registry order. Mutating the returned slice cannot affect protocol admission or frame decoding.
type ProtocolPolicy ¶
type ProtocolPolicy struct {
// AllowExperimental is retained for source compatibility with releases that
// required an opt-in for collection frames. Every implemented frame type is
// stable now, so the field has no effect. It is not a substitute for an
// authenticated manifest, authorization, limits, or tombstone retirement.
//
// Deprecated: all implemented protocol pairs are included by the zero value.
AllowExperimental bool
}
ProtocolPolicy controls which implemented frame types one replication group advertises. It is a local, immutable-by-convention value for connection setup; it does not install a process-wide switch or permit runtime protocol registration.
Peers must compare FrameTypes before sending state or deltas. A matching TypeID remains necessary but is not sufficient: applications still own authentication, authorization, limits, and decoder selection.
Example ¶
package main
import (
"fmt"
"github.com/DarkInno/crdt"
)
func main() {
stable := crdt.ProtocolPolicy{}
compatibility := crdt.ProtocolPolicy{AllowExperimental: true}
fmt.Println(stable.SupportsFrame(crdt.TypeIDRGAState))
fmt.Println(compatibility.SupportsFrame(crdt.TypeIDRGAState))
}
Output: true true
func (ProtocolPolicy) FrameTypes ¶
func (p ProtocolPolicy) FrameTypes() []FrameType
FrameTypes returns a copy of every protocol enabled by p. The returned slice is stable in type-ID order and safe for callers to advertise or modify.
func (ProtocolPolicy) SupportsFrame ¶
func (p ProtocolPolicy) SupportsFrame(typeID uint64) bool
SupportsFrame reports whether typeID is both implemented by this module and enabled by p. It applies to either a state or delta frame type ID.
type ReplicationProfile ¶ added in v1.0.30
type ReplicationProfile struct {
// ID is the stable, case-sensitive profile identifier.
ID string
// Title is a short human-facing name for the underlying CRDT.
Title string
// Summary describes the merge rule in product language.
Summary string
// ConflictRule states the deterministic outcome of concurrent updates.
ConflictRule string
// RecommendedFor lists product facts that fit this merge rule.
RecommendedFor []string
// NotFor lists product decisions that must stay authoritative.
NotFor []string
// HostRequirements lists protocol-specific work that remains with the host.
HostRequirements []string
// RequiresCodecID reports whether the selected frame contract carries an
// application-defined deterministic element codec ID.
RequiresCodecID bool
// FrameType is the canonical state/delta pair and semantics version.
FrameType FrameType
}
ReplicationProfile is a curated, machine-readable starting point for one concrete CRDT protocol. It helps an application choose a merge rule from a business fact before it builds a manifest; it is not a security policy or a capacity configuration.
The profile ID, frame type, and semantics version are stable integration inputs. Applications must still authenticate the exact manifest, authorize every sender, choose decoder and retention limits, and persist the recovery state described by HostRequirements.
func ReplicationProfileFor ¶ added in v1.0.30
func ReplicationProfileFor(id string) (ReplicationProfile, bool)
ReplicationProfileFor returns the profile named by the exact stable ID. IDs are intentionally not normalized: a configuration typo must not choose a different merge rule.
func ReplicationProfiles ¶ added in v1.0.30
func ReplicationProfiles() []ReplicationProfile
ReplicationProfiles returns defensive copies of every curated profile in a stable learning order. The returned values are metadata only: changing them cannot enable a frame type or alter protocol admission.
type StateReporter ¶ added in v1.0.5
type StateReporter interface {
State() StateSnapshot
}
StateReporter exposes an immutable CRDT diagnostic summary.
It intentionally excludes application values, mutation tags, clock state, and framed bytes. Use it for observability only, never to persist or replicate a CRDT.
type StateSnapshot ¶
type StateSnapshot struct {
Type string `json:"type"`
ReplicaID string `json:"replica_id"`
ElementCount int `json:"element_count"`
TombstoneCount int `json:"tombstone_count"`
}
StateSnapshot is an immutable summary of a CRDT state for diagnostics and observability. It never exposes mutable internal data.
type Tag ¶
Tag uniquely identifies a CRDT mutation. WallTime, Logical, and ReplicaID are compared in that order. ReplicaID must be globally unique among live logical replicas; callers that reuse an ID across restarts must persist the last emitted clock state.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package attachment replicates bounded references to externally stored images, audio, video, and arbitrary data.
|
Package attachment replicates bounded references to externally stored images, audio, video, and arbitrary data. |
|
Package awareness implements bounded, ephemeral presence state for a collaboration group.
|
Package awareness implements bounded, ephemeral presence state for a collaboration group. |
|
Package clock implements a hybrid logical clock for CRDT mutation tags.
|
Package clock implements a hybrid logical clock for CRDT mutation tags. |
|
cmd
|
|
|
crdt-analyze
command
Command crdt-analyze reports bounded, transport-safe metadata about one canonical CRDT frame.
|
Command crdt-analyze reports bounded, transport-safe metadata about one canonical CRDT frame. |
|
crdt-benchmark-check
command
Command crdt-benchmark-check compares controlled Go benchmark samples.
|
Command crdt-benchmark-check compares controlled Go benchmark samples. |
|
crdt-cluster-sim
command
Command crdt-cluster-sim exercises run-v2 RGA synchronization over real HTTP links.
|
Command crdt-cluster-sim exercises run-v2 RGA synchronization over real HTTP links. |
|
crdt-compare
command
Command crdt-compare produces the DarkInno side of the reproducible cross-library text-sync comparison.
|
Command crdt-compare produces the DarkInno side of the reproducible cross-library text-sync comparison. |
|
crdt-merkle-sync
command
Command crdt-merkle-sync repairs bounded G-Counter state directories over authenticated HTTP by reconciling their Merkle roots.
|
Command crdt-merkle-sync repairs bounded G-Counter state directories over authenticated HTTP by reconciling their Merkle roots. |
|
crdt-profile
command
Command crdt-profile lists the library's curated CRDT selection profiles.
|
Command crdt-profile lists the library's curated CRDT selection profiles. |
|
crdt-rga-wasm
command
crdt-rga-wasm exposes the bounded RGA browser runtime through one small syscall/js surface.
|
crdt-rga-wasm exposes the bounded RGA browser runtime through one small syscall/js surface. |
|
crdt-sync-probe
command
Command crdt-sync-probe exercises CRDT delta delivery over real HTTP links.
|
Command crdt-sync-probe exercises CRDT delta delivery over real HTTP links. |
|
Package config provides explicit, layered configuration lookup for host applications.
|
Package config provides explicit, layered configuration lookup for host applications. |
|
Package counter implements counter CRDT primitives.
|
Package counter implements counter CRDT primitives. |
|
Package delta provides bounded batching and coalescing for encoded CRDT deltas.
|
Package delta provides bounded batching and coalescing for encoded CRDT deltas. |
|
Package document provides bounded, document-level routing for MoveRGA sequences.
|
Package document provides bounded, document-level routing for MoveRGA sequences. |
|
Package documenttree implements a bounded, framed, fully nested document-tree CRDT.
|
Package documenttree implements a bounded, framed, fully nested document-tree CRDT. |
|
durable
module
|
|
|
Package encoding provides canonical, bounded binary frames for CRDT state.
|
Package encoding provides canonical, bounded binary frames for CRDT state. |
|
Package history provides bounded, local undo/redo and version-history metadata for CRDT applications.
|
Package history provides bounded, local undo/redo and version-history metadata for CRDT applications. |
|
internal
|
|
|
cmd/typeidgen
command
Command typeidgen generates the language-specific CRDT TypeID registries from docs/protocol/type-ids.json.
|
Command typeidgen generates the language-specific CRDT TypeID registries from docs/protocol/type-ids.json. |
|
codecguard
Package codecguard contains the panic boundary for application-provided element codecs.
|
Package codecguard contains the panic boundary for application-provided element codecs. |
|
wasm
Package wasm contains host-neutral state used by the browser-facing Wasm command.
|
Package wasm contains host-neutral state used by the browser-facing Wasm command. |
|
Package list implements a generic, ordered Replicated Growable Array (RGA).
|
Package list implements a generic, ordered Replicated Growable Array (RGA). |
|
Package lww implements last-write-wins CRDT collections.
|
Package lww implements last-write-wins CRDT collections. |
|
Package membership provides a transport-independent, signed membership protocol reference for CRDT replication groups.
|
Package membership provides a transport-independent, signed membership protocol reference for CRDT replication groups. |
|
Package merkle provides deterministic state digests for anti-entropy.
|
Package merkle provides deterministic state digests for anti-entropy. |
|
Package observe connects a CRDT to an application-owned reactive view.
|
Package observe connects a CRDT to an application-owned reactive view. |
|
providers
|
|
|
internal/sqlrelay
module
|
|
|
sqlite
module
|
|
|
Package register implements state-based register CRDTs.
|
Package register implements state-based register CRDTs. |
|
Package replica defines the transport-independent boundary around one framed CRDT replication group.
|
Package replica defines the transport-independent boundary around one framed CRDT replication group. |
|
Package richtext implements bounded, inline formatted collaborative text.
|
Package richtext implements bounded, inline formatted collaborative text. |
|
Package set implements set CRDT primitives.
|
Package set implements set CRDT primitives. |
|
Package shared provides a small, Yjs-style document facade over the bounded document-tree-v2 CRDT.
|
Package shared provides a small, Yjs-style document facade over the bounded document-tree-v2 CRDT. |
|
Package snapshot defines immutable, versioned CRDT state snapshots and bounded recovery plans.
|
Package snapshot defines immutable, versioned CRDT state snapshots and bounded recovery plans. |
|
telemetry
module
|
|
|
Package text implements a state-based Replicated Growable Array (RGA).
|
Package text implements a state-based Replicated Growable Array (RGA). |
|
Package tombstonegc coordinates tombstone collection.
|
Package tombstonegc coordinates tombstone collection. |
|
Package tree implements an observed-remove rooted tree CRDT.
|
Package tree implements an observed-remove rooted tree CRDT. |
|
Package xml provides a bounded, deterministic XML fragment CRDT.
|
Package xml provides a bounded, deterministic XML fragment CRDT. |