package graph

import (
	
	
	crand 
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

	
	
	

	gtypes 
	amhelp 
	am 
	
)

// ErrGraphDrop indicates a test-injected dropped graph update.
var ErrGraphDrop = errors.New("graph update dropped")

// errNoDb is returned when a GQL DB operation is requested without a Db.
var errNoDb = errors.New("graph: Db is nil")

// errNoHistory is returned when a history operation is requested without a
// [HistoryGraph].
var errNoHistory = errors.New("graph: history is nil")

// SchemaInfo describes a source schema for remote graph mirroring.
type SchemaInfo struct {
	Schema      am.Schema
	StatesIndex am.S
}

// NetTracer is a graph source backed by a [rpc.SourceTracer].
type NetTracer struct {
	*rpc.SourceTracer

	// Mach is the source machine.
	Mach am.Api
	// MachId is the source machine ID.
	MachId string
	// SchemaHash identifies the source machine schema.
	SchemaHash string
	// DataLatestSent is the latest graph data sent for this source.
	DataLatestSent *NetTracerData
	// Tags is the last successfully sent tag list.
	Tags []string
	// TagsTime is the machine time of the latest change in tags.
	TagsTime uint64
}

func ( *NetTracer) ( am.Api,  am.Schema) {
	.SchemaHash = amhelp.SchemaHash(.Schema())
}

// NetTracerData is a tracer snapshot decorated with source metadata.
type NetTracerData struct {
	*rpc.TracerData

	// MachId is the source machine ID.
	MachId string
	// SchemaHash identifies the source machine schema.
	SchemaHash string
}

// MsgGraphReqSerialized is when the sender requests a resend of full data
// for mach ID
type MsgGraphReqSerialized struct {
	// MachId is the ID of the machine to resend in full serialized form.
	MachId string `json:"m" msgpack:"m"`
}

// MsgGraphUpdate is a diff update pushed to sinks.
type MsgGraphUpdate struct {
	*rpc.MsgSrvUpdate `json:"u,omitempty" msgpack:"u"`

	// MachId is the machine's ID.
	MachId string `json:"i" msgpack:"i"`
	// MTimeSum is the machine's time, used as a history ID.
	MTimeSum uint64 `json:"m"`
	// SchemaHash identifies the machine's schema.
	SchemaHash string `json:"s" msgpack:"s"`
	// TagsTime is the machine time of the latest change in tags.
	TagsTime uint64 `json:"tt" msgpack:"tt"`

	// Parent is the machine's parent ID. TODO cache
	Parent string `json:"p,omitempty" msgpack:"p"`
	// Tags are the source machine tags. nil means unchanged.
	Tags []string `json:"t" msgpack:"t"`
}

const (
	// sink dial backoff bounds for reconnects.
	sinkDialBackoffMin = 50 * time.Millisecond
	sinkDialBackoffMax = 5 * time.Second
	// dbSyncChunk is the max number of machines synced to the DB per tick, so a
	// burst doesn't block readers for its whole duration.
	dbSyncChunk = 8
)

// ///// ///// /////

// ///// NET GRAPH

// ///// ///// /////

// NetworkGraph transports directional graph updates over UDP using the standard
// library and [GraphUpdate] as the wire message.
type NetworkGraph struct {
	// Addr is the local UDP listen address.
	Addr string
	// Graph is the graph being mirrored.
	Graph *Graph
	// Db optionally mirrors all graph changes into a graph database.
	// See [DbGraph] and pkg/graph/frogql ("frogql" build tag).
	// TODO expose via HTTP+JSON, open way for more transports later
	Db gtypes.DbGraph
	// PushInterval is the interval for emitting clock updates. 0 disables
	// periodic updates.
	PushInterval time.Duration
	// Json uses Json instead of msgpack for the wire format.
	Json bool
	// Logger is used for diagnostics. Defaults to [slog.Default].
	Logger *slog.Logger
	// SchemaStore maps schema hashes to source schemas.
	// TODO migrate to am.Serialized
	SchemaStore map[string]SchemaInfo
	// MissingSchemas contains schema hashes seen in updates but not yet
	// registered in SchemaStore.
	MissingSchemas map[string]struct{}

	// tests injections

	// Enable random drops of broadcast messages.
	TestBroadcastRandomDrops atomic.Bool
	// TODO MetricsEnabled atomic.Bool
	// MetricResendRequests counts sent MsgGraphReqSerialized messages.
	MetricResendRequests atomic.Int32
	MetricUpdateTooOld   atomic.Int32
	// MetricResendsHandled counts handled MsgGraphReqSerialized messages.
	MetricResendsHandled atomic.Int32
	// MetricReconnects counts successful sink dials, incl. reconnects.
	MetricReconnects atomic.Int32

	schemaStoreMx sync.Mutex

	relayPendingMx sync.Mutex
	relayPending   map[string]struct{}
	relaySentMx    sync.Mutex
	relaySent      map[string]*am.Serialized

	listener    net.PacketConn
	readBufSize int
	sinkLocal   string
	// cipher optionally encrypts all datagrams of this graph.
	cipher *Cipher
	// dial creates a datagram conn to a sink address. Overridable for tests.
	dial func(addr string) (net.Conn, error)
	ctx  context.Context

	tracedMx sync.Mutex
	traced   []*NetTracer

	sinksMx      sync.Mutex
	sinks        map[string]net.Conn
	sinkRetry    map[string]chan struct{}
	sinkStop     chan struct{}
	sinkStopOnce sync.Once

	dbSrvMx sync.Mutex
	dbSrv   *Server

	// coalesced clock syncs to the DB
	dbPendingMx sync.Mutex
	dbPending   map[string]struct{}
	dbDone      chan struct{}
	dbDoneOnce  sync.Once
	dbLoopOnce  sync.Once
}

// NetworkGraphOpts configures a new [NetworkGraph].
type NetworkGraphOpts struct {
	// Db optionally mirrors all graph changes into a graph database.
	Db gtypes.DbGraph
	// PushInterval overrides the default clock emit interval.
	PushInterval time.Duration
	// ReadBufSize overrides the UDP read buffer size. Defaults to 64KB.
	ReadBufSize int
	// SinkLocalAddr optionally binds sinks to a specific local address, eg
	// "127.1.2.3:0". Useful when many sinks share the default local address.
	SinkLocalAddr string
	// Listener optionally creates the datagram listener. Tests only, nil uses
	// UDP.
	Listener func(addr string) (net.PacketConn, error)
	// Dial optionally creates a datagram sink conn. Tests only, nil uses UDP.
	Dial func(addr string) (net.Conn, error)
	// Cipher optionally encrypts all graph datagrams with a PSK. The same keys
	// must be configured on peers. See [NewCipher].
	Cipher *Cipher
}

// NewNetworkGraph creates a NetworkGraph listening on addr and mirroring g.
func (
	 context.Context,  string,  *Graph,  ...NetworkGraphOpts,
) (*NetworkGraph, error) {
	if  == nil {
		return nil, errors.New("graph is nil")
	}

	 := listenUDP
	var  func( string) (net.Conn, error)
	var  *Cipher
	if len() > 0 {
		if [0].Listener != nil {
			 = [0].Listener
		}
		if [0].Dial != nil {
			 = [0].Dial
		}
		 = [0].Cipher
	}
	,  := ()
	if  != nil {
		return nil, 
	}
	if  != nil {
		 = .WrapPacketConn()
	}

	 := &NetworkGraph{
		Addr:           .LocalAddr().String(),
		Graph:          ,
		PushInterval:   250 * time.Millisecond,
		Logger:         slog.Default(),
		SchemaStore:    make(map[string]SchemaInfo),
		MissingSchemas: make(map[string]struct{}),

		relayPending: make(map[string]struct{}),
		relaySent:    make(map[string]*am.Serialized),
		dbPending:    make(map[string]struct{}),
		dbDone:       make(chan struct{}),
		listener:     ,
		readBufSize:  64 * 1024,
		cipher:       ,
		ctx:          ,
		sinks:        make(map[string]net.Conn),
		sinkRetry:    make(map[string]chan struct{}),
		sinkStop:     make(chan struct{}),
	}

	if len() > 0 {
		if [0].Db != nil {
			.Db = [0].Db
		}
		if [0].PushInterval > 0 {
			.PushInterval = [0].PushInterval
		}
		if [0].ReadBufSize > 0 {
			.readBufSize = [0].ReadBufSize
		}
		.sinkLocal = [0].SinkLocalAddr
	}

	// use the default dialer unless overridden
	if  == nil {
		.dial = .dialUDP
	} else {
		.dial = 
	}
	if .cipher != nil {
		 := .dial
		.dial = func( string) (net.Conn, error) {
			,  := ()
			if  != nil {
				return nil, 
			}
			return .cipher.WrapConn(), nil
		}
	}

	// fork loops
	go .receiveFromUpstream()
	if .PushInterval > 0 {
		go .broadcastLoop(.PushInterval)
	}

	return , nil
}

// TraceMach adds a machine to the mirrored graph and starts emitting its clock
// updates. It returns the tracer ID used by the source machine.
func ( *NetworkGraph) ( am.Api) (string, error) {
	 := .Id()
	 := .Schema()
	 := .StateNames()
	 := amhelp.SchemaHash()
	.schemaStoreMx.Lock()
	.SchemaStore[] = SchemaInfo{
		Schema:      ,
		StatesIndex: ,
	}
	delete(.MissingSchemas, )
	.schemaStoreMx.Unlock()

	 := &Machine{
		Serialized: &am.Serialized{
			ID:          ,
			StateNames:  slices.Clone(),
			Time:        make(am.Time, len()),
			QueueTick:   1,
			MachineTick: 0,
			Tags:        slices.Clone(.Tags()),
		},
		SchemaHash: ,
		Schema:     .Clone(),
		Parent:     .ParentId(),
	}
	// AddMachine isn't locked internally (it's called under the lock by the
	// receive loop), while TraceMach can run at runtime, eg on discovery.
	.Graph.loop.Lock()
	 := .Graph.AddMachine()
	.Graph.loop.Unlock()
	if  != nil {
		return "", 
	}

	// push the new machine to the DB
	if .Db != nil {
		if  := .Db.UpsertMachine();  != nil {
			.Logger.Error("DbGraph upsert failed", "mach", , "err", )
		}
	}

	 := rpc.NewSourceTracer(, nil)
	.Active.Store(true)
	 := &NetTracer{
		SourceTracer: ,
		Mach:         ,
		MachId:       ,
		SchemaHash:   ,
		DataLatestSent: &NetTracerData{
			TracerData: .DataLatest.Load(),
			MachId:     ,
			SchemaHash: ,
		},
	}
	,  := .TracerBind()
	if  != nil {
		return , 
	}
	.tracedMx.Lock()
	.traced = append(.traced, )
	.tracedMx.Unlock()

	return , nil
}

// EmitToAddr registers a directional UDP destination for graph updates.
// Cancel the returned context to stop emitting to the address.
//
// The first dial happens synchronously (so an immediate broadcast lands), then
// the sink is maintained in the background: failed dials are retried with
// exponential backoff, and broken sinks (write errors) are dropped and
// re-dialed. Use [NetworkGraph.Sinks] to check the live set and
// [NetworkGraph.MetricReconnects] for dial counts. Only one sink per address is
// supported; a duplicate call returns an already-cancelled context.
func ( *NetworkGraph) (
	 string,
) (context.Context, context.CancelFunc) {
	,  := context.WithCancel(.ctx)
	 := make(chan struct{}, 1)

	.sinksMx.Lock()
	if ,  := .sinkRetry[];  {
		.sinksMx.Unlock()
		.Logger.Warn("sink already emitting", "addr", )
		()
		return , 
	}
	.sinkRetry[] = 
	.sinksMx.Unlock()

	// try the first dial synchronously, so an immediate broadcast lands
	,  := .dial()
	if  != nil {
		.Logger.Warn("sink dial failed, retrying", "addr", , "err", )
	} else {
		.MetricReconnects.Add(1)
		.sinksMx.Lock()
		.sinks[] = 
		.sinksMx.Unlock()
		go .receiveFromDownstream()
	}

	go .sinkLoop(, , , )

	return , 
}

// Sinks returns the addresses of the currently connected sinks.
func ( *NetworkGraph) () []string {
	.sinksMx.Lock()
	defer .sinksMx.Unlock()

	 := make([]string, 0, len(.sinks))
	for  := range .sinks {
		 = append(, )
	}
	slices.Sort()

	return 
}

// Broadcast sends an update to every registered UDP destination.
func ( *NetworkGraph) ( *MsgGraphUpdate) error {
	if .TestBroadcastRandomDrops.Load() && rand.IntN(2) == 0 {
		return ErrGraphDrop
	}

	,  := .marshal()
	if  != nil {
		return 
	}

	 := len()
	if .cipher != nil {
		 += .cipher.Overhead()
	}
	if  > 1472 {
		.Logger.Warn("data exceeds 1,472 bytes", "len", )
	}

	type  struct {
		 string
		 net.Conn
	}
	.sinksMx.Lock()
	 := make([], 0, len(.sinks))
	for ,  := range .sinks {
		 = append(, {: , : })
	}
	.sinksMx.Unlock()

	var  []error
	for ,  := range  {
		if ,  := ..Write();  != nil {
			 = append(, )
			.dropSink(., .)
		}
	}

	return errors.Join(...)
}

// Close stops the receiver and all emitters.
func ( *NetworkGraph) () error {
	// stop the DB sync loop and flush the pending clock updates
	.dbDoneOnce.Do(func() { close(.dbDone) })
	.flushDbSyncAll()

	// stop sink reconnects, then close the sinks
	.sinkStopOnce.Do(func() { close(.sinkStop) })

	// close the DB server first, it reads from the graph
	.dbSrvMx.Lock()
	 := .dbSrv
	.dbSrv = nil
	.dbSrvMx.Unlock()
	if  != nil {
		_ = .Close()
	}

	.sinksMx.Lock()
	for ,  := range .sinks {
		_ = .Close()
	}
	clear(.sinks)
	clear(.sinkRetry)
	.sinksMx.Unlock()

	 := .listener.Close()

	return 
}

// PRIVATE

// sinkLoop maintains one sink connection, re-dialing on write errors and
// failed dials.
func ( *NetworkGraph) (
	 context.Context,  string,  chan struct{},  net.Conn,
) {
	defer func() {
		.sinksMx.Lock()
		delete(.sinkRetry, )
		.sinksMx.Unlock()
	}()

	 := sinkDialBackoffMin
	for {
		if  == nil {
			var  error
			,  = .dial()
			if  != nil {
				.Logger.Warn("sink dial failed, retrying", "addr", ,
					"err", , "backoff", )
				select {
				case <-.Done():
					return
				case <-.sinkStop:
					return
				case <-time.After():
				}
				 = min(*2, sinkDialBackoffMax)
				continue
			}
			 = sinkDialBackoffMin

			.sinksMx.Lock()
			select {
			case <-.sinkStop:
				// closed concurrently
				.sinksMx.Unlock()
				_ = .Close()
				return
			default:
			}
			.sinks[] = 
			.sinksMx.Unlock()

			.MetricReconnects.Add(1)
			go .receiveFromDownstream()
		}

		select {
		case <-.Done():
			.removeSink(, )
			return
		case <-.sinkStop:
			.removeSink(, )
			return
		case <-:
			// dropped by Broadcast, re-dial
			 = nil
		}
	}
}

// dialUDP resolves and dials a UDP sink.
func ( *NetworkGraph) ( string) (net.Conn, error) {
	,  := net.ResolveUDPAddr("udp", )
	if  != nil {
		return nil, 
	}

	var  *net.UDPAddr
	if .sinkLocal != "" {
		,  = net.ResolveUDPAddr("udp", .sinkLocal)
		if  != nil {
			return nil, 
		}
	}

	return net.DialUDP("udp", , )
}

// listenUDP creates the default UDP listener.
func listenUDP( string) (net.PacketConn, error) {
	,  := net.ResolveUDPAddr("udp", )
	if  != nil {
		return nil, 
	}

	return net.ListenUDP("udp", )
}

// removeSink closes and unregisters a sink, if it's still current.
func ( *NetworkGraph) ( string,  net.Conn) {
	.sinksMx.Lock()
	defer .sinksMx.Unlock()

	if ,  := .sinks[];  &&  ==  {
		delete(.sinks, )
	}
	_ = .Close()
}

// dropSink removes a broken sink and schedules a reconnect.
func ( *NetworkGraph) ( string,  net.Conn) {
	.sinksMx.Lock()
	defer .sinksMx.Unlock()

	if ,  := .sinks[]; ! ||  !=  {
		return
	}
	delete(.sinks, )
	_ = .Close()

	if  := .sinkRetry[];  != nil {
		select {
		case  <- struct{}{}:
		default:
		}
	}
}

func ( *NetworkGraph) ( *NetTracer) {
	 := .DataLatest.Load()
	if  == nil {
		return
	}

	 := &NetTracerData{
		TracerData: ,
		MachId:     .MachId,
		SchemaHash: .SchemaHash,
	}
	 := .Mach.Tags()
	 := .DataLatestSent

	 := !slices.Equal(, .Tags)
	 := .MachTick != .MachTick
	 := .MTrackedTimeSum != .MTrackedTimeSum ||
		.QueueTick != .QueueTick
	if ! && ! && ! {
		return
	}

	 := rpc.CalcUpdate(false,
		.TracerData, .TracerData,
		false)
	if len(.Indexes) == 0 && ! && ! {
		// TODO warn?
		return
	}

	 := &MsgGraphUpdate{
		MsgSrvUpdate: ,
		MTimeSum:     .MTrackedTimeSum,
		MachId:       .MachId,
		SchemaHash:   .SchemaHash,
		Parent:       .Mach.ParentId(),
		TagsTime:     .TagsTime,
	}
	if  {
		if  == nil {
			 = []string{}
		}
		.Tags = 
		.Tags = 
		.TagsTime = .MTrackedTimeSum
	}
	// TODO optimize: send parent 10 times, and never after a full serialized msg
	if  := .Broadcast();  != nil {
		.Logger.Error("pushLocalTracer", "err", )
		return
	}

	// memorize
	.DataLatestSent = 
}

// broadcastLoop emits local tracers and relays relayPending mirrored machines.
func ( *NetworkGraph) ( time.Duration) {
	 := time.NewTicker()
	defer .Stop()

	for {
		select {
		case <-.ctx.Done():
			return
		case <-.C:
			// TODO optimize: collect updates into a slice and keep under UDP limit
			for ,  := range .tracers() {
				.pushLocalTracer()
			}
			.pushPendingRelay()
		}
	}
}

func ( *NetworkGraph) () []*NetTracer {
	.tracedMx.Lock()
	defer .tracedMx.Unlock()

	return .traced
}

func ( *NetworkGraph) () {
	.relayPendingMx.Lock()
	 := slices.Collect(maps.Keys(.relayPending))
	clear(.relayPending)
	.relayPendingMx.Unlock()

	for ,  := range  {
		.Graph.loop.Lock()
		 := .Graph.Machines[]
		 := &am.Serialized{
			ID:          .ID,
			StateNames:  slices.Clone(.StateNames),
			Time:        slices.Clone(.Time),
			QueueTick:   .QueueTick,
			MachineTick: .MachineTick,
			Tags:        slices.Clone(.Tags),
		}
		 := .SchemaHash
		 := .Parent
		 := .TagsMTimeSum
		.Graph.loop.Unlock()

		.relaySentMx.Lock()
		 := .relaySent[]
		.relaySentMx.Unlock()

		 :=  == nil || !slices.Equal(.Tags, .Tags)
		 :=  == nil || !slices.Equal(.Time, .Time) ||
			.QueueTick != .QueueTick ||
			.MachineTick != .MachineTick
		if ! && ! {
			continue
		}

		 := &rpc.TracerData{QueueTick: 1}
		if  != nil {
			 = tracerDataFromSerialized()
		}
		 := tracerDataFromSerialized()
		 := rpc.CalcUpdate(true, , , false)
		if len(.Indexes) == 0 && ! {
			continue
		}
		if  := .Broadcast(&MsgGraphUpdate{
			MsgSrvUpdate: ,
			MTimeSum:     .Time.Sum(nil),
			MachId:       .ID,
			SchemaHash:   ,
			Parent:       ,
			Tags:         .Tags,
			TagsTime:     ,
		});  != nil {
			.Logger.Warn("relay broadcast failed", "mach", , "err", )
			// retry on the next tick, otherwise a transient send error would
			// drop the relayed machine forever
			.relayPendingMx.Lock()
			.relayPending[] = struct{}{}
			.relayPendingMx.Unlock()
			continue
		}

		.relaySentMx.Lock()
		.relaySent[] = 
		.relaySentMx.Unlock()
	}
}

// queueDbSync schedules a coalesced clock sync of machId to the DB.
func ( *NetworkGraph) ( string) {
	if .Db == nil ||  == "" {
		return
	}

	.dbPendingMx.Lock()
	.dbPending[] = struct{}{}
	.dbPendingMx.Unlock()

	.dbLoopOnce.Do(func() { go .dbSyncLoop(.dbDone) })
}

// dbSyncLoop flushes coalesced clock syncs on the push interval.
func ( *NetworkGraph) ( chan struct{}) {
	 := .PushInterval
	if  <= 0 {
		 = 250 * time.Millisecond
	}

	 := time.NewTicker()
	defer .Stop()

	for {
		select {
		case <-.ctx.Done():
			return
		case <-:
			return
		case <-.C:
			.flushDbSync()
		}
	}
}

// flushDbSync pushes up to [dbSyncChunk] pending clock syncs to the DB.
func ( *NetworkGraph) () {
	if .Db == nil {
		return
	}

	.dbPendingMx.Lock()
	 := make([]string, 0, dbSyncChunk)
	for  := range .dbPending {
		 = append(, )
		delete(.dbPending, )
		if len() >= dbSyncChunk {
			break
		}
	}
	.dbPendingMx.Unlock()

	for ,  := range  {
		,  := .Graph.Machine()
		if ! {
			continue
		}
		if  := .Db.SyncMachine();  != nil {
			.Logger.Error("DbGraph sync failed", "mach", , "err", )
		}
	}
}

// flushDbSyncAll drains all pending clock syncs.
func ( *NetworkGraph) () {
	for {
		.dbPendingMx.Lock()
		 := len(.dbPending)
		.dbPendingMx.Unlock()
		if  == 0 {
			return
		}
		.flushDbSync()
	}
}

func ( *NetworkGraph) ( any) ([]byte, error) {
	if .Json {
		return json.Marshal()
	}
	return msgpack.Marshal()
}

func ( *NetworkGraph) ( []byte,  any) error {
	if .Json {
		return json.Unmarshal(, )
	}
	return msgpack.Unmarshal(, )
}

func ( *NetworkGraph) ( string) (SchemaInfo, bool) {
	.schemaStoreMx.Lock()
	defer .schemaStoreMx.Unlock()

	,  := .SchemaStore[]
	if  {
		delete(.MissingSchemas, )
	} else {
		.MissingSchemas[] = struct{}{}
	}
	return , 
}

// receiveFromDownstream receives messages from downstream peers added via
// [NetworkGraph.EmitToAddr]. It's usually due to data corruption.
func ( *NetworkGraph) ( net.Conn) {
	 := make([]byte, .readBufSize)
	for {
		,  := .Read()
		if  != nil {
			return
		}

		var  MsgGraphReqSerialized
		if  := .unmarshal([:], &);  != nil {
			continue
		}
		if .MachId != "" {
			.sendSerializedToDownstream(.MachId, )
		}
	}
}

// receiveFromUpstream receives graph updates from upstream peers, i.e. peers
// which emit into this graph's listener.
func ( *NetworkGraph) () {
	 := make([]byte, .readBufSize)
	for {
		, ,  := .listener.ReadFrom()
		if  != nil {
			return
		}

		var  MsgGraphUpdate
		 = .unmarshal([:], &)
		if  != nil || .MachId == "" {
			// a full serialized machine resend (see sendSerializedToDownstream)
			var  am.Serialized
			if  := .unmarshal([:], &);  == nil &&
				.ID != "" {
				.processSerializedMachine(&)
				continue
			}
			if  != nil {
				.Logger.Warn("graph update decode failed", "err", )
			}
			continue
		}

		.processUpstreamUpdate(&, )
	}
}

// processSerializedMachine applies a full machine resend to the local mirror.
func ( *NetworkGraph) ( *am.Serialized) {
	.Graph.loop.Lock()
	defer .Graph.loop.Unlock()

	 := .Graph.Machines[.ID]
	if  == nil || .Serialized == nil {
		return
	}
	if !slices.Equal(.StateNames, .StateNames) {
		return
	}

	.Time = slices.Clone(.Time)
	.QueueTick = .QueueTick
	.MachineTick = .MachineTick
	.MTimeSum = .Time.Sum(nil)
	.TagsMTimeSum = .MTimeSum
	.Graph.setClientTags(, .Tags)
	.Graph.histSync(, .QueueTick)

	// drop the relay baseline, so the next relay is a full update
	.relaySentMx.Lock()
	delete(.relaySent, .ID)
	.relaySentMx.Unlock()

	// queue the DB clock sync, coalesced on the sync tick
	.queueDbSync(.ID)

	// relay downstream
	.relayPendingMx.Lock()
	.relayPending[.ID] = struct{}{}
	.relayPendingMx.Unlock()
}

func ( *NetworkGraph) (
	 *MsgGraphUpdate,  net.Addr,
) {
	.Graph.loop.Lock()
	defer .Graph.loop.Unlock()

	 := false

	// init if missing
	 := .Graph.Machines[.MachId]
	if  == nil {
		,  := .schemaInfo(.SchemaHash)
		if ! {
			return
		}
		 := &Machine{
			Serialized: &am.Serialized{
				ID:          .MachId,
				StateNames:  slices.Clone(.StatesIndex),
				Time:        make(am.Time, len(.StatesIndex)),
				QueueTick:   1,
				MachineTick: 0,
			},
			SchemaHash: .SchemaHash,
			Schema:     .Schema.Clone(),
			Parent:     .Parent,
		}
		 := .Graph.AddMachine()
		if  != nil {
			return
		}
		 = true
		 = .Graph.Machines[.MachId]
	}

	// replace the client when the source schema changes
	if  != nil && .Serialized != nil && .SchemaHash != .SchemaHash {
		,  := .schemaInfo(.SchemaHash)
		if ! {
			return
		}
		 := &Machine{
			Serialized: &am.Serialized{
				ID:          .MachId,
				StateNames:  slices.Clone(.StatesIndex),
				Time:        make(am.Time, len(.StatesIndex)),
				QueueTick:   1,
				MachineTick: 0,
			},
			SchemaHash: .SchemaHash,
			Schema:     .Schema.Clone(),
			Parent:     .Parent,
		}
		 := .Graph.AddMachine()
		if  != nil {
			return
		}
		 = true

		// clear relay cache
		.relaySentMx.Lock()
		delete(.relaySent, .MachId)
		.relaySentMx.Unlock()
	}

	// push the new machine to the DB
	if .Db != nil &&  {
		if  := .Graph.Machines[.MachId];  != nil {
			if  := .Db.UpsertMachine();  != nil {
				.Logger.Error("DbGraph upsert failed",
					"mach", .MachId, "err", )
			}
		}
	}

	if .MTimeSum != 0 && .MTimeSum < .MTimeSum {
		.MetricUpdateTooOld.Add(1)

		return
	}

	// process and fwd
	if .Graph.ParseMsgRpc() {
		// queue the DB clock sync, coalesced on the sync tick
		.queueDbSync(.MachId)

		.relayPendingMx.Lock()
		.relayPending[.MachId] = struct{}{}
		.relayPendingMx.Unlock()

		return
	}

	.Logger.Warn("graph apply failed, requesting resend", "mach", .MachId)
	.MetricResendRequests.Add(1)
	_ = .reqSerializedFromUpstream(, .MachId)
}

func ( *NetworkGraph) (
	 net.Addr,  string,
) error {
	,  := .marshal(&MsgGraphReqSerialized{MachId: })
	if  != nil {
		return 
	}
	_,  = .listener.WriteTo(, )

	return 
}

func ( *NetworkGraph) (
	 string,  net.Conn,
) {
	if  == "" {
		return
	}
	.MetricResendsHandled.Add(1)

	// locally traced machines are re-sent from the live machine, the local
	// graph mirror holds the zero baseline
	 := .serializedLocal()

	// mirrored machines are re-sent from the mirrored graph
	if  == nil {
		,  := .Graph.Machine()
		if ! || .Serialized == nil {
			return
		}
		 = &am.Serialized{
			ID:          .ID,
			StateNames:  .StateNames,
			Time:        .Time,
			QueueTick:   .QueueTick,
			MachineTick: .MachineTick,
			Tags:        .Tags,
		}
	}

	,  := .marshal()
	if  != nil {
		.Logger.Error("sendSerializedToDownstream", "err", )
		return
	}
	if ,  := .Write();  != nil {
		.Logger.Error("sendSerializedToDownstream", "err", )
	}
}

// serializedLocal returns a full serialized snapshot of a locally traced
// machine, or nil if the machine is not traced.
func ( *NetworkGraph) ( string) *am.Serialized {
	.tracedMx.Lock()
	defer .tracedMx.Unlock()

	for ,  := range .traced {
		if .MachId !=  {
			continue
		}
		 := .Mach

		return &am.Serialized{
			ID:          ,
			StateNames:  slices.Clone(.StateNames()),
			Time:        slices.Clone(.Time(nil)),
			QueueTick:   .QueueTick(),
			MachineTick: .MachineTick(),
			Tags:        slices.Clone(.Tags()),
		}
	}

	return nil
}

// ///// ///// /////

// ///// SERVER

// ///// ///// /////

// DbServerOpts configures the Db HTTP server.
type DbServerOpts struct {
	// ApiKeys authorizes every request when non-empty. Clients pass a key in
	// the X-API-Key header, or as a Sec-WebSocket-Protocol token for
	// browser/WASM WebSocket clients (like tools/relay).
	ApiKeys []string
}

// Server exposes a types.DbGraph and an optional [HistoryGraph] over
// HTTP+JSON and WebSocket on a single listener. Raw GQL is executed against
// [NetworkGraph.Db].
//
//	POST /query          raw GQL body, JSON reply (msgpack via Accept)
//	GET  /machine?id=X   one machine as [am.Serialized], lowercase JSON
//	GET  /history?id=X   history API of one machine as [HistResp], with
//	                     &action=<HistAction>&state=&states=&start=&end=&limit=
//	GET  /ws             WebSocket, one frame per request:
//	                     GQL / {"machine": "X"} / {"history": "X", ...}
//	                     -> JSON or msgpack reply, matching the frame type
type Server struct {
	// Addr is the actual listen address.
	Addr string

	graph   *NetworkGraph
	srv     *http.Server
	apiKeys []string

	wsMx sync.Mutex
	// TODO option to send JSON over WS
	ws map[*websocket.Conn]struct{}
}

// StartDbHttpServer starts a [Server] on addr exposing [NetworkGraph.Db] and
// the optional [HistoryGraph]. It returns the actual listen address.
// [NetworkGraph.Close] shuts it down.
func ( *NetworkGraph) (
	 string,  ...DbServerOpts,
) (string, error) {
	if .Db == nil && .Graph.Hist() == nil {
		return "", errors.New("graph: Db and history are nil")
	}

	.dbSrvMx.Lock()
	defer .dbSrvMx.Unlock()

	if .dbSrv != nil {
		return "", errors.New("graph: DB server already started")
	}

	,  := net.Listen("tcp", )
	if  != nil {
		return "", 
	}

	 := &Server{
		Addr:  .Addr().String(),
		graph: ,
		ws:    make(map[*websocket.Conn]struct{}),
	}
	for ,  := range  {
		.apiKeys = slices.Clone(.ApiKeys)
	}
	 := http.NewServeMux()
	.HandleFunc("POST "+gtypes.EndpointQuery.Value, .handleQuery)
	.HandleFunc("GET "+gtypes.EndpointMachine.Value, .handleMachine)
	.HandleFunc("GET "+gtypes.EndpointHistory.Value, .handleHistory)
	.HandleFunc("GET "+gtypes.EndpointWS.Value, .handleWS)
	.srv = &http.Server{Handler: .authMiddleware()}

	go func() {
		if  := .srv.Serve();  != nil &&
			!errors.Is(, http.ErrServerClosed) {
			.Logger.Error("DbServer", "err", )
		}
	}()

	.dbSrv = 

	return .Addr, nil
}

// authMiddleware authorizes every request when API keys are configured. Keys
// ride in the X-API-Key header, or in Sec-WebSocket-Protocol for
// browser/WASM WebSocket clients. Mirrors tools/relay.
func ( *Server) ( http.Handler) http.Handler {
	return http.HandlerFunc(func( http.ResponseWriter,  *http.Request) {
		if len(.apiKeys) == 0 {
			.ServeHTTP(, )
			return
		}

		 := .Header.Get("X-API-Key")
		if  == "" {
			// browser/WASM clients can't set headers on the WS handshake
			for ,  := range strings.Split(
				.Header.Get("Sec-WebSocket-Protocol"), ",") {
				 = strings.TrimSpace()
				if  != "" && !strings.EqualFold(, "X-API-Key") {
					 = 
					break
				}
			}
		}

		if !slices.Contains(.apiKeys, ) {
			.Header().Set("Content-Type", "application/json")
			.WriteHeader(http.StatusUnauthorized)
			_, _ = .Write([]byte(`{"error":"Unauthorized"}`))
			return
		}

		.ServeHTTP(, )
	})
}

// Close stops the server and its WebSocket connections.
func ( *Server) () error {
	if  == nil {
		return nil
	}

	.wsMx.Lock()
	for  := range .ws {
		_ = .CloseNow()
	}
	.ws = nil
	.wsMx.Unlock()

	,  := context.WithTimeout(context.Background(), 3*time.Second)
	defer ()

	if  := .srv.Shutdown();  != nil &&
		!errors.Is(, http.ErrServerClosed) {
		return 
	}

	return nil
}

// PRIVATE

// handleQuery serves POST /query with a raw GQL statement.
func ( *Server) ( http.ResponseWriter,  *http.Request) {
	,  := io.ReadAll(io.LimitReader(.Body, 1<<20))
	if  != nil {
		.writeErr(, , http.StatusBadRequest, )
		return
	}

	 := strings.TrimSpace(string())
	if  == "" {
		.writeErr(, , http.StatusBadRequest, errors.New("empty query"))
		return
	}

	// no GQL database attached
	if .graph.Db == nil {
		.writeErr(, , http.StatusBadRequest, errNoDb)
		return
	}

	,  := .graph.Db.Exec()
	if  != nil {
		.writeErr(, , http.StatusBadRequest, )
		return
	}

	.write(, , http.StatusOK, )
}

// handleMachine serves GET /machine?id=X with an [am.Serialized].
func ( *Server) ( http.ResponseWriter,  *http.Request) {
	 := .URL.Query().Get("id")
	if  == "" {
		.writeErr(, , http.StatusBadRequest, errors.New("missing id"))
		return
	}
	if .graph.Db == nil {
		.writeErr(, , http.StatusBadRequest, errNoDb)
		return
	}

	,  := .machineSerialized()
	if  != nil {
		.writeErr(, , http.StatusInternalServerError, )
		return
	}
	if  == nil {
		.writeErr(, , http.StatusNotFound, errors.New("machine not found"))
		return
	}

	.write(, , http.StatusOK, )
}

// handleHistory serves GET /history?id=X as the history API of a machine. See
// [amtypes.HistoryAction] for the available actions and their params.
func ( *Server) ( http.ResponseWriter,  *http.Request) {
	 := .graph.Graph.Hist()
	if  == nil {
		.writeErr(, , http.StatusBadRequest, errNoHistory)
		return
	}

	 := .URL.Query()
	 := .Get("id")
	if  == "" {
		.writeErr(, , http.StatusBadRequest, errors.New("missing id"))
		return
	}

	, ,  := parseHistReq()
	if  != nil {
		.writeErr(, , http.StatusBadRequest, )
		return
	}

	,  := .History(.Context(), , , )
	switch {
	case errors.Is(, ErrMachineNotTracked):
		.writeErr(, , http.StatusNotFound, )
		return
	case errors.Is(, ErrHistoryParams), errors.Is(, ErrHistoryAction):
		.writeErr(, , http.StatusBadRequest, )
		return
	case  != nil:
		.writeErr(, , http.StatusInternalServerError, )
		return
	}

	.write(, , http.StatusOK, )
}

// parseHistReq parses a history action and its params from request values.
func parseHistReq( url.Values) (gtypes.HistoryAction, HistParams, error) {
	var  HistParams
	 := gtypes.HistFindLatest

	if  := .Get("action");  != "" {
		 := gtypes.HistActions.Parse()
		if  == nil {
			return , , fmt.Errorf("%w: %s", ErrHistoryAction, )
		}
		 = *
	}

	.State = .Get("state")
	.States = splitCsv(.Get("states"))
	.Query.Active = splitCsv(.Get("active"))
	.Query.Activated = splitCsv(.Get("activated"))
	.Query.Inactive = splitCsv(.Get("inactive"))
	.Query.Deactivated = splitCsv(.Get("deactivated"))

	for ,  := range map[string]*time.Time{
		"start": &.Start,
		"end":   &.End,
	} {
		 := .Get()
		if  == "" {
			continue
		}
		,  := time.Parse(time.RFC3339, )
		if  != nil {
			return , , fmt.Errorf(
				"%w: %s: %w", ErrHistoryParams, , )
		}
		* = 
	}
	.Query.Start.HTime = .Start
	.Query.End.HTime = .End

	if  := .Get("limit");  != "" {
		,  := strconv.Atoi()
		if  != nil ||  <= 0 {
			return , , fmt.Errorf("%w: limit", ErrHistoryParams)
		}
		.Limit = 
	}

	return , , nil
}

// splitCsv splits a comma-separated list into a state list.
func splitCsv( string) am.S {
	if  == "" {
		return nil
	}

	var  am.S
	for ,  := range strings.Split(, ",") {
		if  = strings.TrimSpace();  != "" {
			 = append(, )
		}
	}

	return 
}

// handleWS serves GET /ws, one frame per request:
//
//	GQL text frame                -> JSON rows
//	{"machine": "<id>"} text      -> JSON [am.Serialized]
//	{"history": "<id>"} text      -> JSON [HistResp]
//	msgpack GQL string (binary)   -> msgpack rows
//	msgpack {"machine": "<id>"}   -> msgpack [am.Serialized]
//	msgpack {"history": "<id>"}   -> msgpack [HistResp]
//
// History frames accepts any [amtypes.HistoryAction], e.g.:
//
//	{"history": "X", "action": "latest-activated", "states": "A,B"}
func ( *Server) ( http.ResponseWriter,  *http.Request) {
	,  := websocket.Accept(, , &websocket.AcceptOptions{
		InsecureSkipVerify: true,
	})
	if  != nil {
		return
	}
	defer func() { _ = .CloseNow() }()

	.wsMx.Lock()
	if .ws == nil {
		// closed concurrently
		.wsMx.Unlock()
		return
	}
	.ws[] = struct{}{}
	.wsMx.Unlock()

	 := .graph.ctx
	for {
		, ,  := .Read()
		if  != nil {
			break
		}

		, ,  := wsFrameRequest(, )

		var  any
		switch {
		case  != nil:
			 := .graph.Graph.Hist()
			if  == nil {
				 = map[string]string{"error": errNoHistory.Error()}
				break
			}
			, ,  := parseHistReq()
			if  != nil {
				 = map[string]string{"error": .Error()}
				break
			}
			if ,  := .History(
				, .Get("history"), , ,
			);  != nil {
				 = map[string]string{"error": .Error()}
			} else {
				 = 
			}
		case  != "":
			if .graph.Db == nil {
				 = map[string]string{"error": errNoDb.Error()}
				break
			}
			,  := .machineSerialized()
			switch {
			case  != nil:
				 = map[string]string{"error": .Error()}
			case  == nil:
				 = map[string]string{"error": "machine not found"}
			default:
				 = 
			}
		case  == "":
			 = map[string]string{"error": "empty query"}
		case .graph.Db == nil:
			 = map[string]string{"error": errNoDb.Error()}
		default:
			if ,  := .graph.Db.Exec();  != nil {
				 = map[string]string{"error": .Error()}
			} else {
				 = 
			}
		}

		,  := encodeWS(, )
		if  != nil {
			break
		}
		if  := .Write(, , );  != nil {
			break
		}
	}

	.wsMx.Lock()
	delete(.ws, )
	.wsMx.Unlock()
}

// ///// ///// /////

// ///// UTILS

// ///// ///// /////

func tracerDataFromSerialized( *am.Serialized) *rpc.TracerData {
	 := make([]int, len(.StateNames))
	for  := range  {
		[] = 
	}
	 := .Time.Sum(nil)

	return &rpc.TracerData{
		MTime:           append(am.Time(nil), .Time...),
		MTrackedTimeSum: ,
		QueueTick:       .QueueTick,
		MachTick:        .MachineTick,
		Checksum:        rpc.Checksum(, .QueueTick, .MachineTick),
		Tracked:         .StateNames,
		TrackedIdxs:     ,
	}
}

// wsFrameRequest parses a WS frame into a GQL query, a serialized machine
// request, or a history request, matching the frame encoding.
func wsFrameRequest(
	 websocket.MessageType,  []byte,
) ( string,  string,  url.Values) {
	 := json.Unmarshal
	if  == websocket.MessageBinary {
		 = msgpack.Unmarshal
	}

	// a JSON/msgpack envelope, eg {"machine": "id"}
	var  map[string]string
	if  := (, &);  == nil {
		if  := ["machine"];  != "" {
			return "", , nil
		}
		if  := ["history"];  != "" {
			 = make(url.Values, len())
			for ,  := range  {
				.Set(, )
			}
			return "", "", 
		}
	}

	 := string()
	if  == websocket.MessageBinary {
		// a msgpack-encoded GQL string
		var  string
		if  := msgpack.Unmarshal(, &);  == nil {
			 = 
		}
	}

	return strings.TrimSpace(), "", nil
}

// machineSerialized rebuilds an [am.Serialized] from the mirrored DB, with
// states ordered by the schema's state index.
func ( *Server) ( string) (*am.Serialized, error) {
	 := .graph
	 := gqlStr()

	// machine props, states, and tags in one statement
	,  := .Db.Exec(fmt.Sprintf(
		"MATCH (m:Machine {id: %s})"+
			" OPTIONAL MATCH (m)-[:HAS]->(s:State)"+
			" OPTIONAL MATCH (m)-[:HAS_TAG]->(t:Tag)"+
			" RETURN m.schema_hash AS schema_hash,"+
			" m.queue_tick AS queue_tick, m.mach_tick AS mach_tick,"+
			" s.name AS state_name, s.tick AS tick, t.name AS tag", ))
	if  != nil {
		return nil, 
	}
	,  := .([]any)
	if ! || len() == 0 {
		return nil, nil
	}

	 := make(map[string]uint64)
	 := make(map[string]struct{})
	var  map[string]any
	for ,  := range  {
		,  := .(map[string]any)
		if ! {
			continue
		}
		if  == nil {
			 = 
		}
		if ,  := ["state_name"].(string);  {
			[] = toUint64(["tick"])
		}
		if ,  := ["tag"].(string);  {
			[] = struct{}{}
		}
	}
	if  == nil {
		return nil, errors.New("unexpected machine row")
	}

	var  []string
	for  := range  {
		 = append(, )
	}
	slices.Sort()

	 := &am.Serialized{
		ID:          ,
		QueueTick:   toUint64(["queue_tick"]),
		MachineTick: uint32(toUint64(["mach_tick"])),
		Tags:        ,
	}

	// states ordered by the schema index
	if ,  := ["schema_hash"].(string);  {
		.schemaStoreMx.Lock()
		,  := .SchemaStore[]
		.schemaStoreMx.Unlock()
		if  {
			.StateNames = slices.Clone(.StatesIndex)
			.Time = make(am.Time, len(.StatesIndex))
			for ,  := range .StatesIndex {
				.Time[] = []
			}
		}
	}

	return , nil
}

// write encodes v according to the request's Accept header.
func ( *Server) (
	 http.ResponseWriter,  *http.Request,  int,  any,
) {
	if wantsMsgpack() {
		,  := msgpack.Marshal()
		if  != nil {
			http.Error(, .Error(), http.StatusInternalServerError)
			return
		}
		.Header().Set("Content-Type", "application/msgpack")
		.WriteHeader()
		_, _ = .Write()
		return
	}

	.Header().Set("Content-Type", "application/json")
	.WriteHeader()
	_ = json.NewEncoder().Encode()
}

// writeErr writes a lowercase error envelope.
func ( *Server) (
	 http.ResponseWriter,  *http.Request,  int,  error,
) {
	.write(, , , map[string]string{"error": .Error()})
}

// encodeWS encodes v in the frame type's format.
func encodeWS( websocket.MessageType,  any) ([]byte, error) {
	if  == websocket.MessageBinary {
		return msgpack.Marshal()
	}

	return json.Marshal()
}

// wantsMsgpack reports whether the request asks for a msgpack reply.
func wantsMsgpack( *http.Request) bool {
	return strings.Contains(.Header.Get("Accept"), "application/msgpack") ||
		strings.Contains(.Header.Get("Content-Type"), "application/msgpack")
}

// toUint64 converts a decoded GQL number to uint64.
func toUint64( any) uint64 {
	switch n := .(type) {
	case float64:
		return uint64()
	case float32:
		return uint64()
	case int:
		return uint64()
	case int64:
		return uint64()
	case uint64:
		return 
	default:
		return 0
	}
}

// gqlStr formats a GQL string literal. The frogql lexer has no escape syntax,
// values containing a single quote are unsupported.
func gqlStr( string) string {
	return "'" +  + "'"
}

// ///// ///// /////

// ///// CRYPTO

// ///// ///// /////

const (
	// CipherKeySize is the required PSK size in bytes.
	CipherKeySize = chacha20poly1305.KeySize
	// cipherVersion is the wire format version.
	cipherVersion = 1
	// cipherHeaderSize is version + key ID + nonce.
	cipherHeaderSize = 2 + chacha20poly1305.NonceSize
	// cipherOverhead is the wire overhead of a plaintext datagram.
	cipherOverhead = cipherHeaderSize + chacha20poly1305.Overhead
)

// ErrCipher is returned for invalid cipher packets.
var ErrCipher = errors.New("graph: cipher")

// Cipher encrypts NetworkGraph datagrams with pre-shared ChaCha20-Poly1305
// keys. The same keys must be configured on all peers.
//
// The wire format is version|keyID|nonce|ciphertext|tag, where nonce is a
// random session prefix followed by a monotonic counter. Datagrams with an
// unknown key, a bad tag, or a replayed counter are dropped.
//
// A Cipher is safe for concurrent use, but keys should be added before the
// cipher is passed to [NetworkGraphOpts].
type Cipher struct {
	mx     sync.RWMutex
	keys   map[uint8]cipher.AEAD
	sendID uint8

	// MetricDropped counts datagrams dropped due to decryption, unknown key,
	// or replay errors.
	MetricDropped atomic.Int64
}

// NewCipher returns a cipher sending with sendID and the given key, which has
// to be [CipherKeySize] bytes long.
func ( uint8,  []byte) (*Cipher, error) {
	 := &Cipher{
		keys:   make(map[uint8]cipher.AEAD),
		sendID: ,
	}
	if  := .AddKey(, );  != nil {
		return nil, 
	}

	return , nil
}

// AddKey registers a receive key, e.g. an old key during rotation.
func ( *Cipher) ( uint8,  []byte) error {
	if len() != CipherKeySize {
		return fmt.Errorf("%w: key %d must be %d bytes, got %d", ErrCipher,
			, CipherKeySize, len())
	}
	,  := chacha20poly1305.New()
	if  != nil {
		return fmt.Errorf("%w: %w", ErrCipher, )
	}

	.mx.Lock()
	defer .mx.Unlock()

	.keys[] = 

	return nil
}

// Overhead returns the number of bytes added to each datagram.
func ( *Cipher) () int {
	return cipherOverhead
}

// WrapPacketConn returns an encrypted view of pc.
func ( *Cipher) ( net.PacketConn) net.PacketConn {
	return &cipherPacketConn{
		pc:     ,
		c:      ,
		nonces: newNonceSource(),
		peers:  make(map[string]*replayWindow),
	}
}

// WrapConn returns an encrypted view of conn, with one replay window for the
// peer.
func ( *Cipher) ( net.Conn) net.Conn {
	return &cipherConn{
		conn:   ,
		c:      ,
		nonces: newNonceSource(),
	}
}

// seal encrypts plain with the next nonce of the given source.
func ( *Cipher) ( *nonceSource,  []byte) []byte {
	return .sealNonce(.next(), )
}

// sealNonce encrypts plain with a specific nonce, used by tests.
func ( *Cipher) ( [chacha20poly1305.NonceSize]byte,
	 []byte,
) []byte {
	.mx.RLock()
	 := .keys[.sendID]
	 := .sendID
	.mx.RUnlock()

	 := make([]byte, cipherHeaderSize)
	[0] = cipherVersion
	[1] = 
	copy([2:], [:])

	 := make([]byte, 0, cipherHeaderSize+len()+
		chacha20poly1305.Overhead)
	 = append(, ...)

	return .Seal(, [:], , )
}

// open decrypts pkt and returns the plaintext and its replay counter.
func ( *Cipher) ( []byte) ([]byte, uint64, error) {
	return .openTo(nil, )
}

// openTo decrypts pkt into dst (when it has enough capacity) and returns the
// plaintext and its replay counter.
func ( *Cipher) (,  []byte) ([]byte, uint64, error) {
	if len() < cipherOverhead {
		return nil, 0, fmt.Errorf("%w: short packet", ErrCipher)
	}
	if [0] != cipherVersion {
		return nil, 0, fmt.Errorf("%w: version %d", ErrCipher, [0])
	}

	 := [1]
	 := [2:cipherHeaderSize]
	.mx.RLock()
	 := .keys[]
	.mx.RUnlock()
	if  == nil {
		return nil, 0, fmt.Errorf("%w: unknown key %d", ErrCipher, )
	}

	var  []byte
	var  error
	if cap() >= len()-cipherOverhead {
		,  = .Open([:0], , [cipherHeaderSize:],
			[:cipherHeaderSize])
	} else {
		,  = .Open(nil, , [cipherHeaderSize:],
			[:cipherHeaderSize])
	}
	if  != nil {
		return nil, 0, fmt.Errorf("%w: %w", ErrCipher, )
	}

	return , binary.BigEndian.Uint64([4:]), nil
}

// nonceSeq is a process-wide counter, so wrappers sharing a key never reuse a
// nonce. It starts at the process start time to stay above counters of a
// previous process.
var nonceSeq atomic.Uint64

func init() {
	nonceSeq.Store(uint64(time.Now().UnixNano()))
}

// nonceSource generates unique nonces: a random session prefix and the global
// monotonic counter.
type nonceSource struct {
	prefix [4]byte
}

func newNonceSource() *nonceSource {
	 := &nonceSource{}
	if ,  := crand.Read(.prefix[:]);  != nil {
		panic(fmt.Sprintf("%s: crypto/rand: %s", ErrCipher, ))
	}

	return 
}

func ( *nonceSource) () [chacha20poly1305.NonceSize]byte {
	 := nonceSeq.Add(1)

	var  [chacha20poly1305.NonceSize]byte
	copy([:4], .prefix[:])
	binary.BigEndian.PutUint64([4:], )

	return 
}

// replayWindow is a 64-bit sliding replay window.
type replayWindow struct {
	mx     sync.Mutex
	max    uint64
	bits   uint64
	inited bool
}

// accept returns true if counter is new.
func ( *replayWindow) ( uint64) bool {
	if  == 0 {
		return false
	}

	.mx.Lock()
	defer .mx.Unlock()

	if !.inited {
		.inited = true
		.max = 
		.bits = 1
		return true
	}

	if  > .max {
		 :=  - .max
		if  >= 64 {
			.bits = 1
		} else {
			.bits = (.bits << ) | 1
		}
		.max = 
		return true
	}

	 := .max - 
	if  >= 64 {
		return false
	}
	 := uint64(1) << 
	if .bits& != 0 {
		return false
	}
	.bits |= 

	return true
}

// cipherPacketConn encrypts a shared [net.PacketConn].
type cipherPacketConn struct {
	pc     net.PacketConn
	c      *Cipher
	nonces *nonceSource

	mx    sync.Mutex
	peers map[string]*replayWindow

	readMx sync.Mutex
	enc    []byte
}

func ( *cipherPacketConn) ( []byte) (int, net.Addr, error) {
	.readMx.Lock()
	defer .readMx.Unlock()

	 := len() + .c.Overhead()
	if cap(.enc) <  {
		.enc = make([]byte, )
	}
	 := .enc[:]

	for {
		, ,  := .pc.ReadFrom()
		if  != nil {
			return 0, nil, 
		}

		, ,  := .c.openTo(, [:])
		if  != nil {
			.c.MetricDropped.Add(1)
			continue
		}
		if !.window().accept() {
			.c.MetricDropped.Add(1)
			continue
		}

		return len(), , nil
	}
}

// window returns the replay window of a peer.
func ( *cipherPacketConn) ( net.Addr) *replayWindow {
	 := .String()

	.mx.Lock()
	defer .mx.Unlock()

	 := .peers[]
	if  == nil {
		 = &replayWindow{}
		.peers[] = 
	}

	return 
}

func ( *cipherPacketConn) ( []byte,  net.Addr) (int, error) {
	if ,  := .pc.WriteTo(.c.seal(.nonces, ), );  != nil {
		return 0, 
	}

	return len(), nil
}

func ( *cipherPacketConn) () error {
	return .pc.Close()
}

func ( *cipherPacketConn) () net.Addr {
	return .pc.LocalAddr()
}

func ( *cipherPacketConn) ( time.Time) error {
	return .pc.SetDeadline()
}

func ( *cipherPacketConn) ( time.Time) error {
	return .pc.SetReadDeadline()
}

func ( *cipherPacketConn) ( time.Time) error {
	return .pc.SetWriteDeadline()
}

// cipherConn encrypts a connected [net.Conn].
type cipherConn struct {
	conn   net.Conn
	c      *Cipher
	nonces *nonceSource
	win    replayWindow

	readMx sync.Mutex
	enc    []byte
}

func ( *cipherConn) ( []byte) (int, error) {
	.readMx.Lock()
	defer .readMx.Unlock()

	 := len() + .c.Overhead()
	if cap(.enc) <  {
		.enc = make([]byte, )
	}
	 := .enc[:]

	for {
		,  := .conn.Read()
		if  != nil {
			return 0, 
		}

		, ,  := .c.openTo(, [:])
		if  != nil {
			.c.MetricDropped.Add(1)
			continue
		}
		if !.win.accept() {
			.c.MetricDropped.Add(1)
			continue
		}

		return len(), nil
	}
}

func ( *cipherConn) ( []byte) (int, error) {
	if ,  := .conn.Write(.c.seal(.nonces, ));  != nil {
		return 0, 
	}

	return len(), nil
}

func ( *cipherConn) () error {
	return .conn.Close()
}

func ( *cipherConn) () net.Addr {
	return .conn.LocalAddr()
}

func ( *cipherConn) () net.Addr {
	return .conn.RemoteAddr()
}

func ( *cipherConn) ( time.Time) error {
	return .conn.SetDeadline()
}

func ( *cipherConn) ( time.Time) error {
	return .conn.SetReadDeadline()
}

func ( *cipherConn) ( time.Time) error {
	return .conn.SetWriteDeadline()
}