replication

package
v0.0.0-...-9268282 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: MIT Imports: 28 Imported by: 0 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.

Documentation

Overview

Package replication plans and executes durable relay synchronization.

Planning is separate from transport. RelayDirectory and Discovery provide routing inputs; PrepareIntents turns them into idempotent storage.Intent values that can be committed with the event that caused them. Delivery, PullTransport and PushTransport perform network operations and are owned by the application that constructs the Service or calls the standalone sync functions. Those callers retain ownership of their transports and stores.

Service owns replication's durable work queue and job state. Handlers can be composed with other work handlers and run by work.RunPool. A handler error is retried by the work package with backoff; a terminal error can be marked with work.Stop. Successful recurring jobs enqueue a new intent, preserving a completed record for the prior run.

WebSocket transports validate relay URLs and public address resolution before dialing. Backup and artifact helpers write complete files through temporary files and same-directory rename.

Index

Constants

View Source
const BackupFormat = "tinyrelay/backup/1"

BackupFormat identifies the JSON archive format produced by this package.

Variables

View Source
var ErrNegentropyUnsupported = errors.New("replication: negentropy unsupported")

ErrNegentropyUnsupported means the peer does not implement NIP-77. It is deliberately distinct from authentication, protocol and transport errors: only this condition is safe to downgrade to an ordinary REQ pull.

View Source
var ErrPullIncomplete = errors.New("replication: pull history is incomplete")

ErrPullIncomplete indicates that a relay returned a full bounded history window but the next page cannot be represented safely by an `until` cursor. Callers should retain the result and retry with a larger or more capable synchronization method.

Functions

func CallbackPayload

func CallbackPayload(reg PushRegistration, e event.Event) ([]byte, error)

func CancelJob

func CancelJob(ctx context.Context, queue *work.Queue, id string, now time.Time) error

func EnqueueJob

func EnqueueJob(ctx context.Context, queue *work.Queue, spec JobSpec, at time.Time) (string, error)

func EnsureJobSchema

func EnsureJobSchema(db interface {
	Exec(string, ...any) (sql.Result, error)
}) error

EnsureJobSchema initializes replication-owned job state for callers that import configuration before constructing a replication service.

func ImportJSONL

func ImportJSONL(ctx context.Context, store *storage.Store, input io.Reader, now int64) error

func IntentForJob

func IntentForJob(spec JobSpec, at time.Time) (storage.Intent, error)

func NewCallbackHandler

func NewCallbackHandler(store *storage.Store, client CallbackClient) work.Handler

func NewCallbackHandlerWithEventVisibility

func NewCallbackHandlerWithEventVisibility(store *storage.Store, client CallbackClient, policy func() CallbackPolicy, enabled func() bool, visible func(context.Context, string) bool, visibleEvent func(context.Context, string, event.Event) bool) work.Handler

NewCallbackHandlerWithEventVisibility is the event-aware variant used by tenant adapters. It rechecks visibility against the exact event immediately before delivery, after registration revocation and filter matching.

func NewCallbackHandlerWithPolicy

func NewCallbackHandlerWithPolicy(store *storage.Store, client CallbackClient, policy func() CallbackPolicy, enabled func() bool, visible func(context.Context, string) bool) work.Handler

func NewPinnedClient

func NewPinnedClient(timeout time.Duration) *http.Client

NewPinnedClient returns an HTTPS client that refuses private addresses and redirects, for calls to third-party services such as push endpoints.

func NextRun

func NextRun(spec JobSpec, finished time.Time) time.Time

func PrepareCallbackIntents

func PrepareCallbackIntents(ctx context.Context, e event.Event, registrations []PushRegistration) []storage.Intent

PrepareCallbackIntents persists references only. Callback I/O is performed later by a worker after registration and event visibility are rechecked.

func PrepareIntents

func PrepareIntents(ctx context.Context, e event.Event, origin Origin, policy Policy, directory RelayDirectory) []storage.Intent

PrepareIntents computes NIP-65 outbox work. The event transaction should pass the returned references to storage.Save as SaveOptions.Intents.

func PushMatches

func PushMatches(reg PushRegistration, e event.Event) bool

func ReplaceJobsTx

func ReplaceJobsTx(ctx context.Context, tx *sql.Tx, specs []ConfigJob) error

ReplaceJobsTx replaces the durable replication jobs represented by specs in a caller-owned transaction. It is used by configuration import so policy, config metadata and replication state commit atomically.

func RescheduleJob

func RescheduleJob(ctx context.Context, queue *work.Queue, spec JobSpec, at time.Time) (string, error)

RescheduleJob makes a recurring job eligible again after a successful run. It is separate from completion so the completed intent remains an audit record and a fresh run receives an independent claim token.

func RestoreBackup

func RestoreBackup(ctx context.Context, store *storage.Store, archive BackupArchive, now int64) (int, error)

func RestoreBackupWithProvider

func RestoreBackupWithProvider(ctx context.Context, store *storage.Store, provider BackupProvider, archive BackupArchive, now int64) (int, error)

func ValidateIntent

func ValidateIntent(intent storage.Intent) error

func ValidateJob

func ValidateJob(spec JobSpec) error

func WriteBackup

func WriteBackup(ctx context.Context, store *storage.Store, output io.Writer, now int64) error

func WriteDump

func WriteDump(ctx context.Context, store *storage.Store, output io.Writer, now int64) error

Types

type BackupArchive

type BackupArchive struct {
	Format  string        `json:"format"`
	Events  []event.Event `json:"events"`
	State   BackupState   `json:"state"`
	SHA256  string        `json:"sha256"`
	Created int64         `json:"created_at"`
}

BackupArchive is a sealed event and application-state export.

func CreateBackup

func CreateBackup(ctx context.Context, store *storage.Store, now int64) (BackupArchive, error)

func CreateBackupWithProvider

func CreateBackupWithProvider(ctx context.Context, store *storage.Store, provider BackupProvider, now int64) (BackupArchive, error)

func ReadBackup

func ReadBackup(input io.Reader) (BackupArchive, error)

func ReadCompatibleBackup

func ReadCompatibleBackup(input io.Reader) (BackupArchive, error)

ReadCompatibleBackup accepts both the native archive and bind.ws/relay-backup/1. The legacy shape is normalized before restore so callers have one validation path.

func SealBackup

func SealBackup(archive BackupArchive) (BackupArchive, error)

type BackupObject

type BackupObject struct {
	Name     string `json:"name"`
	SHA256   string `json:"sha256"`
	Content  []byte `json:"content"`
	Type     string `json:"type,omitempty"`
	Uploader string `json:"uploader,omitempty"`
	Uploaded int64  `json:"uploaded,omitempty"`
}

BackupObject is an exported named file or blob with an integrity digest.

type BackupProvider

type BackupProvider interface {
	Snapshot(ctx context.Context) (BackupState, error)
	Restore(ctx context.Context, state BackupState) error
}

BackupProvider snapshots and restores application state associated with a relay database. The provider owns its external resources.

type BackupState

type BackupState struct {
	Config    json.RawMessage `json:"config,omitempty"`
	Community json.RawMessage `json:"community,omitempty"`
	Identity  json.RawMessage `json:"identity,omitempty"`
	Blobs     []BackupObject  `json:"blobs,omitempty"`
	Sites     []BackupObject  `json:"sites,omitempty"`
	Git       []BackupObject  `json:"git,omitempty"`
	GitSQL    json.RawMessage `json:"sqlGit,omitempty"`
	Database  []BackupTable   `json:"database,omitempty"`
}

BackupState contains application-owned state and exported objects.

type BackupTable

type BackupTable struct {
	Name    string              `json:"name"`
	Columns []string            `json:"columns"`
	Rows    [][]json.RawMessage `json:"rows"`
}

BackupTable is a named table snapshot represented as JSON rows.

type CallbackClient

type CallbackClient struct {
	HTTP     *http.Client
	Resolver Resolver
	Timeout  time.Duration
}

func (CallbackClient) Post

func (c CallbackClient) Post(ctx context.Context, registration PushRegistration, e event.Event) error

type CallbackPolicy

type CallbackPolicy struct {
	HostOrigins  []string
	OwnerOrigins []string
}

type Config

type Config struct {
	Store         *storage.Store
	Policy        Policy
	CurrentPolicy func() Policy
	Directory     RelayDirectory
	// Owner identifies the tenant owner for owner-scoped management jobs.
	// It is used by backfill when the UI leaves the relay list blank.
	Owner           func() string
	Discovery       Discovery
	Delivery        DeliveryTransport
	DeliveryAllowed func(context.Context, storage.Intent) bool
	Pull            PullTransport
	Push            PushTransport
	DataDir         string
	Ingest          func(context.Context, event.Event, Origin) error
	ExecuteExternal func(context.Context, JobSpec) error
	BackupProvider  BackupProvider
	Workers         int
}

Config supplies a Service's store, routing policy, transports and optional application hooks. Store is required. DataDir defaults to the store's directory; Workers defaults to work.RunPool's worker count when Run is used. The caller retains ownership of the supplied transports and store.

type ConfigJob

type ConfigJob struct {
	ID      string
	Payload []byte
}

type DeliveryHandler

type DeliveryHandler func(context.Context, storage.Intent) error

func NewDeliveryHandler

func NewDeliveryHandler(store *storage.Store, transport DeliveryTransport) DeliveryHandler

type DeliveryResult

type DeliveryResult struct {
	Accepted bool
	Message  string
}

DeliveryResult reports the relay's acceptance response. Duplicate acknowledgments are treated as successful delivery by the handlers.

type DeliveryTransport

type DeliveryTransport interface {
	Send(ctx context.Context, target string, e event.Event) (DeliveryResult, error)
}

DeliveryTransport sends one event to a relay target. The implementation owns connection reuse, request deadlines and transport shutdown.

type Dialer

type Dialer interface {
	Dial(ctx context.Context, target string) (Socket, *http.Response, error)
}

Dialer opens a Socket for one relay target and returns its HTTP handshake.

type Discovery

type Discovery interface {
	DiscoverRelays(ctx context.Context, pubkey string) ([]string, error)
}

Discovery resolves write relays for an author.

type FullBackupProvider

type FullBackupProvider interface {
	BackupProvider
	SnapshotArchive(ctx context.Context, created int64) (BackupArchive, error)
}

FullBackupProvider can produce a complete archive using its own snapshot coordination.

type IPResolver

type IPResolver interface {
	LookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, error)
}

IPResolver resolves relay hostnames for address-policy checks and dialing.

type IntentPayload

type IntentPayload struct {
	Origin Origin `json:"origin"`
}

IntentPayload records the event origin in a delivery intent.

func DecodeIntentPayload

func DecodeIntentPayload(raw string) (IntentPayload, error)

type JobHandler

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

JobHandler decodes and validates durable job intents before delegating them.

func NewJobHandler

func NewJobHandler(runner JobRunner) *JobHandler

func (*JobHandler) Handle

func (h *JobHandler) Handle(ctx context.Context, intent work.Intent) error

type JobKind

type JobKind string

JobKind selects the durable replication operation.

const (
	JobPull   JobKind = "pull"
	JobPush   JobKind = "push"
	JobImport JobKind = "import"
	JobMirror JobKind = "mirror"
	JobDump   JobKind = "dump"
	JobBackup JobKind = "backup"
)

type JobRunner

type JobRunner interface {
	Run(ctx context.Context, spec JobSpec) error
}

JobRunner executes a validated job specification.

type JobSpec

type JobSpec struct {
	ID             string   `json:"id"`
	Kind           JobKind  `json:"kind"`
	Relays         []string `json:"relays,omitempty"`
	Filter         string   `json:"filter,omitempty"`
	Every          int      `json:"every,omitempty"`
	DiscoverPubKey string   `json:"discoverPubKey,omitempty"`
}

JobSpec describes one immediate or recurring replication job. Every is an interval in hours; zero runs once.

type JobStatus

type JobStatus struct {
	Spec                                                              JobSpec `json:"spec"`
	Phase                                                             string  `json:"phase"`
	Error                                                             string  `json:"error,omitempty"`
	Stored, Sent, Skipped, Refused, Cursor, Rounds, Started, Finished int64
}

type LegacyCache

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

type NostrTransport

type NostrTransport struct {
	Dialer  Dialer
	Timeout time.Duration

	// LegacyCache may be shared by short-lived transports created for the same
	// tenant. Entries expire so a relay can gain NIP-77 support without a
	// process restart.
	LegacyCache *LegacyCache
	// contains filtered or unexported fields
}

NostrTransport implements PullTransport and PushTransport over Nostr websocket protocols. Dialer defaults to WebsocketDialer when unset, and Timeout defaults to 20 seconds.

func (*NostrTransport) Query

func (t *NostrTransport) Query(ctx context.Context, target string, filter event.Filter) ([]event.Event, error)

func (*NostrTransport) QueryNegentropy

func (t *NostrTransport) QueryNegentropy(ctx context.Context, target string, filter event.Filter, local []syncprotocol.Item) ([]event.Event, error)

QueryNegentropy reconciles a local index with a remote relay, then fetches only IDs the local side lacks. It is optional at the PullTransport boundary so ordinary REQ remains a compatible fallback.

func (*NostrTransport) QueryPaginated

func (t *NostrTransport) QueryPaginated(ctx context.Context, target string, filter event.Filter) ([]event.Event, error)

QueryPaginated reads a bounded history window. It uses the oldest event in each page as the next upper bound, deduplicating events because relays may include the boundary event in their response.

func (*NostrTransport) QuerySynchronized

func (t *NostrTransport) QuerySynchronized(ctx context.Context, target string, filter event.Filter, local []syncprotocol.Item) ([]event.Event, error)

QuerySynchronized prefers NIP-77 negentropy and falls back to bounded, descending REQ pages when the peer does not implement it. GRASP peers are commonly mixed-version, so lack of NIP-77 support must not prevent the ordinary NIP-01 pull from completing.

func (*NostrTransport) Send

func (t *NostrTransport) Send(ctx context.Context, target string, e event.Event) (DeliveryResult, error)

func (*NostrTransport) Subscribe

func (t *NostrTransport) Subscribe(ctx context.Context, target string, filter event.Filter, onEvent func(event.Event) error) error

Subscribe keeps a bounded NIP-01 subscription open until ctx is canceled. Reconnection belongs to the lifecycle owner so it can apply peer backoff and avoid multiplying sockets when a relay is unhealthy.

func (*NostrTransport) SubscribeFilters

func (t *NostrTransport) SubscribeFilters(ctx context.Context, target string, filters []event.Filter, onEvent func(event.Event) error) error

SubscribeFilters opens one subscription for a set of NIP-01 filters. Relays treat filters in one REQ as an OR, which lets callers follow related event families without opening a socket for each family.

type Origin

type Origin string

Origin identifies how an event entered the relay and controls whether it is eligible for outbound fanout.

const (
	OriginClient        Origin = "client"
	OriginImport        Origin = "import"
	OriginServer        Origin = "server"
	OriginPush          Origin = "push"
	OriginBackupRestore Origin = "backup_restore"
)

type Policy

type Policy struct {
	Enabled         bool
	ReadMembersOnly bool
	SelfPubKey      string
	SelfRelayURL    string
}

Policy supplies current fanout decisions and relay identity. The host controls process capacity independently.

type PullTransport

type PullTransport interface {
	Query(ctx context.Context, target string, filter event.Filter) ([]event.Event, error)
}

PullTransport reads events from target. The transport owns network clients and their lifecycle; PullOnce owns validation and storage.

type PushRegistration

type PushRegistration struct {
	ID           string
	Owner        string
	Relay        string
	Callback     string
	Filters      []event.Filter
	Ignore       []event.Filter
	IncludeEvent bool
}

func ParsePushRegistration

func ParsePushRegistration(e event.Event, policy CallbackPolicy, self string) (PushRegistration, error)

type PushTransport

type PushTransport interface {
	Send(ctx context.Context, target string, e event.Event) (DeliveryResult, error)
}

PushTransport sends one event to target. PushAfter advances its cursor only after Send returns, including a relay duplicate acknowledgment.

type ReadDiscovery

type ReadDiscovery interface {
	DiscoverReadRelays(ctx context.Context, pubkey string) ([]string, error)
}

ReadDiscovery resolves read relays for a recipient.

type RelayDirectory

type RelayDirectory interface {
	WriteRelays(pubkey string) []string
	ReadRelays(pubkey string) []string
}

RelayDirectory returns write relays for an author and read relays for a recipient. Returned URLs are filtered by PrepareIntents.

type RelayListDiscovery

type RelayListDiscovery interface {
	RelayList(pubkey string) []string
}

RelayListDiscovery returns the source-ordered NIP-65 relay list used by owner backfill. RelayDirectory's directional methods remain sufficient for delivery planning.

type Resolver

type Resolver interface {
	LookupNetIP(context.Context, string, string) ([]netip.Addr, error)
}

type RestoreFinalizer

type RestoreFinalizer interface {
	FinalizeRestore(ctx context.Context) error
}

RestoreFinalizer runs application cleanup after a successful restore.

type Service

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

Service owns replication job state and the durable queue built on Store.

func NewService

func NewService(config Config) (*Service, error)

NewService initializes replication job tables and returns a service.

func (*Service) AddJob

func (s *Service) AddJob(ctx context.Context, spec JobSpec) error

func (*Service) Execute

func (s *Service) Execute(ctx context.Context, method string, values ...any) (any, error)

Execute accepts decoded arguments for compatibility with existing daemon callers.

func (*Service) ExecuteRaw

func (s *Service) ExecuteRaw(ctx context.Context, method string, params []json.RawMessage) (any, error)

ExecuteRaw accepts raw JSON arguments, matching NIP-86 and HTTP adapters.

func (*Service) Handlers

func (s *Service) Handlers() map[string]work.Handler

Handlers returns the replication-owned durable work handlers. The daemon composes these with tenant handlers before starting its worker pool.

func (*Service) ListJobStatus

func (s *Service) ListJobStatus(ctx context.Context) ([]JobStatus, error)

func (*Service) ListJobs

func (s *Service) ListJobs(ctx context.Context) ([]JobSpec, error)

func (*Service) Methods

func (s *Service) Methods() []string

func (*Service) Prepare

func (s *Service) Prepare(e event.Event, origin Origin) []storage.Intent

func (*Service) Queue

func (s *Service) Queue() *work.Queue

Queue returns the service's durable replication queue.

func (*Service) RemoveJob

func (s *Service) RemoveJob(ctx context.Context, id string) error

func (*Service) Run

func (s *Service) Run(ctx context.Context) error

Run is a convenience for replication-only callers. Applications that own additional durable work should compose Handlers and call work.RunPool.

func (*Service) RunJob

func (s *Service) RunJob(ctx context.Context, id string) error

func (*Service) Store

func (s *Service) Store() *storage.Store

Store returns the service's supplied store.

type Socket

type Socket interface {
	Read(ctx context.Context) ([]byte, error)
	Write(ctx context.Context, message []byte) error
	Close(cause error) error
}

Socket is the message-oriented connection used by NostrTransport. The caller that receives a Socket owns it and closes it when the exchange ends.

type SyncStats

type SyncStats struct {
	Stored     int
	Duplicates int
	Rejected   int
	Sent       int
	Refused    int
}

SyncStats summarizes one pull or push pass.

func PullOnce

func PullOnce(ctx context.Context, store *storage.Store, transport PullTransport, target string, filter event.Filter, now int64) (SyncStats, error)

func PullOnceWithIngest

func PullOnceWithIngest(ctx context.Context, store *storage.Store, transport PullTransport, target string, filter event.Filter, now int64, ingest func(context.Context, event.Event, Origin) error) (SyncStats, error)

func PushAfter

func PushAfter(ctx context.Context, store *storage.Store, transport PushTransport, target string, cursor int64, filter event.Filter, now int64) (SyncStats, int64, error)

type WebsocketDialer

type WebsocketDialer struct {
	AllowPrivate    bool
	MaxMessageBytes int64
	Resolver        IPResolver
	HTTPClient      *http.Client
	// Authenticate answers a NIP-42 challenge when configured for an
	// operator-trusted private peer. Public relays remain unauthenticated.
	Authenticate func(context.Context, string, string) (event.Event, error)
}

WebsocketDialer validates websocket targets, blocks private addresses unless AllowPrivate is set and optionally answers NIP-42 authentication challenges. HTTPClient and Resolver are caller-supplied dependencies and remain owned by the caller.

func (WebsocketDialer) Dial

func (d WebsocketDialer) Dial(ctx context.Context, target string) (Socket, *http.Response, error)

Jump to

Keyboard shortcuts

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