perf: support fastpath in dbauthz GetLatestWorkspaceBuildByWorkspaceID (#21047)

This PR piggy backs on the agent API cached workspace added in earlier PRs to provide a fast path for avoiding `GetWorkspaceByID` calls in `GetLatestWorkspaceBuildByWorkspaceID` via injection of the workspaces RBAC object into the context. We can do this from the `agentConnectionMonitor` easily since we already cache the workspace.

---------

Signed-off-by: Callum Styan <callumstyan@gmail.com>
This commit is contained in:
Callum Styan
2025-12-09 15:53:52 -08:00
committed by GitHub
parent a59a84b2a7
commit 27c3ec072e
4 changed files with 118 additions and 4 deletions
+20
View File
@@ -1,9 +1,13 @@
package agentapi
import (
"context"
"sync"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
)
// CachedWorkspaceFields contains workspace data that is safe to cache for the
@@ -50,3 +54,19 @@ func (cws *CachedWorkspaceFields) AsWorkspaceIdentity() (database.WorkspaceIdent
}
return cws.identity, true
}
// ContextInject attempts to inject the rbac object for the cached workspace fields
// into the given context, either returning the wrapped context or the original.
func (cws *CachedWorkspaceFields) ContextInject(ctx context.Context) (context.Context, error) {
var err error
rbacCtx := ctx
if dbws, ok := cws.AsWorkspaceIdentity(); ok {
rbacCtx, err = dbauthz.WithWorkspaceRBAC(ctx, dbws.RBACObject())
if err != nil {
// Don't error level log here, will exit the function. We want to fall back to GetWorkspaceByAgentID.
//nolint:gocritic
return ctx, xerrors.Errorf("Cached workspace was present but RBAC object was invalid: %w", err)
}
}
return rbacCtx, nil
}