syncedstate

package module
v0.0.0-...-4b5fb68 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2026 License: AGPL-3.0 Imports: 16 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

svelte-synced-state

Easily sync Go backend state with Svelte over WebSockets.

This package keeps typed state objects in a Go process and mirrors them into Svelte 5 $state objects. The backend exports a standard net/http WebSocket handler. The frontend subscribes to named state objects and can sync local changes back as full values or opt-in field deltas.

This project is based on the same state-syncing model as tauri-svelte-synced-store, adapted from Tauri events to a standard Go WebSocket backend.

Go

package main

import (
	"context"
	"log"
	"net/http"

	syncedstate "github.com/synthlabs/svelte-synced-state"
)

type InternalState struct {
	Authenticated bool   `json:"authenticated"`
	Name          string `json:"name"`
}

func main() {
	manager := syncedstate.NewManager()
	internal, err := syncedstate.Define(manager, "InternalState", InternalState{})
	if err != nil {
		log.Fatal(err)
	}

	http.Handle("/synced-state", manager.Handler(
		syncedstate.WithOriginPatterns("http://localhost:*"),
	))

	http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
		err := internal.Update(r.Context(), func(state *InternalState) {
			state.Authenticated = true
			state.Name = r.FormValue("name")
		})
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.WriteHeader(http.StatusNoContent)
	})

	log.Fatal(http.ListenAndServe(":8080", nil))
}

Handler options can tune the websocket send buffer. By default, a client is closed when its send buffer fills. Use WithBlockOnFullBuffer to apply backpressure to the goroutine sending the update instead:

http.Handle("/synced-state", manager.Handler(
	syncedstate.WithSendBuffer(128),
	syncedstate.WithBlockOnFullBuffer(),
))

Backend and forwarded frontend logs use a shared logger. By default, the manager writes text logs to stdout at Info and above. Use WithLogLevel to raise or lower the default logger's threshold, or pass any *slog.Logger with WithLogger:

manager := syncedstate.NewManager(
	syncedstate.WithLogLevel(syncedstate.LevelDebug),
)
manager := syncedstate.NewManager(
	syncedstate.WithLogger(slog.New(slog.NewJSONHandler(os.Stdout, nil))),
)

For longer critical sections, use the lower-level lock handle:

locked, err := internal.Lock(context.Background())
if err != nil {
	return err
}
defer locked.Unlock()

locked.Value().Authenticated = true
locked.Value().Name = "Jerod"
return locked.Sync(context.Background())

Svelte

<script lang="ts">
	import { SyncedState } from 'svelte-synced-state';

	type InternalState = {
		authenticated: boolean;
		name: string;
	};

	const internal = new SyncedState<InternalState>('InternalState', {
		authenticated: false,
		name: ''
	});

	async function login(event: Event) {
		event.preventDefault();
		await internal.sync();
		await fetch('/login', {
			method: 'POST',
			body: new URLSearchParams({ name: internal.obj.name })
		});
	}
</script>

{#if internal.obj.authenticated}
	<h1>Welcome {internal.obj.name}</h1>
{/if}

<form onsubmit={login}>
	<input bind:value={internal.obj.name} />
	<button type="submit">Log in</button>
</form>

Frontend logs can be printed locally and forwarded to the backend over the same WebSocket:

<script lang="ts">
	import { createLogger } from 'svelte-synced-state';

	const logger = createLogger({ scope: 'login' });
	logger.info('login form mounted');

	// Optional: forward existing console.* calls too.
	const restoreConsole = logger.forwardConsole();
</script>

Delta syncing

Choose syncMode: 'delta' on each state or collection to enable deltas in both directions. Full syncing remains the default. No Go API changes are needed:

const settings = new SyncedState<Settings>('Settings', initialSettings, {
  syncMode: 'delta'
});

const customers = new SyncedCollection<Customer>('customer', undefined, {
  syncMode: 'delta'
});

await settings.initialized;
settings.obj.profile.name = 'Jerod';
const result = await settings.sync();

if (customers.entries['123']) {
  customers.entries['123'].name = 'Jerod';
  await customers.sync('123');
}

Nested object fields use JSON Patch add, remove, and replace operations. Arrays are atomic: changing an array element sends the entire array. Initial state snapshots and recovery snapshots always contain full values. Each changed submission or publication uses whichever complete UTF-8 envelope is smaller, with full values winning ties. An unchanged delta sync() succeeds without sending a message. State is still serialized and compared locally; delta mode reduces transport bytes and retains a separate server baseline for each feed.

Delta mode preserves unsynced local edits when server updates arrive, applies unrelated remote changes, and reports overlapping changes:

if (settings.conflict) {
  console.log(settings.conflict.paths);
  // Immutable snapshots: conflict.base, conflict.local, conflict.remote.
  settings.resolveConflict('local'); // Or 'remote'. Only overlaps are resolved.
  await settings.sync();             // Resolution never submits automatically.
}

if (customers.conflicts['123']) {
  customers.resolveConflict('123', 'remote');
  await customers.sync('123');
}

Unresolved overlaps block submission. Ancestor/descendant edits conflict at the overlapping subtree, and arrays conflict as complete values. Stale submissions return { ok: false, version, error, conflict? } and retain local edits; there is no automatic retry, including for unrelated edits. Call sync() explicitly after inspecting the result or resolving an overlap. Full mode retains its existing behavior of replacing local state with server snapshots and updates.

Calls to sync() queue per state or collection entry and recompute changes when their turn starts. Other entries can sync independently. Edits made during an in-flight request remain local after its acknowledgement. Disconnects and close() fail outstanding calls without replay. A missing or mismatched delta baseline triggers an exact full-snapshot request and pauses that entry's writes until recovery completes.

Collections retain future-update-only subscriptions: subscribing to customer:* does not list existing entries. The first observed update for each entry is full. After reconnect, server delivery baselines start fresh; syncing a previously observed entry can request its exact snapshot before submitting.

Version behavior change: versions now advance only when the state's committed JSON value changes. Unchanged backend writes do not broadcast. Frontend full-value or empty-patch no-ops receive an acknowledgement with the current version. Supplied version checks still run before no-op detection. This applies to both full and delta mode, including Set, Update, and Locked.Sync.

Upgrade the Go server before enabling delta clients. The new server continues to support older full-only clients; delta clients do not negotiate fallback with older servers. Full and delta instances can share one SyncedClient; delta feeds have independent subscription IDs, including overlapping exact and wildcard subscriptions. Those independent feeds can produce multiple frames per socket.

Protocol

The WebSocket transport uses JSON envelopes:

{ "type": "subscribe", "id": "1", "name": "InternalState" }
{ "type": "update", "name": "InternalState", "version": 2, "value": { "authenticated": true, "name": "Jerod" } }
{ "type": "set", "id": "2", "name": "InternalState", "version": 3, "value": { "authenticated": false, "name": "" } }
{ "type": "log", "value": { "level": 3, "message": "hello", "timestamp": "2026-06-19T10:00:00.000Z", "scope": "ui" } }

Supported message types are subscribe, unsubscribe, snapshot, set, patch, update, log, and error. Snapshots and updates carry the current server version. Frontend set messages carry the next expected version. Stale writes receive a full snapshot with the latest value/version and an error string. log messages are client-to-backend fire-and-forget events with no broadcast or acknowledgement.

Delta subscriptions add a unique subscriptionId and syncMode:

{ "type": "subscribe", "id": "1", "name": "Settings", "subscriptionId": "settings-feed", "syncMode": "delta" }

Client patch submissions name the exact server version they were based on:

{ "type": "patch", "id": "2", "name": "Settings", "subscriptionId": "settings-feed", "baseVersion": 3, "patch": [{ "op": "replace", "path": "/profile/name", "value": "Jerod" }] }

Server patches include their resulting version:

{ "type": "patch", "id": "2", "name": "Settings", "subscriptionId": "settings-feed", "baseVersion": 3, "version": 4, "patch": [{ "op": "replace", "path": "/profile/name", "value": "Jerod" }] }

Tagged full updates, snapshots, errors, snapshot requests, full set fallbacks, and unsubscribe requests retain the same subscription ID. Request IDs correlate acknowledgements independently from subscription IDs. A server patch's base version is the last successfully delivered version for that feed and entry; it may span committed versions whose delivery was canceled. Subscription IDs are scoped to a WebSocket connection.

Low-level clients can use subscribe(name, handler, { syncMode: 'delta', subscriptionId }), snapshot(name, subscriptionId), and send(message) for tagged operations. Existing two-argument subscribe calls retain full-feed behavior. Operations follow the restricted object-field JSON Patch format; array-index operations, root removal, move, copy, and test are rejected. Paths use JSON Pointer escaping (~0 for ~, ~1 for /). Root replacement, null values, and object-key removal are supported.

Development

pnpm --dir ui install
sh scripts/check.sh

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrAlreadyDefined  = errors.New("syncedstate: state name already defined")
	ErrClosed          = errors.New("syncedstate: locked state already closed")
	ErrInvalidScope    = errors.New("syncedstate: invalid state scope")
	ErrMissingValue    = errors.New("syncedstate: message value is required")
	ErrNotFound        = errors.New("syncedstate: state name not found")
	ErrTypeMismatch    = errors.New("syncedstate: state type mismatch")
	ErrVersionConflict = errors.New("syncedstate: state version conflict")
	ErrWildcardName    = errors.New("syncedstate: wildcard state name requires an exact indexed state name")
)

Functions

This section is empty.

Types

type HandlerOption

type HandlerOption func(*handlerConfig)

func WithBlockOnFullBuffer

func WithBlockOnFullBuffer() HandlerOption

func WithOriginPatterns

func WithOriginPatterns(patterns ...string) HandlerOption

func WithPingInterval

func WithPingInterval(interval time.Duration) HandlerOption

WithPingInterval enables server-side keepalive: the handler pings each client on a ticker and closes the connection if a pong is not received within the interval. This surfaces half-open / silently-dropped links (laptop sleep, NAT idle-reap) as a real close event so the client can reconnect. Zero (the default) disables keepalive.

func WithSendBuffer

func WithSendBuffer(size int) HandlerOption

func WithSlowWriteThreshold

func WithSlowWriteThreshold(threshold time.Duration) HandlerOption

WithSlowWriteThreshold sets the write duration above which a frame counts as a slow write in client stats. The default is 250ms.

func WithStatsInterval

func WithStatsInterval(interval time.Duration) HandlerOption

WithStatsInterval logs a "client stats" record per connection on this interval: messages and bytes written, send-queue depth and high-water mark, the longest queue wait and write, and slow-write counts. Zero (the default) disables the report.

func WithWriteTimeout

func WithWriteTimeout(timeout time.Duration) HandlerOption

type IndexedScope

type IndexedScope[T any] struct {
	// contains filtered or unexported fields
}

func MustIndexedScope

func MustIndexedScope[T any](name string) IndexedScope[T]

func NewIndexedScope

func NewIndexedScope[T any](name string) (IndexedScope[T], error)

func (IndexedScope[T]) Address

func (s IndexedScope[T]) Address(id string) (string, error)

func (IndexedScope[T]) Define

func (s IndexedScope[T]) Define(manager *Manager, id string, initial T, opts ...KeyOption) (*Key[T], error)

func (IndexedScope[T]) Lookup

func (s IndexedScope[T]) Lookup(manager *Manager, id string) (*Key[T], error)

func (IndexedScope[T]) MustAddress

func (s IndexedScope[T]) MustAddress(id string) string

func (IndexedScope[T]) Name

func (s IndexedScope[T]) Name() string

func (IndexedScope[T]) Wildcard

func (s IndexedScope[T]) Wildcard() string

type Key

type Key[T any] struct {
	// contains filtered or unexported fields
}

func Define

func Define[T any](manager *Manager, name string, initial T, opts ...KeyOption) (*Key[T], error)

func DefineIndexed

func DefineIndexed[T any](manager *Manager, scopeName, id string, initial T, opts ...KeyOption) (*Key[T], error)

func DefineSingleton

func DefineSingleton[T any](manager *Manager, name string, initial T, opts ...KeyOption) (*Key[T], error)

func Lookup

func Lookup[T any](manager *Manager, name string) (*Key[T], error)

func LookupIndexed

func LookupIndexed[T any](manager *Manager, scopeName, id string) (*Key[T], error)

func LookupSingleton

func LookupSingleton[T any](manager *Manager, name string) (*Key[T], error)

func (*Key[T]) Lock

func (k *Key[T]) Lock(ctx context.Context) (*Locked[T], error)

func (*Key[T]) Name

func (k *Key[T]) Name() string

func (*Key[T]) Set

func (k *Key[T]) Set(ctx context.Context, value T, opts ...WriteOption) error

func (*Key[T]) Snapshot

func (k *Key[T]) Snapshot(ctx context.Context) (T, Meta, error)

func (*Key[T]) Update

func (k *Key[T]) Update(ctx context.Context, update func(*T), opts ...WriteOption) error

type KeyOption

type KeyOption func(*keyConfig)

type Locked

type Locked[T any] struct {
	// contains filtered or unexported fields
}

func (*Locked[T]) Sync

func (l *Locked[T]) Sync(ctx context.Context, opts ...WriteOption) error

func (*Locked[T]) Unlock

func (l *Locked[T]) Unlock()

func (*Locked[T]) Value

func (l *Locked[T]) Value() *T

type LogLevel

type LogLevel int
const (
	LevelTrace LogLevel = 1
	LevelDebug LogLevel = 2
	LevelInfo  LogLevel = 3
	LevelWarn  LogLevel = 4
	LevelError LogLevel = 5
)

type Logger

type Logger interface {
	Debug(msg string, args ...any)
	Info(msg string, args ...any)
	Warn(msg string, args ...any)
	Error(msg string, args ...any)
}

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

func NewManager

func NewManager(opts ...Option) *Manager

func (*Manager) BufferFullEvents

func (m *Manager) BufferFullEvents() uint64

BufferFullEvents returns how many client connections were closed because their send buffer overflowed since the manager was created.

func (*Manager) Handler

func (m *Manager) Handler(opts ...HandlerOption) http.Handler

type Message

type Message struct {
	Type           MessageType      `json:"type"`
	ID             string           `json:"id,omitempty"`
	Name           string           `json:"name,omitempty"`
	Version        uint64           `json:"version,omitempty"`
	Value          json.RawMessage  `json:"value,omitempty"`
	Error          string           `json:"error,omitempty"`
	BaseVersion    uint64           `json:"baseVersion,omitempty"`
	Patch          []PatchOperation `json:"patch,omitempty"`
	SyncMode       string           `json:"syncMode,omitempty"`
	SubscriptionID string           `json:"subscriptionId,omitempty"`
}

func (Message) MarshalJSON

func (m Message) MarshalJSON() ([]byte, error)

type MessageType

type MessageType string
const (
	MessageSubscribe   MessageType = "subscribe"
	MessageUnsubscribe MessageType = "unsubscribe"
	MessageSet         MessageType = "set"
	MessagePatch       MessageType = "patch"
	MessageSnapshot    MessageType = "snapshot"
	MessageUpdate      MessageType = "update"
	MessageLog         MessageType = "log"
	MessageError       MessageType = "error"
)

type Meta

type Meta struct {
	Name    string
	Version uint64
}

type Option

type Option func(*Manager)

func WithLogLevel

func WithLogLevel(level LogLevel) Option

func WithLogger

func WithLogger(logger Logger) Option

type PatchOperation

type PatchOperation struct {
	Op    string          `json:"op"`
	Path  string          `json:"path"`
	Value json.RawMessage `json:"value,omitempty"`
}

PatchOperation is an object-field JSON Patch operation. Arrays are atomic values.

func (*PatchOperation) UnmarshalJSON

func (op *PatchOperation) UnmarshalJSON(raw []byte) error

type SingletonScope

type SingletonScope[T any] struct {
	// contains filtered or unexported fields
}

func MustSingletonScope

func MustSingletonScope[T any](name string) SingletonScope[T]

func NewSingletonScope

func NewSingletonScope[T any](name string) (SingletonScope[T], error)

func (SingletonScope[T]) Address

func (s SingletonScope[T]) Address() string

func (SingletonScope[T]) Define

func (s SingletonScope[T]) Define(manager *Manager, initial T, opts ...KeyOption) (*Key[T], error)

func (SingletonScope[T]) Lookup

func (s SingletonScope[T]) Lookup(manager *Manager) (*Key[T], error)

func (SingletonScope[T]) Name

func (s SingletonScope[T]) Name() string

type WriteOption

type WriteOption func(*writeConfig)

func WithVersion

func WithVersion(version uint64) WriteOption

Directories

Path Synopsis
indexed command
singleton command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址