pkg/ezagentapi/conn.go

package ezagentapi

import (
	"context"
	"errors"
	"fmt"
	"io"
	"math"
	"reflect"
	"sync"

	"git.cafe/ezterry/ez-agent/pkg/jsonlpipe"
	"git.cafe/ezterry/ez-agent/pkg/protocol"
	"git.cafe/ezterry/ez-agent/pkg/watchdog"
)

// Conn is an ez-agent protocol connection layered over jsonlpipe. jsonlpipe is
// intentionally kept private; public methods should model ez-agent protocol
// operations rather than re-export transport controls.
type Conn struct {
	pipe *jsonlpipe.Conn
	rpc  *RPC
	// clientSide marks the peer that receives service RPC responses and
	// frontend events. Service-side peers can receive request frames whose type
	// overlaps a response type, so unmatched-response filtering does not apply.
	clientSide     bool
	apiReady       chan struct{}
	startOnce      sync.Once
	startErr       error
	localExtras    []ExtraSupport
	extraConfigErr error
	extraEnabled   bool           // guarded by mu; fixed by startup
	apiVersion     int            // guarded by mu; API version in use on this connection
	remoteExtras   map[string]int // guarded by mu
	extraState     ExtraDiscoveryState
	extraDone      chan struct{}
	extraErr       error

	mu              sync.Mutex
	sendMu          sync.Mutex // serializes stamping with jsonlpipe enqueue order
	nextItr         int64
	handlerMu       sync.Mutex
	callbacks       sync.WaitGroup
	terminalOnce    sync.Once
	helloAck        *HelloAck
	closedCh        chan struct{}
	clientHello     protocol.Hello
	ownedOperations map[watchdog.Key]string // guarded by sendMu
	handlerCtx      context.Context
	cancelHandlers  context.CancelFunc
}

// ConnectClient returns a client/module-side connection. Start sends hello,
// waits for hello_ack, validates it, and then begins normal message handling.
func ConnectClient(r io.Reader, w io.Writer, closeFn func() error, opts ClientOptions) *Conn {
	c := &Conn{closedCh: make(chan struct{}), apiReady: make(chan struct{}), nextItr: 1, clientSide: true}
	c.localExtras, c.extraConfigErr = advertisedExtras(opts.Extras, math.MinInt32)
	c.handlerCtx, c.cancelHandlers = context.WithCancel(context.Background())
	c.rpc = newRPC(c)
	c.clientHello = clientOptionsToProtocolHello(opts)
	c.pipe = jsonlpipe.NewInitiator(r, w, closeFn, &c.clientHello, func(f jsonlpipe.Frame) error {
		ack, err := decodeHelloAck(f)
		if err != nil {
			return err
		}
		c.setHelloAck(protocolHelloAckToAPI(ack))
		c.mu.Lock()
		c.apiVersion = ack.Protocol
		c.extraEnabled = ack.Ready && (ack.Protocol >= 2 || ack.ExtraAPISupport)
		c.mu.Unlock()
		return nil
	}, c.dispatchHandler(opts.Handlers))
	return c
}

// ConnectClientRW is ConnectClient over a single ReadWriter.
func ConnectClientRW(rw io.ReadWriter, closeFn func() error, opts ClientOptions) *Conn {
	return ConnectClient(rw, rw, closeFn, opts)
}

// LimitClientOutput bounds queued frames (including flush markers) and bytes.
// Call before Start on a client connection. Zero leaves that dimension unlimited.
// A full queue causes the attempted send to fail; the caller owns shutdown.
func (c *Conn) LimitClientOutput(frames int, bytes int64) error {
	if !c.clientSide {
		return errors.New("ezagentapi: output limit requires a client connection")
	}
	return c.pipe.Configure(jsonlpipe.Options{MaxQueueFrames: frames, MaxQueueBytes: bytes})
}

func startupReplyWithIteration(err error, itr int64) error {
	var startupReply StartupReplyError
	if errors.As(err, &startupReply) {
		stamped, stampErr := stampFrame(startupReply.Frame, itr)
		if stampErr != nil {
			return stampErr
		}
		startupReply.Frame = stamped.(protocol.Error)
		return startupReply
	}
	var startupReplyPtr *StartupReplyError
	if errors.As(err, &startupReplyPtr) && startupReplyPtr != nil {
		copyReply := *startupReplyPtr
		stamped, stampErr := stampFrame(copyReply.Frame, itr)
		if stampErr != nil {
			return stampErr
		}
		copyReply.Frame = stamped.(protocol.Error)
		return &copyReply
	}
	return err
}

// AcceptServiceConn returns a service-side connection. Start reads hello,
// validates it, builds hello_ack, sends it, and then begins normal message handling.
func AcceptServiceConn(r io.Reader, w io.Writer, closeFn func() error, opts ServiceOptions) *Conn {
	c := &Conn{closedCh: make(chan struct{}), apiReady: make(chan struct{}), nextItr: 1}
	c.localExtras, c.extraConfigErr = advertisedExtras(opts.Extras, math.MinInt32)
	c.handlerCtx, c.cancelHandlers = context.WithCancel(context.Background())
	c.rpc = newRPC(c)
	c.pipe = jsonlpipe.NewAcceptor(r, w, closeFn, func(f jsonlpipe.Frame) (any, error) {
		hello, err := decodeHello(f)
		if err != nil {
			return nil, startupReplyWithIteration(err, c.nextItr)
		}
		apiHello := protocolHelloToClientHello(hello)
		ack := HelloAck{ServerID: opts.ServerID, NodeID: opts.NodeID, StateDir: opts.StateDir, ConfigError: opts.ConfigError, Ready: true, Message: "READY"}
		if opts.BuildAck != nil {
			ack, err = opts.BuildAck(apiHello)
			if err != nil {
				return nil, startupReplyWithIteration(err, c.nextItr)
			}
		}
		if opts.OnHello != nil {
			ack, err = opts.OnHello(context.Background(), ServiceHello{Hello: apiHello})
			if err != nil {
				return nil, startupReplyWithIteration(err, c.nextItr)
			}
		}
		// The SDK implements discovery even when a custom hook builds the ack.
		// V2 enables unconditionally and ignores the V1 hello flag. Bootstrap
		// acknowledgements never start discovery.
		ack.ExtraAPISupport = hello.Protocol < 2
		c.mu.Lock()
		c.apiVersion = hello.Protocol
		c.extraEnabled = ack.Ready && (hello.Protocol >= 2 || hello.ExtraAPISupport)
		c.mu.Unlock()
		return stampFrame(helloAckToProtocol(ack), c.nextItr)
	}, c.dispatchHandler(opts.Handlers))
	if opts.Handlers.PrepareInbound != nil {
		_ = c.pipe.Configure(jsonlpipe.Options{SynchronousDispatch: true})
	}
	return c
}

func (c *Conn) trackTerminal() {
	c.terminalOnce.Do(func() {
		go func() {
			<-c.pipe.Closed()
			if c.cancelHandlers != nil {
				c.cancelHandlers()
			}
			// Drain correlation handlers for frames decoded before terminal EOF.
			<-c.pipe.Done()
			c.rpc.closeInvocations()
			c.sendMu.Lock()
			c.ownedOperations = nil
			c.sendMu.Unlock()
			close(c.closedCh)
		}()
		go c.runHeartbeats()
	})
}

// AcceptServiceConnRW is AcceptServiceConn over a single ReadWriter.
func AcceptServiceConnRW(rw io.ReadWriter, closeFn func() error, opts ServiceOptions) *Conn {
	return AcceptServiceConn(rw, rw, closeFn, opts)
}

// HelloAck returns the validated startup acknowledgement received by a client.
func (c *Conn) HelloAck() (HelloAck, bool) {
	c.mu.Lock()
	defer c.mu.Unlock()
	if c.helloAck == nil {
		return HelloAck{}, false
	}
	return *c.helloAck, true
}

func (c *Conn) setHelloAck(ack HelloAck) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.helloAck = &ack
}

// Start completes hello/ack without requesting extra discovery.
func (c *Conn) Start() error {
	c.startOnce.Do(func() {
		c.startErr = c.start()
		if c.startErr != nil {
			_ = c.Close()
			return
		}
		close(c.apiReady)
	})
	return c.startErr
}

func (c *Conn) start() error {
	if c.extraConfigErr != nil {
		return c.extraConfigErr
	}
	if err := c.startHandshake(); err != nil {
		return err
	}
	c.mu.Lock()
	if !c.extraEnabled {
		c.extraState = ExtraDiscoveryUnavailable
	}
	c.mu.Unlock()
	return nil
}

func (c *Conn) startHandshake() error {
	c.trackTerminal()
	c.sendMu.Lock()
	defer c.sendMu.Unlock()
	if c.nextItr == math.MaxInt64 {
		return fmt.Errorf("ezagentapi: outbound iteration exhausted")
	}
	if c.clientHello.Type != "" {
		stamped, err := stampFrame(c.clientHello, c.nextItr)
		if err != nil {
			return err
		}
		c.clientHello = stamped.(protocol.Hello)
	}
	if err := c.pipe.Start(); err != nil {
		return err
	}
	// Initialization enqueues exactly one hello or hello_ack before readiness.
	// A startup error is terminal, so no later outbound frame can reuse its value.
	c.nextItr++
	return nil
}

// Ready returns a channel closed when startup completes and the connection is
// ready for normal traffic.
func (c *Conn) Ready() <-chan struct{} { return c.apiReady }

// Wait blocks until the connection exits and returns its terminal error. All
// connection-owned callback goroutines have returned before Wait returns.
func (c *Conn) Wait() error {
	c.trackTerminal()
	err := c.pipe.Wait()
	<-c.closedCh
	c.mu.Lock()
	discoveryDone := c.extraDone
	c.mu.Unlock()
	if discoveryDone != nil {
		<-discoveryDone
	}
	c.callbacks.Wait()
	return err
}

// Closed returns a channel closed after EOF, local Close, or another transport
// failure and after correlation dispatch for frames already read from the
// transport. It does not wait for user callback goroutines to return.
func (c *Conn) Closed() <-chan struct{} {
	c.trackTerminal()
	return c.closedCh
}

// Err returns the terminal connection error, if any.
func (c *Conn) Err() error { return c.pipe.Err() }

// Close shuts down the connection.
func (c *Conn) Close() error {
	c.trackTerminal()
	return c.pipe.Close()
}

func (c *Conn) sendFrame(ctx context.Context, frame any) error {
	if ctx == nil {
		ctx = context.Background()
	}
	select {
	case <-ctx.Done():
		return ctx.Err()
	default:
	}
	c.sendMu.Lock()
	defer c.sendMu.Unlock()
	if err := ctx.Err(); err != nil {
		return err
	}
	return c.enqueueFrame(frame)
}

// enqueueFrame is called with sendMu held.
func (c *Conn) enqueueFrame(frame any) error {
	if c.nextItr == math.MaxInt64 {
		return fmt.Errorf("ezagentapi: outbound iteration exhausted")
	}
	stamped, err := stampFrame(frame, c.nextItr)
	if err != nil {
		return err
	}
	if err := c.pipe.Send(stamped); err != nil {
		// Failed terminal delivery cannot justify continued liveness. Do not
		// replay it; the peer will observe inactivity or transport failure.
		c.retireOperation(frame)
		return err
	}
	c.nextItr++
	c.retireOperation(frame)
	return nil
}

// stampFrame returns a shallow copy of a top-level protocol frame with its
// direct Itr field set. It accepts values and pointers so public send helpers
// remain free of per-frame sequencing boilerplate.
func stampFrame(frame any, itr int64) (any, error) {
	if frame == nil {
		return nil, errors.New("ezagentapi: cannot stamp nil frame")
	}
	v := reflect.ValueOf(frame)
	isPtr := v.Kind() == reflect.Ptr
	if isPtr {
		if v.IsNil() {
			return nil, errors.New("ezagentapi: cannot stamp nil frame pointer")
		}
		v = v.Elem()
	}
	if v.Kind() != reflect.Struct {
		return nil, fmt.Errorf("ezagentapi: outbound frame %T is not a struct", frame)
	}
	itrField, ok := v.Type().FieldByName("Itr")
	typeField, hasType := v.Type().FieldByName("Type")
	if !ok || !hasType || len(itrField.Index) != 1 || len(typeField.Index) != 1 || itrField.Type != reflect.TypeFor[int64]() || typeField.Type.Kind() != reflect.String || itrField.PkgPath != "" || typeField.PkgPath != "" {
		return nil, fmt.Errorf("ezagentapi: outbound frame %T must declare exported Type string and Itr int64", frame)
	}
	copyValue := reflect.New(v.Type()).Elem()
	copyValue.Set(v)
	copyValue.FieldByIndex(itrField.Index).SetInt(itr)
	if isPtr {
		result := reflect.New(v.Type())
		result.Elem().Set(copyValue)
		return result.Interface(), nil
	}
	return copyValue.Interface(), nil
}