{"modulePath":"github.com/FelineStateMachine/tinyrelay","version":"v0.0.0-20260923223823-92682824e566","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package replication\n\nPackage replication plans and executes durable relay synchronization.\n\nPlanning 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.\n\nService 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.\n\nWebSocket transports validate relay URLs and public address resolution before dialing. Backup and artifact helpers write complete files through temporary files and same-directory rename.\n\n## Constants\n\n```go\nconst BackupFormat = \"tinyrelay/backup/1\"\n```\nBackupFormat identifies the JSON archive format produced by this package.\n\n## Variables\n\n```go\nvar ErrNegentropyUnsupported = errors.New(\"replication: negentropy unsupported\")\n```\nErrNegentropyUnsupported 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.\n\n```go\nvar ErrPullIncomplete = errors.New(\"replication: pull history is incomplete\")\n```\nErrPullIncomplete 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.\n\n## Functions\n\n```go\nfunc CallbackPayload(reg PushRegistration, e event.Event) ([]byte, error)\n```\n\n```go\nfunc CancelJob(ctx context.Context, queue *work.Queue, id string, now time.Time) error\n```\n\n```go\nfunc EnqueueJob(ctx context.Context, queue *work.Queue, spec JobSpec, at time.Time) (string, error)\n```\n\n```go\nfunc EnsureJobSchema(db interface {\n\tExec(string, ...any) (sql.Result, error)\n}) error\n```\nEnsureJobSchema initializes replication-owned job state for callers that import configuration before constructing a replication service.\n\n```go\nfunc ImportJSONL(ctx context.Context, store *storage.Store, input io.Reader, now int64) error\n```\n\n```go\nfunc IntentForJob(spec JobSpec, at time.Time) (storage.Intent, error)\n```\n\n```go\nfunc NewCallbackHandler(store *storage.Store, client CallbackClient) work.Handler\n```\n\n```go\nfunc 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\n```\nNewCallbackHandlerWithEventVisibility 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.\n\n```go\nfunc NewCallbackHandlerWithPolicy(store *storage.Store, client CallbackClient, policy func() CallbackPolicy, enabled func() bool, visible func(context.Context, string) bool) work.Handler\n```\n\n```go\nfunc NewPinnedClient(timeout time.Duration) *http.Client\n```\nNewPinnedClient returns an HTTPS client that refuses private addresses and redirects, for calls to third-party services such as push endpoints.\n\n```go\nfunc NextRun(spec JobSpec, finished time.Time) time.Time\n```\n\n```go\nfunc PrepareCallbackIntents(ctx context.Context, e event.Event, registrations []PushRegistration) []storage.Intent\n```\nPrepareCallbackIntents persists references only. Callback I/O is performed later by a worker after registration and event visibility are rechecked.\n\n```go\nfunc PrepareIntents(ctx context.Context, e event.Event, origin Origin, policy Policy, directory RelayDirectory) []storage.Intent\n```\nPrepareIntents computes NIP-65 outbox work. The event transaction should pass the returned references to storage.Save as SaveOptions.Intents.\n\n```go\nfunc PushMatches(reg PushRegistration, e event.Event) bool\n```\n\n```go\nfunc ReplaceJobsTx(ctx context.Context, tx *sql.Tx, specs []ConfigJob) error\n```\nReplaceJobsTx 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.\n\n```go\nfunc RescheduleJob(ctx context.Context, queue *work.Queue, spec JobSpec, at time.Time) (string, error)\n```\nRescheduleJob 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.\n\n```go\nfunc RestoreBackup(ctx context.Context, store *storage.Store, archive BackupArchive, now int64) (int, error)\n```\n\n```go\nfunc RestoreBackupWithProvider(ctx context.Context, store *storage.Store, provider BackupProvider, archive BackupArchive, now int64) (int, error)\n```\n\n```go\nfunc ValidateIntent(intent storage.Intent) error\n```\n\n```go\nfunc ValidateJob(spec JobSpec) error\n```\n\n```go\nfunc WriteBackup(ctx context.Context, store *storage.Store, output io.Writer, now int64) error\n```\n\n```go\nfunc WriteDump(ctx context.Context, store *storage.Store, output io.Writer, now int64) error\n```\n\n## Types\n\n```go\ntype BackupArchive struct {\n\tFormat  string        `json:\"format\"`\n\tEvents  []event.Event `json:\"events\"`\n\tState   BackupState   `json:\"state\"`\n\tSHA256  string        `json:\"sha256\"`\n\tCreated int64         `json:\"created_at\"`\n}\n```\nBackupArchive is a sealed event and application-state export.\n\n```go\nfunc CreateBackup(ctx context.Context, store *storage.Store, now int64) (BackupArchive, error)\n```\n\n```go\nfunc CreateBackupWithProvider(ctx context.Context, store *storage.Store, provider BackupProvider, now int64) (BackupArchive, error)\n```\n\n```go\nfunc ReadBackup(input io.Reader) (BackupArchive, error)\n```\n\n```go\nfunc ReadCompatibleBackup(input io.Reader) (BackupArchive, error)\n```\nReadCompatibleBackup accepts both the native archive and bind.ws/relay-backup/1. The legacy shape is normalized before restore so callers have one validation path.\n\n```go\nfunc SealBackup(archive BackupArchive) (BackupArchive, error)\n```\n\n```go\ntype BackupObject struct {\n\tName     string `json:\"name\"`\n\tSHA256   string `json:\"sha256\"`\n\tContent  []byte `json:\"content\"`\n\tType     string `json:\"type,omitempty\"`\n\tUploader string `json:\"uploader,omitempty\"`\n\tUploaded int64  `json:\"uploaded,omitempty\"`\n}\n```\nBackupObject is an exported named file or blob with an integrity digest.\n\n```go\ntype BackupProvider interface {\n\tSnapshot(ctx context.Context) (BackupState, error)\n\tRestore(ctx context.Context, state BackupState) error\n}\n```\nBackupProvider snapshots and restores application state associated with a relay database. The provider owns its external resources.\n\n```go\ntype BackupState struct {\n\tConfig    json.RawMessage `json:\"config,omitempty\"`\n\tCommunity json.RawMessage `json:\"community,omitempty\"`\n\tIdentity  json.RawMessage `json:\"identity,omitempty\"`\n\tBlobs     []BackupObject  `json:\"blobs,omitempty\"`\n\tSites     []BackupObject  `json:\"sites,omitempty\"`\n\tGit       []BackupObject  `json:\"git,omitempty\"`\n\tGitSQL    json.RawMessage `json:\"sqlGit,omitempty\"`\n\tDatabase  []BackupTable   `json:\"database,omitempty\"`\n}\n```\nBackupState contains application-owned state and exported objects.\n\n```go\ntype BackupTable struct {\n\tName    string              `json:\"name\"`\n\tColumns []string            `json:\"columns\"`\n\tRows    [][]json.RawMessage `json:\"rows\"`\n}\n```\nBackupTable is a named table snapshot represented as JSON rows.\n\n```go\ntype CallbackClient struct {\n\tHTTP     *http.Client\n\tResolver Resolver\n\tTimeout  time.Duration\n}\n```\n\n```go\nfunc (c CallbackClient) Post(ctx context.Context, registration PushRegistration, e event.Event) error\n```\n\n```go\ntype CallbackPolicy struct {\n\tHostOrigins  []string\n\tOwnerOrigins []string\n}\n```\n\n```go\ntype Config struct {\n\tStore         *storage.Store\n\tPolicy        Policy\n\tCurrentPolicy func() Policy\n\tDirectory     RelayDirectory\n\t// Owner identifies the tenant owner for owner-scoped management jobs.\n\t// It is used by backfill when the UI leaves the relay list blank.\n\tOwner           func() string\n\tDiscovery       Discovery\n\tDelivery        DeliveryTransport\n\tDeliveryAllowed func(context.Context, storage.Intent) bool\n\tPull            PullTransport\n\tPush            PushTransport\n\tDataDir         string\n\tIngest          func(context.Context, event.Event, Origin) error\n\tExecuteExternal func(context.Context, JobSpec) error\n\tBackupProvider  BackupProvider\n\tWorkers         int\n}\n```\nConfig 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.\n\n```go\ntype ConfigJob struct {\n\tID      string\n\tPayload []byte\n}\n```\n\n```go\ntype DeliveryHandler func(context.Context, storage.Intent) error\n```\n\n```go\nfunc NewDeliveryHandler(store *storage.Store, transport DeliveryTransport) DeliveryHandler\n```\n\n```go\ntype DeliveryResult struct {\n\tAccepted bool\n\tMessage  string\n}\n```\nDeliveryResult reports the relay's acceptance response. Duplicate acknowledgments are treated as successful delivery by the handlers.\n\n```go\ntype DeliveryTransport interface {\n\tSend(ctx context.Context, target string, e event.Event) (DeliveryResult, error)\n}\n```\nDeliveryTransport sends one event to a relay target. The implementation owns connection reuse, request deadlines and transport shutdown.\n\n```go\ntype Dialer interface {\n\tDial(ctx context.Context, target string) (Socket, *http.Response, error)\n}\n```\nDialer opens a Socket for one relay target and returns its HTTP handshake.\n\n```go\ntype Discovery interface {\n\tDiscoverRelays(ctx context.Context, pubkey string) ([]string, error)\n}\n```\nDiscovery resolves write relays for an author.\n\n```go\ntype FullBackupProvider interface {\n\tBackupProvider\n\tSnapshotArchive(ctx context.Context, created int64) (BackupArchive, error)\n}\n```\nFullBackupProvider can produce a complete archive using its own snapshot coordination.\n\n```go\ntype IPResolver interface {\n\tLookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, error)\n}\n```\nIPResolver resolves relay hostnames for address-policy checks and dialing.\n\n```go\ntype IntentPayload struct {\n\tOrigin Origin `json:\"origin\"`\n}\n```\nIntentPayload records the event origin in a delivery intent.\n\n```go\nfunc DecodeIntentPayload(raw string) (IntentPayload, error)\n```\n\n```go\ntype JobHandler struct {\n\t// contains filtered or unexported fields\n}\n```\nJobHandler decodes and validates durable job intents before delegating them.\n\n```go\nfunc NewJobHandler(runner JobRunner) *JobHandler\n```\n\n```go\nfunc (h *JobHandler) Handle(ctx context.Context, intent work.Intent) error\n```\n\n```go\ntype JobKind string\n```\nJobKind selects the durable replication operation.\n\n```go\nconst (\n\tJobPull   JobKind = \"pull\"\n\tJobPush   JobKind = \"push\"\n\tJobImport JobKind = \"import\"\n\tJobMirror JobKind = \"mirror\"\n\tJobDump   JobKind = \"dump\"\n\tJobBackup JobKind = \"backup\"\n)\n```\n\n```go\ntype JobRunner interface {\n\tRun(ctx context.Context, spec JobSpec) error\n}\n```\nJobRunner executes a validated job specification.\n\n```go\ntype JobSpec struct {\n\tID             string   `json:\"id\"`\n\tKind           JobKind  `json:\"kind\"`\n\tRelays         []string `json:\"relays,omitempty\"`\n\tFilter         string   `json:\"filter,omitempty\"`\n\tEvery          int      `json:\"every,omitempty\"`\n\tDiscoverPubKey string   `json:\"discoverPubKey,omitempty\"`\n}\n```\nJobSpec describes one immediate or recurring replication job. Every is an interval in hours; zero runs once.\n\n```go\ntype JobStatus struct {\n\tSpec                                                              JobSpec `json:\"spec\"`\n\tPhase                                                             string  `json:\"phase\"`\n\tError                                                             string  `json:\"error,omitempty\"`\n\tStored, Sent, Skipped, Refused, Cursor, Rounds, Started, Finished int64\n}\n```\n\n```go\ntype LegacyCache struct {\n\t// contains filtered or unexported fields\n}\n```\n\n```go\ntype NostrTransport struct {\n\tDialer  Dialer\n\tTimeout time.Duration\n\n\t// LegacyCache may be shared by short-lived transports created for the same\n\t// tenant. Entries expire so a relay can gain NIP-77 support without a\n\t// process restart.\n\tLegacyCache *LegacyCache\n\t// contains filtered or unexported fields\n}\n```\nNostrTransport implements PullTransport and PushTransport over Nostr websocket protocols. Dialer defaults to WebsocketDialer when unset, and Timeout defaults to 20 seconds.\n\n```go\nfunc (t *NostrTransport) Query(ctx context.Context, target string, filter event.Filter) ([]event.Event, error)\n```\n\n```go\nfunc (t *NostrTransport) QueryNegentropy(ctx context.Context, target string, filter event.Filter, local []syncprotocol.Item) ([]event.Event, error)\n```\nQueryNegentropy 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.\n\n```go\nfunc (t *NostrTransport) QueryPaginated(ctx context.Context, target string, filter event.Filter) ([]event.Event, error)\n```\nQueryPaginated 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.\n\n```go\nfunc (t *NostrTransport) QuerySynchronized(ctx context.Context, target string, filter event.Filter, local []syncprotocol.Item) ([]event.Event, error)\n```\nQuerySynchronized 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.\n\n```go\nfunc (t *NostrTransport) Send(ctx context.Context, target string, e event.Event) (DeliveryResult, error)\n```\n\n```go\nfunc (t *NostrTransport) Subscribe(ctx context.Context, target string, filter event.Filter, onEvent func(event.Event) error) error\n```\nSubscribe 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.\n\n```go\nfunc (t *NostrTransport) SubscribeFilters(ctx context.Context, target string, filters []event.Filter, onEvent func(event.Event) error) error\n```\nSubscribeFilters 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.\n\n```go\ntype Origin string\n```\nOrigin identifies how an event entered the relay and controls whether it is eligible for outbound fanout.\n\n```go\nconst (\n\tOriginClient        Origin = \"client\"\n\tOriginImport        Origin = \"import\"\n\tOriginServer        Origin = \"server\"\n\tOriginPush          Origin = \"push\"\n\tOriginBackupRestore Origin = \"backup_restore\"\n)\n```\n\n```go\ntype Policy struct {\n\tEnabled         bool\n\tReadMembersOnly bool\n\tSelfPubKey      string\n\tSelfRelayURL    string\n}\n```\nPolicy supplies current fanout decisions and relay identity. The host controls process capacity independently.\n\n```go\ntype PullTransport interface {\n\tQuery(ctx context.Context, target string, filter event.Filter) ([]event.Event, error)\n}\n```\nPullTransport reads events from target. The transport owns network clients and their lifecycle; PullOnce owns validation and storage.\n\n```go\ntype PushRegistration struct {\n\tID           string\n\tOwner        string\n\tRelay        string\n\tCallback     string\n\tFilters      []event.Filter\n\tIgnore       []event.Filter\n\tIncludeEvent bool\n}\n```\n\n```go\nfunc ParsePushRegistration(e event.Event, policy CallbackPolicy, self string) (PushRegistration, error)\n```\n\n```go\ntype PushTransport interface {\n\tSend(ctx context.Context, target string, e event.Event) (DeliveryResult, error)\n}\n```\nPushTransport sends one event to target. PushAfter advances its cursor only after Send returns, including a relay duplicate acknowledgment.\n\n```go\ntype ReadDiscovery interface {\n\tDiscoverReadRelays(ctx context.Context, pubkey string) ([]string, error)\n}\n```\nReadDiscovery resolves read relays for a recipient.\n\n```go\ntype RelayDirectory interface {\n\tWriteRelays(pubkey string) []string\n\tReadRelays(pubkey string) []string\n}\n```\nRelayDirectory returns write relays for an author and read relays for a recipient. Returned URLs are filtered by PrepareIntents.\n\n```go\ntype RelayListDiscovery interface {\n\tRelayList(pubkey string) []string\n}\n```\nRelayListDiscovery returns the source-ordered NIP-65 relay list used by owner backfill. RelayDirectory's directional methods remain sufficient for delivery planning.\n\n```go\ntype Resolver interface {\n\tLookupNetIP(context.Context, string, string) ([]netip.Addr, error)\n}\n```\n\n```go\ntype RestoreFinalizer interface {\n\tFinalizeRestore(ctx context.Context) error\n}\n```\nRestoreFinalizer runs application cleanup after a successful restore.\n\n```go\ntype Service struct {\n\t// contains filtered or unexported fields\n}\n```\nService owns replication job state and the durable queue built on Store.\n\n```go\nfunc NewService(config Config) (*Service, error)\n```\nNewService initializes replication job tables and returns a service.\n\n```go\nfunc (s *Service) AddJob(ctx context.Context, spec JobSpec) error\n```\n\n```go\nfunc (s *Service) Execute(ctx context.Context, method string, values ...any) (any, error)\n```\nExecute accepts decoded arguments for compatibility with existing daemon callers.\n\n```go\nfunc (s *Service) ExecuteRaw(ctx context.Context, method string, params []json.RawMessage) (any, error)\n```\nExecuteRaw accepts raw JSON arguments, matching NIP-86 and HTTP adapters.\n\n```go\nfunc (s *Service) Handlers() map[string]work.Handler\n```\nHandlers returns the replication-owned durable work handlers. The daemon composes these with tenant handlers before starting its worker pool.\n\n```go\nfunc (s *Service) ListJobStatus(ctx context.Context) ([]JobStatus, error)\n```\n\n```go\nfunc (s *Service) ListJobs(ctx context.Context) ([]JobSpec, error)\n```\n\n```go\nfunc (s *Service) Methods() []string\n```\n\n```go\nfunc (s *Service) Prepare(e event.Event, origin Origin) []storage.Intent\n```\n\n```go\nfunc (s *Service) Queue() *work.Queue\n```\nQueue returns the service's durable replication queue.\n\n```go\nfunc (s *Service) RemoveJob(ctx context.Context, id string) error\n```\n\n```go\nfunc (s *Service) Run(ctx context.Context) error\n```\nRun is a convenience for replication-only callers. Applications that own additional durable work should compose Handlers and call work.RunPool.\n\n```go\nfunc (s *Service) RunJob(ctx context.Context, id string) error\n```\n\n```go\nfunc (s *Service) Store() *storage.Store\n```\nStore returns the service's supplied store.\n\n```go\ntype Socket interface {\n\tRead(ctx context.Context) ([]byte, error)\n\tWrite(ctx context.Context, message []byte) error\n\tClose(cause error) error\n}\n```\nSocket is the message-oriented connection used by NostrTransport. The caller that receives a Socket owns it and closes it when the exchange ends.\n\n```go\ntype SyncStats struct {\n\tStored     int\n\tDuplicates int\n\tRejected   int\n\tSent       int\n\tRefused    int\n}\n```\nSyncStats summarizes one pull or push pass.\n\n```go\nfunc PullOnce(ctx context.Context, store *storage.Store, transport PullTransport, target string, filter event.Filter, now int64) (SyncStats, error)\n```\n\n```go\nfunc 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)\n```\n\n```go\nfunc PushAfter(ctx context.Context, store *storage.Store, transport PushTransport, target string, cursor int64, filter event.Filter, now int64) (SyncStats, int64, error)\n```\n\n```go\ntype WebsocketDialer struct {\n\tAllowPrivate    bool\n\tMaxMessageBytes int64\n\tResolver        IPResolver\n\tHTTPClient      *http.Client\n\t// Authenticate answers a NIP-42 challenge when configured for an\n\t// operator-trusted private peer. Public relays remain unauthenticated.\n\tAuthenticate func(context.Context, string, string) (event.Event, error)\n}\n```\nWebsocketDialer 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.\n\n```go\nfunc (d WebsocketDialer) Dial(ctx context.Context, target string) (Socket, *http.Response, error)\n```\n\n","path":"github.com/FelineStateMachine/tinyrelay/internal/replication","name":"replication","synopsis":"Package replication plans and executes durable relay synchronization.","isRedistributable":true}
