package controlplanerpc import ( "context" "crypto/rand" "encoding/hex" "encoding/json" "errors" "fmt" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1" "github.com/samcharles93/archie-core/internal/domain/access" "github.com/samcharles93/archie-core/internal/domain/workflow/task" ) const workflowDefinitionsKind = "workflow-definitions" // Workflows reads and validates workflow definitions in the caller's org, // through the same control-plane calls the workflow editor makes. type Workflows struct{ rpc pb.ControlPlaneServiceClient } func NewWorkflows(rpc pb.ControlPlaneServiceClient) Workflows { return Workflows{rpc: rpc} } func (w Workflows) Workflows(ctx context.Context) (task.WorkflowDefinitionCollection, error) { var collection task.WorkflowDefinitionCollection response, err := w.rpc.Query(ctx, &pb.QueryRequest{Kind: workflowDefinitionsKind}) if err != nil { return collection, fmt.Errorf("%w: %w", ErrUnavailable, err) } if response.GetResource() == nil || len(response.GetResource().GetValueJson()) == 0 { return collection, nil } if err := json.Unmarshal(response.GetResource().GetValueJson(), &collection); err != nil { return collection, fmt.Errorf("decode workflow definitions: %w", err) } return collection, nil } func (w Workflows) StepTypes(ctx context.Context) (json.RawMessage, error) { catalog, err := w.rpc.Catalog(ctx, &pb.CatalogRequest{}) if err != nil { return nil, fmt.Errorf("%w: %w", ErrUnavailable, err) } for _, resource := range catalog.GetResources() { if resource.GetKind() != workflowDefinitionsKind { continue } var schema struct { StepTypes json.RawMessage `json:"x-step-types"` } if err := json.Unmarshal([]byte(resource.GetSchemaJson()), &schema); err != nil { return nil, fmt.Errorf("decode workflow schema: %w", err) } return schema.StepTypes, nil } return nil, errors.New("the control plane serves no workflow definitions") } func (w Workflows) Validate(ctx context.Context, collection task.WorkflowDefinitionCollection) (string, error) { value, err := json.Marshal(collection) if err != nil { return "", err } _, err = w.rpc.Command(ctx, &pb.CommandRequest{Kind: workflowDefinitionsKind, Command: "validate", ValueJson: value}) if status.Code(err) == codes.InvalidArgument { return status.Convert(err).Message(), nil } if err != nil { return "", fmt.Errorf("%w: %w", ErrUnavailable, err) } return "", nil } const workflowDraftsKind = "workflow-drafts" type workflowDrafts struct { Drafts []task.WorkflowDefinitionEntry `json:"drafts"` } func (w Workflows) drafts(ctx context.Context) (workflowDrafts, int64, error) { var drafts workflowDrafts response, err := w.rpc.Query(ctx, &pb.QueryRequest{Kind: workflowDraftsKind}) if err != nil { return drafts, 0, fmt.Errorf("%w: %w", ErrUnavailable, err) } resource := response.GetResource() if resource == nil || len(resource.GetValueJson()) == 0 { return drafts, resource.GetVersion(), nil } if err := json.Unmarshal(resource.GetValueJson(), &drafts); err != nil { return drafts, 0, fmt.Errorf("decode workflow drafts: %w", err) } return drafts, resource.GetVersion(), nil } // Draft returns a workflow's unpublished YAML, and false when it has none. func (w Workflows) Draft(ctx context.Context, id string) (string, bool, error) { drafts, _, err := w.drafts(ctx) for _, draft := range drafts.Drafts { if draft.ID == id { return draft.YAML, true, err } } return "", false, err } // PutDraft writes a workflow's draft, the same document the editor saves to, // so the operator reviews it there before publishing. The revision is // attributed to the caller the gateway authenticated, never to an actor the // model supplied, and each save carries its own request ID so it lands as a // revision rather than replaying an earlier one. func (w Workflows) PutDraft(ctx context.Context, id, src string) error { principal, ok := access.PrincipalFromContext(ctx) if !ok || principal.IdentityID == "" { return errors.New("save workflow draft: no caller to attribute the draft to") } requestID, err := newChatRequestID() if err != nil { return fmt.Errorf("save workflow draft: %w", err) } drafts, version, err := w.drafts(ctx) if err != nil { return err } next := workflowDrafts{Drafts: make([]task.WorkflowDefinitionEntry, 0, len(drafts.Drafts)+1)} for _, draft := range drafts.Drafts { if draft.ID != id { next.Drafts = append(next.Drafts, draft) } } next.Drafts = append(next.Drafts, task.WorkflowDefinitionEntry{ID: id, YAML: src}) value, err := json.Marshal(next) if err != nil { return err } _, err = w.rpc.Command(ctx, &pb.CommandRequest{ Kind: workflowDraftsKind, Command: "replace", ValueJson: value, ExpectedVersion: version, Actor: string(principal.IdentityID), Source: "chat", RequestId: requestID, }) if err != nil { return fmt.Errorf("save workflow draft: %w", err) } return nil } // newChatRequestID mints the idempotency key of one chat-authored write. It // fails rather than falling back to a weaker value: a repeated request ID is // replayed as the earlier revision, which would report a save that never // happened. func newChatRequestID() (string, error) { var value [16]byte if _, err := rand.Read(value[:]); err != nil { return "", err } return "chat-" + hex.EncodeToString(value[:]), nil } // Resource returns one control-plane document's value in the caller's org. func (w Workflows) Resource(ctx context.Context, kind string) (json.RawMessage, error) { response, err := w.rpc.Query(ctx, &pb.QueryRequest{Kind: kind}) if err != nil { return nil, fmt.Errorf("%w: %w", ErrUnavailable, err) } return response.GetResource().GetValueJson(), nil }