The PRD's deletion gate for the Messaging Service could not pass: go list -deps ./cmd/archie-messaging linked modernc.org/sqlite, internal/store, internal/domain/workflow and internal/agentexec -- all through one import, archiemessaging/run.go -> internal/app/controlplane, from which the service used three symbols. The decision was to sever rather than amend the gate, because a boundary you whitelist around is no longer a boundary (archie-core-1ng1, recorded in docs/architecture/migration-decisions.md). Measured before touching anything: internal/app/controlplane was the ONLY direct import of the service that dragged those runtimes -- every other one was clean -- so severing this one dependency is sufficient for the gate. Moved into the new internal/infrastructure/controlplanerpc: the generic resource client (NewRPCClient, Query), the RuntimeChatConfig projection, the reader interface (now the exported ResourceReader), the wire sentinels, the status mapping (now ClientError), and the channel-settings document with its decode -- ChannelSettings, TelegramSettings, WebhookChannelSettings, EmailSettings, RateLimitSettings, ChannelDuration, DecodeRenamingLegacyKeys. internal/app/controlplane keeps the store-backed server, the Definition registry, every kind's seed/validator/Normalize, the schema derivation, and its resource-specific reads and watches. Its Client embeds the new one, so the read path has one implementation while the workflow, persona and cronstore reads stay with the processes that already link those engines. The documents are type-aliased back into this package so the store-backed side reads them by the names it has always used: one definition, not a copy on each side of the boundary. The gate is now enforced by cmd/archie-messaging/architecture_test.go, measuring the linked binary against the PRD's banned list, with one exception checked in both directions: internal/domain/workflow/task, the Task status and view vocabulary whose own dependency set holds none of the banned runtimes. The UI gate carries the same entry for the same reason, and the fleet skill names it as the precedent. Verified: task check exit 0. The gate was red-proofed twice -- banning internal/channels fails it, and removing the workflow/task exception fails it -- so neither the loop nor the exception is decorative.
179 lines
6.7 KiB
Go
179 lines
6.7 KiB
Go
// Package controlplane owns control-plane resource registration, dispatch, and validation.
|
|
package controlplane
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"time"
|
|
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/status"
|
|
"google.golang.org/protobuf/types/known/timestamppb"
|
|
|
|
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
|
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
|
"github.com/samcharles93/archie-core/internal/store"
|
|
)
|
|
|
|
// 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 {
|
|
Resource(context.Context, string) (store.Resource, error)
|
|
ResourceHistory(context.Context, string, int) ([]store.Resource, error)
|
|
PutResource(context.Context, store.ResourceWrite) (store.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
|
|
definitions map[string]Definition
|
|
ordered []Definition
|
|
}
|
|
|
|
// 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)
|
|
byKind := make(map[string]Definition, len(definitions))
|
|
for _, definition := range definitions {
|
|
byKind[definition.Kind] = definition
|
|
}
|
|
return &Server{store: resources, definitions: byKind, ordered: definitions}, nil
|
|
}
|
|
|
|
func (s *Server) Catalog(context.Context, *pb.CatalogRequest) (*pb.CatalogResponse, error) {
|
|
descriptors := make([]*pb.ResourceDescriptor, 0, len(s.ordered)+len(domainManagedDescriptors()))
|
|
for _, definition := range s.ordered {
|
|
descriptors = append(descriptors, definition.Descriptor())
|
|
}
|
|
descriptors = append(descriptors, domainManagedDescriptors()...)
|
|
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.store.Resource(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, 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()]
|
|
if !ok || request.GetCommand() != "replace" {
|
|
return nil, status.Error(codes.NotFound, "resource or command not found")
|
|
}
|
|
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)
|
|
}
|
|
resource, err := s.store.PutResource(ctx, store.ResourceWrite{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
|
|
}
|
|
|
|
func (s *Server) Watch(request *pb.WatchRequest, stream pb.ControlPlaneService_WatchServer) error {
|
|
if _, ok := s.definitions[request.GetKind()]; !ok {
|
|
return status.Error(codes.NotFound, "resource not found")
|
|
}
|
|
version := request.AfterVersion
|
|
ticker := time.NewTicker(250 * time.Millisecond)
|
|
defer ticker.Stop()
|
|
for {
|
|
resource, err := s.store.Resource(stream.Context(), request.Kind)
|
|
if err == nil && resource.Version > version {
|
|
if err := stream.Send(&pb.WatchResponse{Resource: resourceProto(resource)}); err != nil {
|
|
return err
|
|
}
|
|
version = resource.Version
|
|
} else if err != nil && !errors.Is(err, store.ErrResourceNotFound) {
|
|
return mapError(err)
|
|
}
|
|
select {
|
|
case <-stream.Context().Done():
|
|
return stream.Context().Err()
|
|
case <-ticker.C:
|
|
}
|
|
}
|
|
}
|
|
|
|
func resourceProto(resource store.Resource) *pb.Resource {
|
|
return &pb.Resource{Kind: resource.Kind, Version: resource.Version, ValueJson: resource.Value, UpdatedAt: timestamp(resource.At)}
|
|
}
|
|
|
|
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, store.ErrResourceNotFound):
|
|
return status.Error(codes.NotFound, err.Error())
|
|
case errors.Is(err, store.ErrResourceVersionConflict):
|
|
return status.Error(codes.Aborted, err.Error())
|
|
default:
|
|
return status.Error(codes.Unavailable, err.Error())
|
|
}
|
|
}
|