Files
archie/internal/infrastructure/staterpc/client.go
T
sam 6fa7c15398 fix(staterpc): carry each model provider's credential reference
The State Store wire described a provider's class, base URL and key variable
but never where its key lives, so every provider reached the daemon
credential-less. A task then built its runtime with no key: the egress session
had nothing to bind and the agent parked on 'APIKey is required'.

Carry api_key_engine and api_key_key alongside the provider. They are a
reference, not a secret; the key is still resolved daemon-side and never
travels to a container.
2026-10-20 07:10:58 +11:00

911 lines
33 KiB
Go

package staterpc
import (
"context"
"errors"
"io"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/samcharles93/archie-core/internal/config"
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/harnesssecret"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/storepkg"
"github.com/samcharles93/archie-core/internal/domain/usage"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/logging"
)
// Client is the single remote adapter wrapping one StateStoreServiceClient,
// asserted against whichever narrow Go interfaces its caller needs -- exactly
// as gatewayrpc.Client asserts both messaging.ChatContract and
// messaging.SessionStore.
type Client struct {
client pb.StateStoreServiceClient
controlPlane controlpb.ControlPlaneServiceClient
}
// NewClient wraps conn's generated client. Close is a no-op: the store
// service owns its own DB lifecycle.
func NewClient(conn grpc.ClientConnInterface) *Client {
return &Client{client: pb.NewStateStoreServiceClient(conn), controlPlane: controlpb.NewControlPlaneServiceClient(conn)}
}
// ControlPlane returns the generic control-plane RPC client on the same authenticated connection.
func (c *Client) ControlPlane() controlpb.ControlPlaneServiceClient { return c.controlPlane }
// Close is a no-op; the remote store service owns its own DB lifecycle.
func (c *Client) Close() error { return nil }
var (
_ storecontract.HarnessSecretStore = (*Client)(nil)
_ task.Store = (*Client)(nil)
_ task.Caller = (*Client)(nil)
_ storecontract.TaskStore = (*Client)(nil)
_ storecontract.TaskLogStore = (*Client)(nil)
_ storecontract.CaptureStore = (*Client)(nil)
_ storecontract.MappingStore = (*Client)(nil)
_ storecontract.BindingStore = (*Client)(nil)
_ storecontract.SourceStore = (*Client)(nil)
_ storecontract.BindingDispatcher = (*Client)(nil)
_ storecontract.MappingMatchRecorder = (*Client)(nil)
_ storecontract.BindingTaskCreator = (*Client)(nil)
_ storecontract.PlaybookDispatcher = (*Client)(nil)
_ storecontract.ConfigSnapshotStore = (*Client)(nil)
_ storecontract.ChannelStatusStore = (*Client)(nil)
_ storecontract.ApplyStatusStore = (*Client)(nil)
_ storecontract.PresenceStore = (*Client)(nil)
_ storecontract.CaptureRefusalStore = (*Client)(nil)
_ storecontract.ExecutionCanceller = (*Client)(nil)
_ identity.Repository = (*Client)(nil)
_ storepkg.Installations = (*Client)(nil)
_ identity.PersonalTokens = (*Client)(nil)
)
// Lifecycle
func (c *Client) EnqueueIssue(ctx context.Context, owner, repo string, number int, title, body, labels, identity string) (bool, error) {
r, err := c.client.EnqueueIssue(ctx, &pb.EnqueueIssueRequest{Owner: owner, Repo: repo, Number: int64(number), Title: title, Body: body, Labels: labels, Identity: identity})
if err != nil {
return false, unmapError(err)
}
return r.Inserted, nil
}
func (c *Client) ActiveTasksByOrigin(ctx context.Context, origin string) ([]*task.Task, error) {
r, err := c.client.ActiveTasksByOrigin(ctx, &pb.ActiveTasksByOriginRequest{Origin: origin})
if err != nil {
return nil, unmapError(err)
}
return mapValues(r.Tasks, taskValue), nil
}
func (c *Client) UnpostedOutcomes(ctx context.Context) ([]*task.Task, error) {
r, err := c.client.UnpostedOutcomes(ctx, &pb.UnpostedOutcomesRequest{})
if err != nil {
return nil, unmapError(err)
}
return mapValues(r.Tasks, taskValue), nil
}
func (c *Client) MarkOutcomePosted(ctx context.Context, taskID int64) error {
_, err := c.client.MarkOutcomePosted(ctx, &pb.MarkOutcomePostedRequest{TaskId: taskID})
return unmapError(err)
}
func (c *Client) EnqueueChatTask(ctx context.Context, owner, repo, title, body, wf, identity, origin, draft string, inputs map[string]any) (*task.Task, error) {
encoded, err := task.EncodeInputs(inputs)
if err != nil {
return nil, err
}
r, err := c.client.EnqueueChatTask(ctx, &pb.EnqueueChatTaskRequest{Owner: owner, Repo: repo, Title: title, Body: body, Workflow: wf, Identity: identity, InputsJson: encoded, Origin: origin, DraftYaml: draft})
if err != nil {
return nil, unmapError(err)
}
return taskValue(r.Task), nil
}
func (c *Client) ClaimNext(ctx context.Context) (*task.Task, error) {
r, err := c.client.ClaimNext(ctx, &pb.ClaimNextRequest{})
if err != nil {
return nil, unmapError(err)
}
if !r.Found {
return nil, nil
}
return taskValue(r.Task), nil
}
func (c *Client) ClaimByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error) {
r, err := c.client.ClaimByIssue(ctx, &pb.ClaimByIssueRequest{Owner: owner, Repo: repo, Number: int64(number)})
if err != nil {
return nil, unmapError(err)
}
if !r.Found {
return nil, nil
}
return taskValue(r.Task), nil
}
func (c *Client) Transition(ctx context.Context, taskID int64, from, to, detail string) error {
_, err := c.client.Transition(ctx, &pb.TransitionRequest{TaskId: taskID, From: from, To: to, Detail: detail})
return unmapError(err)
}
// TaskModels returns what the task's org resolves models against.
func (c *Client) TaskModels(ctx context.Context, taskID int64) (config.OrgModels, error) {
r, err := c.client.TaskModels(ctx, &pb.TaskModelsRequest{TaskId: taskID})
if err != nil {
return config.OrgModels{}, unmapError(err)
}
providers := make(map[string]config.Provider, len(r.Providers))
for name, p := range r.Providers {
providers[name] = modelProviderFromPB(p)
}
return config.OrgModels{Org: r.OrgId, Aliases: r.Aliases, Providers: providers}, nil
}
// TaskInstructions returns the instance and organisation instructions for the
// task's org.
func (c *Client) TaskInstructions(ctx context.Context, taskID int64) (instance, organisation string, err error) {
r, err := c.client.TaskInstructions(ctx, &pb.TaskInstructionsRequest{TaskId: taskID})
if err != nil {
return "", "", unmapError(err)
}
return r.GetInstance(), r.GetOrganisation(), nil
}
// CallerModels returns the calling principal's org and the aliases it may
// use.
func (c *Client) CallerModels(ctx context.Context) (string, map[string]string, error) {
r, err := c.client.CallerModels(ctx, &pb.CallerModelsRequest{})
if err != nil {
return "", nil, unmapError(err)
}
return r.OrgId, r.Aliases, nil
}
// RecordUsage appends one model call's usage record.
func (c *Client) RecordUsage(ctx context.Context, r usage.Record) error {
_, err := c.client.RecordUsage(ctx, &pb.RecordUsageRequest{Record: usageProto(r)})
return unmapError(err)
}
// 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),
ParentId: s.ParentID, Kind: s.Kind, Name: s.Name,
CalledExecutionId: s.CalledExecutionID,
})
if err != nil {
return 0, events.Event{}, unmapError(err)
}
event := events.Event{}
if r.Event != nil {
event = eventValue(r.Event)
}
return r.StepId, event, nil
}
// CancelExecution is the one cancel path:
// the State Store records the cancellation -- every non-terminal step of the
// current attempt plus the execution's own move, and its waited-on callees --
// and returns the callees it cancelled; the caller cancels the runs'
// in-memory contexts afterwards.
func (c *Client) CancelExecution(ctx context.Context, taskID int64, reason, to string) ([]int64, error) {
r, err := c.client.CancelExecution(ctx, &pb.CancelExecutionRequest{TaskId: taskID, Reason: reason, To: to})
if err != nil {
return nil, unmapError(err)
}
return r.CancelledCalleeIds, nil
}
func (c *Client) FinishStep(ctx context.Context, s task.StepFinish) (events.Event, error) {
r, err := c.client.FinishStep(ctx, &pb.FinishStepRequest{
ExecutionId: s.ExecutionID, StepId: s.StepID,
From: string(s.From), To: string(s.To), Detail: s.Detail, TokensUsed: s.TokensUsed, Results: s.Results,
})
if err != nil {
return events.Event{}, unmapError(err)
}
event := events.Event{}
if r.Event != nil {
event = eventValue(r.Event)
}
return event, nil
}
func (c *Client) ListSteps(ctx context.Context, executionID int64, attempt int) ([]task.StepExecution, error) {
r, err := c.client.ListSteps(ctx, &pb.ListStepsRequest{ExecutionId: executionID, Attempt: int64(attempt)})
if err != nil {
return nil, unmapError(err)
}
steps := make([]task.StepExecution, len(r.Steps))
for i, s := range r.Steps {
steps[i] = stepExecutionValue(s)
}
return steps, nil
}
func (c *Client) Update(ctx context.Context, t *task.Task) error {
_, err := c.client.Update(ctx, &pb.UpdateRequest{Task: taskProto(t)})
return unmapError(err)
}
func (c *Client) Requeue(ctx context.Context, taskID int64, fromStatus, wf string) error {
_, err := c.client.Requeue(ctx, &pb.RequeueRequest{TaskId: taskID, FromStatus: fromStatus, Workflow: wf})
return unmapError(err)
}
func (c *Client) ParkTask(ctx context.Context, taskID int64, from, detail, class, blocker string) error {
_, err := c.client.ParkTask(ctx, &pb.ParkTaskRequest{TaskId: taskID, From: from, Detail: detail, Class: class, Blocker: blocker})
return unmapError(err)
}
func (c *Client) RecoverStale(ctx context.Context) (int64, error) {
r, err := c.client.RecoverStale(ctx, &pb.RecoverStaleRequest{})
if err != nil {
return 0, unmapError(err)
}
return r.Count, nil
}
// Archive / Retry
func (c *Client) ArchiveTask(ctx context.Context, taskID int64, fromStatus string, audit events.Event) (int64, error) {
r, err := c.client.ArchiveTask(ctx, &pb.ArchiveTaskRequest{TaskId: taskID, FromStatus: fromStatus, Audit: eventProto(audit)})
if err != nil {
return 0, unmapError(err)
}
return r.EventId, nil
}
func (c *Client) RetryTask(ctx context.Context, taskID int64, fromStatus, wf, retryMode string, resume task.Resume, currentDefinition bool) error {
_, err := c.client.RetryTask(ctx, &pb.RetryTaskRequest{
TaskId: taskID, FromStatus: fromStatus, Workflow: wf, RetryMode: retryMode,
ResumeFrom: resume.From, ResumeAfter: resume.After, CurrentDefinition: currentDefinition,
})
return unmapError(err)
}
func (c *Client) RespondReviewGate(ctx context.Context, taskID int64, fromStatus, gate string, rereview bool, maxRounds int) error {
_, err := c.client.RespondReviewGate(ctx, &pb.RespondReviewGateRequest{
TaskId: taskID, FromStatus: fromStatus, Gate: gate, Rereview: rereview, Cap: int64(maxRounds),
})
return unmapError(err)
}
func (c *Client) BeginRemediation(ctx context.Context, taskID int64, payload string) error {
_, err := c.client.BeginRemediation(ctx, &pb.BeginRemediationRequest{TaskId: taskID, Payload: payload})
return unmapError(err)
}
func (c *Client) UpdateReviewPayload(ctx context.Context, taskID int64, payload string) error {
_, err := c.client.UpdateReviewPayload(ctx, &pb.UpdateReviewPayloadRequest{TaskId: taskID, Payload: payload})
return unmapError(err)
}
func (c *Client) SetReviewCursors(ctx context.Context, taskID, reviewCursor, commentCursor int64) error {
_, err := c.client.SetReviewCursors(ctx, &pb.SetReviewCursorsRequest{TaskId: taskID, ReviewCursor: reviewCursor, CommentCursor: commentCursor})
return unmapError(err)
}
// Queries
func (c *Client) TaskByIssue(ctx context.Context, owner, repo string, number int) (*task.Task, error) {
r, err := c.client.TaskByIssue(ctx, &pb.TaskByIssueRequest{Owner: owner, Repo: repo, Number: int64(number)})
if err != nil {
return nil, unmapError(err)
}
if !r.Found {
return nil, nil
}
return taskValue(r.Task), nil
}
func (c *Client) OpenTaskByPR(ctx context.Context, owner, repo string, number int) (*task.Task, error) {
r, err := c.client.OpenTaskByPR(ctx, &pb.OpenTaskByPRRequest{Owner: owner, Repo: repo, Number: int64(number)})
if err != nil {
return nil, unmapError(err)
}
if !r.Found {
return nil, nil
}
return taskValue(r.Task), nil
}
func (c *Client) TaskByID(ctx context.Context, taskID int64) (*task.Task, error) {
r, err := c.client.TaskByID(ctx, &pb.TaskByIDRequest{TaskId: taskID})
if err != nil {
return nil, unmapError(err)
}
if !r.Found {
return nil, nil
}
return taskValue(r.Task), nil
}
func (c *Client) OpenPRs(ctx context.Context) ([]task.Task, error) {
r, err := c.client.OpenPRs(ctx, &pb.OpenPRsRequest{})
if err != nil {
return nil, unmapError(err)
}
return mapValues(r.Tasks, func(t *pb.Task) task.Task { return *taskValue(t) }), nil
}
func (c *Client) ClearTerminalTasks(ctx context.Context) (int64, error) {
r, err := c.client.ClearTerminalTasks(ctx, &pb.ClearTerminalTasksRequest{})
if err != nil {
return 0, unmapError(err)
}
return r.Count, nil
}
// Tasks returns the most recently updated tasks.
func (c *Client) Tasks(ctx context.Context, limit int) ([]task.Task, error) {
return c.TasksPage(ctx, storecontract.TaskPage{Limit: limit})
}
// TasksPage returns one page of tasks, most recently updated first.
func (c *Client) TasksPage(ctx context.Context, page storecontract.TaskPage) ([]task.Task, error) {
r, err := c.client.Tasks(ctx, &pb.TasksRequest{
Limit: int64(page.Limit), Statuses: page.Statuses, Workflow: page.Workflow,
AfterUpdatedAt: timestamp(page.After.UpdatedAt), AfterId: page.After.ID,
})
if err != nil {
return nil, unmapError(err)
}
return mapValues(r.Tasks, func(t *pb.Task) task.Task { return *taskValue(t) }), nil
}
func (c *Client) StatusCounts(ctx context.Context) (map[string]int, error) {
r, err := c.client.StatusCounts(ctx, &pb.StatusCountsRequest{})
if err != nil {
return nil, unmapError(err)
}
out := make(map[string]int, len(r.Counts))
for k, v := range r.Counts {
out[k] = int(v)
}
return out, nil
}
// Events
func (c *Client) InsertEvent(ctx context.Context, e events.Event) (int64, error) {
r, err := c.client.InsertEvent(ctx, &pb.InsertEventRequest{Event: eventProto(e)})
if err != nil {
return 0, unmapError(err)
}
return r.Id, nil
}
func (c *Client) EventsSince(ctx context.Context, cursor string, limit int) ([]events.Event, error) {
r, err := c.client.EventsSince(ctx, &pb.EventsSinceRequest{SinceId: cursor, Limit: int64(limit)})
if err != nil {
return nil, unmapError(err)
}
return mapValues(r.Events, eventValue), nil
}
func (c *Client) TaskEvents(ctx context.Context, taskID int64) ([]events.Event, error) {
r, err := c.client.TaskEvents(ctx, &pb.TaskEventsRequest{TaskId: taskID})
if err != nil {
return nil, unmapError(err)
}
return mapValues(r.Events, eventValue), nil
}
func (c *Client) WorkflowStats(ctx context.Context) ([]storecontract.WorkflowStat, error) {
r, err := c.client.WorkflowStats(ctx, &pb.WorkflowStatsRequest{})
if err != nil {
return nil, unmapError(err)
}
return mapValues(r.Stats, workflowStatValue), nil
}
func (c *Client) StageStats(ctx context.Context) ([]storecontract.StageStat, error) {
r, err := c.client.StageStats(ctx, &pb.StageStatsRequest{})
if err != nil {
return nil, unmapError(err)
}
return mapValues(r.Stats, stageStatValue), nil
}
func (c *Client) TokensByDay(ctx context.Context, days int) ([]storecontract.DayTokens, error) {
r, err := c.client.TokensByDay(ctx, &pb.TokensByDayRequest{Days: int64(days)})
if err != nil {
return nil, unmapError(err)
}
return mapValues(r.Tokens, dayTokensValue), nil
}
// Capture
func (c *Client) InsertCapture(ctx context.Context, ce storecontract.CapturedEvent, retention time.Duration, maxEvents int) (string, error) {
r, err := c.client.InsertCapture(ctx, &pb.InsertCaptureRequest{Capture: capturedEventProto(ce), RetentionSeconds: int64(retention.Seconds()), MaxEvents: int64(maxEvents)})
if err != nil {
return "", unmapError(err)
}
return r.Id, nil
}
// PutConfigSnapshot publishes the dashboard's configuration projection. The
// server admits it on the administrative token only; a task-scoped grant
// cannot reach it (see TaskGrants).
func (c *Client) PutConfigSnapshot(ctx context.Context, snapshot storecontract.ConfigSnapshot) error {
_, err := c.client.PutConfigSnapshot(ctx, &pb.PutConfigSnapshotRequest{Snapshot: configSnapshotProto(snapshot)})
if err != nil {
return unmapError(err)
}
return nil
}
// ConfigSnapshot reads the published projection. found is false, with a nil
// error, before a daemon has published one.
func (c *Client) ConfigSnapshot(ctx context.Context) (storecontract.ConfigSnapshot, bool, error) {
reply, err := c.client.GetConfigSnapshot(ctx, &pb.GetConfigSnapshotRequest{})
if err != nil {
return storecontract.ConfigSnapshot{}, false, unmapError(err)
}
if !reply.Found {
return storecontract.ConfigSnapshot{}, false, nil
}
return configSnapshotValue(reply.Snapshot), true, nil
}
// PutChannelStatus publishes the channel state the hosting process observes.
// Administrative, like the config snapshot pair: the server admits it on the
// administrative token only, so a task-scoped grant cannot reach it.
func (c *Client) PutChannelStatus(ctx context.Context, channels []storecontract.ChannelStatus) error {
_, err := c.client.PutChannelStatus(ctx, &pb.PutChannelStatusRequest{Channels: channelStatusesProto(channels)})
if err != nil {
return unmapError(err)
}
return nil
}
// ChannelStatus reads every reported channel.
func (c *Client) ChannelStatus(ctx context.Context) ([]storecontract.ChannelStatus, error) {
reply, err := c.client.ListChannelStatus(ctx, &pb.ListChannelStatusRequest{})
if err != nil {
return nil, unmapError(err)
}
return channelStatusesValue(reply.Channels), nil
}
// PutApplyStatus reports what this process applied for one resource kind.
// Administrative, like the config snapshot pair: a task-scoped grant cannot
// reach it.
func (c *Client) PutApplyStatus(ctx context.Context, status storecontract.ApplyStatus) error {
_, err := c.client.PutApplyStatus(ctx, &pb.PutApplyStatusRequest{Status: applyStatusProto(status)})
if err != nil {
return unmapError(err)
}
return nil
}
// ListApplyStatus reads every process's report. An empty slice means nothing
// has reported yet, which is not an error.
func (c *Client) ListApplyStatus(ctx context.Context) ([]storecontract.ApplyStatus, error) {
reply, err := c.client.ListApplyStatus(ctx, &pb.ListApplyStatusRequest{})
if err != nil {
return nil, unmapError(err)
}
statuses := make([]storecontract.ApplyStatus, 0, len(reply.Statuses))
for _, status := range reply.Statuses {
statuses = append(statuses, applyStatusValue(status))
}
return statuses, nil
}
// PutPresence re-stamps this service instance's record. Administrative.
func (c *Client) PutPresence(ctx context.Context, presence storecontract.Presence) error {
_, err := c.client.PutPresence(ctx, &pb.PutPresenceRequest{Presence: presenceProto(presence)})
if err != nil {
return unmapError(err)
}
return nil
}
// ListPresence reads every service instance's record.
func (c *Client) ListPresence(ctx context.Context) ([]storecontract.Presence, error) {
reply, err := c.client.ListPresence(ctx, &pb.ListPresenceRequest{})
if err != nil {
return nil, unmapError(err)
}
out := make([]storecontract.Presence, 0, len(reply.Presences))
for _, presence := range reply.Presences {
out = append(out, presenceValue(presence))
}
return out, nil
}
// RecordCaptureRefusal counts one event the network rules refused.
func (c *Client) RecordCaptureRefusal(ctx context.Context, source, addr string, at time.Time) error {
_, err := c.client.RecordCaptureRefusal(ctx, &pb.RecordCaptureRefusalRequest{Source: source, Addr: addr, RefusedAt: timestamp(at)})
return unmapError(err)
}
// CaptureRefusals reads each source's refusals since a time.
func (c *Client) CaptureRefusals(ctx context.Context, since time.Time) ([]storecontract.CaptureRefusals, error) {
reply, err := c.client.ListCaptureRefusals(ctx, &pb.ListCaptureRefusalsRequest{Since: timestamp(since)})
if err != nil {
return nil, unmapError(err)
}
out := make([]storecontract.CaptureRefusals, 0, len(reply.Sources))
for _, s := range reply.Sources {
out = append(out, storecontract.CaptureRefusals{Source: s.Source, Refused: s.Refused, Accepted: s.Accepted, Addrs: s.Addrs})
}
return out, nil
}
// ListCaptures streams one capture per message; see StreamCaptures in
// server.go.
func (c *Client) ListCaptures(ctx context.Context, limit int) ([]storecontract.CapturedEvent, error) {
stream, err := c.client.StreamCaptures(ctx, &pb.StreamCapturesRequest{Limit: int64(limit)})
if err != nil {
return nil, unmapError(err)
}
var captures []storecontract.CapturedEvent
for {
r, err := stream.Recv()
if errors.Is(err, io.EOF) {
return captures, nil
}
if err != nil {
return nil, unmapError(err)
}
captures = append(captures, capturedEventValue(r.Capture))
}
}
// Mapping
func (c *Client) InsertMapping(ctx context.Context, m mapping.Mapping) (string, error) {
r, err := c.client.InsertMapping(ctx, &pb.InsertMappingRequest{Mapping: mappingProto(m)})
if err != nil {
return "", unmapError(err)
}
return r.Id, nil
}
func (c *Client) GetMapping(ctx context.Context, id string) (*mapping.Mapping, error) {
r, err := c.client.GetMapping(ctx, &pb.GetMappingRequest{Id: id})
if err != nil {
return nil, unmapError(err)
}
if !r.Found {
return nil, nil
}
v := mappingValue(r.Mapping)
return &v, nil
}
func (c *Client) ListMappings(ctx context.Context) ([]mapping.Mapping, error) {
r, err := c.client.ListMappings(ctx, &pb.ListMappingsRequest{})
if err != nil {
return nil, unmapError(err)
}
return mapValues(r.Mappings, mappingValue), nil
}
func (c *Client) UpdateMapping(ctx context.Context, m mapping.Mapping) error {
_, err := c.client.UpdateMapping(ctx, &pb.UpdateMappingRequest{Mapping: mappingProto(m)})
return unmapError(err)
}
func (c *Client) DeleteMapping(ctx context.Context, id string) error {
_, err := c.client.DeleteMapping(ctx, &pb.DeleteMappingRequest{Id: id})
return unmapError(err)
}
func (c *Client) RecordMappingMatch(ctx context.Context, mappingID, captureID string) error {
_, err := c.client.RecordMappingMatch(ctx, &pb.RecordMappingMatchRequest{MappingId: mappingID, CaptureId: captureID})
return unmapError(err)
}
// Binding
func (c *Client) InsertBinding(ctx context.Context, b binding.Binding) (string, error) {
r, err := c.client.InsertBinding(ctx, &pb.InsertBindingRequest{Binding: bindingProto(b)})
if err != nil {
return "", unmapError(err)
}
return r.Id, nil
}
func (c *Client) GetBinding(ctx context.Context, id string) (*binding.Binding, error) {
r, err := c.client.GetBinding(ctx, &pb.GetBindingRequest{Id: id})
if err != nil {
return nil, unmapError(err)
}
if !r.Found {
return nil, nil
}
v := bindingValue(r.Binding)
return &v, nil
}
func (c *Client) ListBindings(ctx context.Context) ([]binding.Binding, error) {
r, err := c.client.ListBindings(ctx, &pb.ListBindingsRequest{})
if err != nil {
return nil, unmapError(err)
}
return mapValues(r.Bindings, bindingValue), nil
}
func (c *Client) ListDispatches(ctx context.Context, filter storecontract.DispatchFilter) ([]storecontract.Dispatch, error) {
r, err := c.client.ListDispatches(ctx, &pb.ListDispatchesRequest{
BindingId: filter.BindingID, CaptureId: filter.CaptureID, TaskId: filter.TaskID, Limit: int32(filter.Limit), // the store clamps it
})
if err != nil {
return nil, unmapError(err)
}
return mapValues(r.Dispatches, func(d *pb.Dispatch) storecontract.Dispatch {
return storecontract.Dispatch{
BindingID: d.BindingId, BindingVersion: d.BindingVersion, CaptureID: d.CaptureId,
TaskID: d.TaskId, Reason: d.Reason, DispatchedAt: timeValue(d.DispatchedAt),
}
}), nil
}
func (c *Client) UpdateBinding(ctx context.Context, b binding.Binding) error {
_, err := c.client.UpdateBinding(ctx, &pb.UpdateBindingRequest{Binding: bindingProto(b)})
return unmapError(err)
}
func (c *Client) DeleteBinding(ctx context.Context, id string) error {
_, err := c.client.DeleteBinding(ctx, &pb.DeleteBindingRequest{Id: id})
return unmapError(err)
}
func (c *Client) PauseBinding(ctx context.Context, id string) error {
_, err := c.client.PauseBinding(ctx, &pb.PauseBindingRequest{Id: id})
return unmapError(err)
}
func (c *Client) ResumeBinding(ctx context.Context, id string) error {
_, err := c.client.ResumeBinding(ctx, &pb.ResumeBindingRequest{Id: id})
return unmapError(err)
}
func (c *Client) ApproveBinding(ctx context.Context, id string) error {
_, err := c.client.ApproveBinding(ctx, &pb.ApproveBindingRequest{Id: id})
return unmapError(err)
}
// Source
func (c *Client) InsertSource(ctx context.Context, s source.Source) error {
_, err := c.client.InsertSource(ctx, &pb.InsertSourceRequest{Source: sourceProto(s)})
return unmapError(err)
}
func (c *Client) GetSource(ctx context.Context, path string) (*source.Source, error) {
r, err := c.client.GetSource(ctx, &pb.GetSourceRequest{Path: path})
if err != nil {
return nil, unmapError(err)
}
if !r.Found {
return nil, nil
}
v := sourceValue(r.Source)
return &v, nil
}
func (c *Client) ListSources(ctx context.Context) ([]source.Source, error) {
r, err := c.client.ListSources(ctx, &pb.ListSourcesRequest{})
if err != nil {
return nil, unmapError(err)
}
return mapValues(r.Sources, sourceValue), nil
}
func (c *Client) SetSourceSigning(ctx context.Context, path string, from, to source.Signing) error {
_, err := c.client.SetSourceSigning(ctx, &pb.SetSourceSigningRequest{Path: path, From: string(from), To: string(to)})
return unmapError(err)
}
func (c *Client) SetSourceName(ctx context.Context, path, name string) error {
_, err := c.client.SetSourceName(ctx, &pb.SetSourceNameRequest{Path: path, Name: name})
return unmapError(err)
}
func (c *Client) SetSourceDeliveryHeader(ctx context.Context, path, header string) error {
_, err := c.client.SetSourceDeliveryHeader(ctx, &pb.SetSourceDeliveryHeaderRequest{Path: path, Header: header})
return unmapError(err)
}
func (c *Client) DeleteSource(ctx context.Context, path string) error {
_, err := c.client.DeleteSource(ctx, &pb.DeleteSourceRequest{Path: path})
return unmapError(err)
}
func (c *Client) SetSourceSecret(ctx context.Context, path, secret string) error {
_, err := c.client.SetSourceSecret(ctx, &pb.SetSourceSecretRequest{Path: path, Secret: secret})
return unmapError(err)
}
// Dispatch
func (c *Client) ArmedBindingsForSource(ctx context.Context, source string) ([]binding.Binding, error) {
r, err := c.client.ArmedBindingsForSource(ctx, &pb.ArmedBindingsForSourceRequest{Source: source})
if err != nil {
return nil, unmapError(err)
}
return mapValues(r.Bindings, bindingValue), nil
}
func (c *Client) RecordDispatch(ctx context.Context, bindingID string, bindingVersion int64, captureID string, taskID int64, reason string) error {
_, err := c.client.RecordDispatch(ctx, &pb.RecordDispatchRequest{BindingId: bindingID, BindingVersion: bindingVersion, CaptureId: captureID, TaskId: taskID, Reason: reason})
return unmapError(err)
}
// Playbook dispatch
func (c *Client) RecordPlaybookDispatch(ctx context.Context, playbookID, playbookVersion, eventID, actionID string) error {
_, err := c.client.RecordPlaybookDispatch(ctx, &pb.RecordPlaybookDispatchRequest{PlaybookId: playbookID, PlaybookVersion: playbookVersion, EventId: eventID, ActionId: actionID})
return unmapError(err)
}
func (c *Client) DeletePlaybookDispatches(ctx context.Context, playbookID string) error {
_, err := c.client.DeletePlaybookDispatches(ctx, &pb.DeletePlaybookDispatchesRequest{PlaybookId: playbookID})
return unmapError(err)
}
// ListUndispatchedCaptures streams for the same reason as ListCaptures.
func (c *Client) ListUndispatchedCaptures(ctx context.Context, bindings []string, limit int) ([]storecontract.CapturedEvent, error) {
stream, err := c.client.StreamUndispatchedCaptures(ctx, &pb.StreamUndispatchedCapturesRequest{Bindings: bindings, Limit: int64(limit)})
if err != nil {
return nil, unmapError(err)
}
var captures []storecontract.CapturedEvent
for {
r, err := stream.Recv()
if errors.Is(err, io.EOF) {
return captures, nil
}
if err != nil {
return nil, unmapError(err)
}
captures = append(captures, capturedEventValue(r.Capture))
}
}
// BindingTaskCreator
func (c *Client) EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity, bindingID string, bindingVersion int, captureID string, inputs map[string]any) (*task.Task, error) {
encoded, err := task.EncodeInputs(inputs)
if err != nil {
return nil, err
}
r, err := c.client.EnqueueBindingTask(ctx, &pb.EnqueueBindingTaskRequest{Owner: owner, Repo: repo, Title: title, Body: body, Workflow: wf, Identity: identity, BindingId: bindingID, BindingVersion: int64(bindingVersion), InputsJson: encoded, CaptureId: captureID})
if err != nil {
return nil, unmapError(err)
}
return taskValue(r.Task), nil
}
// WorkflowCaller: the workflow.call step's two RPCs. StartCall encodes the
// call's inputs in the same form every other wire crossing uses; CallStatus
// rehydrates the sentinels the server maps, so a caller's errors.Is(err,
// storecontract.ErrCallNotYours) works across the wire.
func (c *Client) StartCall(ctx context.Context, callerTaskID int64, callKey, wf string, inputs map[string]any) (*task.Task, error) {
encoded, err := task.EncodeInputs(inputs)
if err != nil {
return nil, err
}
r, err := c.client.EnqueueCallTask(ctx, &pb.EnqueueCallTaskRequest{CallerTaskId: callerTaskID, CallKey: callKey, Workflow: wf, InputsJson: encoded})
if err != nil {
return nil, unmapError(err)
}
return taskValue(r.Task), nil
}
func (c *Client) CallStatus(ctx context.Context, callerTaskID, callTaskID int64) (string, string, map[string]any, error) {
r, err := c.client.WorkflowCallStatus(ctx, &pb.WorkflowCallStatusRequest{CallerTaskId: callerTaskID, CallTaskId: callTaskID})
if err != nil {
return "", "", nil, unmapError(err)
}
return r.Status, r.Detail, outputsValue(r.OutputsJson), nil
}
// Task log
// TaskLog reads one task attempt's decoded log over the wire. found=false with
// a nil error is the attempt-has-no-log answer; a process with no reader at
// all comes back as an unavailable error, not as an empty page, so a caller
// can tell the two apart.
func (c *Client) TaskLog(ctx context.Context, taskID int64, attempt int, q logging.Query) (logging.TaskLogPage, error) {
r, err := c.client.ReadTaskLog(ctx, taskLogRequestProto(taskID, attempt, q))
if err != nil {
return logging.TaskLogPage{}, unmapError(err)
}
if !r.Found {
return logging.TaskLogPage{
Entries: []logging.Entry{},
Components: []string{},
}, nil
}
// Both collections are normalised: protobuf decodes an empty `repeated`
// field to nil, and a nil slice marshals to JSON null rather than an empty
// list, so the field's type would otherwise depend on whether it happened
// to have contents. mapValues owns the entries side.
components := r.Components
if components == nil {
components = []string{}
}
return logging.TaskLogPage{
Entries: mapValues(r.Entries, taskLogEntryValue),
Truncated: r.Truncated,
MoreAvailable: r.MoreAvailable,
Cursor: r.Cursor,
File: r.File,
Found: true,
Components: components,
}, nil
}
// TaskLogContent streams one attempt's log verbatim into w, for a download.
// found is false, with a nil error, when the attempt has no log file.
func (c *Client) TaskLogContent(ctx context.Context, taskID int64, attempt int, w io.Writer) (bool, error) {
stream, err := c.client.StreamTaskLogContent(ctx, &pb.StreamTaskLogContentRequest{TaskId: taskID, Attempt: int64(attempt)})
if err != nil {
return false, unmapError(err)
}
found := false
for {
r, err := stream.Recv()
if errors.Is(err, io.EOF) {
return found, nil
}
if err != nil {
return found, unmapError(err)
}
found = found || r.Found
if len(r.Chunk) == 0 {
continue
}
if _, err := w.Write(r.Chunk); err != nil {
return found, err
}
}
}
// GetHarnessSecret returns the stored OAuth token set for an org/service
// credential binding, or storecontract.ErrHarnessSecretNotFound.
func (c *Client) GetHarnessSecret(ctx context.Context, org, service string) (harnesssecret.Secret, error) {
r, err := c.client.GetHarnessSecret(ctx, &pb.GetHarnessSecretRequest{Service: service, RunCredential: harnesssecret.RunCredential(ctx)})
if err != nil {
return harnesssecret.Secret{}, unmapError(err)
}
if r.Org != org {
return harnesssecret.Secret{}, status.Error(codes.PermissionDenied, "harness secret belongs to another org")
}
value := harnessSecretValue(r.Secret)
value.Org = r.Org
return value, nil
}
// PutHarnessSecret upserts an org/service credential binding's OAuth token
// set, called by the setup terminal's first capture and by the egress
// proxy's every refresh.
func (c *Client) PutHarnessSecret(ctx context.Context, s harnesssecret.Secret) error {
_, err := c.client.PutHarnessSecret(ctx, &pb.PutHarnessSecretRequest{Secret: harnessSecretProto(s), RunCredential: harnesssecret.RunCredential(ctx)})
return unmapError(err)
}