Files
archie/internal/infrastructure/controlplanestore/controlplane.go
T
sam 161e8f95bf perf(store): share one control-plane version read across all watchers (#1858)
The control-plane Watch was a 250 ms database poll per subscription: an idle instance ran about 180 transactions a second (archied 14 streams, gateway 5, dashboard 26), almost all sequential scans of the small resources table. The State Store now keeps one shared view of every stored resource version, read once per 250 ms window and reused by every Watch stream; a stream reads its own resource only when its kind's version advanced, so idle database work is one read per interval for the whole process whatever the subscriber count.

The watch contract is unchanged: resume from AfterVersion, no missed update (versions are monotonic per org and kind), the immediate seed probe, the same 250 ms latency bound (streams wake on the same window boundary), and a store error still ends the stream with Unavailable so the clients' existing reconnect backoff applies.
2026-11-11 03:03:37 +11:00

252 lines
10 KiB
Go

// Package controlplanestore owns control-plane resource registration, dispatch, and validation.
package controlplanestore
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/samcharles93/archie-core/internal/config"
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
)
// The control-plane wire sentinels cross gRPC matched on (code, canonical
// message), so their definitions live with the contract in
// internal/infrastructure/controlplanerpc. These are the same values re-exported,
// so every existing caller keeps one name and errors.Is keeps matching identity.
var (
ErrValidation = controlplanerpc.ErrValidation
ErrNotFound = controlplanerpc.ErrNotFound
ErrVersionConflict = controlplanerpc.ErrVersionConflict
ErrUnavailable = controlplanerpc.ErrUnavailable
)
// ResourceStore is the persistence the control plane requires. The composition
// root asserts the State Store against it, so this is the single definition of
// what a control-plane backing store must offer.
type ResourceStore interface {
ListResources(context.Context) ([]storecontract.Resource, error)
Resource(ctx context.Context, orgID, kind string) (storecontract.Resource, error)
ResourceHistory(ctx context.Context, orgID, kind string, limit int) ([]storecontract.Resource, error)
PutResource(context.Context, storecontract.ResourceWrite) (storecontract.Resource, error)
}
// defaultHistoryLimit caps an unbounded request. A settings resource edited
// daily for a year still fits, and the dashboard pages rather than streams.
const defaultHistoryLimit = 200
type Server struct {
pb.UnimplementedControlPlaneServiceServer
store ResourceStore
watch watchSnapshot
definitions map[string]Definition
ordered []Definition
steps workflow.StepRegistry
}
// NewServer builds the control plane server the State Store serves. steps is
// the workflow step vocabulary the composition root registered; this is the
// validating side of the vocabulary archie-agent executes against in a
// matching build (see stepRegistry: a skewed deploy can still disagree).
func NewServer(resources ResourceStore, steps *workflow.Manager) (*Server, error) {
registry, err := stepRegistry(steps)
if err != nil {
return nil, err
}
definitions := builtinDefinitions(registry, steps.Settings())
byKind := make(map[string]Definition, len(definitions))
for _, definition := range definitions {
byKind[definition.Kind] = definition
}
return &Server{store: resources, definitions: byKind, ordered: definitions, steps: registry}, nil
}
// Catalog advertises the resources the caller's org can use. A definition is
// instance-only when the runtime layers it from the system org's copy alone,
// so another org would be offered a control whose write is refused; hide it
// there. Query and Command still enforce the same rule server-side.
func (s *Server) Catalog(ctx context.Context, _ *pb.CatalogRequest) (*pb.CatalogResponse, error) {
instanceOrg := requestOrg(ctx) == storecontract.DefaultOrgID
descriptors := make([]*pb.ResourceDescriptor, 0, len(s.ordered)+len(domainManagedDescriptors()))
for _, definition := range s.ordered {
if instanceOnlyKinds[definition.Kind] && !instanceOrg {
continue
}
descriptors = append(descriptors, definition.Descriptor())
}
for _, descriptor := range domainManagedDescriptors() {
if instanceOnlyKinds[descriptor.GetKind()] && !instanceOrg {
continue
}
descriptors = append(descriptors, descriptor)
}
return &pb.CatalogResponse{Resources: descriptors}, nil
}
func (s *Server) Query(ctx context.Context, request *pb.QueryRequest) (*pb.QueryResponse, error) {
if _, ok := s.definitions[request.GetKind()]; !ok {
return nil, status.Error(codes.NotFound, "resource not found")
}
resource, err := s.resource(ctx, requestOrg(ctx), request.Kind)
if err != nil {
return nil, mapError(err)
}
return &pb.QueryResponse{Resource: resourceProto(resource)}, nil
}
// History answers a resource's audit trail. The value of each revision comes
// back with it: restoring one is an ordinary replace of that value, so no
// rollback command of its own is needed.
func (s *Server) History(ctx context.Context, request *pb.HistoryRequest) (*pb.HistoryResponse, error) {
if _, ok := s.definitions[request.GetKind()]; !ok {
return nil, status.Error(codes.NotFound, "resource not found")
}
limit := int(request.GetLimit())
if limit <= 0 || limit > defaultHistoryLimit {
limit = defaultHistoryLimit
}
revisions, err := s.store.ResourceHistory(ctx, requestOrg(ctx), request.Kind, limit)
if err != nil {
return nil, mapError(err)
}
out := make([]*pb.Revision, 0, len(revisions))
for _, revision := range revisions {
out = append(out, &pb.Revision{
Version: revision.Version, ValueJson: revision.Value, Actor: revision.Actor,
Source: revision.Source, RequestId: revision.RequestID, At: timestamp(revision.At),
})
}
return &pb.HistoryResponse{Revisions: out}, nil
}
func (s *Server) Command(ctx context.Context, request *pb.CommandRequest) (*pb.CommandResponse, error) {
definition, ok := s.definitions[request.GetKind()]
command := request.GetCommand()
if !ok || (command != "replace" && command != "validate") {
return nil, status.Error(codes.NotFound, "resource or command not found")
}
if command == "validate" {
// The same checks a replace runs, without writing: a caller can learn
// that a document would be refused before it asks for the change.
value, err := definition.Decode(request.ValueJson)
if err == nil {
err = s.checkOrgWrite(ctx, requestOrg(ctx), request.Kind, value)
}
if err != nil {
return nil, mapError(err)
}
return &pb.CommandResponse{}, nil
}
if request.GetActor() == "" || request.GetSource() == "" || request.GetRequestId() == "" {
return nil, status.Error(codes.InvalidArgument, "actor, source, and request ID are required")
}
value, err := definition.Decode(request.ValueJson)
if err != nil {
return nil, mapError(err)
}
if err := s.checkOrgWrite(ctx, requestOrg(ctx), request.Kind, value); err != nil {
return nil, mapError(err)
}
resource, err := s.store.PutResource(ctx, storecontract.ResourceWrite{OrgID: requestOrg(ctx), Kind: request.Kind, Value: value, Actor: request.Actor, Source: request.Source, RequestID: request.RequestId, ExpectedVersion: request.ExpectedVersion, At: time.Now().UTC()})
if err != nil {
return nil, mapError(err)
}
return &pb.CommandResponse{Resource: resourceProto(resource)}, nil
}
// orgSeededKinds are the kinds every organisation holds its own document of.
// Reading one an org has never written answers with the empty document: an
// org that has configured nothing has nothing, rather than the system org's
// configuration or a not-found the dashboard cannot tell from a failure.
var orgSeededKinds = map[string]bool{
WorkflowDefinitionsKind: true, WorkflowEnablementKind: true,
ForgeConnectionsKind: true, RepositoryPoliciesKind: true,
}
// orgEmptyDocuments are the kinds an org other than the system org reads as
// an unset document until it writes one: its unset fields fall back to the
// instance's, so nothing is stored for it and the instance's values are not
// copied in.
var orgEmptyDocuments = map[string]string{
ChannelSettingsKind: `{"operator":"","show_tool_calls":false,"max_steps":0,"allowed_user_ids":[],"rate_limit":{"window":0,"max_requests":0},"unrestricted_filesystem":false,"workspace":"","agent":""}`,
TaskPolicyKind: `{"notify_webhook":"","notify_min_severity":"","notify_secret":{}}`,
SchedulingPolicyKind: `{"poll_interval":"","max_retries":0,"intake_per_pass":0,"dispatch":{"trigger":"","ack_reaction":""}}`,
}
// resource seeds an org's workflow documents on first use, including orgs
// created after this process started. File-derived settings are never copied.
func (s *Server) resource(ctx context.Context, orgID, kind string) (storecontract.Resource, error) {
resource, err := s.store.Resource(ctx, orgID, kind)
if empty, ok := orgEmptyDocuments[kind]; ok && orgID != storecontract.DefaultOrgID && errors.Is(err, storecontract.ErrResourceNotFound) {
return storecontract.Resource{OrgID: orgID, Kind: kind, Value: []byte(empty)}, nil
}
if !errors.Is(err, storecontract.ErrResourceNotFound) || !orgSeededKinds[kind] {
// Serve the current channel schema so stored settings remain editable.
if err == nil && kind == ChannelSettingsKind {
resource.Value, err = normalizeChannels(resource.Value)
}
return resource, err
}
if _, _, err := s.seedKind(ctx, orgID, s.definitions[kind], config.Config{}); err != nil && !errors.Is(err, storecontract.ErrResourceVersionConflict) {
return storecontract.Resource{}, err
}
return s.store.Resource(ctx, orgID, kind)
}
func resourceProto(resource storecontract.Resource) *pb.Resource {
return &pb.Resource{OrgId: resource.OrgID, Kind: resource.Kind, Version: resource.Version, ValueJson: resource.Value, UpdatedAt: timestamp(resource.At)}
}
// requestOrg is the org a request acts in, derived from the caller's
// principal when the call carried one (rpcidentity.Callers).
func requestOrg(ctx context.Context) string {
return string(org.OrgFromContext(ctx))
}
func timestamp(value time.Time) *timestamppb.Timestamp {
if value.IsZero() {
return nil
}
return timestamppb.New(value)
}
func mapError(err error) error {
switch {
case errors.Is(err, ErrValidation):
return status.Error(codes.InvalidArgument, err.Error())
case errors.Is(err, storecontract.ErrResourceNotFound):
return status.Error(codes.NotFound, err.Error())
case errors.Is(err, storecontract.ErrResourceVersionConflict):
return status.Error(codes.Aborted, err.Error())
default:
return status.Error(codes.Unavailable, err.Error())
}
}
// checkModelAliases refuses workflow definitions whose agent steps name a
// model alias the writing org cannot resolve.
func (s *Server) checkModelAliases(ctx context.Context, orgID string, value []byte) error {
models, err := s.ModelsFor(ctx, orgID)
if err != nil {
return err
}
var collection workflow.WorkflowDefinitionCollection
if err := json.Unmarshal(value, &collection); err != nil {
return err
}
if err := workflow.CheckModelAliases(collection, s.steps, models.Aliases); err != nil {
return fmt.Errorf("%w: %w", ErrValidation, err)
}
return nil
}