package rpc

// TODO call ClientBye on Disposing

import (
	
	
	
	
	
	
	
	
	
	
	

	
	
	amhelp 
	am 
	
	ampipe 
)

var (
	ssS  = states.ServerStates
	ssSs = states.StateSourceStates
)

type ServerOpts struct {
	// Parent is a parent state machine for a new Server state machine.
	Parent am.Api // Typed arguments struct pointer
	// optional list of typed args
	Args []am.ArgsApi
	// optional RPC args parser, defaults to [amhelp.NewArgsUnmarshaller] when
	// [ServerOpts.Args] present. Useful for REPLs.
	ArgsUnmarshaller amhelp.ArgsUnmarshallerFn

	// WebSocket

	// Listen on a WebSocket connection instead of TCP.
	WebSocket bool
	// HTTP URL without proto to tunnel the TCP listen over a WebSocket conn.
	// See WsListenPath.
	WebSocketTunnel string
	// WebSocketTunnelPubKey is the API key used for authenticating with the
	// WebSocket tunnel.
	WebSocketTunnelPubKey string

	// Authentication

	// AllowedMachIds will limit clients to specified machine IDs (optional).
	AllowedMachIds []string
	// AllowedWsOrigins is a list of allowed origins for WebSocket
	// connections (optional).
	AllowedWsOrigins []string
	// AllowedWsPubKeys is a list of allowed API keys for WebSocket (optional).
	AllowedWsPubKeys []string
}

// Server is an RPC server that can be bound to a worker machine and provide
// remote access to its states and methods.
type Server struct {
	*ExceptionHandler
	Mach *am.Machine

	// Source is a state Source, either a local or remote RPC worker.
	Source am.Api
	// Addr is the address of the server on the network.
	Addr string
	// DeliveryTimeout is a timeout to SendPayload to the client.
	DeliveryTimeout time.Duration
	// Listener can be set manually before starting the server.
	Listener atomic.Pointer[net.Listener]
	// Conn can be set manually before starting the server. TODO atomic?
	Conn       net.Conn
	LogEnabled bool
	CallCount  uint64
	// List of typed arguments.
	Args []am.ArgsApi
	Opts ServerOpts

	// settings - live

	// PushInterval is the interval for clock updates, effectively throttling
	// the number of updates sent to the client within the interval window.
	// 0 means pushes are disabled. Setting to a very small value will make
	// pushes instant.
	PushInterval atomic.Pointer[time.Duration]
	// AllowedMachIds will limit clients to specified IDs (optional).
	AllowedMachIds atomic.Pointer[[]string]
	// AllowedWsPubKeys will limit clients to specified public keys (optional).
	// Requires [ServerOpts.AllowedWsPubKeys] to be set.
	AllowedWsPubKeys atomic.Pointer[[]string]
	// TODO AllowedWsOrigins

	// settings - stopped

	// WsTunReconn enables retrying the WebSocket tunnel.
	WsTunReconn bool
	// WsTunConnTimeout is the maximum time to wait for a WebSocket tunnel
	// connection to be established.
	WsTunConnTimeout time.Duration
	// WsTunConnRetries is the number of retries for a connection.
	WsTunConnRetries int
	// WsTunConnRetryTimeout is the maximum time to retry a connection.
	WsTunConnRetryTimeout time.Duration
	// WsTunConnRetryDelay is the time to wait between retries. If
	// WsTunConnRetryBackoff is set, this is the initial delay and doubles on each
	// retry.
	WsTunConnRetryDelay time.Duration
	// WsTunConnRetryBackoff is the maximum time to wait between retries.
	WsTunConnRetryBackoff time.Duration

	// security

	// internal

	rpcServer *rpcServer
	// rpcClient is the internal rpc2 client.
	rpcClient atomic.Pointer[rpcClient]
	tracer    *SourceTracer
	// TODO bind the a machine ticker (if handlers bound)
	ticker *time.Ticker

	// lock data collection (RemoteHello and tracer data)
	lockCollection sync.Mutex
	// lock exporting updates (PushClient and responses to mutations)
	lockExport sync.Mutex
	// server is currently responding to a client, and pushing should be skipped
	// respInProgress atomic.Bool

	// ID of the currently connected client.
	clientId        atomic.Pointer[string]
	lastPush        time.Time
	lastPushData    *TracerData
	httpSrv         *http.Server
	wsTunRetryRound atomic.Int32
	Config          *SourceConfig
}

// serverTracer couples a [SourceTracer] with server-side pushes and schema
// syncs.
type serverTracer struct {
	*SourceTracer
	server *Server
}

func ( *serverTracer) ( *am.Transition) {
	.SourceTracer.TransitionEnd()
	go .server.PushClient()
}

func ( *serverTracer) ( am.Api,  am.Schema) {
	.SourceTracer.SchemaChange(, )
	.server.schemaChange(, )
}

// interfaces
var (
	_ serverRpcMethods    = &Server{}
	_ clientServerMethods = &Server{}
)

// NewServer creates a new RPC server, bound to a worker machine.
// The source machine has to implement [states.StateSourceStatesDef] interface.
//
// addr: can be empty if [Server.Listener] or [Server.Conn] is set later.
func (
	 context.Context,  string,  string,  am.Api,
	 *ServerOpts,
) (*Server, error) {
	// TODO SPLIT

	if  == "" {
		 = "rpc"
	}
	if  == nil {
		 = &ServerOpts{}
	}
	if .Args != nil && .ArgsUnmarshaller == nil {
		.ArgsUnmarshaller = amhelp.NewArgsUnmarshaller(.Args)
	}
	// TODO WASM auto-tunnel
	if .WebSocketTunnel != "" &&  == "" {
		return nil, nofmt.Errorf("addr required for WebSocketTunnel")
	}
	if .WebSocket &&  == "" {
		return nil, nofmt.Errorf("addr required for WebSocket")
	}
	if .WebSocket && amhelp.IsWasm() {
		return nil, nofmt.Errorf("WebSocket server not supported in browser WASM")
	}

	// check the source
	if  == nil {
		return nil, nofmt.Errorf("stateSource required")
	}
	if !.StatesVerified() {
		return nil, nofmt.Errorf(
			"net source states not verified, call VerifyStates()",
		)
	}
	 := len(.Handlers()) > 0

	if  && !.Has(ssSs.Names()) {
		// error only when some handlers bound, skip deterministic machines
		 := nofmt.Errorf(
			"%w: StateSource mach with handlers has to implement "+
				"pkg/rpc/states.StateSourceStatesDef",
			am.ErrSchema,
		)

		return nil, 
	}

	// TODO validate state names

	 := &Server{
		ExceptionHandler: &ExceptionHandler{},
		Addr:             ,
		DeliveryTimeout:  5 * time.Second,
		LogEnabled:       os.Getenv(EnvAmRpcLogServer) != "",
		Source:           ,
		Args:             .Args,
		Opts:             *,

		WsTunReconn:           true,
		WsTunConnTimeout:      3 * time.Second,
		WsTunConnRetryTimeout: 5 * time.Minute,
		WsTunConnRetries:      50,
		WsTunConnRetryDelay:   time.Second,
		WsTunConnRetryBackoff: 10 * time.Second,

		lastPushData: &TracerData{},
	}
	 := 250 * time.Millisecond
	.PushInterval.Store(&)
	.AllowedWsPubKeys.Store(&.AllowedWsPubKeys)
	.AllowedMachIds.Store(&.AllowedMachIds)

	// state machine
	,  := am.NewCommon(, "rs-"+, states.ServerSchema, ssS.Names(),
		nil, .Parent, &am.Opts{
			Tags: []string{states.TagRpcServer},
		})
	if  != nil {
		return nil, 
	}
	if _,  = BindHandlersServer(, );  != nil {
		return nil, 
	}
	.SemLogger().SetArgsMapper(amhelp.LogArgsMapper)
	.SetGroups(states.ServerGroups, ssS)
	.OnDispose(func( string,  context.Context) {
		if  := .Listener.Load();  != nil {
			_ = (*).Close()
			.Listener.Store(nil)
		}
		.rpcServer = nil
		_ = .Source.DetachTracer(.tracer.TracerId())
	})
	.Mach = 
	// optional env debug
	if os.Getenv(EnvAmRpcDbg) != "" {
		_ = amhelp.MachDebugEnv()
	}

	// states
	if .WebSocketTunnel != "" {
		.Add1(ssS.WebSocketTunnel, nil)
	}

	// bind to source via Tracer API (inactive until activated)
	.Config = &SourceConfig{}
	.tracer = NewSourceTracer(.Id(), .Config)
	if _,  = .BindTracer(&serverTracer{
		SourceTracer: .tracer,
		server:       ,
	});  != nil {
		return nil, 
	}

	// longer timeouts
	if amhelp.IsDebug() {
		.log("debug, extending timeouts")
		.WsTunConnRetryTimeout *= 10
	}

	// debug
	// mach.AddBreakpoint1("", ssS.RpcReady, true)
	// mach.AddBreakpoint1("", ssS.RpcReady, false)

	return , nil
}

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

// ///// HANDLERS

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

var _ = am.StateException

func ( *Server) ( *am.Event) {
	// call super
	.ExceptionHandler.ExceptionState()

	// WebsocketTunnel
	if .Mach.Is1(ssS.WebSocketTunnel) {
		// clean up on errs
		if .Conn != nil {
			_ = .Conn.Close()
		}

		// retry?
		,  := .Transition().TimeIndexDiff()
		 := .wsTunRetryRound.Load() < int32(.WsTunConnRetries) &&
			.WsTunReconn
		if .Is1(ssS.ErrNetwork) &&  {
			.log("WebSocket exception retry")
			.Mach.Remove1(ssS.Exception, nil)
			.Mach.Add1(ssS.RpcStarting, nil)
		}
	}
}

var _ = ssS.Start

func ( *Server) ( *am.Event) {
	 := .Mach
	 := .NewStateCtx(ssS.Start)

	// start websocket server early
	if .Opts.WebSocket {
		.httpSrv = &http.Server{
			Addr:    .Addr,
			Handler: .newWebsocketHandler(),
		}

		.Fork(, , func() {
			 := .httpSrv.ListenAndServe()
			if  != nil {
				// add err to mach
				AddErrNetwork(, , )
				// add outcome to mach
				.Remove1(ssS.RpcStarting, nil)
			}
		})
	}
}

func ( *Server) ( *am.Event) {
	if .Opts.WebSocket {
		if .Conn != nil {
			_ = .Conn.Close()
		}
		go func() {
			_ = .httpSrv.Shutdown(.Mach.Context())
		}()
	} else if .Mach.Is1(ssS.WebSocketTunnel) && .Conn != nil {
		_ = .Conn.Close()
	}
	if am.ParseArgs[A](.Args).Dispose {
		.Mach.Dispose()
	}
}

var _ = ssS.RpcStarting

func ( *Server) ( *am.Event) bool {
	// check listening
	if .Addr == "" && .Listener.Load() == nil && .Conn == nil {
		return false
	}

	return true
}

func ( *Server) ( *am.Event) {
	 := .Mach
	 := .NewStateCtx(ssS.Start)
	.log("Starting RPC on %s", .Addr)
	.bindRpcHandlers()

	// skip for websocket server
	if .Opts.WebSocket {
		return
	}

	.Fork(, , func() {
		// has to be ctxStart, not ctxRpcStarting
		// websocket listener (HTTP)
		if .Opts.WebSocketTunnel != "" {
			 := "ws://" + .Addr + .Opts.WebSocketTunnel
			 := .WsTunConnRetryDelay
			 := time.Now()

			// TODO WsTunConnectingState
			// go func() {
			// retry loop
			.Conn = nil
			for .Err() == nil &&
				(.WsTunReconn || .wsTunRetryRound.Load() == 0) &&
				.wsTunRetryRound.Load() < int32(.WsTunConnRetries) {

				// wait for time or exit
				.wsTunRetryRound.Add(1)
				if !amhelp.Wait(, ) {
					return // expired
				}

				// dial
				.log("Dialing (round %d) %s", .wsTunRetryRound.Load(), )
				var  []string
				if .Opts.WebSocketTunnelPubKey != "" {
					 = []string{"X-API-Key", .Opts.WebSocketTunnelPubKey}
				}
				,  := dialWebSocket(, , ,
					.WsTunConnTimeout)
				if  != nil {
					.log("WebSocket err")
					if .Err() == nil && isNetTimeout() {
						AddErrNetworkTimeout(, , )
					} else {
						AddErrNetwork(, , )
					}

				} else {
					.log("WebSocket OK")
					.log("Tunnel OK")
					.Conn = 
					// reset the retry counter
					.wsTunRetryRound.Store(0)
					break
				}

				// double the delay when backoff set
				if .WsTunConnRetryBackoff > 0 {
					 *= 2
					if  > .WsTunConnRetryBackoff {
						 = .WsTunConnRetryBackoff
					}
				}

				// last try?
				if  := .WsTunConnRetryTimeout;  > 0 && time.Since() >  {
					.log("WebSocket RetryTimeout")
					break
				}

				// try again
			}

			// failed?
			if .Conn == nil {
				.log("WebSocket tunnel failure")
				.EvRemove1(, ssS.RpcStarting, nil)
				return
			}

			// existing connection
		} else if .Conn != nil {
			.log("Using existing connection %s", .Conn.LocalAddr())
			.Addr = .Conn.LocalAddr().String()

			// existing listener
		} else if  := .Listener.Load();  != nil {
			// update Addr from listener (support for external and :0)
			.Addr = (*).Addr().String()

			// new listener
		} else {
			// create a listener if not provided
			// use Start as the context
			,  := listenTCP(, "tcp4", .Addr)
			if  != nil {
				// add err to mach
				AddErrNetwork(, , )
				// add outcome to mach
				.EvRemove1(, ssS.RpcStarting, nil)

				return
			}

			.Listener.Store(&)
			// update Addr from listener (support for external and :0)
			.Addr = .Addr().String()
		}

		// next
		.EvAdd1(, ssS.RpcAccepting, nil)
	})
}

var _ = ssS.RpcAccepting

func ( *Server) ( *am.Event) bool {
	return .Listener.Load() != nil || .Conn != nil
}

func ( *Server) ( *am.Event) {
	 := .Mach.NewStateCtx(ssS.RpcAccepting)
	 := .Mach.NewStateCtx(ssS.Start)
	 := .rpcServer

	.log("RPC started on %s", .Addr)

	// addr tag, unless the server creator (eg iroh) already set a dialable addr
	if amhelp.TagValue(.Mach.Tags(), states.TagKeyAddr) == "" {
		amhelp.TagSetOnMach(.Mach, states.TagKeyAddr, .Addr)
	}

	// unblock
	.Mach.Fork(, , func() {
		// fork to accept TODO state?
		.Mach.Go(, func() {
			// mark as ready
			.Mach.EvAdd1(, ssS.RpcReady, Pass(&A{
				Addr: .Addr,
			}))

			// accept (block)
			 := .Listener.Load()
			if .Conn != nil {
				.ServeConn(.Conn)
			} else if  != nil {
				.Accept(*)
			} else {
				AddErrNetwork(, .Mach, nofmt.Errorf("no listener"))
				.Mach.EvRemove1(, ssS.RpcReady, nil)

				return
			}
			if .Err() != nil {
				return // expired
			}

			// clean up
			if  != nil {
				(*).Close()
				.Listener.Store(nil)
			}
			if .Err() != nil {
				return // expired
			}

			// restart on failed listener
			if .Mach.Is1(ssS.Start) {
				.log("restarting on failed listener")
				.Mach.EvRemove1(, ssS.RpcReady, nil)
				.Mach.EvAdd1(, ssS.RpcStarting, nil)
			}
		})

		// bind to RPC server events (or override)
		.OnDisconnect(func( *rpcClient) {
			.Mach.EvRemove1(, ssS.ClientConnected, Pass(&AClientConnected{
				Client: ,
			}))
		})
		.OnConnect(func( *rpcClient) {
			.Mach.EvAdd1(, ssS.ClientConnected, Pass(&AClientConnected{
				Client: ,
			}))
		})
	})
}

var _ = ssS.RpcReady

func ( *Server) ( *am.Event) bool {
	// only from RpcAccepting
	return .Mach.Is1(ssS.RpcAccepting)
}

// RpcReadyState starts a ticker to compensate for clock push debounces.
func ( *Server) ( *am.Event) {
	if .Opts.WebSocketTunnel != "" {
		.log("ws tunnel ok: %s", .Opts.WebSocketTunnel)
	}

	// no ticker for instant clocks
	if *.PushInterval.Load() == 0 {
		return
	}

	 := .Mach.NewStateCtx(ssS.RpcReady)
	if .ticker == nil {
		.ticker = time.NewTicker(*.PushInterval.Load())
	}

	// avoid dispose
	 := .ticker

	.Mach.Fork(, , func() {
		// push clock updates, debounced by getLatestUpdate
		for {
			select {
			case <-.Done():
				.ticker.Stop()
				return

			case <-.C:
				.PushClient()
			}
		}
	})
}

var _ = ssS.HandshakeDone

func ( *Server) ( *am.Event) {
	, ,  := .Source.Export()

	// locks
	.lockCollection.Lock()
	defer .lockCollection.Unlock()

	// push meantime changes
	 := .lastPushData.MTrackedTimeSum
	if .Time.Sum(.tracer.TrackedStateIdxs) !=  {
		.PushClient()
	}
}

func ( *Server) ( *am.Event) {
	if  := .rpcClient.Load();  != nil {
		_ = .Close()
		// s.rpcClient = nil
	}
}

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

// ///// METHODS

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

// Start starts the server, optionally creating a Listener (if Addr provided).
// Results in either RpcReady or Exception.
func ( *Server) ( *am.Event) am.Result {
	return .Mach.EvAdd1(, ssS.Start, nil)
}

// Stop stops the server, and optionally disposes resources.
func ( *Server) ( *am.Event,  bool) am.Result {
	// TODO waitTillCtx
	if .Mach == nil {
		return am.Canceled
	}
	if  {
		.log("disposing")
	}
	amhelp.DisposeEv(.Mach, )

	return am.Executed
}

// SendPayload sends a payload to the client.
//
// srcEvent: optional event for tracing.
func ( *Server) (
	 context.Context,  *am.Event,  *MsgSrvPayload,
) error {
	// TODO add SendPayloadAsync calling RemoteSendingPayload first
	// TODO bind to an async state

	if .Mach.Not1(ssS.ClientConnected) || .Mach.Not1(ssS.HandshakeDone) {
		return ErrNoConn
	}

	// check destination
	 := .ClientId()
	if .Destination != "" &&  != .Destination {
		return nofmt.Errorf("%w: %s != %s", ErrDestination, .Destination, )
	}

	defer .Mach.PanicToErr(nil)

	.Token = utils.RandId(0)
	if  != nil {
		.Source = .MachineId
		.SourceTx = .TransitionId
	}
	.log("sending payload %s from %s to %s", .Name, .Source,
		.Destination)

	// TODO failsafe
	return .rpcClient.Load().CallWithContext(,
		ClientSendPayload.Value, , &MsgEmpty{})
}

func ( *Server) () string {
	 := .clientId.Load()
	if  == nil {
		return ""
	}

	return *
}

// GetKind returns a kind of RPC component (server / client).
func ( *Server) () Kind {
	return KindServer
}

func ( *Server) ( string,  ...any) {
	if !.LogEnabled {
		return
	}
	.Mach.Log(, ...)
}

func ( *Server) () {
	// new RPC instance, release prev resources
	.rpcServer = newRpcServer()
	if os.Getenv(EnvAmRpcLogServer) != "" &&
		os.Getenv(am.EnvAmTestRunner) == "" {

		setRpcDebugLog(true)
	}

	.rpcServer.Handle(ServerHello.Value, .RemoteHello)
	.rpcServer.Handle(ServerHandshake.Value, .RemoteHandshake)
	.rpcServer.Handle(ServerAdd.Value, .RemoteAdd)
	.rpcServer.Handle(ServerAddNS.Value, .RemoteAddNS)
	.rpcServer.Handle(ServerRemove.Value, .RemoteRemove)
	.rpcServer.Handle(ServerSet.Value, .RemoteSet)
	.rpcServer.Handle(ServerSync.Value, .RemoteSync)
	.rpcServer.Handle(ServerArgs.Value, .RemoteArgs)
	.rpcServer.Handle(ServerBye.Value, .RemoteBye)

	// TODO RemoteWhenArgs

	// s.rpcServer.Handle("RemoteLog", s.RemoteLog)
	// s.rpcServer.Handle("RemoteWhenArgs", s.RemoteWhenArgs)
}

// schemaChange syncs a source schema change to the client. It is called by
// [SourceTracer.SchemaChange].
func ( *Server) ( am.Api,  am.Schema) {
	.lockCollection.Lock()
	defer .lockCollection.Unlock()

	if !.tracer.Active.Load() {
		return
	}

	 := &MsgSrvHello{}
	.Serialized, .Schema, _ = .Export()
	.StatesCount = uint32(len(.Serialized.StateNames))
	 := .Serialized.StateNames

	// client-bound indexes when no schema synced
	 := .Serialized
	if !.tracer.Config.SyncSchema.Load() {
		.StateNames = am.StatesShared(.StateNames,
			.tracer.TrackedStates)
		.Time = .Time.Filter(.tracer.TrackedStateIdxs)

		// zero non-tracked for consistent checksums
	} else {
		for  := range  {
			if slices.Contains(.tracer.TrackedStateIdxs, ) {
				continue
			}
			.Time[] = 0
		}
	}

	// init cache
	if .tracer.TrackedStates == nil {
		.tracer.calcTrackedStates()
	}

	// memorize
	 := .lastPushData
	.MTime = .Time
	.QueueTick = .QueueTick
	.MTrackedTimeSum = .Time.Sum(.tracer.TrackedStateIdxs)
	.Checksum = Checksum(.MTrackedTimeSum, .QueueTick, .MachTick)

	// fork and push
	go func() {
		 := .rpcClient.Load()
		if  == nil {
			return
		}

		.lockExport.Lock()
		defer .lockExport.Unlock()

		// send
		 := .CallWithContext(.Context(), ClientSchemaChange.Value,
			, &MsgEmpty{})
		.AddErr(, nil)
	}()
}

// PushClient triggers a manual push of an update to the client. It can be
// either a single or a multi update. It can also be throttled and happen later.
func ( *Server) () {
	 := .rpcClient.Load()
	if  == nil {
		return
	}

	// push disabled or not ready
	if *.PushInterval.Load() == 0 || .Mach.Not1(ssS.HandshakeDone) {
		return
	}

	// skip if currently exporting
	if !.lockExport.TryLock() {
		.log("skip parallel export")
		return
	}
	defer .lockExport.Unlock()

	// collect
	 := .tracer.DataLatest.Load()
	if  == nil {
		return
	}

	// no change
	if .lastPushData.MTrackedTimeSum == .MTrackedTimeSum &&
		.lastPushData.QueueTick == .QueueTick {

		// s.log("skip no diff")
		return
	}

	// too often
	if time.Since(.lastPush) < *.PushInterval.Load() {
		// s.log("update too soon")
		return
	}

	// sync
	.log("pushClient:try t%d", .MTrackedTimeSum)
	var  error
	if .tracer.Config.SyncMutations.Load() {
		var  []TracerMutation
		if  := .tracer.DataQueue.Swap(nil);  != nil {
			 = *
		}
		.tracer.DataLatest.Store(nil)

		 = .pushUpdateMutations()
	} else {
		 = .pushUpdateLatest()
	}
	if  != nil {
		.Mach.Remove1(ssS.ClientConnected, nil)
		AddErr(nil, .Mach, "pushClient", )

		return
	}
	.log("pushClient:ok t%d", .MTrackedTimeSum)

	.storeLastPush()
}

// call via by PushClient
func ( *Server) ( []TracerMutation) error {
	 := .rpcClient.Load()
	if  == nil {
		return nil
	}
	defer .Mach.PanicToErr(nil)

	// calculate diffs
	 := calcUpdateMutations(.tracer.Config.SyncSchema.Load(), ,
		.lastPushData)

	// nothing to push
	if len(.MutationType) == 0 {
		return nil
	}

	// notify without a response
	.CallCount++

	// TODO failsafe retry (stateful)
	return .Notify(ClientUpdateMutations.Value, )
}

// call via by PushClient
func ( *Server) ( *TracerData) error {
	 := .rpcClient.Load()
	if  == nil {
		return nil
	}
	defer .Mach.PanicToErr(nil)

	// calculate diff
	 := calcUpdate(.tracer.Config.SyncSchema.Load(), , .lastPushData,
		.tracer.Config.SyncShallowClocks.Load())

	// nothing to push
	if len(.Indexes) == 0 {
		return nil
	}

	// notify without a response
	.CallCount++
	// fmt.Printf("[S] update %v\n", update)
	// fmt.Printf("[S] time %v\n", data.mTime)

	// TODO failsafe retry (stateful)
	return .Notify(ClientUpdate.Value, )
}

// newMsgMutation creates a new response to a mutation call from the client.
// Requires [s.lockExport]
func ( *Server) (
	 am.Result,  *TracerData,
) *MsgSrvMutation {
	 := MsgSrvMutation{Result: }
	// calculate diff
	if .tracer.Config.SyncMutations.Load() {
		var  []TracerMutation
		if  := .tracer.DataQueue.Swap(nil);  != nil {
			 = *
		}
		.tracer.DataLatest.Store(nil)

		.Mutations = calcUpdateMutations(.tracer.Config.SyncSchema.Load(), ,
			.lastPushData)
	} else {
		.Update = calcUpdate(.tracer.Config.SyncSchema.Load(), ,
			.lastPushData, .tracer.Config.SyncShallowClocks.Load())
	}

	// fmt.Printf("[S] QueueTick: %d - %d\n", data.queueTick, s.lastPushQTick)
	// fmt.Printf("[S] MachTick: %d - %d\n", data.machTick, s.lastPushMachTick)

	.storeLastPush()

	return &
}

func ( *Server) ( *TracerData) {
	.lastPush = time.Now()
	.lastPushData = 
}

func ( *Server) ( *am.Event) http.HandlerFunc {
	return func( http.ResponseWriter,  *http.Request) {
		// check origin
		if !wsOriginAllowed(, .Opts.AllowedWsOrigins) {
			.Header().Set("Content-Type", "application/json")
			.WriteHeader(http.StatusForbidden)
			_, _ = .Write([]byte(`{"error": "forbidden origin"}`))
			return
		}

		// check API key
		 := .AllowedWsPubKeys.Load()
		if  != nil && len(*) > 0 {
			 := .Header.Get("X-API-Key")
			if  == "" {
				 := .Header.Get("Sec-WebSocket-Protocol")
				if  != "" {
					 := strings.Split(, ",")
					for ,  := range  {
						 = strings.TrimSpace()
						if !strings.EqualFold(, "X-API-Key") &&  != "" {
							 = 
							break
						}
					}
				}
			}

			 := false
			if  != "" {
				for ,  := range * {
					if  ==  {
						 = true
						break
					}
				}
			}
			if ! {
				.Header().Set("Content-Type", "application/json")
				.WriteHeader(http.StatusUnauthorized)
				_, _ = .Write([]byte(`{"error": "unauthorized"}`))
				return
			}
		}

		// handle
		 := &wsHandlerServer{
			s:     ,
			event: .Export(),
		}
		.ServeHTTP(, )
	}
}

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

// ///// REMOTE METHODS

// ///// ///// /////
// TODO add local errs

func ( *Server) (
	 *rpcClient,  *MsgCliHello,  *MsgSrvHello,
) error {
	// validate
	if .Mach.Not1(ssS.Start) {
		return am.ErrCanceled
	}
	if  == nil || .Id == "" {
		.Mach.Remove1(ssS.Handshaking, nil)
		AddErrRpcStr(nil, .Mach, "handshake failed: ID missing")

		return ErrInvalidParams
	}

	// locks
	.lockCollection.Lock()
	defer .lockCollection.Unlock()

	// check access TODO test
	 := .AllowedMachIds.Load()
	if  != nil && len(*) > 0 && !slices.Contains(*, .Id) {
		.Mach.Remove1(ssS.Handshaking, nil)

		return nofmt.Errorf("%w: %d keys, but not '%s'",
			ErrNoAccess, len(*), .Id)
	}

	// set up sync
	 := .tracer.Config
	.SyncAllowedStates.Store(&.AllowedStates)
	.SyncSkippedStates.Store(&.SkippedStates)
	.SyncShallowClocks.Store(.ShallowClocks)
	.SyncMutations.Store(.SyncMutations)
	.SyncSchema.Store(.SyncSchema)

	// prep the mach msg
	, ,  := .Source.Export()
	.tracer.calcTrackedStates(.StateNames)
	.tracer.Active.Store(true)
	 := len(.StateNames)
	 := .Time.Filter(.tracer.TrackedStateIdxs).Sum(nil)

	// client-bound indexes when no schema synced
	if !.SyncSchema {
		.StateNames = am.StatesShared(.StateNames,
			.tracer.TrackedStates)
		.Time = .Time.Filter(.tracer.TrackedStateIdxs)

		// zero non-tracked for consistent checksums
	} else {
		for  := range .StateNames {
			if slices.Contains(.tracer.TrackedStateIdxs, ) {
				continue
			}
			.Time[] = 0
		}
	}
	* = MsgSrvHello{
		Serialized:  ,
		StatesCount: uint32(),
	}

	// return the schema if requested
	if .SyncSchema {
		if .SchemaHash == "" ||
			.SchemaHash != amhelp.SchemaHash() {

			.Schema = 
		}
	}

	// memorize
	.lastPushData.MTime = .Time
	.lastPushData.QueueTick = .QueueTick
	.lastPushData.MTrackedTimeSum = 
	.lastPush = time.Now()
	.clientId.Store(&.Id)

	.log("RemoteHello: t%v q%d", , .QueueTick)
	.Mach.Add1(ssS.Handshaking, nil)

	// TODO timeout for RemoteHandshake via push loop

	return nil
}

func ( *Server) (
	 *rpcClient,  *MsgEmpty,  *MsgEmpty,
) error {
	if .Mach.Not1(ssS.Start) {
		return am.ErrCanceled
	}
	 := .clientId.Load()
	if  == nil {
		return ErrNoConn
	}
	 := .Source.Time(nil).Sum(nil)
	 := .Source.QueueTick()
	.log("RemoteHandshake: t%v q%d", , )

	// accept the client
	.rpcClient.Store()
	.Mach.Add1(ssS.HandshakeDone, Pass(&A{
		Id: *,
	}))

	return nil
}

func ( *Server) (
	 *rpcClient,  *MsgCliMutation,  *MsgSrvMutation,
) error {
	//

	if .Mach.Not1(ssS.Start) {
		return am.ErrCanceled
	}
	.lockExport.Lock()
	defer .lockExport.Unlock()

	// validate
	if .States == nil {
		return ErrInvalidParams
	}

	// typed args
	 := .Args
	if .Opts.ArgsUnmarshaller != nil {
		 = .Opts.ArgsUnmarshaller()
	}

	// execute
	var  am.Result
	if .Event != nil {
		 = .Source.EvAdd(.Event, amhelp.IndexesToStates(
			.Source.StateNames(), .States,
		), )
	} else {
		// TODO eval
		 = .Source.Add(amhelp.IndexesToStates(.Source.StateNames(),
			.States), )
	}
	waitMutation(.Source, )

	// return
	 := .tracer.DataLatest.Load()
	* = *.newMsgMutation(, )

	return nil
}

func ( *Server) (
	 *rpcClient,  *MsgCliMutation,  *MsgEmpty,
) error {
	if .Mach.Not1(ssS.Start) {
		return am.ErrCanceled
	}
	.lockExport.Lock()
	defer .lockExport.Unlock()

	// validate
	if .States == nil {
		return ErrInvalidParams
	}

	// typed args
	 := .Args
	if .Opts.ArgsUnmarshaller != nil {
		 = .Opts.ArgsUnmarshaller()
	}

	// execute TODO event trace
	_ = .Source.Add(amhelp.IndexesToStates(.Source.StateNames(), .States),
		)

	return nil
}

func ( *Server) (
	 *rpcClient,  *MsgCliMutation,  *MsgSrvMutation,
) error {
	if .Mach.Not1(ssS.Start) {
		return am.ErrCanceled
	}
	.lockExport.Lock()
	defer .lockExport.Unlock()

	// validate
	if .States == nil {
		return ErrInvalidParams
	}

	// typed args
	 := .Args
	if .Opts.ArgsUnmarshaller != nil {
		 = .Opts.ArgsUnmarshaller()
	}

	// execute TODO event trace
	 := .Source.Remove(amhelp.IndexesToStates(.Source.StateNames(),
		.States), )
	waitMutation(.Source, )

	// return
	 := .tracer.DataLatest.Load()
	* = *.newMsgMutation(, )

	return nil
}

func ( *Server) (
	 *rpcClient,  *MsgCliMutation,  *MsgSrvMutation,
) error {
	if .Mach.Not1(ssS.Start) {
		return am.ErrCanceled
	}
	.lockExport.Lock()
	defer .lockExport.Unlock()

	// validate
	if .States == nil {
		return ErrInvalidParams
	}

	// typed args
	 := .Args
	if .Opts.ArgsUnmarshaller != nil {
		 = .Opts.ArgsUnmarshaller()
	}

	// execute TODO event trace
	 := .Source.Set(amhelp.IndexesToStates(.Source.StateNames(),
		.States), )
	waitMutation(.Source, )

	// return
	 := .tracer.DataLatest.Load()
	* = *.newMsgMutation(, )

	return nil
}

func ( *Server) (
	 *rpcClient,  *MsgEmpty,  *MsgSrvSync,
) error {
	if .Mach.Not1(ssS.Start) {
		return am.ErrCanceled
	}
	.Mach.Add1(ssS.MetricSync, nil)

	* = MsgSrvSync{
		Time:      .Source.Time(nil),
		QueueTick: .Source.QueueTick(),
	}
	.log("RemoteSync: [%v]", .Time)

	return nil
}

// RemoteArgs returns a list of registered arguments.
func ( *Server) (
	 *rpcClient,  *MsgEmpty,  *MsgSrvArgs,
) error {
	if .Mach.Not1(ssS.Start) {
		return am.ErrCanceled
	}

	// args TODO cache
	if .Args == nil {
		return nil
	}

	,  := amhelp.ArgsNames(.Args)
	if  != nil {
		return 
	}

	(*).Args = 
	return nil
}

// RemoteBye means the client says goodbye and will disconnect shortly.
func ( *Server) (
	 *rpcClient,  *MsgEmpty,  *MsgEmpty,
) error {
	if .Mach.Not1(ssS.Start) {
		return am.ErrCanceled
	}
	.log("RemoteBye")

	.Mach.Remove1(ssS.ClientConnected, Pass(&A{
		Addr: .Addr,
	}))
	go func() {
		select {
		case <-time.After(100 * time.Millisecond):
			.log("rpc.Close timeout")
		case <-amhelp.ExecAndClose(func() {
			if  := .rpcClient.Load();  != nil {
				_ = .Close()
			}
		}):
			.log("rpc.Close")
		}

		time.Sleep(100 * time.Millisecond)
		.Mach.Remove1(ssS.HandshakeDone, nil)
	}()

	// forget client
	.rpcClient.Store(nil)
	.clientId.Store(nil)

	return nil
}

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

// ///// MISC

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

// BindServer binds RpcReady and HandshakeDone with Add/Remove, to custom
// states.
func (
	,  *am.Machine, ,  string,
) (string, error) {
	// TODO use ampipe.BindMany
	if  == "" ||  == "" {
		return "", nofmt.Errorf("rpcReady and clientConn must be set")
	}

	 := &struct {
		 am.HandlerFinal
		   am.HandlerFinal

		 am.HandlerFinal
		   am.HandlerFinal
	}{
		: ampipe.Add(, , ssS.RpcReady, ),
		:   ampipe.Remove(, , ssS.RpcReady, ),

		: ampipe.Add(, , ssS.ClientConnected,
			),
		: ampipe.Remove(, , ssS.ClientConnected,
			),
	}

	return .HandlersBind()
}

// BindServerMulti binds RpcReady, ClientConnected, and ClientDisconnected.
// RpcReady is Add/Remove, the other two are Add-only to passed multi states.
func (
	,  *am.Machine, , ,  string,
) (string, error) {
	if  == "" ||  == "" ||  == "" {
		return "", nofmt.Errorf(
			"rpcReady, clientConn, and clientDisconn must be set")
	}
	// TODO use ampipe.BindMany

	 := &struct {
		 am.HandlerFinal
		   am.HandlerFinal

		 am.HandlerFinal
		   am.HandlerFinal
	}{
		: ampipe.Add(, , ssS.RpcReady, ),
		:   ampipe.Remove(, , ssS.RpcReady, ),

		: ampipe.Add(, ,
			ssS.ClientConnected, ),
		: ampipe.Add(, ,
			ssS.ClientConnected, ),
	}

	return .HandlersBind()
}

// BindServerRpcReady bind RpcReady using Add to a custom multi state.
func (,  *am.Machine,
	 string,
) (string, error) {
	// TODO use ampipe.Bind
	 := &struct {
		 am.HandlerFinal
	}{
		: ampipe.Add(, , ssS.RpcReady, ),
	}

	return .HandlersBind()
}

// waitMutation waits until a queued mutation is processed.
func waitMutation( am.Api,  am.Result) {
	if  >= am.Queued {
		<-.WhenQueue()
	}
}

// CalcUpdate calculates a new update based on previously pushed data.
func (
	 bool, ,  *TracerData,  bool,
) *MsgSrvUpdate {
	return calcUpdate(, , , )
}

// calcUpdate calculates a new update based on previously pushed data.
func calcUpdate(
	 bool, ,  *TracerData,  bool,
) *MsgSrvUpdate {
	var  []uint16
	var  []uint32
	if  {
		,  = genShallowUpdate(, , )
	} else {
		,  = genDeepUpdate(, , )
	}

	return &MsgSrvUpdate{
		QueueTick: uint16(.QueueTick - .QueueTick),
		MachTick:  uint8(.MachTick - .MachTick),
		Indexes:   ,
		Ticks:     ,
		Checksum:  .Checksum,
	}
}

// calcUpdate calculates a new mutation update based on the queue and previously
// pushed data.
func calcUpdateMutations(
	 bool,  []TracerMutation,  *TracerData,
) *MsgSrvUpdateMuts {
	 := &MsgSrvUpdateMuts{}
	for  := range  {
		 := &[]
		.MutationType = append(.MutationType, .MutType)
		 := make([]uint16, len(.CalledIdxs))
		for  := range .CalledIdxs {
			[] = uint16(.CalledIdxs[])
		}
		.CalledStates = append(.CalledStates, )
		.Updates = append(.Updates, *calcUpdate(, &.Data, ,
			false))

		 = &.Data
	}

	return 
}

func genDeepUpdate(
	 bool, ,  *TracerData,
) ( []uint16,  []uint32) {
	 = make([]uint16, 0, len(.Tracked))
	 = make([]uint32, 0, len(.Tracked))

	for  := range .Tracked {
		 := .TrackedIdxs[]
		 := .MTime
		 := .MTime

		// client has shorter state names
		 := uint16()
		if ! {
			 = uint16()
		}

		// first call or new schema
		if  == nil ||  >= len() {
			if [] == 0 {
				continue
			}
			 = append(, )
			 = append(, uint32([]))

			// regular update
		} else if [] != [] {
			 = append(, )
			 = append(, uint32([]-[]))
		}
	}

	return , 
}

func genShallowUpdate(
	 bool, ,  *TracerData,
) ( []uint16,  []uint32) {
	 = make([]uint16, 0, len(.Tracked))
	 = make([]uint32, 0, len(.Tracked))

	for  := range .Tracked {
		 := .TrackedIdxs[]
		 := .MTime
		 := .MTime

		// client has shorter state names
		 := uint16()
		if ! {
			 = uint16()
		}

		// first call or new schema
		if  == nil || int() >= len() {
			if [] == 0 {
				continue
			}
			 = append(, )
			 := 0
			if am.IsActiveTick([]) {
				 = 1
			}
			 = append(, uint32())

			// regular update
		} else if []%2 != []%2 {
			 = append(, )
			 = append(, uint32(1))
		}
	}

	return , 
}

// wsOriginAllowed checks the Origin header against the allowed patterns. An
// empty list allows any origin. Patterns can be either hosts or full origins
// and support wildcards, eg "*.example.com".
func wsOriginAllowed( *http.Request,  []string) bool {
	if len() == 0 {
		return true
	}

	 := .Header.Get("Origin")
	if  == "" {
		return false
	}
	,  := url.Parse()
	if  != nil || .Host == "" {
		return false
	}
	 := .Hostname()

	for ,  := range  {
		 = strings.TrimSpace()
		if  == "" {
			continue
		}
		// full origins as well as bare hosts
		if ,  := url.Parse();  == nil && .Host != "" {
			if matchWSHost(.Hostname(), ) {
				return true
			}
			continue
		}
		if matchWSHost(, ) {
			return true
		}
	}

	return false
}

func matchWSHost(,  string) bool {
	if  ==  {
		return true
	}
	if strings.Contains(, "*") {
		,  := path.Match(, )
		return  == nil && 
	}

	return false
}