relay

package
v0.0.1-rc Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: MIT Imports: 33 Imported by: 0

Documentation

Overview

Store and DB logging helpers for the relay (see LogStoreErr).

Severity policy (relay-facing):

  • Error: relay degraded or client received a misleading hard failure (e.g. REQ internal error path).
  • Warn: policy, overload, or secondary failures worth tailing at default log level.
  • Debug: parse noise, per-hot-path visibility checks, and companion detail for store errors.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrSubscriptionIDTooLong is returned when sub id exceeds configured max.
	ErrSubscriptionIDTooLong = errors.New("relay: subscription id too long")
	// ErrTooManySubscriptions is returned when a connection exceeds its sub cap.
	ErrTooManySubscriptions = errors.New("relay: too many subscriptions")
	// ErrTooManyFilters is returned when a REQ carries too many filters.
	ErrTooManyFilters = errors.New("relay: too many filters per REQ")
)
View Source
var ErrNIP11ImageExternal = errors.New("nip11 image is an external url")

ErrNIP11ImageExternal means the image is an operator URL, not a hosted file.

View Source
var ErrSlowConsumer = errors.New("relay: send buffer full")

ErrSlowConsumer indicates the outbound buffer is full.

Functions

func AcceptsNostrJSON

func AcceptsNostrJSON(r *http.Request) bool

AcceptsNostrJSON reports whether the request asks for NIP-11 JSON.

func LogStoreErr

func LogStoreErr(log zerolog.Logger, primaryLevel zerolog.Level, operation string, err error, msg string, debugFields func(*zerolog.Event))

LogStoreErr logs a store/DB failure at primaryLevel (typically Warn or Error) with operation and err, then emits a Debug line with the same err when debugFields is non-nil (must add extra context only there).

func MsgIDFromCtx

func MsgIDFromCtx(ctx context.Context) string

MsgIDFromCtx returns the per-message correlation id, or empty if absent.

func ReadNIP11Preview

func ReadNIP11Preview(cfgPath string, section config.NIP11Section, asset string) ([]byte, string, error)

ReadNIP11Preview returns the bytes the relay would serve for a hosted icon or banner. External URL mode returns ErrNIP11ImageExternal.

func RegisterNIP01

func RegisterNIP01(s *Server, store storage.Store)

RegisterNIP01 wires NIP-01 validation, hooks, and message handlers.

func RegisterNIP17

func RegisterNIP17(s *Server, _ storage.Store)

RegisterNIP17 registers NIP-17 policy (always) and full gift-wrap handling when NIP-17 is in nips.enabled.

func RegisterNIP29

func RegisterNIP29(s *Server, store storage.Store)

RegisterNIP29 registers NIP-29 validators and hooks (previous, late publish, restricted write, moderation by relay key or latest kind-39001 admin list, open-group 9021 join flow with relay-signed 9000, 9022 with relay-signed 9001, private read gating). Remaining optional gaps: closed-group invite codes (9009 + code tag), publishing/updating 39003 roles, keeping 39001 in sync on every moderation action.

func RegisterNIP42

func RegisterNIP42(s *Server, _ storage.Store)

RegisterNIP42 registers AUTH handling and publish policy validation (NIP-42).

func RegisterNIP50

func RegisterNIP50(s *Server, _ storage.Store)

RegisterNIP50 replaces the REQ handler with one that enables NIP-50 search filters. Call after RegisterNIP01. Requires nip 50 in config nips.enabled (loader enforces order).

func RegisterNIP77

func RegisterNIP77(s *Server, _ storage.Store)

RegisterNIP77 registers NEG-* handlers and starts the negentropy worker queue.

func RunImportedEventFanout

func RunImportedEventFanout(ctx context.Context, s *Server, store storage.Store, n storage.EventNotifier, log zerolog.Logger)

RunImportedEventFanout loads events by id from NOTIFY/LISTEN, notifies plugins that subscribe to the event, and broadcasts to REQ subscriptions. It returns when ctx is done or the notifier channel is closed. Same-origin LISTEN is filtered by the notifier, so the importing instance notifies plugins from persistImportedEvent instead of this loop.

func WithMsgID

func WithMsgID(ctx context.Context, msgID string) context.Context

WithMsgID returns ctx annotated for one inbound WebSocket text message (after JSON parse).

Types

type Conn

type Conn struct {
	ID string
	// contains filtered or unexported fields
}

Conn is one WebSocket client attachment to the relay.

func (*Conn) Log

func (c *Conn) Log() zerolog.Logger

Log returns the per-connection logger (full pubkeys should be logged at call sites).

type ConnAuditLiveDetail

type ConnAuditLiveDetail struct {
	ConnAuditLiveSummary
	SubscriptionDetails []SubConnAudit `json:"subscription_details"`
	NegSessions         []NegConnAudit `json:"neg_sessions,omitempty"`
}

ConnAuditLiveDetail is a live connection plus per-subscription metrics.

type ConnAuditLiveSummary

type ConnAuditLiveSummary struct {
	Ref               string          `json:"ref"`
	ConnID            string          `json:"conn_id"`
	PeerIP            string          `json:"peer_ip"`
	RemoteAddr        string          `json:"remote_addr"`
	StartedUnix       int64           `json:"started_unix"`
	SubscriptionCount int             `json:"subscriptions"`
	TotalAuth         int64           `json:"total_auth"`
	TotalReq          int64           `json:"total_req"`
	TotalClientEvent  int64           `json:"total_client_event"`
	TotalNegOpen      int64           `json:"total_neg_open"`
	TotalNegMsg       int64           `json:"total_neg_msg"`
	Series            json.RawMessage `json:"series"`
}

ConnAuditLiveSummary is one open WebSocket connection for admin audit APIs.

type ConnLimiter

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

ConnLimiter is per-WebSocket-connection rate state.

func (*ConnLimiter) AllowEvent

func (cl *ConnLimiter) AllowEvent() bool

AllowEvent counts one EVENT against the per-minute cap (after AllowInboundBytes).

func (*ConnLimiter) AllowInboundBytes

func (cl *ConnLimiter) AllowInboundBytes(n int) bool

AllowInboundBytes counts raw message bytes against the per-second cap.

func (*ConnLimiter) AllowNegMsg

func (cl *ConnLimiter) AllowNegMsg() bool

AllowNegMsg counts one NEG-MSG against the NIP-77 per-minute cap.

func (*ConnLimiter) AllowNegOpen

func (cl *ConnLimiter) AllowNegOpen() bool

AllowNegOpen counts one NEG-OPEN against the NIP-77 per-minute cap.

func (*ConnLimiter) AllowReq

func (cl *ConnLimiter) AllowReq() bool

AllowReq counts one REQ against the per-minute cap.

type EventValidator

type EventValidator interface {
	Validate(ctx context.Context, conn *Conn, ev *nostr.Event) error
}

EventValidator runs one validation step on an event before storage.

type EventValidatorFunc

type EventValidatorFunc func(ctx context.Context, conn *Conn, ev *nostr.Event) error

EventValidatorFunc adapts a function to EventValidator.

func (EventValidatorFunc) Validate

func (f EventValidatorFunc) Validate(ctx context.Context, conn *Conn, ev *nostr.Event) error

Validate implements EventValidator.

type HealthHandler

type HealthHandler struct {
	Store storage.Store
}

HealthHandler answers GET /health when the store is reachable.

func (*HealthHandler) ServeHTTP

func (h *HealthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP returns 200 with body "ok" if CountEvents succeeds.

type HookChain

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

HookChain runs registered hooks in registration order. Hook names appear in errors from Run as "post_hook <name>: ..." for observability.

func (*HookChain) Append

func (c *HookChain) Append(name string, h PostStoreHook)

Append registers a named hook (stable grep-friendly name, e.g. nip01_audit_event).

func (*HookChain) Prepend

func (c *HookChain) Prepend(name string, h PostStoreHook)

Prepend registers hooks to run before those added with Append.

func (*HookChain) Run

func (c *HookChain) Run(ctx context.Context, env HookEnv) error

Run executes all hooks; the first error is returned wrapped with the hook name.

type HookEnv

type HookEnv struct {
	Conn   *Conn
	Event  *nostr.Event
	Stored bool
}

HookEnv is passed to each post-accept hook after an event is validated.

type Hub

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

Hub coordinates IP-level and constructs per-connection limiters.

func NewLimiterHub

func NewLimiterHub(cfg *config.Config) *Hub

NewLimiterHub builds rate limit state from config.

func (*Hub) AllowMessage

func (h *Hub) AllowMessage(ip string) bool

AllowMessage counts one inbound message toward the IP cap (all WS messages).

func (*Hub) AllowNewConnection

func (h *Hub) AllowNewConnection(ip string) bool

AllowNewConnection reports whether a new TCP/WebSocket from ip is allowed.

func (*Hub) NewConnLimiter

func (h *Hub) NewConnLimiter() *ConnLimiter

NewConnLimiter returns a new per-connection limiter.

type MessageHandler

type MessageHandler func(ctx context.Context, c *Conn, msg any) error

MessageHandler handles a parsed NIP-01 client message for one connection.

type NIP11Handler

type NIP11Handler struct {
	Cfg     *config.Config
	RelayID *relayidentity.Identity
}

NIP11Handler serves relay information when the client requests application/nostr+json.

func (*NIP11Handler) ServeHTTP

func (h *NIP11Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP writes JSON metadata; callers should only invoke for GET / with matching Accept.

type NegConnAudit

type NegConnAudit struct {
	SubID            string `json:"sub_id"`
	OpenedUnix       int64  `json:"opened_unix"`
	FilterKinds      []int  `json:"filter_kinds,omitempty"`
	RecordCount      int    `json:"record_count"`
	Rounds           int    `json:"rounds"`
	LastActivityUnix int64  `json:"last_activity_unix"`
}

NegConnAudit is one open NIP-77 session for admin connection audit.

type NegQueue

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

NegQueue runs NEG-OPEN DB loads off the WebSocket read loop.

func (*NegQueue) Enqueue

func (q *NegQueue) Enqueue(job *negOpenJob) bool

func (*NegQueue) PendingDepth

func (q *NegQueue) PendingDepth() int

PendingDepth returns waiting NEG-OPEN jobs.

type PostStoreHook

type PostStoreHook func(ctx context.Context, env HookEnv) error

PostStoreHook runs after a valid EVENT is accepted (stored or ephemeral fan-out).

type ReaderQueue

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

ReaderQueue serializes paginated REQ reads so long snapshots do not block the read loop.

func (*ReaderQueue) Enqueue

func (q *ReaderQueue) Enqueue(job *reqPageJob) bool

Enqueue schedules remaining REQ pages. Returns false when the queue is full (caller drains sync).

func (*ReaderQueue) PendingDepth

func (q *ReaderQueue) PendingDepth() int

PendingDepth returns the number of REQ page jobs waiting in the queue.

type RecentLatencySample

type RecentLatencySample struct {
	TUnixMs int64 `json:"t_unix_ms"`
	Ms      int64 `json:"ms"`
}

RecentLatencySample is one REQ query latency observation for GET /api/stats JSON.

type Registry

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

Registry maps client command names ("EVENT", "REQ", "CLOSE", "AUTH", …) to handlers.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns an empty handler registry.

func (*Registry) Dispatch

func (r *Registry) Dispatch(ctx context.Context, c *Conn, msg any) error

Dispatch runs the handler for the parsed message.

func (*Registry) Register

func (r *Registry) Register(typ string, h MessageHandler)

Register associates a message type with a handler (replaces any prior).

type RelayMetrics

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

RelayMetrics holds hot-path atomics, a partial-minute buffer for DB flush, and a fixed ring of REQ query latencies.

func (*RelayMetrics) CountersJSON

func (m *RelayMetrics) CountersJSON() map[string]any

CountersJSON returns cumulative relay_counters for GET /api/stats.

func (*RelayMetrics) FlushOpenMinute

func (m *RelayMetrics) FlushOpenMinute(ctx context.Context, store storage.Store, subsSnapshot func() int) error

FlushOpenMinute writes the current partial UTC minute to storage (best-effort shutdown).

func (*RelayMetrics) IncClose

func (m *RelayMetrics) IncClose()

func (*RelayMetrics) IncEventsEphemeralOK

func (m *RelayMetrics) IncEventsEphemeralOK()

func (*RelayMetrics) IncEventsRejected

func (m *RelayMetrics) IncEventsRejected()

func (*RelayMetrics) IncEventsStoredOK

func (m *RelayMetrics) IncEventsStoredOK()

func (*RelayMetrics) IncIdleDisconnect

func (m *RelayMetrics) IncIdleDisconnect()

func (*RelayMetrics) IncNegBlocked

func (m *RelayMetrics) IncNegBlocked()

func (*RelayMetrics) IncNegErr

func (m *RelayMetrics) IncNegErr()

func (*RelayMetrics) IncNegMsg

func (m *RelayMetrics) IncNegMsg()

func (*RelayMetrics) IncNegOpen

func (m *RelayMetrics) IncNegOpen()

func (*RelayMetrics) IncNegUpstreamFailure

func (m *RelayMetrics) IncNegUpstreamFailure()

func (*RelayMetrics) IncNegUpstreamImported

func (m *RelayMetrics) IncNegUpstreamImported(n int64)

func (*RelayMetrics) IncNegUpstreamJob

func (m *RelayMetrics) IncNegUpstreamJob()

func (*RelayMetrics) IncRateLimitBandwidth

func (m *RelayMetrics) IncRateLimitBandwidth()

func (*RelayMetrics) IncRateLimitEvents

func (m *RelayMetrics) IncRateLimitEvents()

func (*RelayMetrics) IncRateLimitMaxConnections

func (m *RelayMetrics) IncRateLimitMaxConnections()

func (*RelayMetrics) IncRateLimitMessages

func (m *RelayMetrics) IncRateLimitMessages()

func (*RelayMetrics) IncRateLimitNewConnections

func (m *RelayMetrics) IncRateLimitNewConnections()

func (*RelayMetrics) IncRateLimitPerIPOpen

func (m *RelayMetrics) IncRateLimitPerIPOpen()

func (*RelayMetrics) IncRateLimitReqs

func (m *RelayMetrics) IncRateLimitReqs()

func (*RelayMetrics) IncReq

func (m *RelayMetrics) IncReq()

func (*RelayMetrics) PartialMinuteBucket

func (m *RelayMetrics) PartialMinuteBucket() (startUnix int64, b storage.RelayMetricBucket)

PartialMinuteBucket returns the aligned UTC minute start and in-flight aggregates for charts.

func (*RelayMetrics) RecentLatencySamples

func (m *RelayMetrics) RecentLatencySamples() []RecentLatencySample

RecentLatencySamples returns up to recentQueryRingCap newest samples (oldest first).

func (*RelayMetrics) RecordNegLoadLatency

func (m *RelayMetrics) RecordNegLoadLatency(d time.Duration)

func (*RelayMetrics) RecordNegReconcileLatency

func (m *RelayMetrics) RecordNegReconcileLatency(d time.Duration)

func (*RelayMetrics) RecordQueryLatency

func (m *RelayMetrics) RecordQueryLatency(d time.Duration)

func (*RelayMetrics) StartFlushLoop

func (m *RelayMetrics) StartFlushLoop(ctx context.Context, store storage.Store, retentionDays int, log zerolog.Logger, subsSnapshot func() int)

StartFlushLoop aligns to UTC minute boundaries, flushes the previous minute, and prunes old buckets. subsSnapshot, if non-nil, records open REQ subscription count for the completed minute row.

type Server

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

Server is the Nostr relay HTTP and WebSocket front end.

func NewServer

func NewServer(cfg *config.Config, store storage.Store, log zerolog.Logger, relayID *relayidentity.Identity) (*Server, error)

NewServer constructs a relay server (handlers and NIP hooks are registered separately). relayID may be nil in tests; NIP-29 relay-signed paths require a non-nil identity.

func (*Server) Addr

func (s *Server) Addr() string

Addr returns the bound listener address when serving.

func (*Server) AppendPostHook

func (s *Server) AppendPostHook(name string, h PostStoreHook)

AppendPostHook adds a post-accept hook with a stable name (logged on hook failure).

func (*Server) AppendValidator

func (s *Server) AppendValidator(v EventValidator)

AppendValidator adds to the event validation chain.

func (*Server) ConnAuditLiveDetailByConnID

func (s *Server) ConnAuditLiveDetailByConnID(connID string) (*ConnAuditLiveDetail, bool)

ConnAuditLiveDetailByConnID returns live detail for connID, or false if not connected.

func (*Server) ConnAuditLiveSummaries

func (s *Server) ConnAuditLiveSummaries() []ConnAuditLiveSummary

ConnAuditLiveSummaries returns all open connections (newest started last; sorted by conn_id for stability).

func (*Server) EventVisibleToSubscription

func (s *Server) EventVisibleToSubscription(connID string, ev *nostr.Event) bool

EventVisibleToSubscription applies NIP-17 gift-wrap read rules and NIP-29 private-group read rules using NIP-42 authenticated pubkeys on the connection.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(addr string) error

ListenAndServe binds to addr and serves until closed.

func (*Server) Metrics

func (s *Server) Metrics() *RelayMetrics

Metrics returns wire-level counters and latency samples for the admin API.

func (*Server) NotifyPluginStoredEvent

func (s *Server) NotifyPluginStoredEvent(ev *nostr.Event, stored bool)

NotifyPluginStoredEvent delivers an already-persisted event to plugins that subscribe via OnStoredEvent or Observe EVENT. Used for NIP-77 imports which skip the WebSocket EVENT handler. Kind matching stays inside the plugin Runtime.

func (*Server) OpenConnections

func (s *Server) OpenConnections() int64

OpenConnections returns the number of active WebSocket relay connections.

func (*Server) PrependPostHook

func (s *Server) PrependPostHook(name string, h PostStoreHook)

PrependPostHook adds a hook that runs before hooks registered with AppendPostHook.

func (*Server) RegisterMessageHandler

func (s *Server) RegisterMessageHandler(typ string, h MessageHandler)

func (*Server) RelayBusyForNeg

func (s *Server) RelayBusyForNeg() bool

RelayBusyForNeg reports whether inbound NEG-OPEN should be rejected for REQ backpressure.

func (*Server) Serve

func (s *Server) Serve(ln net.Listener) error

Serve runs the HTTP server on an existing listener (e.g. :0 in tests).

func (*Server) SetConfigPath

func (s *Server) SetConfigPath(path string)

SetConfigPath records the JSON config path so uploaded NIP-11 images can be read from nip11-assets beside that file.

func (*Server) SetPluginRuntime

func (s *Server) SetPluginRuntime(rt plugin.Runtime)

SetPluginRuntime attaches the plugin manager (nil-safe). Listen enqueue never blocks the relay.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown stops listening and closes active WebSocket connections.

func (*Server) StartedAtUnix

func (s *Server) StartedAtUnix() int64

StartedAtUnix is set when Serve begins (0 before first Serve).

func (*Server) Subscriptions

func (s *Server) Subscriptions() *SubscriptionManager

Subscriptions exposes the subscription manager (e.g. for tests).

type SubConnAudit

type SubConnAudit struct {
	SubID             string `json:"sub_id"`
	OpenedUnix        int64  `json:"opened_unix"`
	FilterCount       int    `json:"filter_count"`
	Kinds             []int  `json:"kinds,omitempty"`
	InitialSent       uint64 `json:"initial_events_sent"`
	InitialDropped    uint64 `json:"initial_events_dropped"`
	BroadcastEnqueued uint64 `json:"broadcast_events_enqueued"`
	BroadcastDropped  uint64 `json:"broadcast_events_dropped"`
	EOSESent          uint32 `json:"eose_sent"`
}

SubConnAudit is subscription-level metrics for admin connection audit.

type SubscriptionManager

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

SubscriptionManager tracks REQ subscriptions per connection and broadcasts events.

func NewSubscriptionManager

func NewSubscriptionManager(cfg *config.Config, relayLog zerolog.Logger) *SubscriptionManager

NewSubscriptionManager builds a manager from relay config slices.

func (*SubscriptionManager) Add

func (m *SubscriptionManager) Add(connID, subID string, filters []nostr.Filter) error

Add creates or replaces a subscription for connID.

func (*SubscriptionManager) AuditSubscriptionsForConn

func (m *SubscriptionManager) AuditSubscriptionsForConn(connID string) []SubConnAudit

AuditSubscriptionsForConn returns a snapshot of open subscriptions for admin (connID must be live).

func (*SubscriptionManager) Broadcast

func (m *SubscriptionManager) Broadcast(ev *nostr.Event, visible func(connID string, ev *nostr.Event) bool)

Broadcast delivers EVENT to every matching subscription. If visible is nil, all connections receive matching events. Otherwise visible(connID, ev) must be true.

func (*SubscriptionManager) FinishSnapshot

func (m *SubscriptionManager) FinishSnapshot(connID, subID string)

FinishSnapshot marks the initial REQ snapshot complete and flushes buffered live events.

func (*SubscriptionManager) IsOpen

func (m *SubscriptionManager) IsOpen(connID, subID string) bool

IsOpen reports whether connID/subID is an active subscription with a registered sender.

func (*SubscriptionManager) IsSameSnapshot

func (m *SubscriptionManager) IsSameSnapshot(connID, subID string, openedUnix int64) bool

IsSameSnapshot reports whether connID/subID is still the subscription opened at openedUnix.

func (*SubscriptionManager) NoteSubEOSE

func (m *SubscriptionManager) NoteSubEOSE(connID, subID string)

NoteSubEOSE records one EOSE sent for a subscription (admin audit).

func (*SubscriptionManager) NoteSubInitialDelivery

func (m *SubscriptionManager) NoteSubInitialDelivery(connID, subID string, ok bool)

NoteSubInitialDelivery records one initial REQ query EVENT delivery attempt for admin audit.

func (*SubscriptionManager) RegisterSender

func (m *SubscriptionManager) RegisterSender(connID string, send func([]byte) bool)

RegisterSender records how to deliver EVENT/EOSE/CLOSED to a connection.

func (*SubscriptionManager) Remove

func (m *SubscriptionManager) Remove(connID, subID string)

Remove drops one subscription.

func (*SubscriptionManager) SubCount

func (m *SubscriptionManager) SubCount(connID string) int

SubCount returns how many active subscriptions a connection has (for tests).

func (*SubscriptionManager) SubOpenedUnix

func (m *SubscriptionManager) SubOpenedUnix(connID, subID string) (int64, bool)

SubOpenedUnix returns the opened_unix stamp for an active subscription.

func (*SubscriptionManager) TotalSubscriptions

func (m *SubscriptionManager) TotalSubscriptions() int

TotalSubscriptions returns the number of open REQ subscriptions across all connections.

func (*SubscriptionManager) UnregisterSender

func (m *SubscriptionManager) UnregisterSender(connID string) []string

UnregisterSender removes send routing and all subs for connID.

type ValidatorChain

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

ValidatorChain is an ordered list of validators (e.g. NIP-01 ID+signature).

func (*ValidatorChain) Append

func (c *ValidatorChain) Append(v ...EventValidator)

Append adds validators to the chain in order.

func (*ValidatorChain) Validate

func (c *ValidatorChain) Validate(ctx context.Context, conn *Conn, ev *nostr.Event) error

Validate runs all validators; the first error stops the chain.

Jump to

Keyboard shortcuts

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