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
- Variables
- func CallbackPayload(reg PushRegistration, e event.Event) ([]byte, error)
- func CancelJob(ctx context.Context, queue *work.Queue, id string, now time.Time) error
- func EnqueueJob(ctx context.Context, queue *work.Queue, spec JobSpec, at time.Time) (string, error)
- func EnsureJobSchema(db interface{ ... }) error
- func ImportJSONL(ctx context.Context, store *storage.Store, input io.Reader, now int64) error
- func IntentForJob(spec JobSpec, at time.Time) (storage.Intent, error)
- func NewCallbackHandler(store *storage.Store, client CallbackClient) work.Handler
- func NewCallbackHandlerWithEventVisibility(store *storage.Store, client CallbackClient, policy func() CallbackPolicy, ...) work.Handler
- func NewCallbackHandlerWithPolicy(store *storage.Store, client CallbackClient, policy func() CallbackPolicy, ...) work.Handler
- func NewPinnedClient(timeout time.Duration) *http.Client
- func NextRun(spec JobSpec, finished time.Time) time.Time
- func PrepareCallbackIntents(ctx context.Context, e event.Event, registrations []PushRegistration) []storage.Intent
- func PrepareIntents(ctx context.Context, e event.Event, origin Origin, policy Policy, ...) []storage.Intent
- func PushMatches(reg PushRegistration, e event.Event) bool
- func ReplaceJobsTx(ctx context.Context, tx *sql.Tx, specs []ConfigJob) error
- func RescheduleJob(ctx context.Context, queue *work.Queue, spec JobSpec, at time.Time) (string, error)
- func RestoreBackup(ctx context.Context, store *storage.Store, archive BackupArchive, now int64) (int, error)
- func RestoreBackupWithProvider(ctx context.Context, store *storage.Store, provider BackupProvider, ...) (int, error)
- func ValidateIntent(intent storage.Intent) error
- func ValidateJob(spec JobSpec) error
- func WriteBackup(ctx context.Context, store *storage.Store, output io.Writer, now int64) error
- func WriteDump(ctx context.Context, store *storage.Store, output io.Writer, now int64) error
- type BackupArchive
- func CreateBackup(ctx context.Context, store *storage.Store, now int64) (BackupArchive, error)
- func CreateBackupWithProvider(ctx context.Context, store *storage.Store, provider BackupProvider, now int64) (BackupArchive, error)
- func ReadBackup(input io.Reader) (BackupArchive, error)
- func ReadCompatibleBackup(input io.Reader) (BackupArchive, error)
- func SealBackup(archive BackupArchive) (BackupArchive, error)
- type BackupObject
- type BackupProvider
- type BackupState
- type BackupTable
- type CallbackClient
- type CallbackPolicy
- type Config
- type ConfigJob
- type DeliveryHandler
- type DeliveryResult
- type DeliveryTransport
- type Dialer
- type Discovery
- type FullBackupProvider
- type IPResolver
- type IntentPayload
- type JobHandler
- type JobKind
- type JobRunner
- type JobSpec
- type JobStatus
- type LegacyCache
- type NostrTransport
- func (t *NostrTransport) Query(ctx context.Context, target string, filter event.Filter) ([]event.Event, error)
- func (t *NostrTransport) QueryNegentropy(ctx context.Context, target string, filter event.Filter, ...) ([]event.Event, error)
- func (t *NostrTransport) QueryPaginated(ctx context.Context, target string, filter event.Filter) ([]event.Event, error)
- func (t *NostrTransport) QuerySynchronized(ctx context.Context, target string, filter event.Filter, ...) ([]event.Event, error)
- func (t *NostrTransport) Send(ctx context.Context, target string, e event.Event) (DeliveryResult, error)
- func (t *NostrTransport) Subscribe(ctx context.Context, target string, filter event.Filter, ...) error
- func (t *NostrTransport) SubscribeFilters(ctx context.Context, target string, filters []event.Filter, ...) error
- type Origin
- type Policy
- type PullTransport
- type PushRegistration
- type PushTransport
- type ReadDiscovery
- type RelayDirectory
- type RelayListDiscovery
- type Resolver
- type RestoreFinalizer
- type Service
- func (s *Service) AddJob(ctx context.Context, spec JobSpec) error
- func (s *Service) Execute(ctx context.Context, method string, values ...any) (any, error)
- func (s *Service) ExecuteRaw(ctx context.Context, method string, params []json.RawMessage) (any, error)
- func (s *Service) Handlers() map[string]work.Handler
- func (s *Service) ListJobStatus(ctx context.Context) ([]JobStatus, error)
- func (s *Service) ListJobs(ctx context.Context) ([]JobSpec, error)
- func (s *Service) Methods() []string
- func (s *Service) Prepare(e event.Event, origin Origin) []storage.Intent
- func (s *Service) Queue() *work.Queue
- func (s *Service) RemoveJob(ctx context.Context, id string) error
- func (s *Service) Run(ctx context.Context) error
- func (s *Service) RunJob(ctx context.Context, id string) error
- func (s *Service) Store() *storage.Store
- type Socket
- type SyncStats
- func PullOnce(ctx context.Context, store *storage.Store, transport PullTransport, ...) (SyncStats, error)
- func PullOnceWithIngest(ctx context.Context, store *storage.Store, transport PullTransport, ...) (SyncStats, error)
- func PushAfter(ctx context.Context, store *storage.Store, transport PushTransport, ...) (SyncStats, int64, error)
- type WebsocketDialer
Constants ¶
const BackupFormat = "tinyrelay/backup/1"
BackupFormat identifies the JSON archive format produced by this package.
Variables ¶
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.
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 EnqueueJob ¶
func EnsureJobSchema ¶
EnsureJobSchema initializes replication-owned job state for callers that import configuration before constructing a replication service.
func ImportJSONL ¶
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 NewPinnedClient ¶
NewPinnedClient returns an HTTPS client that refuses private addresses and redirects, for calls to third-party services such as push endpoints.
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 ¶
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 RestoreBackupWithProvider ¶
func RestoreBackupWithProvider(ctx context.Context, store *storage.Store, provider BackupProvider, archive BackupArchive, now int64) (int, error)
func ValidateIntent ¶
func ValidateJob ¶
func WriteBackup ¶
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 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 ¶
func (CallbackClient) Post ¶
func (c CallbackClient) Post(ctx context.Context, registration PushRegistration, e event.Event) error
type CallbackPolicy ¶
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 DeliveryHandler ¶
func NewDeliveryHandler ¶
func NewDeliveryHandler(store *storage.Store, transport DeliveryTransport) DeliveryHandler
type DeliveryResult ¶
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 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 ¶
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
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 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) 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.
type Policy ¶
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 ¶
RelayListDiscovery returns the source-ordered NIP-65 relay list used by owner backfill. RelayDirectory's directional methods remain sufficient for delivery planning.
type RestoreFinalizer ¶
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 ¶
NewService initializes replication job tables and returns a service.
func (*Service) Execute ¶
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 ¶
Handlers returns the replication-owned durable work handlers. The daemon composes these with tenant handlers before starting its worker pool.
func (*Service) ListJobStatus ¶
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 ¶
SyncStats summarizes one pull or push pass.
func PullOnceWithIngest ¶
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.