From 5a207f622a7d3b385d208c6260d17595a2098600 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:51:57 -0500 Subject: [PATCH] fix(client-go): keepalive, stream error classification, auth composition, CLI batch reuse (CGO-001..008, #257) - Dial/DialGalaxy set HTTP/2 keepalive (30 s / 10 s / PermitWithoutStream), configurable via Options.KeepAliveTime/KeepAliveTimeout (CGO-001, D7) - auth installed with chain interceptors and attached per call by Client/GalaxyClient (CGO-002) - a server-sent Canceled status or a context deadline ends a stream with a terminal error; only the caller's own cancellation is silent (CGO-003) - stream context cancelled when the stream ends (CGO-004) - dialConnected keeps the last connection error in the returned error (CGO-005) - WatchDeployEvents closes events before errs; CLI drains buffered events (CGO-006) - Register/AddItem/AddItem2 return MalformedReplyError on a payload-less reply (CGO-007) - CLI batch reuses dialed connections; bench-read-bulk backs off on failures (CGO-008) --- clients/go/GoClientDesign.md | 12 +- clients/go/README.md | 38 ++- clients/go/cmd/mxgw-go/batchcache.go | 134 +++++++++ clients/go/cmd/mxgw-go/main.go | 161 +++++++---- clients/go/cmd/mxgw-go/main_test.go | 119 ++++++++ clients/go/mxgateway/alarms.go | 4 +- clients/go/mxgateway/auth.go | 5 + clients/go/mxgateway/client.go | 64 ++++- clients/go/mxgateway/galaxy.go | 29 +- clients/go/mxgateway/galaxy_test.go | 4 + clients/go/mxgateway/options.go | 40 +++ clients/go/mxgateway/review_phase6_test.go | 302 +++++++++++++++++++++ clients/go/mxgateway/session.go | 48 +++- 13 files changed, 868 insertions(+), 92 deletions(-) create mode 100644 clients/go/cmd/mxgw-go/batchcache.go create mode 100644 clients/go/mxgateway/review_phase6_test.go diff --git a/clients/go/GoClientDesign.md b/clients/go/GoClientDesign.md index dd0d51b5..3ae236fd 100644 --- a/clients/go/GoClientDesign.md +++ b/clients/go/GoClientDesign.md @@ -54,6 +54,8 @@ type Options struct { ServerNameOverride string DialTimeout time.Duration CallTimeout time.Duration + KeepAliveTime time.Duration // default 30s; negative disables + KeepAliveTimeout time.Duration // default 10s } func Dial(ctx context.Context, opts Options) (*Client, error) @@ -94,6 +96,10 @@ authorization: Bearer ``` The interceptor should use `metadata.AppendToOutgoingContext` or call options. +Install it with `grpc.WithChainUnaryInterceptor` / `WithChainStreamInterceptor` so it +composes with caller interceptors, and have `Client` also attach the key per call so +`NewClient` over a caller-supplied connection authenticates. Dial sets HTTP/2 +keepalive (30 s ping, 10 s timeout, `PermitWithoutStream`) before `DialOptions`. Do not print API keys in errors. ## TLS @@ -132,8 +138,10 @@ type EventResult struct { } ``` -The receive goroutine exits on stream end, context cancellation, or error. The -channel should be closed exactly once. Do not reorder events. +The receive goroutine exits on stream end, context cancellation, or error, and +cancels the stream context on exit. Only a clean EOF or the caller's own +cancellation ends silently; a server-sent `Canceled` status or a deadline is a +terminal `Err`. The channel should be closed exactly once. Do not reorder events. ## Error Handling diff --git a/clients/go/README.md b/clients/go/README.md index c2ca0075..147bfd85 100644 --- a/clients/go/README.md +++ b/clients/go/README.md @@ -108,7 +108,32 @@ diagnostic that never decides the verdict. A nil entry is success. (the endpoint resolves with the `passthrough` scheme unless it names one) and then waits for the channel to become READY, bounded by `DialTimeout` (default 10 s) or the context deadline. A failure is returned as a `GatewayError` with -`Op == "dial"`. Passing a connection to `NewClient`/`NewGalaxyClient` stays lazy. +`Op == "dial"`. When the deadline expires the error still matches +`errors.Is(err, context.DeadlineExceeded)` and also carries the last connection +error (for example `connection refused` or a TLS verification failure). Passing a +connection to `NewClient`/`NewGalaxyClient` stays lazy. + +### Keepalive and authentication + +`Dial`/`DialGalaxy` enable HTTP/2 keepalive: a ping every `Options.KeepAliveTime` +(default `DefaultKeepAliveTime`, 30 s) with a `Options.KeepAliveTimeout` (default +`DefaultKeepAliveTimeout`, 10 s), sent even while no RPC is active +(`PermitWithoutStream`). Without it a stream `Recv` on a half-open connection +never returns. The gateway permits client pings at this rate by default; an +interval below the server's minimum draws a `too_many_pings` GOAWAY. A negative +`KeepAliveTime` disables it, and a `grpc.WithKeepaliveParams` in `DialOptions` +overrides it. Keepalive is a dial option, so a connection passed to `NewClient` +keeps whatever the caller configured. + +The API key is installed with the chain interceptor options, so a caller's own +`grpc.WithUnaryInterceptor` / `WithStreamInterceptor` in `DialOptions` composes +with it instead of replacing it. `Client`/`GalaxyClient` also attach +`Options.APIKey` to every call they make, so `NewClient(conn, Options{APIKey: k})` +over a shared connection authenticates; calls made directly on `RawClient()` rely on +the connection's own interceptor. + +`Register`, `AddItem` and `AddItem2` return a `*MalformedReplyError` for an OK reply +with neither the typed payload nor an int32 `return_value`, rather than handle 0. ### Event buffering @@ -406,8 +431,12 @@ for { ``` Cancel the supplied context to tear down the stream cleanly. Both channels -close after EOF, cancellation, or a terminal error; surfaced errors are wrapped -in `*GatewayError`. +close after EOF, cancellation, or a terminal error; `events` closes before `errs`, +so drain `events` and then read `errs`. A gateway-sent `Canceled` status or a context +deadline is delivered as a terminal error (only the caller's own cancellation ends +the stream silently); surfaced errors are wrapped in `*GatewayError`. The same rule +applies to `Session.Events`/`SubscribeEvents`: the stream context is also released +when the stream ends, so `EventsAfter` does not leak a context per reconnect. The CLI exposes the same RPC via `galaxy-watch`: @@ -500,6 +529,9 @@ sentinel, so a failing command does not abort the batch. The input scanner buffer is widened to 16 MiB so a single long command line (e.g. a bulk write with thousands of handles) does not trip bufio's default 64 KiB token-too-long limit; a line that still exceeds 16 MiB surfaces as a framed error and ends the session. +Consecutive lines with the same connection options reuse one dialed connection +(closed at EOF) instead of dialing per command. `bench-read-bulk` backs off +(10 ms doubling to 1 s) after consecutive failing calls instead of spinning. Use TLS options for a secured gateway. Over TLS (no `-plaintext`) with no `-ca-cert`, `mxgw-go` skips certificate verification by default (self-signed diff --git a/clients/go/cmd/mxgw-go/batchcache.go b/clients/go/cmd/mxgw-go/batchcache.go new file mode 100644 index 00000000..fc7d1524 --- /dev/null +++ b/clients/go/cmd/mxgw-go/batchcache.go @@ -0,0 +1,134 @@ +package main + +import ( + "context" + "sync" + "time" + + mxgateway "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/mxgateway" +) + +type batchCacheKey struct{} + +// batchConnection identifies one distinct connection configuration. +type batchConnection struct { + endpoint string + apiKey string + plaintext bool + caCertFile string + serverName string + requireTLS bool + timeout time.Duration +} + +func newBatchConnection(options commonOptions) batchConnection { + return batchConnection{ + endpoint: options.Endpoint, + apiKey: options.apiKeyValue, + plaintext: options.Plaintext, + caCertFile: options.CACertFile, + serverName: options.ServerName, + requireTLS: options.RequireCertificateValidation, + timeout: options.timeout, + } +} + +// batchClientCache keeps one dialed client per connection configuration for the +// lifetime of a batch run, so consecutive lines do not each pay a connection setup. +type batchClientCache struct { + mu sync.Mutex + clients map[batchConnection]*mxgateway.Client + galaxy map[batchConnection]*mxgateway.GalaxyClient +} + +func batchCacheFrom(ctx context.Context) *batchClientCache { + cache, _ := ctx.Value(batchCacheKey{}).(*batchClientCache) + return cache +} + +func (c *batchClientCache) client(ctx context.Context, options commonOptions) (*mxgateway.Client, error) { + key := newBatchConnection(options) + c.mu.Lock() + defer c.mu.Unlock() + if client, ok := c.clients[key]; ok { + return client, nil + } + client, err := mxgateway.Dial(ctx, options.dialOptions()) + if err != nil { + return nil, err + } + if c.clients == nil { + c.clients = map[batchConnection]*mxgateway.Client{} + } + c.clients[key] = client + return client, nil +} + +func (c *batchClientCache) galaxyClient(ctx context.Context, options commonOptions) (*mxgateway.GalaxyClient, error) { + key := newBatchConnection(options) + c.mu.Lock() + defer c.mu.Unlock() + if client, ok := c.galaxy[key]; ok { + return client, nil + } + client, err := mxgateway.DialGalaxy(ctx, options.dialOptions()) + if err != nil { + return nil, err + } + if c.galaxy == nil { + c.galaxy = map[batchConnection]*mxgateway.GalaxyClient{} + } + c.galaxy[key] = client + return client, nil +} + +func (c *batchClientCache) ownsClient(client *mxgateway.Client) bool { + c.mu.Lock() + defer c.mu.Unlock() + for _, cached := range c.clients { + if cached == client { + return true + } + } + return false +} + +func (c *batchClientCache) ownsGalaxyClient(client *mxgateway.GalaxyClient) bool { + c.mu.Lock() + defer c.mu.Unlock() + for _, cached := range c.galaxy { + if cached == client { + return true + } + } + return false +} + +func (c *batchClientCache) closeAll() { + c.mu.Lock() + defer c.mu.Unlock() + for _, client := range c.clients { + _ = client.Close() + } + for _, client := range c.galaxy { + _ = client.Close() + } + c.clients = nil + c.galaxy = nil +} + +// releaseClient closes a command's client unless the batch cache owns it. +func releaseClient(ctx context.Context, client *mxgateway.Client) { + if cache := batchCacheFrom(ctx); cache != nil && cache.ownsClient(client) { + return + } + _ = client.Close() +} + +// releaseGalaxyClient closes a command's Galaxy client unless the batch cache owns it. +func releaseGalaxyClient(ctx context.Context, client *mxgateway.GalaxyClient) { + if cache := batchCacheFrom(ctx); cache != nil && cache.ownsGalaxyClient(client) { + return + } + _ = client.Close() +} diff --git a/clients/go/cmd/mxgw-go/main.go b/clients/go/cmd/mxgw-go/main.go index d9dd6acf..26b13b8c 100644 --- a/clients/go/cmd/mxgw-go/main.go +++ b/clients/go/cmd/mxgw-go/main.go @@ -201,7 +201,7 @@ func runOpenSession(ctx context.Context, args []string, stdout, stderr io.Writer if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) reply, err := client.OpenSessionRaw(ctx, (&mxgateway.OpenSessionOptions{ RequestedBackend: *backend, @@ -241,7 +241,7 @@ func runCloseSession(ctx context.Context, args []string, stdout, stderr io.Write if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) reply, err := client.CloseSessionRaw(ctx, &mxgateway.CloseSessionRequest{SessionId: *sessionID}) if err != nil { @@ -278,7 +278,7 @@ func runPing(ctx context.Context, args []string, stdout, stderr io.Writer) error if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) reply, err := session.PingRaw(ctx, *message) @@ -324,7 +324,7 @@ func runRegister(ctx context.Context, args []string, stdout, stderr io.Writer) e if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) reply, err := session.RegisterRaw(ctx, *clientName) @@ -351,7 +351,7 @@ func runAddItem(ctx context.Context, args []string, stdout, stderr io.Writer) er if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) reply, err := session.AddItemRaw(ctx, int32(*serverHandle), *item) @@ -378,7 +378,7 @@ func runAdvise(ctx context.Context, args []string, stdout, stderr io.Writer) err if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) reply, err := session.AdviseRaw(ctx, int32(*serverHandle), int32(*itemHandle)) @@ -405,7 +405,7 @@ func runAdviseSupervisory(ctx context.Context, args []string, stdout, stderr io. if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) reply, err := session.AdviseSupervisoryRaw(ctx, int32(*serverHandle), int32(*itemHandle)) @@ -441,7 +441,7 @@ func runWriteSecured(ctx context.Context, args []string, stdout, stderr io.Write if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) reply, err := session.WriteSecuredRaw(ctx, int32(*serverHandle), int32(*itemHandle), int32(*currentUserID), int32(*verifierUserID), value) @@ -496,7 +496,7 @@ func runAuthenticateUser(ctx context.Context, args []string, stdout, stderr io.W if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) // The raw reply carries only the resolved user id, never the credential, so @@ -526,7 +526,7 @@ func runSubscribeBulk(ctx context.Context, args []string, stdout, stderr io.Writ if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) results, err := session.SubscribeBulk(ctx, int32(*serverHandle), parseStringList(*items)) @@ -553,7 +553,7 @@ func runUnsubscribeBulk(ctx context.Context, args []string, stdout, stderr io.Wr if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) handles, err := parseInt32List(*itemHandles) if err != nil { @@ -586,7 +586,7 @@ func runReadBulk(ctx context.Context, args []string, stdout, stderr io.Writer) e if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) results, err := session.ReadBulk(ctx, int32(*serverHandle), parseStringList(*items), time.Duration(*timeoutMs)*time.Millisecond) @@ -682,7 +682,7 @@ func runWriteBulkVariant(ctx context.Context, args []string, stdout, stderr io.W if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) @@ -777,7 +777,7 @@ func runBenchReadBulk(ctx context.Context, args []string, stdout, stderr io.Writ if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session, err := client.OpenSession(ctx, mxgateway.OpenSessionOptions{ClientSessionName: *clientName}) if err != nil { @@ -814,15 +814,21 @@ func runBenchReadBulk(ctx context.Context, args []string, stdout, stderr io.Writ // failing ReadBulk calls until the wall-clock deadline elapses. warmupDeadline := time.Now().Add(time.Duration(*warmupSeconds) * time.Second) timeout := time.Duration(*timeoutMs) * time.Millisecond + warmupFailures := 0 for time.Now().Before(warmupDeadline) && ctx.Err() == nil { - _, _ = session.ReadBulk(ctx, serverHandle, tags, timeout) + if _, err := session.ReadBulk(ctx, serverHandle, tags, timeout); err != nil { + warmupFailures++ + benchBackoff(ctx, warmupFailures) + } else { + warmupFailures = 0 + } } // Steady state: per-call latency captured via time.Now() deltas. latenciesMs := make([]float64, 0, 65536) var totalReadResults int64 var cachedReadResults int64 - var successfulCalls, failedCalls int + var successfulCalls, failedCalls, consecutiveFailures int steadyStart := time.Now() steadyDeadline := steadyStart.Add(time.Duration(*durationSeconds) * time.Second) @@ -833,8 +839,11 @@ func runBenchReadBulk(ctx context.Context, args []string, stdout, stderr io.Writ latenciesMs = append(latenciesMs, float64(elapsed.Nanoseconds())/1e6) if err != nil { failedCalls++ + consecutiveFailures++ + benchBackoff(ctx, consecutiveFailures) continue } + consecutiveFailures = 0 successfulCalls++ for _, r := range results { totalReadResults++ @@ -876,6 +885,26 @@ func runBenchReadBulk(ctx context.Context, args []string, stdout, stderr io.Writ return nil } +// benchBackoff pauses after a failed ReadBulk. A failing call returns in microseconds, so +// without a pause the loop issues failing RPCs as fast as the CPU allows and burst-loads +// the gateway when it returns (CGO-008). The delay doubles from 10 ms to a 1 s cap. +func benchBackoff(ctx context.Context, consecutiveFailures int) { + shift := consecutiveFailures + if shift > 7 { + shift = 7 + } + delay := time.Duration(10< time.Second { + delay = time.Second + } + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-timer.C: + case <-ctx.Done(): + } +} + // percentileSummary returns the same { p50, p95, p99, max, mean } shape every // language bench emits, rounded to 3 decimal places so the PowerShell driver // sees one schema across all five clients. @@ -955,7 +984,7 @@ func runWrite(ctx context.Context, args []string, stdout, stderr io.Writer) erro if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) reply, err := session.WriteRaw(ctx, int32(*serverHandle), int32(*itemHandle), value, int32(*userID)) @@ -982,7 +1011,7 @@ func runStreamEvents(ctx context.Context, args []string, stdout, stderr io.Write if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) @@ -1060,7 +1089,7 @@ func runStreamAlarms(ctx context.Context, args []string, stdout, stderr io.Write if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) // Mirror runStreamEvents so Ctrl+C on a long-running stream-alarms command // cancels the gRPC stream cleanly (the gateway sees codes.Canceled rather @@ -1161,7 +1190,7 @@ func runAcknowledgeAlarm(ctx context.Context, args []string, stdout, stderr io.W if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) reply, err := client.AcknowledgeAlarm(ctx, &mxgateway.AcknowledgeAlarmRequest{ AlarmFullReference: *reference, @@ -1204,7 +1233,7 @@ func runSmoke(ctx context.Context, args []string, stdout, stderr io.Writer) erro if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session, err := client.OpenSession(ctx, mxgateway.OpenSessionOptions{ClientSessionName: *clientName}) if err != nil { @@ -1309,15 +1338,12 @@ func dialForCommand(ctx context.Context, common *commonOptions) (*mxgateway.Clie return nil, options, err } - client, err := mxgateway.Dial(ctx, mxgateway.Options{ - Endpoint: options.Endpoint, - APIKey: options.apiKeyValue, - Plaintext: options.Plaintext, - CACertFile: options.CACertFile, - ServerNameOverride: options.ServerName, - RequireCertificateValidation: options.RequireCertificateValidation, - CallTimeout: options.timeout, - }) + if cache := batchCacheFrom(ctx); cache != nil { + client, err := cache.client(ctx, options) + return client, options, err + } + + client, err := mxgateway.Dial(ctx, options.dialOptions()) return client, options, err } @@ -1476,6 +1502,12 @@ const batchEOR = "__MXGW_BATCH_EOR__" // If a line still exceeds the cap, the error is surfaced as a per-command // error-with-sentinel and the session continues. func runBatch(ctx context.Context, in io.Reader, stdout, stderr io.Writer) error { + // One dialed client per distinct connection configuration, reused across lines instead + // of a blocking TCP/TLS/HTTP/2 dial per command (CGO-008). + cache := &batchClientCache{} + defer cache.closeAll() + ctx = context.WithValue(ctx, batchCacheKey{}, cache) + bw := bufio.NewWriter(stdout) scanner := bufio.NewScanner(in) scanner.Buffer(make([]byte, 0, 64*1024), 16*1024*1024) @@ -1526,18 +1558,27 @@ func dialGalaxyForCommand(ctx context.Context, common *commonOptions) (*mxgatewa return nil, options, err } - client, err := mxgateway.DialGalaxy(ctx, mxgateway.Options{ - Endpoint: options.Endpoint, - APIKey: options.apiKeyValue, - Plaintext: options.Plaintext, - CACertFile: options.CACertFile, - ServerNameOverride: options.ServerName, - RequireCertificateValidation: options.RequireCertificateValidation, - CallTimeout: options.timeout, - }) + if cache := batchCacheFrom(ctx); cache != nil { + client, err := cache.galaxyClient(ctx, options) + return client, options, err + } + + client, err := mxgateway.DialGalaxy(ctx, options.dialOptions()) return client, options, err } +func (o commonOptions) dialOptions() mxgateway.Options { + return mxgateway.Options{ + Endpoint: o.Endpoint, + APIKey: o.apiKeyValue, + Plaintext: o.Plaintext, + CACertFile: o.CACertFile, + ServerNameOverride: o.ServerName, + RequireCertificateValidation: o.RequireCertificateValidation, + CallTimeout: o.timeout, + } +} + func runGalaxyTestConnection(ctx context.Context, args []string, stdout, stderr io.Writer) error { flags := flag.NewFlagSet("galaxy-test-connection", flag.ContinueOnError) flags.SetOutput(stderr) @@ -1552,7 +1593,7 @@ func runGalaxyTestConnection(ctx context.Context, args []string, stdout, stderr if err != nil { return err } - defer client.Close() + defer releaseGalaxyClient(ctx, client) ok, err := client.TestConnection(ctx) if err != nil { @@ -1583,7 +1624,7 @@ func runGalaxyLastDeploy(ctx context.Context, args []string, stdout, stderr io.W if err != nil { return err } - defer client.Close() + defer releaseGalaxyClient(ctx, client) deployTime, present, err := client.GetLastDeployTime(ctx) if err != nil { @@ -1622,7 +1663,7 @@ func runGalaxyDiscover(ctx context.Context, args []string, stdout, stderr io.Wri if err != nil { return err } - defer client.Close() + defer releaseGalaxyClient(ctx, client) objects, err := client.DiscoverHierarchy(ctx) if err != nil { @@ -1670,7 +1711,7 @@ func runGalaxyWatch(ctx context.Context, args []string, stdout, stderr io.Writer if err != nil { return err } - defer client.Close() + defer releaseGalaxyClient(ctx, client) signalCtx, stopSignals := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM) defer stopSignals() @@ -1683,22 +1724,28 @@ func runGalaxyWatch(ctx context.Context, args []string, stdout, stderr io.Writer return err } + printEvent := func(event *mxgateway.DeployEvent) { + if *jsonOutput { + fmt.Fprintln(stdout, string(mustMarshalProto(event))) + } else { + fmt.Fprintln(stdout, formatDeployEvent(event)) + } + } + count := 0 + selectErrs := errs for { select { case event, ok := <-events: if !ok { - // Drain any terminal error before returning. + // events closes before errs, so the terminal error (if any) is already buffered or + // about to be: drain it before returning. if streamErr, errOk := <-errs; errOk && streamErr != nil { return streamErr } return nil } - if *jsonOutput { - fmt.Fprintln(stdout, string(mustMarshalProto(event))) - } else { - fmt.Fprintln(stdout, formatDeployEvent(event)) - } + printEvent(event) count++ if *limit > 0 && count >= *limit { cancelStream() @@ -1710,13 +1757,23 @@ func runGalaxyWatch(ctx context.Context, args []string, stdout, stderr io.Writer } return nil } - case streamErr, ok := <-errs: + case streamErr, ok := <-selectErrs: if !ok { - return nil + // A closed errs channel is not the end of the stream: events may still hold + // buffered items. Stop selecting on it and let the events branch finish + // the drain (CGO-006). + selectErrs = nil + continue + } + // The terminal error is sent after every event was queued: print what is still + // buffered before reporting it so the last events are not lost. + for event := range events { + printEvent(event) } if streamErr != nil { return streamErr } + return nil case <-signalCtx.Done(): cancelStream() // Allow goroutine to drain. @@ -1782,7 +1839,7 @@ func runGalaxyBrowse(ctx context.Context, args []string, stdout, stderr io.Write if err != nil { return err } - defer client.Close() + defer releaseGalaxyClient(ctx, client) // A specific parent → one level of children via the raw parent-scoped RPC. if *parent >= 0 { diff --git a/clients/go/cmd/mxgw-go/main_test.go b/clients/go/cmd/mxgw-go/main_test.go index 05ed4358..a8ae0193 100644 --- a/clients/go/cmd/mxgw-go/main_test.go +++ b/clients/go/cmd/mxgw-go/main_test.go @@ -7,11 +7,14 @@ import ( "flag" "net" "strings" + "sync/atomic" "testing" "time" pb "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated" "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) func TestRunVersionJSON(t *testing.T) { @@ -881,3 +884,119 @@ func TestRequireCertificateValidationFlag(t *testing.T) { t.Fatal("flag must set RequireCertificateValidation") } } + +// countingListener counts accepted connections so a test can assert connection reuse. +type countingListener struct { + net.Listener + accepts atomic.Int32 +} + +func (l *countingListener) Accept() (net.Conn, error) { + conn, err := l.Listener.Accept() + if err == nil { + l.accepts.Add(1) + } + return conn, err +} + +// TestRunBatchReusesOneConnectionAcrossLines pins CGO-008: batch mode dials once per +// connection configuration rather than once per line. +func TestRunBatchReusesOneConnectionAcrossLines(t *testing.T) { + raw, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + listener := &countingListener{Listener: raw} + server := grpc.NewServer() + pb.RegisterMxAccessGatewayServer(server, &benchFakeGateway{}) + go func() { _ = server.Serve(listener) }() + defer server.Stop() + + line := "close-session -endpoint " + raw.Addr().String() + " -plaintext -api-key k -session-id s -json\n" + var stdout, stderr bytes.Buffer + if err := runBatch(t.Context(), strings.NewReader(line+line+line), &stdout, &stderr); err != nil { + t.Fatalf("runBatch() error = %v; stderr = %s", err, stderr.String()) + } + if got := strings.Count(stdout.String(), batchEOR); got != 3 { + t.Fatalf("EOR count = %d, want 3; out = %s", got, stdout.String()) + } + if got := listener.accepts.Load(); got != 1 { + t.Fatalf("server accepted %d connections for 3 batch lines, want 1", got) + } +} + +type failingReadBulkGateway struct { + benchFakeGateway + readBulkCalls atomic.Int32 +} + +func (g *failingReadBulkGateway) Invoke(ctx context.Context, req *pb.MxCommandRequest) (*pb.MxCommandReply, error) { + if req.GetCommand().GetKind() == pb.MxCommandKind_MX_COMMAND_KIND_READ_BULK { + g.readBulkCalls.Add(1) + return nil, status.Error(codes.Unavailable, "gateway down") + } + return g.benchFakeGateway.Invoke(ctx, req) +} + +// TestRunBenchReadBulkBacksOffOnFailures pins CGO-008: failing ReadBulk calls must not +// spin as fast as the CPU allows. +func TestRunBenchReadBulkBacksOffOnFailures(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + fake := &failingReadBulkGateway{} + server := grpc.NewServer() + pb.RegisterMxAccessGatewayServer(server, fake) + go func() { _ = server.Serve(listener) }() + defer server.Stop() + + var stdout, stderr bytes.Buffer + args := []string{ + "bench-read-bulk", "-endpoint", listener.Addr().String(), "-plaintext", "-api-key", "k", + "-duration-seconds", "1", "-warmup-seconds", "0", "-bulk-size", "1", "-json", + } + if err := runWithIO(t.Context(), args, &stdout, &stderr); err != nil { + t.Fatalf("runWithIO() error = %v; stderr = %s", err, stderr.String()) + } + if calls := fake.readBulkCalls.Load(); calls > 40 { + t.Fatalf("%d failing ReadBulk calls in a 1 s window, want a bounded number (backoff)", calls) + } +} + +type watchFakeGalaxy struct { + pb.UnimplementedGalaxyRepositoryServer +} + +func (g *watchFakeGalaxy) WatchDeployEvents(_ *pb.WatchDeployEventsRequest, stream grpc.ServerStreamingServer[pb.DeployEvent]) error { + for i := 0; i < 3; i++ { + if err := stream.Send(&pb.DeployEvent{}); err != nil { + return err + } + } + return nil +} + +// TestRunGalaxyWatchPrintsEveryBufferedEventBeforeExit pins CGO-006: the CLI must not return +// on a closed error channel while events are still buffered. +func TestRunGalaxyWatchPrintsEveryBufferedEventBeforeExit(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + server := grpc.NewServer() + pb.RegisterGalaxyRepositoryServer(server, &watchFakeGalaxy{}) + go func() { _ = server.Serve(listener) }() + defer server.Stop() + + for i := 0; i < 20; i++ { + var stdout, stderr bytes.Buffer + args := []string{"galaxy-watch", "-endpoint", listener.Addr().String(), "-plaintext", "-api-key", "k", "-json"} + if err := runWithIO(t.Context(), args, &stdout, &stderr); err != nil { + t.Fatalf("runWithIO() error = %v; stderr = %s", err, stderr.String()) + } + if got := len(strings.Split(strings.TrimSpace(stdout.String()), "\n")); got != 3 { + t.Fatalf("iteration %d printed %d events, want 3; out = %q", i, got, stdout.String()) + } + } +} diff --git a/clients/go/mxgateway/alarms.go b/clients/go/mxgateway/alarms.go index b0fe2abf..25b1a56a 100644 --- a/clients/go/mxgateway/alarms.go +++ b/clients/go/mxgateway/alarms.go @@ -49,7 +49,7 @@ func (c *Client) QueryActiveAlarms(ctx context.Context, req *QueryActiveAlarmsRe return nil, errors.New("mxgateway: query active alarms request is required") } - stream, err := c.raw.QueryActiveAlarms(ctx, req) + stream, err := c.raw.QueryActiveAlarms(authContext(ctx, c.opts.APIKey), req) if err != nil { return nil, &GatewayError{Op: "query active alarms", Err: err} } @@ -72,7 +72,7 @@ func (c *Client) StreamAlarms(ctx context.Context, req *StreamAlarmsRequest) (St return nil, errors.New("mxgateway: stream alarms request is required") } - stream, err := c.raw.StreamAlarms(ctx, req) + stream, err := c.raw.StreamAlarms(authContext(ctx, c.opts.APIKey), req) if err != nil { return nil, &GatewayError{Op: "stream alarms", Err: err} } diff --git a/clients/go/mxgateway/auth.go b/clients/go/mxgateway/auth.go index b8157b9d..164c74d4 100644 --- a/clients/go/mxgateway/auth.go +++ b/clients/go/mxgateway/auth.go @@ -25,6 +25,11 @@ func authContext(ctx context.Context, apiKey string) context.Context { if apiKey == "" { return ctx } + // Idempotent: the client attaches the key per call and the dial interceptor + // may attach it again, which must not send two authorization headers. + if md, ok := metadata.FromOutgoingContext(ctx); ok && len(md.Get(authorizationHeader)) > 0 { + return ctx + } return metadata.AppendToOutgoingContext(ctx, authorizationHeader, "Bearer "+apiKey) } diff --git a/clients/go/mxgateway/client.go b/clients/go/mxgateway/client.go index 5b647cf6..c837fabb 100644 --- a/clients/go/mxgateway/client.go +++ b/clients/go/mxgateway/client.go @@ -15,6 +15,7 @@ import ( "context" "crypto/tls" "errors" + "fmt" "strings" "time" @@ -23,7 +24,9 @@ import ( "google.golang.org/grpc/connectivity" "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/durationpb" + "google.golang.org/protobuf/types/known/emptypb" ) const ( @@ -59,14 +62,7 @@ func Dial(ctx context.Context, opts Options) (*Client, error) { return nil, err } - dialOptions := []grpc.DialOption{ - grpc.WithTransportCredentials(transportCredentials), - grpc.WithUnaryInterceptor(unaryAuthInterceptor(opts.APIKey)), - grpc.WithStreamInterceptor(streamAuthInterceptor(opts.APIKey)), - } - dialOptions = append(dialOptions, opts.DialOptions...) - - conn, err := dialConnected(dialCtx, opts.Endpoint, dialOptions) + conn, err := dialConnected(dialCtx, opts.Endpoint, buildDialOptions(opts, transportCredentials)) if err != nil { return nil, &GatewayError{Op: "dial", Err: err} } @@ -74,6 +70,23 @@ func Dial(ctx context.Context, opts Options) (*Client, error) { return NewClient(conn, opts), nil } +// buildDialOptions assembles the dial options shared by Dial and DialGalaxy. The +// defaults (keepalive, auth) come before opts.DialOptions so callers can override +// keepalive. Auth is installed with the chain interceptor options, which compose +// with — rather than replace — a caller's own WithUnaryInterceptor / +// WithStreamInterceptor (CGO-002). +func buildDialOptions(opts Options, transportCredentials credentials.TransportCredentials) []grpc.DialOption { + dialOptions := []grpc.DialOption{ + grpc.WithTransportCredentials(transportCredentials), + grpc.WithChainUnaryInterceptor(unaryAuthInterceptor(opts.APIKey)), + grpc.WithChainStreamInterceptor(streamAuthInterceptor(opts.APIKey)), + } + if params, ok := opts.keepAliveParams(); ok { + dialOptions = append(dialOptions, grpc.WithKeepaliveParams(params)) + } + return append(dialOptions, opts.DialOptions...) +} + // NewClient wraps an existing gRPC connection. The caller owns closing conn // unless it calls Close on the returned Client. func NewClient(conn *grpc.ClientConn, opts Options) *Client { @@ -171,7 +184,7 @@ func (c *Client) StreamEventsRaw(ctx context.Context, req *StreamEventsRequest) return nil, errors.New("mxgateway: stream events request is required") } - stream, err := c.raw.StreamEvents(ctx, req) + stream, err := c.raw.StreamEvents(authContext(ctx, c.opts.APIKey), req) if err != nil { return nil, &GatewayError{Op: "stream events", Err: err} } @@ -193,6 +206,10 @@ func (c *Client) callContext(ctx context.Context) (context.Context, context.Canc if timeout == 0 { timeout = defaultCallTimeout } + // The API key is attached here as well as by the dial-time interceptors, so a + // client built with NewClient over a caller-supplied connection (no auth + // interceptor) still authenticates. authContext is idempotent. + ctx = authContext(ctx, c.opts.APIKey) if timeout < 0 { return ctx, func() {} } @@ -282,6 +299,7 @@ func dialConnected(ctx context.Context, endpoint string, dialOptions []grpc.Dial return nil, err } conn.Connect() + var lastCause error for { state := conn.GetState() if state == connectivity.Ready { @@ -291,9 +309,37 @@ func dialConnected(ctx context.Context, endpoint string, dialOptions []grpc.Dial _ = conn.Close() return nil, errors.New("connection shut down while connecting") } + if state == connectivity.TransientFailure { + // Keep waiting (the gateway may be restarting) but remember why the last attempt + // failed: ctx.Err() alone reports only "deadline exceeded" for a refused + // connection or a TLS verification failure (CGO-005). + if cause := connectionFailureCause(ctx, conn); cause != nil { + lastCause = cause + } + } if !conn.WaitForStateChange(ctx, state) { _ = conn.Close() + if lastCause != nil { + return nil, fmt.Errorf("%w: last connection error: %v", ctx.Err(), lastCause) + } return nil, ctx.Err() } } } + +// connectionFailureCause issues a fail-fast RPC on a channel in TRANSIENT_FAILURE. +// grpc-go does not expose the dial error directly, but a non-wait-for-ready RPC +// fails immediately with Unavailable carrying "connection error: desc = ...". The +// RPC never reaches a server, so the method name is arbitrary. +func connectionFailureCause(ctx context.Context, conn *grpc.ClientConn) error { + probeCtx, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + err := conn.Invoke(probeCtx, "/mxaccess_gateway.v1.MxAccessGateway/ConnectionProbe", &emptypb.Empty{}, &emptypb.Empty{}) + if err == nil { + return nil + } + if st, ok := status.FromError(err); ok { + return errors.New(st.Message()) + } + return err +} diff --git a/clients/go/mxgateway/galaxy.go b/clients/go/mxgateway/galaxy.go index 8d09056a..e900f5de 100644 --- a/clients/go/mxgateway/galaxy.go +++ b/clients/go/mxgateway/galaxy.go @@ -10,8 +10,6 @@ import ( pb "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated" "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/timestamppb" ) @@ -95,14 +93,7 @@ func DialGalaxy(ctx context.Context, opts Options) (*GalaxyClient, error) { return nil, err } - dialOptions := []grpc.DialOption{ - grpc.WithTransportCredentials(transportCredentials), - grpc.WithUnaryInterceptor(unaryAuthInterceptor(opts.APIKey)), - grpc.WithStreamInterceptor(streamAuthInterceptor(opts.APIKey)), - } - dialOptions = append(dialOptions, opts.DialOptions...) - - conn, err := dialConnected(dialCtx, opts.Endpoint, dialOptions) + conn, err := dialConnected(dialCtx, opts.Endpoint, buildDialOptions(opts, transportCredentials)) if err != nil { return nil, &GatewayError{Op: "dial", Err: err} } @@ -203,7 +194,7 @@ func (c *GalaxyClient) WatchDeployEventsRaw(ctx context.Context, req *WatchDeplo req = &pb.WatchDeployEventsRequest{} } - stream, err := c.raw.WatchDeployEvents(ctx, req) + stream, err := c.raw.WatchDeployEvents(authContext(ctx, c.opts.APIKey), req) if err != nil { return nil, &GatewayError{Op: "galaxy watch deploy events", Err: err} } @@ -238,8 +229,10 @@ func (c *GalaxyClient) WatchDeployEvents( events := make(chan *DeployEvent, 16) errs := make(chan error, 1) go func() { - defer close(events) + // events closes before errs (defers run last-in first-out) so a consumer that + // selects on both never sees errs close while events are still buffered (CGO-006). defer close(errs) + defer close(events) for { event, recvErr := stream.Recv() if recvErr == nil { @@ -253,12 +246,16 @@ func (c *GalaxyClient) WatchDeployEvents( if recvErr == io.EOF { return } - if status.Code(recvErr) == codes.Canceled || ctx.Err() != nil { + // Silent end only for the caller's own cancellation; a gateway-sent Canceled + // status or a context deadline is reported as a terminal error (CGO-003). + if errors.Is(ctx.Err(), context.Canceled) { return } + // errs has room for one error; a plain select against ctx.Done() could drop it + // at random when ctx has expired. select { case errs <- &GatewayError{Op: "galaxy watch deploy events", Err: recvErr}: - case <-ctx.Done(): + default: } return } @@ -480,6 +477,10 @@ func (c *GalaxyClient) callContext(ctx context.Context) (context.Context, contex if timeout == 0 { timeout = defaultCallTimeout } + // The API key is attached here as well as by the dial-time interceptors, so a + // client built with NewClient over a caller-supplied connection (no auth + // interceptor) still authenticates. authContext is idempotent. + ctx = authContext(ctx, c.opts.APIKey) if timeout < 0 { return ctx, func() {} } diff --git a/clients/go/mxgateway/galaxy_test.go b/clients/go/mxgateway/galaxy_test.go index ffa165db..c8ad98df 100644 --- a/clients/go/mxgateway/galaxy_test.go +++ b/clients/go/mxgateway/galaxy_test.go @@ -425,6 +425,7 @@ type fakeGalaxyServer struct { watchRequest *pb.WatchDeployEventsRequest watchSendInterval time.Duration watchHoldOpen bool + watchTerminalErr error browseChildrenCalls []*pb.BrowseChildrenRequest browseChildrenReplies []*pb.BrowseChildrenReply browseChildrenError error @@ -475,6 +476,9 @@ func (s *fakeGalaxyServer) WatchDeployEvents(req *pb.WatchDeployEventsRequest, s } } } + if s.watchTerminalErr != nil { + return s.watchTerminalErr + } if s.watchHoldOpen { <-stream.Context().Done() } diff --git a/clients/go/mxgateway/options.go b/clients/go/mxgateway/options.go index 173e406d..99f9ff27 100644 --- a/clients/go/mxgateway/options.go +++ b/clients/go/mxgateway/options.go @@ -7,6 +7,7 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/credentials" + "google.golang.org/grpc/keepalive" ) // Options configures gateway connections. @@ -26,6 +27,17 @@ type Options struct { // CallTimeout bounds each unary RPC; zero applies a built-in default and // negative disables the bound entirely. CallTimeout time.Duration + // KeepAliveTime is the interval between HTTP/2 keepalive pings. Zero applies + // DefaultKeepAliveTime (30 s); negative disables client keepalive. Pings are + // sent even while no RPC is active so a half-open connection under an idle + // event stream is detected. The gateway permits client pings at this rate by + // default; an interval shorter than the server's minimum draws a GOAWAY + // "too_many_pings". + KeepAliveTime time.Duration + // KeepAliveTimeout is how long to wait for a ping acknowledgement before the + // connection is closed and in-flight RPCs fail. Zero applies + // DefaultKeepAliveTimeout (10 s). + KeepAliveTimeout time.Duration // TLSConfig supplies a custom TLS configuration; takes precedence over // CACertFile when TransportCredentials is unset. TLSConfig *tls.Config @@ -45,6 +57,34 @@ type Options struct { EventBufferSize int } +// Default HTTP/2 keepalive values (D7), identical across the five gateway clients. +const ( + // DefaultKeepAliveTime is the default Options.KeepAliveTime. + DefaultKeepAliveTime = 30 * time.Second + // DefaultKeepAliveTimeout is the default Options.KeepAliveTimeout. + DefaultKeepAliveTimeout = 10 * time.Second +) + +// keepAliveParams returns the keepalive parameters for the options, and false when +// keepalive is disabled. PermitWithoutStream keeps pinging while no call is active. +func (o Options) keepAliveParams() (keepalive.ClientParameters, bool) { + if o.KeepAliveTime < 0 { + return keepalive.ClientParameters{}, false + } + params := keepalive.ClientParameters{ + Time: o.KeepAliveTime, + Timeout: o.KeepAliveTimeout, + PermitWithoutStream: true, + } + if params.Time == 0 { + params.Time = DefaultKeepAliveTime + } + if params.Timeout == 0 { + params.Timeout = DefaultKeepAliveTimeout + } + return params, true +} + // DefaultEventBufferSize is the default Options.EventBufferSize. const DefaultEventBufferSize = 1024 diff --git a/clients/go/mxgateway/review_phase6_test.go b/clients/go/mxgateway/review_phase6_test.go new file mode 100644 index 00000000..afd73daf --- /dev/null +++ b/clients/go/mxgateway/review_phase6_test.go @@ -0,0 +1,302 @@ +package mxgateway + +import ( + "context" + "errors" + "io" + "net" + "strings" + "testing" + "time" + + pb "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/grpc/test/bufconn" +) + +func TestKeepAliveDefaultsMatchDecisionD7(t *testing.T) { + params, ok := (Options{}).keepAliveParams() + if !ok { + t.Fatal("keepalive disabled by default, want enabled") + } + if params.Time != 30*time.Second || params.Timeout != 10*time.Second { + t.Fatalf("keepalive = %v / %v, want 30s / 10s", params.Time, params.Timeout) + } + if !params.PermitWithoutStream { + t.Fatal("PermitWithoutStream = false, want pings while no call is active") + } +} + +func TestKeepAliveConfigurable(t *testing.T) { + params, ok := (Options{KeepAliveTime: 45 * time.Second, KeepAliveTimeout: 5 * time.Second}).keepAliveParams() + if !ok || params.Time != 45*time.Second || params.Timeout != 5*time.Second { + t.Fatalf("keepalive = %+v ok=%v, want 45s / 5s", params, ok) + } + if _, ok := (Options{KeepAliveTime: -1}).keepAliveParams(); ok { + t.Fatal("negative KeepAliveTime should disable keepalive") + } +} + +// A caller-supplied single interceptor must compose with the auth interceptor instead of +// replacing it (CGO-002). +func TestDialAuthComposesWithCallerInterceptors(t *testing.T) { + fake := &fakeGatewayServer{} + callerSawCall := false + client, cleanup := newBufconnClientWithOptions(t, fake, Options{ + DialOptions: []grpc.DialOption{ + grpc.WithUnaryInterceptor(func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { + callerSawCall = true + return invoker(ctx, method, req, reply, cc, opts...) + }), + }, + }) + defer cleanup() + + if _, err := client.OpenSession(context.Background(), OpenSessionOptions{}); err != nil { + t.Fatalf("OpenSession() error = %v", err) + } + if !callerSawCall { + t.Fatal("caller interceptor did not run") + } + if fake.openAuth != "Bearer test-api-key" { + t.Fatalf("authorization = %q, want the API key", fake.openAuth) + } +} + +// NewClient over a caller-supplied connection has no dial-time interceptor; the client +// itself must attach Options.APIKey (CGO-002). +func TestNewClientAttachesAPIKeyWithoutDialInterceptor(t *testing.T) { + fake := &fakeGatewayServer{} + listener := bufconn.Listen(bufSize) + server := grpc.NewServer() + pb.RegisterMxAccessGatewayServer(server, fake) + go func() { _ = server.Serve(listener) }() + defer server.Stop() + conn, err := grpc.NewClient("passthrough:///bufnet", + grpc.WithTransportCredentials(insecure.NewCredentials()), + grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) })) + if err != nil { + t.Fatalf("NewClient conn: %v", err) + } + defer conn.Close() + + client := NewClient(conn, Options{APIKey: "shared-conn-key"}) + if _, err := client.OpenSession(context.Background(), OpenSessionOptions{}); err != nil { + t.Fatalf("OpenSession() error = %v", err) + } + if fake.openAuth != "Bearer shared-conn-key" { + t.Fatalf("authorization = %q, want the API key from Options", fake.openAuth) + } + // Dial-installed interceptor + per-call attach must not double the header. + fake2 := &fakeGatewayServer{} + client2, cleanup := newBufconnClient(t, fake2) + defer cleanup() + if _, err := client2.OpenSession(context.Background(), OpenSessionOptions{}); err != nil { + t.Fatalf("OpenSession() error = %v", err) + } + if fake2.openAuth != "Bearer test-api-key" { + t.Fatalf("authorization = %q", fake2.openAuth) + } +} + +// A Canceled status the gateway sends while the caller's context is live is not a clean end +// (CGO-003): the consumer must see a terminal error. +func TestEventsServerCanceledStatusIsTerminalError(t *testing.T) { + fake := &fakeGatewayServer{streamTerminalErr: status.Error(codes.Canceled, "gateway shutting down")} + client, cleanup := newBufconnClient(t, fake) + defer cleanup() + session := NewSessionForID(client, "session-1") + + events, err := session.Events(context.Background()) + if err != nil { + t.Fatalf("Events() error = %v", err) + } + var sawErr error + for result := range events { + if result.Err != nil { + sawErr = result.Err + } + } + if sawErr == nil { + t.Fatal("stream ended with no terminal error, want the Canceled status surfaced") + } + if status.Code(errors.Unwrap(sawErr)) != codes.Canceled { + t.Fatalf("terminal error = %v, want the Canceled gRPC status preserved", sawErr) + } +} + +// A context deadline that ends the stream is reported, not silent (CGO-003). +func TestEventsContextDeadlineIsTerminalError(t *testing.T) { + fake := &fakeGatewayServer{} + client, cleanup := newBufconnClient(t, fake) + defer cleanup() + session := NewSessionForID(client, "session-1") + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancel() + + events, err := session.SubscribeEvents(ctx) + if err != nil { + t.Fatalf("SubscribeEvents() error = %v", err) + } + var sawErr error + for result := range events.Events() { + if result.Err != nil { + sawErr = result.Err + } + } + if sawErr == nil { + t.Fatal("deadline ended the stream silently, want a terminal error") + } + if status.Code(errors.Unwrap(sawErr)) != codes.DeadlineExceeded { + t.Fatalf("terminal error = %v, want DeadlineExceeded", sawErr) + } +} + +// The caller's own cancellation still ends the stream with no error. +func TestEventsCallerCancelEndsSilently(t *testing.T) { + fake := &fakeGatewayServer{streamStarted: make(chan struct{})} + client, cleanup := newBufconnClient(t, fake) + defer cleanup() + session := NewSessionForID(client, "session-1") + ctx, cancel := context.WithCancel(context.Background()) + + events, err := session.Events(ctx) + if err != nil { + t.Fatalf("Events() error = %v", err) + } + <-fake.streamStarted + cancel() + for result := range events { + if result.Err != nil { + t.Fatalf("caller cancellation surfaced error %v, want a silent close", result.Err) + } + } +} + +type ctxCapturingRaw struct { + pb.MxAccessGatewayClient + streamCtx context.Context +} + +func (f *ctxCapturingRaw) StreamEvents(ctx context.Context, _ *pb.StreamEventsRequest, _ ...grpc.CallOption) (grpc.ServerStreamingClient[pb.MxEvent], error) { + f.streamCtx = ctx + return eofEventStream{}, nil +} + +type eofEventStream struct{ grpc.ClientStream } + +func (eofEventStream) Recv() (*pb.MxEvent, error) { return nil, io.EOF } + +// The stream context is released when the stream ends, not only on Close (CGO-004). +func TestEventsCancelsStreamContextOnEOF(t *testing.T) { + raw := &ctxCapturingRaw{} + client := &Client{raw: raw} + session := NewSessionForID(client, "session-1") + parent, cancel := context.WithCancel(context.Background()) + defer cancel() + + events, err := session.EventsAfter(parent, 0) + if err != nil { + t.Fatalf("EventsAfter() error = %v", err) + } + for range events { + } + deadline := time.After(2 * time.Second) + for raw.streamCtx.Err() == nil { + select { + case <-deadline: + t.Fatal("stream context still live after EOF; the per-stream cancelCtx leaks") + case <-time.After(5 * time.Millisecond): + } + } +} + +func TestDialErrorIncludesLastConnectionCause(t *testing.T) { + start := time.Now() + _, err := Dial(context.Background(), Options{ + Endpoint: "bufnet", + Plaintext: true, + DialTimeout: 1500 * time.Millisecond, + DialOptions: []grpc.DialOption{grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) { + return nil, errors.New("connection refused by test dialer") + })}, + }) + if err == nil { + t.Fatal("Dial() error = nil") + } + if !strings.Contains(err.Error(), "connection refused by test dialer") { + t.Fatalf("Dial() error = %q, want it to carry the underlying connection error", err) + } + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("Dial() error = %v, want errors.Is(DeadlineExceeded) preserved", err) + } + if time.Since(start) > 5*time.Second { + t.Fatalf("Dial() took %v", time.Since(start)) + } +} + +func TestHandleReturningCommandsRejectMissingPayload(t *testing.T) { + for _, tc := range []struct { + name string + call func(*Session) error + }{ + {"register", func(s *Session) error { _, err := s.Register(context.Background(), "c"); return err }}, + {"add item", func(s *Session) error { _, err := s.AddItem(context.Background(), 1, "Tag.A"); return err }}, + {"add item2", func(s *Session) error { _, err := s.AddItem2(context.Background(), 1, "Tag.A", "ctx"); return err }}, + } { + t.Run(tc.name, func(t *testing.T) { + fake := &fakeGatewayServer{invokeReply: &pb.MxCommandReply{SessionId: "session-1", ProtocolStatus: okStatus()}} + client, cleanup := newBufconnClient(t, fake) + defer cleanup() + err := tc.call(NewSessionForID(client, "session-1")) + var malformed *MalformedReplyError + if !errors.As(err, &malformed) { + t.Fatalf("error = %v, want *MalformedReplyError", err) + } + }) + } +} + +func TestRegisterAcceptsInt32ReturnValueWithoutPayload(t *testing.T) { + fake := &fakeGatewayServer{invokeReply: &pb.MxCommandReply{ + SessionId: "session-1", + ProtocolStatus: okStatus(), + ReturnValue: &pb.MxValue{Kind: &pb.MxValue_Int32Value{Int32Value: 7}}, + }} + client, cleanup := newBufconnClient(t, fake) + defer cleanup() + handle, err := NewSessionForID(client, "session-1").Register(context.Background(), "c") + if err != nil || handle != 7 { + t.Fatalf("Register() = %d, %v; want 7, nil", handle, err) + } +} + +// A Canceled status from the gateway while the caller's context is live is reported on the +// error channel, and events queued before it are still delivered (CGO-003, CGO-006). +func TestWatchDeployEventsServerCanceledIsReportedAfterEvents(t *testing.T) { + fake := &fakeGalaxyServer{ + watchEvents: []*pb.DeployEvent{{}, {}, {}}, + watchTerminalErr: status.Error(codes.Canceled, "gateway shutting down"), + } + client, cleanup := newGalaxyBufconnClient(t, fake) + defer cleanup() + + events, errs, err := client.WatchDeployEvents(context.Background(), nil) + if err != nil { + t.Fatalf("WatchDeployEvents() error = %v", err) + } + received := 0 + for range events { + received++ + } + if received != 3 { + t.Fatalf("received %d events, want 3", received) + } + streamErr, ok := <-errs + if !ok || streamErr == nil { + t.Fatal("no terminal error for a gateway-sent Canceled status") + } +} diff --git a/clients/go/mxgateway/session.go b/clients/go/mxgateway/session.go index b2a0223c..eb8e21e8 100644 --- a/clients/go/mxgateway/session.go +++ b/clients/go/mxgateway/session.go @@ -13,8 +13,6 @@ import ( "time" pb "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" ) const maxBulkItems = 1000 @@ -143,7 +141,13 @@ func (s *Session) Register(ctx context.Context, clientName string) (int32, error if reply.GetRegister() != nil { return reply.GetRegister().GetServerHandle(), nil } - return reply.GetReturnValue().GetInt32Value(), nil + if x, ok := reply.GetReturnValue().GetKind().(*pb.MxValue_Int32Value); ok { + return x.Int32Value, nil + } + return 0, &MalformedReplyError{ + Op: "register", + Detail: "reply carried neither a Register payload nor an int32 return_value", + } } // RegisterRaw invokes MXAccess Register and returns the raw reply. @@ -199,7 +203,13 @@ func (s *Session) AddItem(ctx context.Context, serverHandle int32, itemDefinitio if reply.GetAddItem() != nil { return reply.GetAddItem().GetItemHandle(), nil } - return reply.GetReturnValue().GetInt32Value(), nil + if x, ok := reply.GetReturnValue().GetKind().(*pb.MxValue_Int32Value); ok { + return x.Int32Value, nil + } + return 0, &MalformedReplyError{ + Op: "add item", + Detail: "reply carried neither a AddItem payload nor an int32 return_value", + } } // AddItemRaw invokes MXAccess AddItem and returns the raw reply. @@ -228,7 +238,13 @@ func (s *Session) AddItem2(ctx context.Context, serverHandle int32, itemDefiniti if reply.GetAddItem2() != nil { return reply.GetAddItem2().GetItemHandle(), nil } - return reply.GetReturnValue().GetInt32Value(), nil + if x, ok := reply.GetReturnValue().GetKind().(*pb.MxValue_Int32Value); ok { + return x.Int32Value, nil + } + return 0, &MalformedReplyError{ + Op: "add item2", + Detail: "reply carried neither a AddItem2 payload nor an int32 return_value", + } } // AddItem2Raw invokes MXAccess AddItem2 and returns the raw reply. @@ -1118,6 +1134,10 @@ func (s *Session) subscribeEventsAfter(ctx context.Context, afterWorkerSequence results := make(chan EventResult, dataSlots+eventBufferReservedSlots) done := make(chan struct{}) go func() { + // Release the stream context when the stream ends (EOF or terminal error), not only + // on EventSubscription.Close: Events/EventsAfter hand the caller no handle, so + // without this each reconnect leaves a child context attached to ctx (CGO-004). + defer cancel() defer close(results) defer close(done) for { @@ -1136,7 +1156,12 @@ func (s *Session) subscribeEventsAfter(ctx context.Context, afterWorkerSequence } continue } - if err == io.EOF || status.Code(err) == codes.Canceled || streamCtx.Err() != nil { + // Silent end only for a clean server end or the caller's own cancellation. A + // Canceled status while the context is still live was produced by the gateway + // (session closed/killed, shutdown), and a context deadline is not a clean end + // either: both are delivered as a terminal error so the consumer can tell them + // from the session simply closing (CGO-003). + if err == io.EOF || errors.Is(streamCtx.Err(), context.Canceled) { return } // A genuine terminal stream error must be reported as itself, even @@ -1178,11 +1203,14 @@ func ensureBulkSize(name string, length int) error { // silently drop the terminal error, breaking the never-drop contract; instead // block until the consumer drains a slot (or the stream context is cancelled). func sendTerminalEventResult(ctx context.Context, results chan<- EventResult, result EventResult, cancelWhenBufferFull bool) { + // Prefer a free slot: when ctx is already done (a deadline ended the stream), a plain + // select between the send and ctx.Done() could randomly drop the terminal error. + select { + case results <- result: + return + default: + } if cancelWhenBufferFull { - select { - case results <- result: - default: - } return } select {