Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Skip empty TrueNAS app stats and explain session disposal

pulse-triage[bot]b8cc3b44f8b7
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index a8a2e2ebed..c7ba9d2954 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -196,6 +196,47 @@ server, opening-context cancellation, concurrent controls/RPCs and sender dispos
cycles, completion timestamps and unchanged failure backoff. These are synthetic
runtime proofs, not native firmware timeout or reporter-resolution evidence.
+### TrueNAS empty app inventories and session-disposal evidence
+
+An empty or null `app.query`/legacy `/app` result remains a successful empty
+app inventory. It must not request `app.stats`: there is no workload to enrich,
+and a stopped Apps service must not consume the operation budget or dispose of
+an otherwise usable monitoring session just to enrich no rows. Nonempty app
+inventories retain best-effort stats enrichment. This removes a needless
+subscription path reported in #2396; it does not establish the exact
+`notify_unsubscribed` envelope or resolve rejection with nonempty inventories.
+Unrecognised stream notifications remain bounded by the existing operation
+timeout, not classified as a known subscription's rejection without evidence.
+
+The one permitted stream transport retry uses the same disposal rules as the
+initial exchange. Malformed events, empty subscription IDs and failed
+unsubscribe cleanup discard the second session and report disconnected status;
+normal app-log idle completion returns the collected tail and discards its
+timed-out socket rather than surfacing an internal consumed-session sentinel.
+No extra retry, action replay or REST downgrade is introduced.
+
+Each authenticated socket's first local disposal records an INFO event with
+`component=truenas_rpc`, `action=close_session`, a fixed `reason`, authenticated
+`session_age`, and optional request-method/error-category classifications. Causes
+distinguish client closure, stream completion/error, transport error and failed
+keepalive writes. Error categories distinguish timeout, cancellation, method,
+transport and protocol errors. No error text, params, subscription ID, endpoint,
+username or credential is logged. Keepalive failure may precede a subsequent
+poll's disposal, so that first cause must be preserved and logged only once.
+These are local close-path observations, not appliance/proxy diagnoses or
+evidence that #2400's minute-by-minute reauthentication has been resolved. There
+is still no fixed session-age or per-poll closure policy.
+
+Verification in `internal/truenas/transport_test.go`:
+`TestJSONRPCEmptyAppsDoNotSubscribeToStats`,
+`TestLegacyRESTEmptyAppsDoNotNegotiateStats`, the snapshot inventory contract,
+`TestJSONRPCStreamRetryDiscardsUnusableSecondSession`,
+`TestJSONRPCStreamRetryReturnsCompletedLogTail`, `TestRPCSessionCloseDetails`,
+`TestRPCSessionCloseLogIsBoundedAndSecretFree` and
+`TestRPCSessionCloseLogKeepsFirstKeepaliveCause`. These controlled runtime tests
+preserve inventory, retry limits, fresh-session recovery and log confidentiality;
+native SCALE behaviour, published delivery and field acceptance remain separate.
+
### TrueNAS reporting summaries preserve raw History — issue #2346
diff --git a/internal/truenas/client.go b/internal/truenas/client.go
index 6ad3e11046..ada44b00fb 100644
--- a/internal/truenas/client.go
+++ b/internal/truenas/client.go
@@ -260,7 +260,7 @@ func (c *Client) GetSystemTelemetry(ctx context.Context) (*SystemInfo, error) {
}
telemetry, err = rpc.readSystemTelemetryEvent(ctx, defaultRealtimeIntervalSeconds)
if err != nil {
- return discardRPCSessionForStreamError(err)
+ return discardRPCSessionForStreamError("reporting.realtime", err)
}
return rpc.unsubscribe(ctx, subscriptionID)
})
@@ -1743,12 +1743,18 @@ func (c *Client) getAppsREST(ctx context.Context) ([]App, error) {
}
func (c *Client) parseAppsWithStats(ctx context.Context, response []map[string]any) []App {
+ apps := make([]App, 0, len(response))
+ // There is nothing to enrich when app.query returns an empty inventory.
+ // Subscribing anyway can wait on a stopped Apps service and needlessly
+ // discard an otherwise healthy, persistent monitoring session.
+ if len(response) == 0 {
+ return apps
+ }
statsByApp, err := c.GetAppStats(ctx)
if err != nil {
statsByApp = nil
}
- apps := make([]App, 0, len(response))
for _, item := range response {
activeWorkloads := readMapAny(item, "active_workloads", "activeWorkloads")
@@ -1813,7 +1819,7 @@ func (c *Client) GetAppStats(ctx context.Context) (map[string]AppStats, error) {
}
stats, err = rpc.readAppStatsEvent(ctx, defaultAppStatsIntervalSeconds)
if err != nil {
- return discardRPCSessionForStreamError(err)
+ return discardRPCSessionForStreamError("app.stats", err)
}
return rpc.unsubscribe(ctx, subscriptionID)
})
@@ -1869,7 +1875,7 @@ func (c *Client) GetAppLogs(ctx context.Context, appName, containerID string, ta
var reusable bool
lines, reusable, err = rpc.readAppLogEvents(ctx, tailLines)
if err != nil {
- return discardRPCSessionForStreamError(err)
+ return discardRPCSessionForStreamError("app.container_log_follow", err)
}
if !reusable {
return errRPCStreamSessionConsumed
@@ -2335,6 +2341,8 @@ func appendDiskTemperature(out map[string]int, diskName string, value any) {
type trueNASRPCClient struct {
conn *websocket.Conn
nextID int64
+ openedAt time.Time
+ closeOnce sync.Once
keepaliveStop chan struct{}
keepaliveDone chan struct{}
}
@@ -2346,7 +2354,7 @@ func (c *trueNASRPCClient) subscribe(ctx context.Context, event string) (string,
}
subscriptionID = strings.TrimSpace(subscriptionID)
if subscriptionID == "" {
- return "", &discardRPCSessionError{err: fmt.Errorf("truenas rpc core.subscribe returned an empty subscription id")}
+ return "", &discardRPCSessionError{method: "core.subscribe", err: fmt.Errorf("truenas rpc core.subscribe returned an empty subscription id")}
}
return subscriptionID, nil
}
@@ -2357,7 +2365,7 @@ func (c *trueNASRPCClient) unsubscribe(ctx context.Context, subscriptionID strin
return fmt.Errorf("truenas rpc subscription id is required")
}
if err := c.call(ctx, "core.unsubscribe", []any{subscriptionID}, nil); err != nil {
- return &discardRPCSessionError{err: fmt.Errorf("unsubscribe %q: %w", subscriptionID, err)}
+ return &discardRPCSessionError{method: "core.unsubscribe", err: fmt.Errorf("unsubscribe %q: %w", subscriptionID, err)}
}
return nil
}
diff --git a/internal/truenas/transport.go b/internal/truenas/transport.go
index 16f1093e0f..bee97cd715 100644
--- a/internal/truenas/transport.go
+++ b/internal/truenas/transport.go
@@ -12,6 +12,7 @@ import (
"time"
"github.com/gorilla/websocket"
+ "github.com/rs/zerolog/log"
)
var errRPCStreamSessionConsumed = errors.New("truenas rpc stream session cannot be reused")
@@ -60,7 +61,8 @@ func (c *Client) rpcOperationContext(ctx context.Context) (context.Context, cont
}
type discardRPCSessionError struct {
- err error
+ method string
+ err error
}
func (e *discardRPCSessionError) Error() string {
@@ -69,7 +71,7 @@ func (e *discardRPCSessionError) Error() string {
func (e *discardRPCSessionError) Unwrap() error { return e.err }
-func discardRPCSessionForStreamError(err error) error {
+func discardRPCSessionForStreamError(method string, err error) error {
if err == nil {
return nil
}
@@ -77,7 +79,7 @@ func discardRPCSessionForStreamError(err error) error {
if errors.As(err, &transportErr) {
return err
}
- return &discardRPCSessionError{err: err}
+ return &discardRPCSessionError{method: method, err: err}
}
// TransportMode is the connection-local API transport selected for an
@@ -326,6 +328,7 @@ func (c *Client) openAuthenticatedRPC(ctx context.Context) (*trueNASRPCClient, s
_ = conn.Close()
return nil, "", err
}
+ rpc.openedAt = time.Now()
rpc.startKeepalive(25 * time.Second)
return rpc, authMechanism, nil
}
@@ -354,13 +357,13 @@ func (c *Client) withRPC(ctx context.Context, operation func(context.Context, *t
}
if err := operation(ctx, c.rpc); err != nil {
if errors.Is(err, errRPCStreamSessionConsumed) {
- c.closeRPCLocked()
+ c.discardRPCLocked("stream_complete", err)
c.reconnect = 0
return nil
}
var discardErr *discardRPCSessionError
if errors.As(err, &discardErr) {
- c.closeRPCLocked()
+ c.discardRPCLocked("stream_error", err)
c.recordTransportError(err)
return err
}
@@ -369,7 +372,7 @@ func (c *Client) withRPC(ctx context.Context, operation func(context.Context, *t
c.recordRPCOperationError(err)
return err
}
- c.closeRPCLocked()
+ c.discardRPCLocked("transport_error", err)
c.recordTransportError(err)
if err := c.waitReconnectBackoff(ctx); err != nil {
return err
@@ -390,9 +393,18 @@ func (c *Client) withRPC(ctx context.Context, operation func(context.Context, *t
status.LastError = ""
})
if err := operation(ctx, c.rpc); err != nil {
+ if errors.Is(err, errRPCStreamSessionConsumed) {
+ c.discardRPCLocked("stream_complete", err)
+ c.reconnect = 0
+ return nil
+ }
+ var secondDiscardErr *discardRPCSessionError
var secondTransportErr *RPCTransportError
- if errors.As(err, &secondTransportErr) {
- c.closeRPCLocked()
+ if errors.As(err, &secondDiscardErr) {
+ c.discardRPCLocked("stream_error", err)
+ c.recordTransportError(err)
+ } else if errors.As(err, &secondTransportErr) {
+ c.discardRPCLocked("transport_error", err)
c.recordTransportError(err)
} else {
c.recordRPCOperationError(err)
@@ -442,7 +454,7 @@ func (c *Client) callRPCWithRetry(ctx context.Context, method string, params any
return err
}
- c.closeRPCLocked()
+ c.discardRPCLocked("transport_error", err)
c.recordTransportError(err)
if !retryRead {
return fmt.Errorf("truenas action %s transport failed after dispatch; outcome is unknown and Pulse will not replay it: %w", method, err)
@@ -470,7 +482,7 @@ func (c *Client) callRPCWithRetry(ctx context.Context, method string, params any
if err := c.rpc.call(ctx, method, params, result); err != nil {
var secondTransportErr *RPCTransportError
if errors.As(err, &secondTransportErr) {
- c.closeRPCLocked()
+ c.discardRPCLocked("transport_error", err)
c.recordTransportError(err)
} else {
c.recordRPCOperationError(err)
@@ -502,7 +514,13 @@ func (c *Client) waitReconnectBackoff(ctx context.Context) error {
}
func (c *Client) closeRPCLocked() {
+ c.discardRPCLocked("client_closed", nil)
+}
+
+func (c *Client) discardRPCLocked(reason string, err error) {
if c.rpc != nil && c.rpc.conn != nil {
+ method, category := rpcSessionCloseDetails(err)
+ c.rpc.closeSocket(reason, method, category)
c.rpc.close()
}
c.rpc = nil
@@ -531,7 +549,7 @@ func (c *trueNASRPCClient) startKeepalive(interval time.Duration) {
if err := c.conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(5*time.Second)); err != nil {
// Unblock any in-flight reader; ordinary transport handling owns retry
// and status, including the no-replay rule for actions.
- _ = c.conn.Close()
+ c.closeSocket("keepalive_write_error", "", "transport_error")
return
}
}
@@ -544,12 +562,68 @@ func (c *trueNASRPCClient) close() {
if c.keepaliveStop != nil {
close(c.keepaliveStop)
}
- _ = c.conn.Close()
+ c.closeSocket("client_closed", "", "")
if c.keepaliveDone != nil {
<-c.keepaliveDone
}
}
+// Record the first local disposal cause, including an idle keepalive failure
+// which may precede the next poll. Never log wire errors, params, subscription
+// IDs, endpoints or credentials. These fixed classifications explain a close;
+// they do not diagnose the appliance or proxy that caused an exchange to fail.
+func (c *trueNASRPCClient) closeSocket(reason, method, category string) {
+ c.closeOnce.Do(func() {
+ event := log.Info().
+ Str("component", "truenas_rpc").
+ Str("action", "close_session").
+ Str("reason", reason)
+ if !c.openedAt.IsZero() {
+ event.Dur("session_age", time.Since(c.openedAt))
+ }
+ if method != "" {
+ event.Str("method", method)
+ }
+ if category != "" {
+ event.Str("category", category)
+ }
+ event.Msg("Closing TrueNAS RPC session")
+ _ = c.conn.Close()
+ })
+}
+
+func rpcSessionCloseDetails(err error) (method, category string) {
+ if err == nil {
+ return "", ""
+ }
+ if errors.Is(err, errRPCStreamSessionConsumed) {
+ return "app.container_log_follow", "idle_timeout"
+ }
+ var discardErr *discardRPCSessionError
+ var transportErr *RPCTransportError
+ var rpcErr *RPCError
+ if errors.As(err, &discardErr) {
+ method = discardErr.method
+ } else if errors.As(err, &transportErr) {
+ method = transportErr.Method
+ } else if errors.As(err, &rpcErr) {
+ method = rpcErr.Method
+ }
+ switch {
+ case errors.Is(err, context.Canceled):
+ category = "cancelled"
+ case errors.Is(err, context.DeadlineExceeded) || isTimeoutError(err):
+ category = "timeout"
+ case errors.As(err, &rpcErr):
+ category = "method_error"
+ case errors.As(err, &transportErr):
+ category = "transport_error"
+ default:
+ category = "protocol_error"
+ }
+ return method, category
+}
+
func (c *Client) recordTransportError(err error) {
message := c.sanitizeTransportError(err)
c.updateTransportStatus(func(status *TransportStatus) {
diff --git a/internal/truenas/transport_test.go b/internal/truenas/transport_test.go
index 00d284e872..cdbf583517 100644
--- a/internal/truenas/transport_test.go
+++ b/internal/truenas/transport_test.go
@@ -1,6 +1,7 @@
package truenas
import (
+ "bytes"
"context"
"encoding/json"
"errors"
@@ -16,6 +17,8 @@ import (
"time"
"github.com/gorilla/websocket"
+ "github.com/rs/zerolog"
+ "github.com/rs/zerolog/log"
)
type protocolFixtureReply struct {
@@ -786,8 +789,8 @@ func TestJSONRPCFetchSnapshotUsesPublishedTrueNAS26MethodsWithoutREST(t *testing
subscribeCalls := methodCalls["core.subscribe"]
unsubscribeCalls := methodCalls["core.unsubscribe"]
methodCallsMu.Unlock()
- if subscribeCalls != 2 || unsubscribeCalls != 2 {
- t.Fatalf("subscription lifecycle calls: subscribe=%d unsubscribe=%d, want 2/2", subscribeCalls, unsubscribeCalls)
+ if subscribeCalls != 1 || unsubscribeCalls != 1 {
+ t.Fatalf("subscription lifecycle calls: subscribe=%d unsubscribe=%d, want 1/1 (realtime only for empty apps)", subscribeCalls, unsubscribeCalls)
}
if fixture.sessions.Load() != 1 || fixture.restRequests.Load() != 0 {
t.Fatalf("snapshot sessions=%d REST=%d, want one modern session and no REST",
@@ -1419,3 +1422,272 @@ func TestJSONRPCSnapshotContinuesAfterTelemetryTimeout(t *testing.T) {
t.Fatalf("inventory did not recover on RPC after discarding the stream: sessions=%d rest=%d", fixture.sessions.Load(), fixture.restRequests.Load())
}
}
+
+func TestJSONRPCEmptyAppsDoNotSubscribeToStats(t *testing.T) {
+ var appQueries, statsSubscriptions atomic.Int32
+ fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
+ switch request.Method {
+ case "auth.login_ex":
+ return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
+ case "app.query":
+ if appQueries.Add(1) == 1 {
+ return protocolFixtureReply{result: nil}
+ }
+ return protocolFixtureReply{result: []any{}}
+ case "core.subscribe":
+ statsSubscriptions.Add(1)
+ // Deliberately silent stats on an appliance with no apps. The final
+ // client must never issue this request, even with a cancellation-only
+ // caller context like the production poller.
+ return protocolFixtureReply{result: "unavailable-apps"}
+ case "system.info":
+ return protocolFixtureReply{result: map[string]any{"hostname": "empty-app-nas", "version": "TrueNAS-SCALE-25.04.2.6"}}
+ default:
+ t.Errorf("unexpected method %s", request.Method)
+ return protocolFixtureReply{close: true}
+ }
+ }, nil)
+ client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user", Timeout: 100 * time.Millisecond})
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ for i := 0; i < 2; i++ {
+ apps, err := client.GetApps(ctx)
+ if err != nil || apps == nil || len(apps) != 0 {
+ t.Fatalf("empty app query %d did not preserve an empty successful inventory", i)
+ }
+ }
+ if statsSubscriptions.Load() != 0 {
+ t.Fatal("empty inventory still issued a stats subscription")
+ }
+ if _, err := client.GetSystemInfo(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if fixture.sessions.Load() != 1 || fixture.restRequests.Load() != 0 || !client.TransportStatus().Connected {
+ t.Fatal("empty apps discarded the healthy authenticated session or changed transport")
+ }
+}
+
+func TestLegacyRESTEmptyAppsDoNotNegotiateStats(t *testing.T) {
+ var appQueries atomic.Int32
+ fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
+ t.Errorf("empty legacy app inventory issued RPC method %s", request.Method)
+ return protocolFixtureReply{close: true}
+ }, func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/v2.0/app" {
+ t.Errorf("unexpected legacy path %s", r.URL.Path)
+ return
+ }
+ appQueries.Add(1)
+ _ = json.NewEncoder(w).Encode([]any{})
+ })
+ client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key"})
+ // Negotiation is covered separately; isolate the already-selected legacy
+ // inventory path here, so no attempted JSON-RPC stats lookup is hidden.
+ client.mode = TransportLegacyREST
+ apps, err := client.GetApps(context.Background())
+ if err != nil || apps == nil || len(apps) != 0 || appQueries.Load() != 1 || fixture.sessions.Load() != 0 {
+ t.Fatal("empty legacy app inventory did not stay a single REST read")
+ }
+}
+
+func TestJSONRPCStreamRetryDiscardsUnusableSecondSession(t *testing.T) {
+ for _, failure := range []string{"malformed_event", "empty_subscription", "unsubscribe_error"} {
+ t.Run(failure, func(t *testing.T) {
+ var subscribes atomic.Int32
+ fixture := newProtocolFixture(t, func(session int, request trueNASRPCRequest) protocolFixtureReply {
+ switch request.Method {
+ case "auth.login_ex":
+ return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
+ case "core.subscribe":
+ subscribes.Add(1)
+ if session == 1 {
+ return protocolFixtureReply{close: true}
+ }
+ if failure == "empty_subscription" {
+ return protocolFixtureReply{result: ""}
+ }
+ var fields any = []any{map[string]any{"app_name": "fixture-app", "cpu_usage": 3}}
+ if failure == "malformed_event" {
+ fields = "invalid-fields"
+ }
+ return protocolFixtureReply{result: "private-subscription-id", notifications: []protocolFixtureNotification{{method: "collection_update", params: map[string]any{"collection": "app.stats:{\"interval\":2}", "fields": fields}}}}
+ case "core.unsubscribe":
+ return protocolFixtureReply{err: &trueNASRPCError{Code: -32001, Message: "fixture-method-error"}}
+ case "pool.query":
+ if session != 3 {
+ t.Error("next read reused an unusable second stream session")
+ }
+ return protocolFixtureReply{result: []any{}}
+ default:
+ t.Errorf("unexpected method %s", request.Method)
+ return protocolFixtureReply{close: true}
+ }
+ }, nil)
+ client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user"})
+ if _, err := client.GetAppStats(context.Background()); err == nil {
+ t.Fatal("bad second stream session appeared successful")
+ }
+ if client.TransportStatus().Connected {
+ t.Fatal("unusable second stream session remained connected")
+ }
+ if client.rpc != nil {
+ t.Fatal("unusable second stream session was retained")
+ }
+ if _, err := client.GetPools(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if subscribes.Load() != 2 || fixture.sessions.Load() != 3 || fixture.restRequests.Load() != 0 {
+ t.Fatal("stream retry/disposal changed its retry limit or downgraded transport")
+ }
+ })
+ }
+}
+
+func TestJSONRPCStreamRetryReturnsCompletedLogTail(t *testing.T) {
+ fixture := newProtocolFixture(t, func(session int, request trueNASRPCRequest) protocolFixtureReply {
+ switch request.Method {
+ case "auth.login_ex":
+ return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
+ case "core.subscribe":
+ if session == 1 {
+ return protocolFixtureReply{close: true}
+ }
+ return protocolFixtureReply{result: "fixture-log-sub", notifications: []protocolFixtureNotification{{method: "collection_update", params: map[string]any{"collection": "app.container_log_follow:{}", "fields": []any{map[string]any{"data": "fixture-line"}}}}}}
+ case "pool.query":
+ if session != 3 {
+ t.Error("timed-out log socket was reused")
+ }
+ return protocolFixtureReply{result: []any{}}
+ default:
+ t.Errorf("unexpected method %s", request.Method)
+ return protocolFixtureReply{close: true}
+ }
+ }, nil)
+ client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user"})
+ lines, err := client.GetAppLogs(context.Background(), "fixture-app", "fixture-container", 100)
+ if err != nil || len(lines) != 1 || lines[0].Data != "fixture-line" {
+ t.Fatal("completed retry lost its log tail or returned a consumed-session sentinel")
+ }
+ if client.TransportStatus().Connected || client.rpc != nil {
+ t.Fatal("completed retry kept a timed-out log socket")
+ }
+ if _, err := client.GetPools(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if fixture.sessions.Load() != 3 || fixture.restRequests.Load() != 0 {
+ t.Fatal("next read did not open exactly one fresh modern session")
+ }
+}
+
+func TestRPCSessionCloseDetails(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ err error
+ method, category string
+ }{
+ {"explicit", nil, "", ""},
+ {"idle tail", errRPCStreamSessionConsumed, "app.container_log_follow", "idle_timeout"},
+ {"timeout", &RPCTransportError{Method: "pool.query", Phase: "read", Err: context.DeadlineExceeded}, "pool.query", "timeout"},
+ {"cancel", &RPCTransportError{Method: "app.start", Phase: "read", Err: context.Canceled}, "app.start", "cancelled"},
+ {"transport", &RPCTransportError{Method: "system.info", Phase: "read", Err: errors.New("private-error-text")}, "system.info", "transport_error"},
+ {"stream decode", &discardRPCSessionError{method: "app.stats", err: errors.New("private-event-text")}, "app.stats", "protocol_error"},
+ {"unsubscribe refusal", &discardRPCSessionError{method: "core.unsubscribe", err: &RPCError{Method: "core.unsubscribe", Message: "private-wire-message"}}, "core.unsubscribe", "method_error"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ method, category := rpcSessionCloseDetails(tc.err)
+ if method != tc.method || category != tc.category {
+ t.Fatalf("close classification = %s/%s, want %s/%s", method, category, tc.method, tc.category)
+ }
+ })
+ }
+}
+
+func captureRPCCloseLogs(t *testing.T) *bytes.Buffer {
+ t.Helper()
+ var output bytes.Buffer
+ previous := log.Logger
+ log.Logger = zerolog.New(&output)
+ t.Cleanup(func() { log.Logger = previous })
+ return &output
+}
+
+func rpcCloseLogRecords(t *testing.T, output *bytes.Buffer) []map[string]any {
+ t.Helper()
+ var records []map[string]any
+ decoder := json.NewDecoder(bytes.NewReader(output.Bytes()))
+ for decoder.More() {
+ var record map[string]any
+ if err := decoder.Decode(&record); err != nil {
+ t.Fatal("close log is not structured JSON")
+ }
+ records = append(records, record)
+ }
+ return records
+}
+
+func TestRPCSessionCloseLogIsBoundedAndSecretFree(t *testing.T) {
+ output := captureRPCCloseLogs(t)
+ fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
+ switch request.Method {
+ case "auth.login_ex":
+ return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
+ case "core.subscribe":
+ return protocolFixtureReply{result: "private-subscription-id", notifications: []protocolFixtureNotification{{method: "collection_update", params: map[string]any{"collection": "app.stats:{\"interval\":2}", "fields": []any{}}}}}
+ case "core.unsubscribe":
+ return protocolFixtureReply{err: &trueNASRPCError{Code: -32001, Message: "private-wire-message private-api-key private-password private-subscription-id"}}
+ default:
+ return protocolFixtureReply{close: true}
+ }
+ }, nil)
+ client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "private-api-key", Password: "private-password", Username: "private-owner"})
+ if _, err := client.GetAppStats(context.Background()); err == nil {
+ t.Fatal("fixture did not fail its unsubscribe")
+ }
+ client.Close()
+ records := rpcCloseLogRecords(t, output)
+ if len(records) != 1 {
+ t.Fatalf("close records = %d, want exactly one for disposal and subsequent Close", len(records))
+ }
+ record := records[0]
+ if record["reason"] != "stream_error" || record["method"] != "core.unsubscribe" || record["category"] != "method_error" || record["component"] != "truenas_rpc" || record["action"] != "close_session" {
+ t.Fatal("close log lost its fixed local cause")
+ }
+ if _, ok := record["session_age"].(float64); !ok {
+ t.Fatal("close log lost the authenticated session age")
+ }
+ for _, private := range []string{"private-api-key", "private-password", "private-owner", "private-wire-message", "private-subscription-id", fixture.server.URL} {
+ if bytes.Contains(output.Bytes(), []byte(private)) {
+ t.Fatal("close log contains private wire/configuration data")
+ }
+ }
+ for key := range record {
+ switch key {
+ case "component", "action", "reason", "method", "category", "session_age", "level", "message":
+ default:
+ t.Fatalf("unexpected close log field %s", key)
+ }
+ }
+}
+
+func TestRPCSessionCloseLogKeepsFirstKeepaliveCause(t *testing.T) {
+ output := captureRPCCloseLogs(t)
+ fixture := newProtocolFixture(t, func(_ int, _ trueNASRPCRequest) protocolFixtureReply { return protocolFixtureReply{result: true} }, nil)
+ client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{})
+ conn, err := client.dialRPC(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ rpc := &trueNASRPCClient{conn: conn, nextID: 1, openedAt: time.Now()}
+ rpc.startKeepalive(time.Millisecond)
+ _ = conn.Close() // Inject a control-write failure, without an RPC payload.
+ select {
+ case <-rpc.keepaliveDone:
+ case <-time.After(time.Second):
+ t.Fatal("failed keepalive did not stop")
+ }
+ rpc.close()
+ records := rpcCloseLogRecords(t, output)
+ if len(records) != 1 || records[0]["reason"] != "keepalive_write_error" || records[0]["category"] != "transport_error" {
+ t.Fatal("later client disposal overwrote or duplicated the first keepalive close cause")
+ }
+}