Skip to content

Commit 109ad40

Browse files
committed
feat(bigtable): add Session primitives (AttemptOutcome, vRPC ctx, msgtype)
Adds the standalone types that the Session struct and its lifecycle / vRPC / debug halves all depend on. Each file is self-contained (no cross-references) so this PR compiles and passes tests on its own. - attempt_outcome.go — AttemptState (StateUncommitted / StateTransportFailure / StateServerResult), tagErr, TagErr, ClassifyErr. Models Java's VRpc.VRpcResult.State so the RetryingVRpc interceptor (later PR) can classify errors the same way as java-bigtable. - vrpc.go — ctx-metadata helpers (WithVRpcMetadata, WithAttempt, VRpcAttempt, VRpcMethod, WithPrevAttemptErr, PrevAttemptErr). Session Invoke reads these from its ctx. - session_msgtype.go — reqMsgType / respMsgType enums + classifyReq / classifyResp helpers. Used by the debug surface + tracer to bucket Session request/response types. Part 3a/3c of the Session core sub-split (a follow-up to the original Session core PR #20112, which is being reshaped into three thinner PRs). Stacks on #20115 (metrics.TransportTypeName export) and #20114 (debug tag counter); each of those can merge in any order.
1 parent 25127e3 commit 109ad40

5 files changed

Lines changed: 491 additions & 0 deletions

File tree

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
// Copyright 2026 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package internal
16+
17+
import "errors"
18+
19+
// AttemptState classifies how far a single vRPC attempt progressed before
20+
// terminating. RetryingVRpc consumes this instead of raw gRPC codes so
21+
// retry decisions match Java's VRpc.VRpcResult.State semantics:
22+
//
23+
// - Uncommitted: safe to retry unconditionally (server saw nothing).
24+
// - TransportFailure: safe only for idempotent ops (server may have applied).
25+
// - ServerResult: retry only if the server explicitly permits it via
26+
// RetryInfo, or the code is in the narrowed always-retryable set.
27+
type AttemptState int
28+
29+
const (
30+
// StateServerResult is the zero value: any bare error from a code
31+
// path that hasn't yet adopted tagErr (or an error introduced by a
32+
// non-vRPC layer) classifies here. Under the strict Java-parity
33+
// default (see shouldRetryDefault in retrying.go) StateServerResult
34+
// does NOT retry unless the server explicitly attached RetryInfo or
35+
// the caller set RetryingOptions.ShouldRetry to override the whole
36+
// classifier. Callers that need a permissive fallback must opt in.
37+
StateServerResult AttemptState = iota
38+
// StateUncommitted means the attempt never reached the wire — encode
39+
// failed, session was Closing, etc. Retry is safe regardless of
40+
// idempotency.
41+
StateUncommitted
42+
// StateTransportFailure means the frame was handed to the transport but
43+
// we never observed a server response — the server may or may not have
44+
// processed it. Retry only for idempotent ops.
45+
StateTransportFailure
46+
)
47+
48+
func (s AttemptState) String() string {
49+
switch s {
50+
case StateUncommitted:
51+
return "Uncommitted"
52+
case StateTransportFailure:
53+
return "TransportFailure"
54+
case StateServerResult:
55+
return "ServerResult"
56+
}
57+
return "Unknown"
58+
}
59+
60+
// AttemptOutcome pairs the classification with the underlying error so
61+
// callers can inspect both. Err is always non-nil for a failed attempt.
62+
type AttemptOutcome struct {
63+
State AttemptState
64+
Err error
65+
}
66+
67+
// vrpcErr wraps a raw error with its outcome so RetryingVRpc can classify
68+
// by state. Unwrap() exposes the underlying err so status.FromError(err) and
69+
// errors.Is(err, ...) continue to work for callers that don't know about
70+
// the wrapper.
71+
type vrpcErr struct {
72+
outcome AttemptOutcome
73+
}
74+
75+
func (e *vrpcErr) Error() string { return e.outcome.Err.Error() }
76+
func (e *vrpcErr) Unwrap() error { return e.outcome.Err }
77+
78+
// tagErr wraps err with the given AttemptState. Returns nil for nil err so
79+
// call sites can compose without extra guards.
80+
func tagErr(state AttemptState, err error) error {
81+
if err == nil {
82+
return nil
83+
}
84+
return &vrpcErr{outcome: AttemptOutcome{State: state, Err: err}}
85+
}
86+
87+
// TagErr wraps err with the given AttemptState so callers outside this
88+
// package can produce errors that carry the same classifier hint the
89+
// real transport attaches. Intended for test doubles / fakes that stand
90+
// in for a Session or a SessionPool: production errors from Session.Invoke
91+
// are always tagged (see session_vrpc.go, session_pool.go), so a test's
92+
// fake Invoker must tag its errors the same way for the RetryingVRpc
93+
// interceptor's default classification to see them.
94+
//
95+
// Returns nil for nil err. Wraps unwrap()-transparently — errors.Is and
96+
// status.FromError continue to see the underlying err.
97+
func TagErr(state AttemptState, err error) error { return tagErr(state, err) }
98+
99+
// ClassifyErr returns the outcome for any error. Untagged errors fall
100+
// through as StateServerResult — which, under the current default, is
101+
// NOT retryable without server-attached RetryInfo. Callers that produce
102+
// errors on paths where retry is expected must tag with the appropriate
103+
// state via tagErr (see session_vrpc.go for the reference call sites).
104+
func ClassifyErr(err error) AttemptOutcome {
105+
if err == nil {
106+
return AttemptOutcome{}
107+
}
108+
var v *vrpcErr
109+
if errors.As(err, &v) {
110+
return v.outcome
111+
}
112+
return AttemptOutcome{State: StateServerResult, Err: err}
113+
}
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
// Copyright 2026 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package internal
16+
17+
import (
18+
"errors"
19+
"fmt"
20+
"testing"
21+
)
22+
23+
func TestAttemptState_String(t *testing.T) {
24+
tests := []struct {
25+
s AttemptState
26+
want string
27+
}{
28+
{StateServerResult, "ServerResult"},
29+
{StateUncommitted, "Uncommitted"},
30+
{StateTransportFailure, "TransportFailure"},
31+
{AttemptState(99), "Unknown"},
32+
}
33+
for _, tt := range tests {
34+
if got := tt.s.String(); got != tt.want {
35+
t.Errorf("AttemptState(%d).String() = %q, want %q", int(tt.s), got, tt.want)
36+
}
37+
}
38+
}
39+
40+
// TestTagErr_NilPassesThrough guarantees callers can compose without extra
41+
// guards: tagErr(state, nil) must return nil regardless of state.
42+
func TestTagErr_NilPassesThrough(t *testing.T) {
43+
if got := tagErr(StateUncommitted, nil); got != nil {
44+
t.Errorf("tagErr(StateUncommitted, nil) = %v, want nil", got)
45+
}
46+
if got := TagErr(StateTransportFailure, nil); got != nil {
47+
t.Errorf("TagErr(StateTransportFailure, nil) = %v, want nil", got)
48+
}
49+
}
50+
51+
// TestTagErr_WrapsAndUnwraps verifies the wrapper is transparent to
52+
// errors.Is and errors.Unwrap so upstream callers that don't know about
53+
// the AttemptOutcome tagging still see the original sentinel.
54+
func TestTagErr_WrapsAndUnwraps(t *testing.T) {
55+
sentinel := errors.New("sentinel")
56+
wrapped := tagErr(StateUncommitted, fmt.Errorf("wrap: %w", sentinel))
57+
58+
if !errors.Is(wrapped, sentinel) {
59+
t.Error("errors.Is should see the underlying sentinel through the tagErr wrapper")
60+
}
61+
if wrapped.Error() == "" {
62+
t.Error("wrapped error should have non-empty message")
63+
}
64+
}
65+
66+
// TestClassifyErr_Cases covers the three branches: nil, tagged, and
67+
// untagged. Untagged errors default to StateServerResult (retry only with
68+
// server-attached RetryInfo — Java-parity behavior).
69+
func TestClassifyErr_Cases(t *testing.T) {
70+
// Nil error → zero outcome.
71+
if got := ClassifyErr(nil); got.State != StateServerResult || got.Err != nil {
72+
t.Errorf("ClassifyErr(nil) = %+v, want zero-value outcome", got)
73+
}
74+
75+
// Tagged error → preserves state and err.
76+
inner := errors.New("boom")
77+
tagged := tagErr(StateTransportFailure, inner)
78+
out := ClassifyErr(tagged)
79+
if out.State != StateTransportFailure {
80+
t.Errorf("ClassifyErr(tagged).State = %v, want StateTransportFailure", out.State)
81+
}
82+
if !errors.Is(out.Err, inner) {
83+
t.Errorf("ClassifyErr(tagged).Err should preserve inner, got %v", out.Err)
84+
}
85+
86+
// Untagged error → StateServerResult fallback with err preserved.
87+
untagged := errors.New("plain")
88+
out = ClassifyErr(untagged)
89+
if out.State != StateServerResult {
90+
t.Errorf("ClassifyErr(untagged).State = %v, want StateServerResult", out.State)
91+
}
92+
if out.Err != untagged {
93+
t.Errorf("ClassifyErr(untagged).Err = %v, want %v", out.Err, untagged)
94+
}
95+
}
96+
97+
// TestClassifyErr_FindsThroughWrapper ensures errors.As-style traversal
98+
// works even when the tagErr wrapper is buried behind another fmt.Errorf.
99+
func TestClassifyErr_FindsThroughWrapper(t *testing.T) {
100+
tagged := tagErr(StateUncommitted, errors.New("x"))
101+
outer := fmt.Errorf("outer: %w", tagged)
102+
out := ClassifyErr(outer)
103+
if out.State != StateUncommitted {
104+
t.Errorf("ClassifyErr(outer-wrapped).State = %v, want StateUncommitted", out.State)
105+
}
106+
}
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
// Copyright 2026 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package internal
16+
17+
import spb "cloud.google.com/go/bigtable/apiv2/bigtablepb"
18+
19+
// reqMsgType / respMsgType label the oneof payload variants of
20+
// SessionRequest / SessionResponse. They're used as indices into the fixed
21+
// per-session atomic-counter arrays so the breakdown stays lock-free.
22+
//
23+
// The "other" bucket catches frames whose oneof is unset or carries a
24+
// payload type we haven't enumerated here (forward-compat with new server
25+
// frames). Add new values BEFORE numReq/Resp so the totals stay aligned
26+
// with the array size.
27+
type reqMsgType int
28+
29+
const (
30+
reqMsgOpenSession reqMsgType = iota
31+
reqMsgVirtualRpc
32+
reqMsgCloseSession
33+
reqMsgOther
34+
numReqMsgTypes
35+
)
36+
37+
func (t reqMsgType) String() string {
38+
switch t {
39+
case reqMsgOpenSession:
40+
return "OpenSession"
41+
case reqMsgVirtualRpc:
42+
return "VirtualRpc"
43+
case reqMsgCloseSession:
44+
return "CloseSession"
45+
default:
46+
return "other"
47+
}
48+
}
49+
50+
func classifyReq(req *spb.SessionRequest) reqMsgType {
51+
if req == nil {
52+
return reqMsgOther
53+
}
54+
switch req.GetPayload().(type) {
55+
case *spb.SessionRequest_OpenSession:
56+
return reqMsgOpenSession
57+
case *spb.SessionRequest_VirtualRpc:
58+
return reqMsgVirtualRpc
59+
case *spb.SessionRequest_CloseSession:
60+
return reqMsgCloseSession
61+
default:
62+
return reqMsgOther
63+
}
64+
}
65+
66+
type respMsgType int
67+
68+
const (
69+
respMsgOpenSession respMsgType = iota
70+
respMsgVirtualRpc
71+
respMsgError
72+
respMsgSessionParameters
73+
respMsgHeartbeat
74+
respMsgGoAway
75+
respMsgSessionRefreshConfig
76+
respMsgOther
77+
numRespMsgTypes
78+
)
79+
80+
func (t respMsgType) String() string {
81+
switch t {
82+
case respMsgOpenSession:
83+
return "OpenSession"
84+
case respMsgVirtualRpc:
85+
return "VirtualRpc"
86+
case respMsgError:
87+
return "Error"
88+
case respMsgSessionParameters:
89+
return "SessionParameters"
90+
case respMsgHeartbeat:
91+
return "Heartbeat"
92+
case respMsgGoAway:
93+
return "GoAway"
94+
case respMsgSessionRefreshConfig:
95+
return "SessionRefreshConfig"
96+
default:
97+
return "other"
98+
}
99+
}
100+
101+
func classifyResp(resp *spb.SessionResponse) respMsgType {
102+
if resp == nil {
103+
return respMsgOther
104+
}
105+
switch resp.GetPayload().(type) {
106+
case *spb.SessionResponse_OpenSession:
107+
return respMsgOpenSession
108+
case *spb.SessionResponse_VirtualRpc:
109+
return respMsgVirtualRpc
110+
case *spb.SessionResponse_Error:
111+
return respMsgError
112+
case *spb.SessionResponse_SessionParameters:
113+
return respMsgSessionParameters
114+
case *spb.SessionResponse_Heartbeat:
115+
return respMsgHeartbeat
116+
case *spb.SessionResponse_GoAway:
117+
return respMsgGoAway
118+
case *spb.SessionResponse_SessionRefreshConfig:
119+
return respMsgSessionRefreshConfig
120+
default:
121+
return respMsgOther
122+
}
123+
}

0 commit comments

Comments
 (0)
⌂ 换网址