refactor(staterpc,releaseupdate,agentexec,storecontract,worktree): cut comments down to what the code does

This commit is contained in:
sam committed 2026-10-03 22:00:43 +10:00
1 parent ee5f59e189
commit 2fc11b60e1
22 files changed
+175 -822

No files matched your search

+2 -12
View File
@@ -11,24 +11,14 @@ import (
// Metadata, never a URL.
const tokenMetadataKey = "state-store-token"
// UnaryClientTokenInterceptor attaches token to every outgoing call's
// metadata under tokenMetadataKey. One token covers a task's container
// lifetime so it does not need to be
// refreshed mid-connection. Used by the agent's long-lived client
// connection to the State Store's bridge-address listener.
// UnaryClientTokenInterceptor attaches token to every outgoing call.
func UnaryClientTokenInterceptor(token string) grpc.UnaryClientInterceptor {
return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
return invoker(metadata.AppendToOutgoingContext(ctx, tokenMetadataKey, token), method, req, reply, cc, opts...)
}
}
// StreamClientTokenInterceptor attaches token to the outgoing stream's
// context, covering the server-streaming read RPCs (StreamCaptures,
// StreamUndispatchedCaptures) the unary interceptor cannot see. Without it
// those calls reach a token-protected listener with no credential and the
// server's stream interceptor refuses them, leaving the capture batch reads
// -- the ones moved onto streams precisely so a large batch crosses -- with
// no working path.
// StreamClientTokenInterceptor attaches token to every outgoing stream.
func StreamClientTokenInterceptor(token string) grpc.StreamClientInterceptor {
return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
return streamer(metadata.AppendToOutgoingContext(ctx, tokenMetadataKey, token), desc, cc, method, opts...)
+2 -5
View File
@@ -114,11 +114,8 @@ func (c *Client) Transition(ctx context.Context, taskID int64, from, to, detail
return unmapError(err)
}
// StartStep and FinishStep record the run's step executions
// under the run credential, which
// the State Store's grant interceptor scopes to the execution the requests
// name. Each returns the transition's persisted event for the caller's
// post-commit publish.
// StartStep and FinishStep record step executions and return the persisted
// event.
func (c *Client) StartStep(ctx context.Context, s task.StepStart) (int64, events.Event, error) {
r, err := c.client.StartStep(ctx, &pb.StartStepRequest{
ExecutionId: s.ExecutionID, Attempt: int64(s.Attempt),
+11 -85
View File
@@ -11,16 +11,9 @@ import (
"google.golang.org/grpc/keepalive"
)
// Dial returns a State Store contract client for target, applying the
// transport security boundary: a
// loopback target dials insecure with no credential, while a non-loopback
// target requires a bearer token and fails closed without one. The returned
// cleanup closes the connection; Client.Close is a no-op because the store
// service owns its own DB lifecycle.
//
// The rule lives here rather than in a composition root so the server side
// (which decides whether to install the token interceptors) and every client
// that dials it share one implementation.
// Dial returns a State Store client for target. A loopback target dials
// insecure; any other target requires a token. The cleanup closes the
// connection.
func Dial(target, token string, options ...grpc.DialOption) (*Client, func(), error) {
target = strings.TrimSpace(target)
if target == "" {
@@ -38,24 +31,7 @@ func Dial(target, token string, options ...grpc.DialOption) (*Client, func(), er
}
opts := []grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
// Client keepalive. grpc-go's default client keepalive time is
// infinity (internal/transport.defaultClientKeepaliveTime), so a
// connection that half-opens under an idle client -- peer gone, socket
// still ESTABLISHED -- produces no error here. That is load-bearing for
// this dial because the control-plane Watch stream is silent by design
// while the watched resource's version is unchanged
// (internal/app/controlplane's Watch): with neither peer writing,
// neither notices, and the caller's watch stays frozen for the life of
// the process with no error and no log.
//
// Time 10s is the soonest a dead peer can be detected: gRPC clamps a
// client ping interval up to internal.KeepaliveMinPingTime (10s), and
// 10s of connection-level silence costs one HTTP/2 PING, which is far
// below the traffic this link already carries (the store service polls
// its store every 250ms per watch). Timeout 5s bounds detection at
// ~15s: a PING the peer does not ACK within 5s tears the transport
// down, turning a half-open connection into a stream error the caller
// can act on.
// Keepalive detects a dead peer on an otherwise silent watch stream.
grpc.WithKeepaliveParams(ClientKeepaliveParams()),
}
if token != "" {
@@ -75,18 +51,8 @@ func Dial(target, token string, options ...grpc.DialOption) (*Client, func(), er
return NewClient(conn), func() { _ = conn.Close() }, nil
}
// ClientKeepaliveParams are the client keepalive settings Dial installs; see
// Dial's option comment for why each value is what it is. PermitWithoutStream
// is deliberately left false (the library default): the pings this dial needs
// are covered by an active stream, and pinging a connection with no streams is
// what a peer's keepalive enforcement policy records as a ping strike --
// against the State Store's default policy a streamless ping draws GOAWAY
// too_many_pings and would churn connections that are healthy today.
//
// It is the dialer's half of the keepalive agreement with
// ServerKeepalivePolicy, so it is exported: the side that installs a server
// option reads the interval this dialer actually pings at from here rather
// than restating it.
// ClientKeepaliveParams are Dial's keepalive settings: ping after 10s idle,
// 5s timeout, no pings without streams.
func ClientKeepaliveParams() keepalive.ClientParameters {
return keepalive.ClientParameters{
Time: 10 * time.Second,
@@ -100,50 +66,13 @@ func ClientKeepaliveParams() keepalive.ClientParameters {
// ServerKeepaliveOption carries the arithmetic.
const serverKeepaliveMinTime = 5 * time.Second
// ServerKeepaliveOption returns the server half of the keepalive agreement
// Dial's clients enter, for the composition that serves the State Store
// contract to install on its grpc.Server (internal/app/archied's
// stateStoreServerOpts installs it on every listener).
//
// The two sides have to agree on one number. A ping arriving less than
// EnforcementPolicy.MinTime after the previous ping is a strike, and the server
// answers the third strike with GOAWAY too_many_pings (maxPingStrikes is 2; a
// write on that transport is what resets the counter). grpc's default policy
// MinTime is 5 minutes while the client above pings every 10 seconds, so a
// connection that carries no write for ~40s -- which is what a watch is while
// the watched resource's version is unchanged -- is torn down where before the
// client keepalive existed it stayed up. A process that writes on the same
// transport every 30s (the apply-status re-stamp, applystatus.RestampInterval)
// resets the counter often enough to hide this; an idle connection is what it
// kills, and a keepalive that disconnects is worse than no keepalive.
//
// MinTime is 5s, half the client's ping interval. The client's interval is the
// larger of its Time and grpc's KeepaliveMinPingTime clamp -- 10s, so no caller
// can ask for faster pings -- and its keepalive loop arms its timer Time ahead
// and re-arms it only later, on read activity, so consecutive pings are never
// closer than ~10s apart. A 5s floor thus separates every ping from a strike by
// a factor of two, worth more than Go's timer granularity and any scheduling
// delay, which can only push pings further apart. A MinTime of 10s would sit
// exactly on the boundary the clamp already enforces, where a ping a
// microsecond early is a strike; 5 minutes is the defect itself.
//
// The floor is not a blanket exemption: a ping arriving less than 5s after the
// previous one, and any ping on a connection with no stream, still strikes.
// PermitWithoutStream stays false, matching the client, which never pings a
// connection with no streams: every client this server has is a staterpc.Dial
// -- the daemon's control-plane client, the archie-ui dashboard, archie-
// messaging and the archie-agent container -- so permitting streamless pings
// would only relax a setting none of them exercises.
// ServerKeepaliveOption returns the server keepalive enforcement matching
// Dial's clients: pings at least 5s apart are allowed while a stream is open.
func ServerKeepaliveOption() grpc.ServerOption {
return grpc.KeepaliveEnforcementPolicy(ServerKeepalivePolicy())
}
// ServerKeepalivePolicy returns the policy ServerKeepaliveOption installs as a
// value. A grpc.ServerOption is a closure over unexported grpc state with no
// accessor, so the option cannot be read back once built; this value is
// therefore the handle the agreement is held to -- a caller installing the
// option can assert the policy it is built from, and ClientKeepaliveParams
// gives the interval that policy must stay below.
// ServerKeepalivePolicy returns the policy ServerKeepaliveOption installs.
func ServerKeepalivePolicy() keepalive.EnforcementPolicy {
return keepalive.EnforcementPolicy{
MinTime: serverKeepaliveMinTime,
@@ -151,11 +80,8 @@ func ServerKeepalivePolicy() keepalive.EnforcementPolicy {
}
}
// TargetIsLoopback reports whether addr's host is a loopback address. Both
// literal loopback IPs (127.0.0.1, ::1) and the "localhost" hostname count;
// everything else (including the wildcard 0.0.0.0 and DNS names) is treated
// as network-reachable and therefore non-loopback. It applies to a listen
// address and a dial target alike -- the same host decides both.
// TargetIsLoopback reports whether addr's host is a loopback IP or
// "localhost".
func TargetIsLoopback(addr string) (bool, error) {
host, _, err := net.SplitHostPort(addr)
if err != nil {
+5 -24
View File
@@ -43,12 +43,7 @@ var (
errBindingTaskCreatorUnavailable = status.Error(codes.Unavailable, "binding task creator unavailable")
errPlaybookDispatcherUnavailable = status.Error(codes.Unavailable, "playbook dispatcher unavailable")
errWorkflowCallerUnavailable = status.Error(codes.Unavailable, "workflow caller unavailable")
// errTaskLogsUnavailable is the "this process cannot read task logs at
// all" answer, and it is deliberately distinct from a found=false read
// result: only the first is a deployment matter. A dashboard that receives
// this reports that the log cannot be read here; it must never turn it
// into "task logging was not enabled for this run", which is what the
// absent-handle path used to do.
// errTaskLogsUnavailable reports that this process cannot read task logs.
errTaskLogsUnavailable = status.Error(codes.Unavailable, msgTaskLogsUnavailable)
)
@@ -129,12 +124,8 @@ type Deps struct {
// Denials records and lists denial records. Optional: nil disables the
// pair with codes.Unavailable.
Denials access.DenialStore
// TaskLogs reads one task attempt's persisted log out of the state
// directory this process owns. Optional, and nil is the honest default for
// a store service that shares no state directory with the daemon:
// ReadTaskLog then answers codes.Unavailable, which the dashboard reports
// as "this process cannot read logs" rather than as "this attempt has no
// log". Conflating those two is the bug this contract exists to fix.
// TaskLogs reads task attempt logs. Nil answers ReadTaskLog with
// Unavailable.
TaskLogs storecontract.TaskLogStore
Log *slog.Logger
}
@@ -165,13 +156,7 @@ func (s *server) logErr(rpc string, err error) error {
return mapError(err)
}
// validationFailure answers a write the owning feature's own Validate refused.
// The domain-managed kinds (identities, captures, mappings, bindings) are
// advertised in the control-plane catalog but are not stored as generic
// documents, so it is these RPC handlers -- not the catalog -- that must apply
// the feature's rule. The rule itself stays in the domain package; this only
// translates its error for the wire, and it is deliberately not codes.Internal
// (an unjudged value is the caller's fault, not this process's).
// validationFailure maps a domain validation error to InvalidArgument.
func validationFailure(err error) error {
return status.Error(codes.InvalidArgument, err.Error())
}
@@ -221,11 +206,7 @@ func (s *server) Transition(ctx context.Context, r *pb.TransitionRequest) (*pb.T
return &pb.TransitionResponse{}, nil
}
// StartStep and FinishStep are the step-execution writes.
// Each is the store's own
// transaction -- guarded row write plus the event row -- and the store's
// response carries the persisted event back for the caller's post-commit
// publish.
// StartStep and FinishStep write a step transition and return its event.
func (s *server) StartStep(ctx context.Context, r *pb.StartStepRequest) (*pb.StartStepResponse, error) {
if s.deps.Steps == nil {
return nil, status.Error(codes.Unavailable, "step recorder unavailable")
@@ -91,20 +91,14 @@ func (g *TaskGrants) taskFor(token string) int64 {
}
// authorizesTaskScopedCall reports whether a task-scoped token may make this
// call: only when the RPC is in taskScopedTargets and targets taskID. Every
// other RPC, including grant registration, is refused, so a task grant only
// narrows. workflow.call and step-execution writes carry the caller's own task
// ID; the handler checks step membership, so this never reads the database.
// call: only RPCs in taskScopedTargets that target taskID.
func authorizesTaskScopedCall(fullMethod string, req any, taskID int64) bool {
target := taskScopedTargets[fullMethod]
return target != nil && target(req) == taskID
}
// taskScopedTargets maps each RPC a task grant may ever authorize to the
// function naming the task ID its request targets (0 for a request it cannot
// read). Held as data so the sanctioned widenings stop growing a switch: a
// new authorized RPC registers one row here, and the deny-by-default rule
// above covers everything else.
// taskScopedTargets maps each RPC a task grant may call to the task ID its
// request targets.
var taskScopedTargets = map[string]func(any) int64{
pb.StateStoreService_Update_FullMethodName: func(req any) int64 {
r, ok := req.(*pb.UpdateRequest)
+7 -46
View File
@@ -41,15 +41,7 @@ func timeValue(t *timestamppb.Timestamp) time.Time {
return t.AsTime()
}
// mapValues maps a slice of proto values to domain values, always returning a
// non-nil result for empty input.
//
// Protobuf decodes an empty `repeated` field to nil, and Go marshals a nil
// slice to JSON null rather than []. Returning nil here made every decoded
// collection field's JSON type depend on whether it happened to have contents,
// and made the wire path disagree with the local path, which normalises its own
// slices. []B{} for empty input keeps the shape stable at every call site
// without making each one remember to guard.
// mapValues maps a slice, returning an empty non-nil slice for empty input.
func mapValues[A, B any](in []A, f func(A) B) []B {
if len(in) == 0 {
return []B{}
@@ -417,27 +409,13 @@ const (
// errors.Is on the client without changing behaviour visibly.
msgRereviewCapReached = "store: re-review cap reached"
msgInternal = "state store: internal error"
// msgTaskLogsUnavailable is the public phrase for "this service has no
// task-log reader". It is a wire contract like the sentinels above: the
// client rehydrates logging.ErrTaskLogsUnavailable from (Unavailable, this
// message), and a caller depends on that to tell "this process cannot read
// logs" from "this attempt has no log".
// msgTaskLogsUnavailable is part of the wire contract for
// ErrTaskLogsUnavailable.
msgTaskLogsUnavailable = "task log reader unavailable"
)
// mapError converts a store sentinel error into a structured gRPC status
// carrying a short, public, stable message -- never the raw wrapped chain
// (which may contain SQL, provider detail, or secrets). Infra errors map to
// codes.Internal with a sanitised message; the caller is expected to log the
// full error server-side before calling mapError.
//
// A context cancellation/deadline raised by the store must retain its identity,
// not be folded into codes.Internal: gRPC-Go surfaces
// context.Canceled/DeadlineExceeded to the client only for those exact codes,
// and the agent's workflow consumer depends on errors.Is(err,
// context.DeadlineExceeded) to distinguish an interrupted stage from a failed
// one. So a context error maps to its own gRPC code (and unmapError rehydrates
// it back to the sentinel).
// mapError converts a store sentinel to a gRPC status with a stable public
// message; other errors become Internal. Context errors keep their codes.
func mapError(err error) error {
if err == nil {
return nil
@@ -456,25 +434,8 @@ func mapError(err error) error {
return status.Error(codes.Internal, msgInternal)
}
// unmapError rehydrates a gRPC status error back to the store sentinel it
// came from, so a caller's errors.Is(err, storecontract.ErrX) keeps working across
// the wire. A non-status error (e.g. a transport failure) is returned
// unchanged.
//
// The deadline/cancel identity must survive too: the agent's
// deadlineStore bounds each Store call with context.WithTimeout, and the
// workflow consumer checks errors.Is(err, context.DeadlineExceeded) to
// decide whether a stage was interrupted by shutdown rather than failed
// (workflow.go). gRPC-Go surfaces an expired or cancelled context as a
// *status.Error whose code is DeadlineExceeded or Canceled, so we rehydrate
// those back to the standard context sentinels -- otherwise the consumer
// would (wrongly) park a task that was merely interrupted.
//
// Unavailable carries one message this package owns: the absent task-log
// reader. It is rehydrated for the same reason the error sentinels are --
// the dashboard's whole bug was rendering "this process cannot read logs" as
// "the attempt has no log", and only the typed error makes that distinction
// available to a caller.
// unmapError turns a gRPC status back into its store sentinel, context error
// or ErrTaskLogsUnavailable. Non-status errors are returned unchanged.
func unmapError(err error) error {
if err == nil {
return nil