Documentation
¶
Index ¶
- Variables
- func ComputeParamsHash(graphKey string, params map[string]any) string
- func EnsureTriggers(ctx context.Context, exec TriggerExec, channel string, ...) error
- func GenerateTables(w io.Writer, registry *Registry) error
- func GenerateTriggerSQL(channel string, tables map[string][]string) []string
- func GenerateViews(w io.Writer, registry *Registry) error
- func ValidateParams(schema ParamSchema, raw map[string]any, strict ...bool) (map[string]any, error)
- func WithIdentity(ctx context.Context, id *Identity) context.Context
- func WorkspaceID(ctx context.Context) string
- type AuthFunc
- type BatchMessage
- type CentrifugoConfig
- type CentrifugoTransport
- func (t *CentrifugoTransport) DisconnectSeance(ctx context.Context, seanceID string) error
- func (t *CentrifugoTransport) SendBatch(ctx context.Context, msgs []BatchMessage) error
- func (t *CentrifugoTransport) SendToSeance(ctx context.Context, seanceID string, msg Message) error
- func (t *CentrifugoTransport) SendToWorkspace(ctx context.Context, workspaceID string, msg Message) error
- type Change
- type ChangeDetector
- type Config
- type DataStore
- func (s *DataStore) DecrRef(wsID, table, rowID string) bool
- func (s *DataStore) Delete(wsID, table, rowID string) (*StoreRow, bool)
- func (s *DataStore) GC(wsID, table, rowID string)
- func (s *DataStore) GCAll()
- func (s *DataStore) Get(wsID, table, rowID string) (*StoreRow, bool)
- func (s *DataStore) GetFields(wsID, table, rowID string) map[string]any
- func (s *DataStore) IncrRef(wsID, table, rowID string)
- func (s *DataStore) RowCount() int
- func (s *DataStore) RowVersion(wsID, table, rowID string) int64
- func (s *DataStore) Upsert(wsID, table, rowID string, fields map[string]any) (oldFields map[string]any, diff []PatchOp, isNew bool)
- type Engine
- func (e *Engine) DevToolsHandler() http.Handler
- func (e *Engine) Handler() http.Handler
- func (e *Engine) Mutate(ctx context.Context, req MutateRequest) (*MutateResponse, error)
- func (e *Engine) Notify(ctx context.Context, change Change)
- func (e *Engine) NotifyTable(ctx context.Context, table, rowID string, columns []string)
- func (e *Engine) Register(defs ...GraphDef) error
- func (e *Engine) RegisterMutation(defs ...MutationDef) error
- func (e *Engine) Registry() *Registry
- func (e *Engine) Start(ctx context.Context) error
- func (e *Engine) Stats() EngineStats
- func (e *Engine) Stop() error
- func (e *Engine) WSHandler() http.Handler
- type EngineStats
- type ExplicitNotifier
- type FactoryFunc
- type GraphDef
- type Identity
- type Invalidator
- type Manager
- func (m *Manager) GetActive(seanceID string) []*Subscription
- func (m *Manager) GetByGraphKey(graphKey string) []*Subscription
- func (m *Manager) Stats() (subs int, seances int)
- func (m *Manager) Subscribe(ctx context.Context, req SubscribeRequest) (*SubscribeResponse, error)
- func (m *Manager) SubscriptionCount() int
- func (m *Manager) Sync(ctx context.Context, req SyncRequest) (*SyncResponse, error)
- func (m *Manager) Unsubscribe(seanceID, paramsHash string) error
- func (m *Manager) UnsubscribeAll(seanceID string)
- func (m *Manager) UpdateSubscription(subID string, refs []Ref, version int64, entry *VersionEntry)
- type Message
- type MutateRequest
- type MutateResponse
- type MutationDef
- type MutationFunc
- type MutationResult
- type Notification
- type PGNotifyConfig
- type PGNotifyConn
- type PGNotifyListener
- type ParamDef
- type ParamDefBuilder
- type ParamSchema
- type ParamType
- type Params
- type PatchOp
- type Querier
- type Ref
- type Registry
- func (r *Registry) Get(key string) (*GraphDef, bool)
- func (r *Registry) GetByTable(table string) []*GraphDef
- func (r *Registry) GetMutation(key string) (*MutationDef, bool)
- func (r *Registry) GraphCount() int
- func (r *Registry) HasColumn(table, column string) bool
- func (r *Registry) Keys() []string
- func (r *Registry) MutationKeys() []string
- func (r *Registry) Register(defs ...GraphDef) error
- func (r *Registry) RegisterMutation(defs ...MutationDef) error
- func (r *Registry) RepTable() map[string][]string
- type Result
- type Row
- type Rows
- type StoreRow
- type SubscribeRequest
- type SubscribeResponse
- type Subscription
- type SubscriptionStore
- type SyncRequest
- type SyncResponse
- type SyncViewRequest
- type SyncViewResponse
- type TableDep
- type TableStore
- type Transport
- type TriggerExec
- type VersionEntry
- type WALConfig
- type WALListener
- type WSTransport
- func (t *WSTransport) ConnStats() (conns int, workspaces int)
- func (t *WSTransport) DisconnectSeance(ctx context.Context, seanceID string) error
- func (t *WSTransport) SendToSeance(ctx context.Context, seanceID string, msg Message) error
- func (t *WSTransport) SendToWorkspace(ctx context.Context, workspaceID string, msg Message) error
- func (t *WSTransport) ServeHTTP(w http.ResponseWriter, r *http.Request)
- type WSTransportConfig
- type WorkspaceStore
Constants ¶
This section is empty.
Variables ¶
var ( // ErrForbidden is returned when a user lacks permission to access a graph. ErrForbidden = errors.New("arcana: forbidden") // ErrNotFound is returned when a requested graph or subscription does not exist. ErrNotFound = errors.New("arcana: not found") // ErrInvalidParams is returned when subscription parameters fail validation. ErrInvalidParams = errors.New("arcana: invalid params") // ErrTooManySubscriptions is returned when a seance exceeds its subscription limit. ErrTooManySubscriptions = errors.New("arcana: too many subscriptions") // ErrAlreadyStarted is returned when Start is called on a running engine. ErrAlreadyStarted = errors.New("arcana: already started") // ErrNotStarted is returned when operations are attempted before Start. ErrNotStarted = errors.New("arcana: not started") // ErrTransportNotReady is returned when WSTransport is used before Engine.Start. ErrTransportNotReady = errors.New("arcana: transport not ready") )
Functions ¶
func ComputeParamsHash ¶
ComputeParamsHash produces a deterministic hash of graphKey + sorted params.
func EnsureTriggers ¶
func EnsureTriggers(ctx context.Context, exec TriggerExec, channel string, tables map[string][]string) error
EnsureTriggers creates pg_notify triggers for all registered tables.
func GenerateTables ¶
GenerateTables writes TypeScript type definitions for all tables based on the representation table.
func GenerateTriggerSQL ¶
GenerateTriggerSQL generates CREATE OR REPLACE FUNCTION + DROP/CREATE TRIGGER SQL for each table in the tables map (table_name -> []tracked_columns). channel is the pg_notify channel name (e.g. "arcana_changes"). Returns a slice of SQL statements (3 per table: function + drop trigger + create trigger).
func GenerateViews ¶
GenerateViews writes TypeScript type definitions for all views with their params and refs structure.
func ValidateParams ¶
ValidateParams validates raw input against a ParamSchema, applying defaults and type checks. Returns resolved values or an error. When strict is true, any parameter key not defined in the schema causes an error.
func WithIdentity ¶
WithIdentity stores an Identity in the context.
func WorkspaceID ¶
WorkspaceID is a shorthand to get workspace ID from the context identity.
Types ¶
type BatchMessage ¶ added in v0.1.1
BatchMessage represents a single message in a batch publish.
type CentrifugoConfig ¶
CentrifugoConfig holds configuration for CentrifugoTransport.
type CentrifugoTransport ¶
type CentrifugoTransport struct {
// contains filtered or unexported fields
}
CentrifugoTransport publishes messages via Centrifugo HTTP API.
func NewCentrifugoTransport ¶
func NewCentrifugoTransport(cfg CentrifugoConfig) *CentrifugoTransport
NewCentrifugoTransport creates a transport that publishes via Centrifugo HTTP API.
func (*CentrifugoTransport) DisconnectSeance ¶
func (t *CentrifugoTransport) DisconnectSeance(ctx context.Context, seanceID string) error
DisconnectSeance disconnects a client by seance ID.
func (*CentrifugoTransport) SendBatch ¶ added in v0.1.1
func (t *CentrifugoTransport) SendBatch(ctx context.Context, msgs []BatchMessage) error
SendBatch publishes multiple messages in a single HTTP call.
func (*CentrifugoTransport) SendToSeance ¶
SendToSeance publishes a message to the seance-specific channel.
func (*CentrifugoTransport) SendToWorkspace ¶
func (t *CentrifugoTransport) SendToWorkspace(ctx context.Context, workspaceID string, msg Message) error
SendToWorkspace publishes a message to the workspace channel.
type Change ¶
type Change struct {
Table string `json:"table"`
RowID string `json:"id"`
Op string `json:"op,omitempty"` // "INSERT", "UPDATE", "DELETE"
Columns []string `json:"columns,omitempty"`
}
Change represents a data mutation event from the application or database.
func ParsePGNotifyPayload ¶
ParsePGNotifyPayload parses a JSON payload from pg_notify into a Change. Expected format: {"table":"users","id":"uuid","op":"UPDATE","columns":["name"]}
type ChangeDetector ¶
type ChangeDetector interface {
// Start begins listening for changes. The handler is called for each detected change.
Start(ctx context.Context, handler func(Change)) error
// Stop terminates the change detection loop.
Stop() error
}
ChangeDetector listens for data changes and dispatches them to the engine.
type Config ¶
type Config struct {
// Pool is the PostgreSQL connection pool (required).
Pool Querier
// Transport delivers messages to clients (required).
Transport Transport
// AuthFunc extracts identity from an incoming HTTP request.
AuthFunc AuthFunc
// ChangeDetector determines how data changes are detected.
// Defaults to an internal explicit notifier if nil.
ChangeDetector ChangeDetector
// InvalidationDebounce batches changes within this window. Default: 50ms.
InvalidationDebounce time.Duration
// MaxSubscriptionsPerSeance limits subscriptions per client session. Default: 100.
MaxSubscriptionsPerSeance int
// SnapshotThreshold sends a full snapshot instead of diffs when version
// difference exceeds this value. Default: 50.
SnapshotThreshold int
// GCInterval is how often the store garbage-collects unreferenced rows. Default: 1min.
GCInterval time.Duration
// WSConfig configures the built-in WebSocket transport.
// Used when Transport is nil (auto-creation mode).
// If nil and Transport is nil, default WSTransportConfig is used.
WSConfig *WSTransportConfig
}
Config holds the configuration for an Arcana engine instance.
type DataStore ¶
type DataStore struct {
// contains filtered or unexported fields
}
DataStore is the in-memory normalized data store. Structure: workspace_id → table_name → row_id → StoreRow.
func (*DataStore) DecrRef ¶
DecrRef atomically decrements the reference count. Returns true if the count reached zero (candidate for GC).
func (*DataStore) Delete ¶
Delete removes a row from the store. Returns the deleted row and true, or nil and false if the row didn't exist.
func (*DataStore) GCAll ¶
func (s *DataStore) GCAll()
GCAll iterates all rows and removes those with RefCount <= 0.
func (*DataStore) GetFields ¶
GetFields returns a copy of the row's fields. Returns nil if not found.
func (*DataStore) RowCount ¶ added in v0.1.1
RowCount returns the total number of rows across all workspaces and tables.
func (*DataStore) RowVersion ¶
RowVersion returns the version of a row, or 0 if not found.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine is the main entry point for the Arcana reactive sync library.
func (*Engine) DevToolsHandler ¶ added in v0.2.0
DevToolsHandler returns an http.Handler that serves a DevTools dashboard for inspecting engine state. Mount with StripPrefix at your chosen path:
mux.Handle("/devtools/", http.StripPrefix("/devtools", engine.DevToolsHandler()))
func (*Engine) Handler ¶
Handler returns an http.Handler for the Arcana endpoints. Mount this on your router: mux.Mount("/arcana", engine.Handler())
func (*Engine) Mutate ¶ added in v0.2.0
func (e *Engine) Mutate(ctx context.Context, req MutateRequest) (*MutateResponse, error)
Mutate executes a registered mutation. Identity must be in the context.
func (*Engine) NotifyTable ¶
NotifyTable is a convenience method for notifying about a table change.
func (*Engine) Register ¶
Register adds graph definitions to the engine. Must be called before Start.
func (*Engine) RegisterMutation ¶ added in v0.2.0
func (e *Engine) RegisterMutation(defs ...MutationDef) error
RegisterMutation adds mutation definitions to the engine. Must be called before Start.
func (*Engine) Registry ¶
Registry returns the engine's graph registry (for codegen and inspection).
func (*Engine) Stats ¶ added in v0.1.1
func (e *Engine) Stats() EngineStats
Stats returns current engine statistics for monitoring/admin endpoints.
type EngineStats ¶ added in v0.1.1
type EngineStats struct {
Running bool `json:"running"`
RegisteredGraphs int `json:"registered_graphs"`
ActiveSubscriptions int `json:"active_subscriptions"`
SeancesWithSubs int `json:"seances_with_subs"`
DataStoreRows int `json:"data_store_rows"`
}
EngineStats holds runtime statistics about the engine.
type ExplicitNotifier ¶
type ExplicitNotifier struct {
// contains filtered or unexported fields
}
ExplicitNotifier is the default ChangeDetector that receives changes via a channel. Application code calls engine.Notify() which sends to this channel.
func NewExplicitNotifier ¶
func NewExplicitNotifier(bufferSize int) *ExplicitNotifier
NewExplicitNotifier creates a notifier with the given buffer size.
func (*ExplicitNotifier) Send ¶
func (n *ExplicitNotifier) Send(change Change)
Send enqueues a change for processing.
func (*ExplicitNotifier) Start ¶
func (n *ExplicitNotifier) Start(_ context.Context, handler func(Change)) error
Start begins processing changes from the channel.
func (*ExplicitNotifier) Stop ¶
func (n *ExplicitNotifier) Stop() error
Stop terminates the processing loop.
type FactoryFunc ¶
FactoryFunc executes SQL queries and returns normalized refs + rows.
type GraphDef ¶
type GraphDef struct {
Key string
Params ParamSchema
Deps []TableDep
Factory FactoryFunc
}
GraphDef defines a reactive data graph — a named SQL-backed query with dependencies and a factory function that produces normalized results.
type Identity ¶
type Identity struct {
SeanceID string
UserID string
WorkspaceID string
Role string
Permissions []string
}
Identity represents an authenticated user session.
func IdentityFromCtx ¶
IdentityFromCtx retrieves the Identity from the context.
func (*Identity) HasPermission ¶
HasPermission checks whether the identity has the given permission.
type Invalidator ¶
type Invalidator struct {
// contains filtered or unexported fields
}
Invalidator processes data changes and dispatches updates to affected subscriptions.
func NewInvalidator ¶
func NewInvalidator(registry *Registry, store *DataStore, transport Transport, subs SubscriptionStore, pool Querier, logger *slog.Logger) *Invalidator
NewInvalidator creates an Invalidator.
func (*Invalidator) Invalidate ¶
func (inv *Invalidator) Invalidate(ctx context.Context, change Change)
Invalidate processes a Change event: finds affected graphs, filters by columns, and dispatches table_diff and view_diff to affected subscriptions.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager orchestrates subscription lifecycle and connects Registry, DataStore, Invalidator, and Transport.
func NewManager ¶
func NewManager(registry *Registry, store *DataStore, transport Transport, pool Querier, config *Config, logger *slog.Logger) *Manager
NewManager creates a Manager.
func (*Manager) GetActive ¶
func (m *Manager) GetActive(seanceID string) []*Subscription
GetActive returns all active subscriptions for a seance.
func (*Manager) GetByGraphKey ¶
func (m *Manager) GetByGraphKey(graphKey string) []*Subscription
GetByGraphKey implements SubscriptionStore for Invalidator.
func (*Manager) Subscribe ¶
func (m *Manager) Subscribe(ctx context.Context, req SubscribeRequest) (*SubscribeResponse, error)
Subscribe creates a new subscription, executes the factory, and returns initial data.
func (*Manager) SubscriptionCount ¶
SubscriptionCount returns total active subscriptions.
func (*Manager) Sync ¶
func (m *Manager) Sync(ctx context.Context, req SyncRequest) (*SyncResponse, error)
Sync processes a reconnect request, returning catch-up diffs or full snapshots.
func (*Manager) Unsubscribe ¶
Unsubscribe removes a subscription identified by seanceID and paramsHash.
func (*Manager) UnsubscribeAll ¶
UnsubscribeAll removes all subscriptions for a seance (on disconnect).
func (*Manager) UpdateSubscription ¶
func (m *Manager) UpdateSubscription(subID string, refs []Ref, version int64, entry *VersionEntry)
UpdateSubscription updates a subscription's LastRefs and Version, and records a version history entry for catch-up sync.
type MutateRequest ¶ added in v0.2.0
type MutateRequest struct {
Action string `json:"action"`
Params map[string]any `json:"params"`
SeanceID string `json:"-"`
UserID string `json:"-"`
WorkspaceID string `json:"-"`
}
MutateRequest is the input for a mutation execution.
type MutateResponse ¶ added in v0.2.0
MutateResponse is returned after a successful mutation.
type MutationDef ¶ added in v0.2.0
type MutationDef struct {
Key string
Params ParamSchema
Handler MutationFunc
}
MutationDef defines a named write operation with parameter validation and a handler function. Register mutations with Engine.RegisterMutation.
type MutationFunc ¶ added in v0.2.0
MutationFunc executes a mutation. Identity is available via IdentityFromCtx(ctx). Returns a result containing response data and a list of changes for reactive invalidation.
type MutationResult ¶ added in v0.2.0
type MutationResult struct {
// Data is returned to the client in the response.
Data any `json:"data,omitempty"`
// Changes lists the tables/rows affected by this mutation.
// Arcana auto-notifies these after the handler returns,
// triggering reactive invalidation of affected views.
Changes []Change `json:"-"`
}
MutationResult holds the outcome of a mutation.
type Notification ¶
Notification represents a PostgreSQL notification.
type PGNotifyConfig ¶
type PGNotifyConfig struct {
Conn PGNotifyConn
Channel string // default: "arcana_changes"
Logger *slog.Logger
MaxRetries int // 0 = unlimited retries
}
PGNotifyConfig configures the PGNotifyListener.
type PGNotifyConn ¶
type PGNotifyConn interface {
Exec(ctx context.Context, sql string, args ...any) error
WaitForNotification(ctx context.Context) (*Notification, error)
}
PGNotifyConn abstracts a PostgreSQL connection capable of LISTEN/NOTIFY. Compatible with pgx.Conn.
type PGNotifyListener ¶
type PGNotifyListener struct {
// contains filtered or unexported fields
}
PGNotifyListener listens to PostgreSQL LISTEN/NOTIFY for change detection.
func NewPGNotifyListener ¶
func NewPGNotifyListener(cfg PGNotifyConfig) *PGNotifyListener
NewPGNotifyListener creates a listener for PostgreSQL notifications.
func (*PGNotifyListener) Start ¶
func (l *PGNotifyListener) Start(ctx context.Context, handler func(Change)) error
Start begins listening on the PostgreSQL notification channel.
func (*PGNotifyListener) Stop ¶
func (l *PGNotifyListener) Stop() error
Stop terminates the listener.
type ParamDefBuilder ¶
type ParamDefBuilder struct {
// contains filtered or unexported fields
}
ParamDefBuilder provides a fluent API for constructing ParamDef values.
func ParamFloat ¶
func ParamFloat() ParamDefBuilder
ParamFloat creates a float parameter definition.
func ParamString ¶
func ParamString() ParamDefBuilder
ParamString creates a string parameter definition.
func (ParamDefBuilder) Build ¶
func (b ParamDefBuilder) Build() ParamDef
Build returns the completed ParamDef without setting required or default.
func (ParamDefBuilder) Default ¶
func (b ParamDefBuilder) Default(v any) ParamDef
Default sets a default value and returns the completed definition.
func (ParamDefBuilder) OneOf ¶
func (b ParamDefBuilder) OneOf(vals ...string) ParamDefBuilder
OneOf restricts allowed string values (only for ParamTypeString).
func (ParamDefBuilder) Required ¶
func (b ParamDefBuilder) Required() ParamDef
Required marks the parameter as required.
type ParamSchema ¶
ParamSchema defines the expected parameters for a graph subscription.
type Params ¶
type Params struct {
// contains filtered or unexported fields
}
Params provides typed access to resolved subscription parameters.
type PatchOp ¶
type PatchOp struct {
Op string `json:"op"`
Path string `json:"path"`
Value any `json:"value,omitempty"`
}
PatchOp represents a single JSON Patch (RFC 6902) operation.
func DiffFields ¶
DiffFields computes a JSON Patch (RFC 6902) between two field maps of the same row. Only top-level keys are compared.
type Querier ¶
type Querier interface {
Query(ctx context.Context, sql string, args ...any) (Rows, error)
QueryRow(ctx context.Context, sql string, args ...any) Row
}
Querier abstracts database query execution (compatible with pgx).
func PgxQuerier ¶
PgxQuerier adapts a pgxpool.Pool to the Querier interface. pgx.Rows and pgx.Row structurally satisfy arcana.Rows and arcana.Row.
type Ref ¶
type Ref struct {
Table string `json:"table"`
ID string `json:"id"`
Fields []string `json:"fields"`
Nested map[string]Ref `json:"nested,omitempty"`
}
Ref represents a reference to a normalized row, defining view structure.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry stores graph definitions, mutation definitions, and provides lookup indices.
func (*Registry) GetByTable ¶
GetByTable returns all graph definitions that depend on the given table.
func (*Registry) GetMutation ¶ added in v0.2.0
func (r *Registry) GetMutation(key string) (*MutationDef, bool)
GetMutation returns a mutation definition by key.
func (*Registry) GraphCount ¶
GraphCount returns the number of registered graphs.
func (*Registry) MutationKeys ¶ added in v0.2.0
MutationKeys returns all registered mutation keys.
func (*Registry) Register ¶
Register adds one or more graph definitions to the registry. Returns an error if a graph key is already registered.
func (*Registry) RegisterMutation ¶ added in v0.2.0
func (r *Registry) RegisterMutation(defs ...MutationDef) error
RegisterMutation adds one or more mutation definitions to the registry.
type Result ¶
type Result struct {
// contains filtered or unexported fields
}
Result accumulates the output of a graph Factory execution. It holds both normalized table rows and the ref structure that defines the view.
func (*Result) AddRow ¶
AddRow adds a normalized row to the result's table data. If the row already exists, fields are merged (new values overwrite).
func (*Result) SetTotal ¶ added in v0.1.3
SetTotal stores the total row count for paginated graph results. This is typically populated from a COUNT(*) OVER() window function.
type StoreRow ¶
type StoreRow struct {
Fields map[string]any
Version int64
RefCount int32 // managed atomically
// contains filtered or unexported fields
}
StoreRow is a single row in the normalized store.
type SubscribeRequest ¶
type SubscribeRequest struct {
GraphKey string
Params map[string]any
SeanceID string
UserID string
WorkspaceID string
}
SubscribeRequest contains the parameters for a Subscribe call.
type SubscribeResponse ¶
type SubscribeResponse struct {
ParamsHash string `json:"params_hash"`
Version int64 `json:"version"`
Refs []Ref `json:"refs"`
Tables map[string]map[string]map[string]any `json:"tables"`
Total int `json:"total,omitempty"`
SeanceID string `json:"seance_id"`
}
SubscribeResponse contains the initial data returned to the client.
type Subscription ¶
type Subscription struct {
ID string
SeanceID string
WorkspaceID string
UserID string
GraphKey string
Params map[string]any
ParamsHash string
LastRefs []Ref
Version int64
CreatedAt time.Time
// VersionHistory stores recent view_diff messages for catch-up sync.
// Ring buffer of size SnapshotThreshold.
VersionHistory []VersionEntry
}
Subscription represents an active client subscription to a graph view.
type SubscriptionStore ¶
type SubscriptionStore interface {
// GetByGraphKey returns all active subscriptions for a graph key.
GetByGraphKey(graphKey string) []*Subscription
// UpdateSubscription updates a subscription's LastRefs, Version, and records
// a version history entry for catch-up sync.
UpdateSubscription(subID string, refs []Ref, version int64, entry *VersionEntry)
}
SubscriptionStore provides access to active subscriptions for invalidation.
type SyncRequest ¶
type SyncRequest struct {
SeanceID string
WorkspaceID string
Views []SyncViewRequest
}
SyncRequest contains the parameters for a Sync call.
type SyncResponse ¶
type SyncResponse struct {
Views []SyncViewResponse `json:"views"`
}
SyncResponse contains the sync result for the client.
type SyncViewRequest ¶
type SyncViewRequest struct {
View string `json:"view"`
ParamsHash string `json:"params_hash"`
Version int64 `json:"version"`
}
SyncViewRequest describes a single view to sync.
type SyncViewResponse ¶
type SyncViewResponse struct {
View string `json:"view"`
ParamsHash string `json:"params_hash"`
Mode string `json:"mode"` // "catch_up" or "snapshot"
Patches []VersionEntry `json:"patches,omitempty"`
// Full snapshot fields (used when mode == "snapshot")
Version int64 `json:"version,omitempty"`
Refs []Ref `json:"refs,omitempty"`
Tables map[string]map[string]map[string]any `json:"tables,omitempty"`
Total int `json:"total,omitempty"`
}
SyncViewResponse contains the sync result for a single view.
type TableDep ¶
TableDep declares a dependency on a database table and specific columns. When any of these columns change, graphs depending on this table are invalidated.
type TableStore ¶
type TableStore struct {
// contains filtered or unexported fields
}
TableStore holds all rows for a single table within a workspace.
type Transport ¶
type Transport interface {
// SendToSeance delivers a message to a specific client session.
SendToSeance(ctx context.Context, seanceID string, msg Message) error
// SendToWorkspace delivers a message to all sessions in a workspace.
SendToWorkspace(ctx context.Context, workspaceID string, msg Message) error
// DisconnectSeance forcibly disconnects a client session.
DisconnectSeance(ctx context.Context, seanceID string) error
}
Transport abstracts the message delivery layer (Centrifugo, WebSocket, SSE).
type TriggerExec ¶
TriggerExec can execute DDL statements. *pgxpool.Pool satisfies this.
type VersionEntry ¶
type VersionEntry struct {
Version int64 `json:"version"`
RefsPatch []PatchOp `json:"refs_patch"`
Tables map[string]map[string]map[string]any `json:"tables,omitempty"`
}
VersionEntry records a single version's diff for catch-up sync.
type WALConfig ¶ added in v0.1.2
type WALConfig struct {
// ConnString is the PostgreSQL connection string.
// Must NOT include replication=database — it will be added automatically.
ConnString string
// SlotName is the replication slot name. Default: "arcana_slot".
SlotName string
// Publication is the publication name. Default: "arcana_pub".
Publication string
// Tables to replicate. If empty, all tables in the publication are used.
Tables []string
// Logger for structured logging.
Logger *slog.Logger
// StandbyTimeout is how often to send standby status updates. Default: 10s.
StandbyTimeout time.Duration
}
WALConfig configures the WALListener.
type WALListener ¶ added in v0.1.2
type WALListener struct {
// contains filtered or unexported fields
}
WALListener implements ChangeDetector using PostgreSQL logical replication. Requires wal_level=logical on the PostgreSQL server.
func NewWALListener ¶ added in v0.1.2
func NewWALListener(cfg WALConfig) *WALListener
NewWALListener creates a WAL-based change detector.
func (*WALListener) Start ¶ added in v0.1.2
func (l *WALListener) Start(ctx context.Context, handler func(Change)) error
Start begins listening for WAL changes.
func (*WALListener) Stop ¶ added in v0.1.2
func (l *WALListener) Stop() error
Stop terminates the WAL listener.
type WSTransport ¶ added in v0.2.0
type WSTransport struct {
// contains filtered or unexported fields
}
WSTransport is a built-in WebSocket transport implementing Transport and http.Handler.
func NewWSTransport ¶ added in v0.2.0
func NewWSTransport(cfg WSTransportConfig) *WSTransport
NewWSTransport creates a built-in WebSocket transport.
func (*WSTransport) ConnStats ¶ added in v0.2.0
func (t *WSTransport) ConnStats() (conns int, workspaces int)
ConnStats returns connection count and workspace count for WSTransport.
func (*WSTransport) DisconnectSeance ¶ added in v0.2.0
func (t *WSTransport) DisconnectSeance(ctx context.Context, seanceID string) error
DisconnectSeance forcibly disconnects a client session.
func (*WSTransport) SendToSeance ¶ added in v0.2.0
SendToSeance delivers a message to a specific client session.
func (*WSTransport) SendToWorkspace ¶ added in v0.2.0
SendToWorkspace delivers a message to all sessions in a workspace.
func (*WSTransport) ServeHTTP ¶ added in v0.2.0
func (t *WSTransport) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP handles WebSocket upgrade requests.
type WSTransportConfig ¶ added in v0.2.0
type WSTransportConfig struct {
// AuthFunc authenticates the HTTP upgrade request (cookies, headers).
// If nil, the engine's AuthFunc is used automatically.
AuthFunc AuthFunc
// TokenAuthFunc authenticates a token sent in the first WS message.
// Used for SPA/mobile clients where cookies are unavailable.
// If both AuthFunc and TokenAuthFunc are nil, connections are rejected.
TokenAuthFunc func(token string) (*Identity, error)
// WriteBufferSize is the number of messages buffered per connection
// before drops occur. Default: 256.
WriteBufferSize int
// PingInterval is how often to send WebSocket pings. Default: 30s.
PingInterval time.Duration
// PingTimeout is how long to wait for a pong before disconnecting. Default: 10s.
PingTimeout time.Duration
// AcceptOptions are passed to websocket.Accept for the upgrade.
AcceptOptions *websocket.AcceptOptions
}
WSTransportConfig configures the built-in WebSocket transport.
type WorkspaceStore ¶
type WorkspaceStore struct {
// contains filtered or unexported fields
}
WorkspaceStore holds all table data for a single workspace.
Source Files
¶
- arcana.go
- change.go
- change_batcher.go
- change_explicit.go
- change_pgnotify.go
- change_wal.go
- codegen.go
- config.go
- context.go
- devtools.go
- diff.go
- errors.go
- handler.go
- invalidator.go
- manager.go
- middleware.go
- mutation.go
- pgnotify_triggers.go
- pgx_adapter.go
- registry.go
- result.go
- store.go
- subscription.go
- transport.go
- transport_centrifugo.go
- transport_ws.go
- types.go
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
arcana-gen
command
Command arcana-gen generates TypeScript type definitions from a registered Arcana graph registry.
|
Command arcana-gen generates TypeScript type definitions from a registered Arcana graph registry. |
|
examples
|
|
|
basic
command
Example: basic Arcana setup with explicit notify.
|
Example: basic Arcana setup with explicit notify. |
|
dashboard
command
Example: real-time dashboard with WebSocket transport, mutations, and DevTools.
|
Example: real-time dashboard with WebSocket transport, mutations, and DevTools. |