feat(state-store): generalize storerpc as the State Store gRPC contract (archie-core-8cda.4.2) (#770)
* feat(state-store): generalize storerpc as the State Store gRPC contract Implements archie-core-8cda.4.2 against docs/prds/state-store-contract.md rev. 2c: generate protobuf/gRPC client and server adapters for every ratified store contract (proto/state/v1/state.proto, 40 RPCs, one StateStoreService), add internal/infrastructure/staterpc with a bufconn conformance suite exercising both local and remote adapters, serve the service in-process (bridge address + mandatory per-task bearer token when agent containers exist, loopback-only otherwise), and flip archie-agent's workflow.Store to a long-lived gRPC client when the daemon injects STATE_STORE_URL/STATE_STORE_TOKEN (falling back to the legacy NATS storerpc path otherwise -- one agent process is never both). Also drops the *sql.Tx parameter from store.BindingDispatcher.RecordDispatch (a required wire-blocker fix: a transaction cannot cross a gRPC boundary, and production always passed nil). fix(store): drop RecordDispatch's unusable *sql.Tx parameter feat(config): add services.state contract-adapter selector * fix(state-store): apply no-mistakes review decisions - Drop StreamTokenInterceptor (unused; the State Store service has no streaming RPCs and nothing calls it). - Make StateStoreTokens.Validate compare tokens in constant time (crypto/subtle) per the auto-fix hardening.ing finding. - Amend config.example.toml / config.Services.State doc text so it frames [services.state].target as the ratified surface consumed by the upcoming standalone archie-state-store binary (.4.3), not active today.
This commit is contained in:
1 parent
d5e8669991
commit
2b102b04a2
21 files changed
+9347
-71
No files matched your search
@@ -182,6 +182,40 @@ structures found in legacy packages.
|
||||
- **MCP Providers:** Daemon registers providers as optional via
|
||||
`providerRegistry.RegisterOptional`. Missing or failed providers log warnings
|
||||
and degrade health without terminating the process.
|
||||
- **`internal/infrastructure/staterpc/` (State Store gRPC contract):**
|
||||
Authority is `docs/prds/state-store-contract.md` (rev. 2c) -- read it before
|
||||
changing this package or its callers.
|
||||
- The proto (`proto/state/v1/state.proto`, service `StateStoreService`,
|
||||
package `statev1` in `internal/contracts/state/v1/`) is one gRPC service
|
||||
fronting every ratified store contract (40 RPCs); the Go consumer facades
|
||||
stay narrow (`workflow.Store`, `store.TaskStore`, etc., all ≤8 methods
|
||||
except the `TaskStore` composite) via `staterpc.Client`'s multiple `var _`
|
||||
assertions -- never add a Go interface method without a matching RPC.
|
||||
- Error sentinels (`store.ErrStaleTransition`, `ErrBindingNotFound`, ...)
|
||||
cross the wire via `mapError`/`unmapError` in `values.go`, matched on
|
||||
`(code, exact canonical message)`. Changing a canonical message string
|
||||
breaks `errors.Is` on the client without changing behavior visibly --
|
||||
treat those message constants as part of the wire contract.
|
||||
- The daemon serves this service in-process (multiplexed), bound to the
|
||||
Docker bridge gateway address with mandatory per-task bearer-token auth
|
||||
when a container pool exists, or loopback-only with no token when it does
|
||||
not (`boot.startStateStoreServer` in `internal/app/archied/bootstrap.go`).
|
||||
Never add a second listener for the same service.
|
||||
- `daemon.StateStoreTokens` is a per-task, per-incumbence token registry:
|
||||
`containerEnv` calls `Generate` on every container acquisition (so a new
|
||||
container's token supersedes the task's old one) and `process()` calls
|
||||
`Revoke` on release. The gRPC interceptor (`staterpc.UnaryTokenInterceptor`)
|
||||
is the only thing that checks it.
|
||||
- `archie-agent` picks its `workflow.Store` implementation once at boot
|
||||
(`agenttransport/nats.Transport.Store`): gRPC via `staterpc.Client` when
|
||||
`STATE_STORE_URL` was injected, otherwise the legacy NATS `storerpc.Client`.
|
||||
A single agent process is never both; `internal/storerpc` (NATS transport)
|
||||
is deleted only after every agent path is on gRPC (PRD §12 step 4) -- do
|
||||
not delete it while `STATE_STORE_URL` injection is still optional.
|
||||
- `store.BindingDispatcher.RecordDispatch` takes no `*sql.Tx` (dropped in
|
||||
`.4.2` -- it cannot cross a gRPC boundary; production always passed `nil`).
|
||||
Do not reintroduce a transaction parameter on a producer-owned store
|
||||
interface that a remote adapter must also implement.
|
||||
- **`internal/forge/webhook/` (forge webhook receiver):**
|
||||
- Verify HMAC (`webhookguard.VerifyHMAC` against `X-Hub-Signature-256`) before
|
||||
parsing the payload, never after -- an unverified body must not reach
|
||||
@@ -275,3 +309,10 @@ bd remember # Persist cross-session architectural facts
|
||||
unless explicitly instructed.
|
||||
6. **Handoff:** Report changed files, gate verification results, and active
|
||||
issue states.
|
||||
|
||||
## Maintaining this file
|
||||
|
||||
Keep this file for knowledge useful to almost every future agent session in this project.
|
||||
Do not repeat what the codebase already shows; point to the authoritative file or command instead.
|
||||
Prefer rewriting or pruning existing entries over appending new ones.
|
||||
When updating this file, preserve this bar for all agents and keep entries concise.
|
||||
@@ -29,6 +29,8 @@ func runCommand(args []string, getenv func(string) string, stderr io.Writer, run
|
||||
flags := flag.NewFlagSet("archie-agent", flag.ContinueOnError)
|
||||
flags.SetOutput(stderr)
|
||||
natsURLFlag := flags.String("nats-url", "", "NATS server URL (defaults to NATS_URL)")
|
||||
stateStoreURLFlag := flags.String("state-store-url", "", "State Store gRPC target (defaults to STATE_STORE_URL; empty uses the legacy NATS storerpc path)")
|
||||
stateStoreTokenFlag := flags.String("state-store-token", "", "State Store bearer token (defaults to STATE_STORE_TOKEN)")
|
||||
if err := flags.Parse(args); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return 0
|
||||
@@ -47,9 +49,20 @@ func runCommand(args []string, getenv func(string) string, stderr io.Writer, run
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
stateStoreURL := *stateStoreURLFlag
|
||||
if stateStoreURL == "" {
|
||||
stateStoreURL = getenv("STATE_STORE_URL")
|
||||
}
|
||||
stateStoreToken := *stateStoreTokenFlag
|
||||
if stateStoreToken == "" {
|
||||
stateStoreToken = getenv("STATE_STORE_TOKEN")
|
||||
}
|
||||
|
||||
if err := runWorker(ctx, agentworker.Settings{
|
||||
NATSURL: natsURL,
|
||||
NATSToken: natsToken,
|
||||
NATSURL: natsURL,
|
||||
NATSToken: natsToken,
|
||||
StateStoreTarget: stateStoreURL,
|
||||
StateStoreToken: stateStoreToken,
|
||||
}, log); err != nil {
|
||||
return 1
|
||||
}
|
||||
|
||||
@@ -261,6 +261,18 @@ max_steps = 60
|
||||
wall_clock = "30m"
|
||||
gate_max_failures = 5
|
||||
|
||||
# Services selects contract adapters at composition time. Leave the section
|
||||
# absent to use every adapter's default (see docs/prds/state-store-contract.md).
|
||||
# [services.gateway]
|
||||
# target = "127.0.0.1:8585" # archie-gateway's gRPC address (always remote once set)
|
||||
|
||||
# [services.state]
|
||||
# target = "" # empty (default) = local *store.Store adapter.
|
||||
# # This surface is consumed by the upcoming
|
||||
# # standalone archie-state-store binary (.4.3); the
|
||||
# # daemon does not read it yet -- it still serves the
|
||||
# # State Store gRPC service in-process today.
|
||||
|
||||
# NATS is the sole autonomous workflow handoff. mode changes only where the
|
||||
# broker runs; every workflow still runs in a managed task container:
|
||||
# "embedded" – in-process nats-server (the default; no external server)
|
||||
|
||||
@@ -32,6 +32,14 @@ type Settings struct {
|
||||
NATSURL string
|
||||
NATSToken string
|
||||
WorkDir string
|
||||
|
||||
// StateStoreTarget and StateStoreToken are the daemon-injected State
|
||||
// Store gRPC endpoint and per-task bearer token (docs/prds/
|
||||
// state-store-contract.md §6: STATE_STORE_URL/STATE_STORE_TOKEN,
|
||||
// mirroring the NATS_URL/NATS_TOKEN handoff). Empty keeps the legacy
|
||||
// NATS storerpc path for workflow.Store.
|
||||
StateStoreTarget string
|
||||
StateStoreToken string
|
||||
}
|
||||
|
||||
type workerTransport interface {
|
||||
@@ -83,8 +91,10 @@ func run(ctx context.Context, settings Settings, log *slog.Logger, dependencies
|
||||
dependencies.markSafe(ctx, workDir, log)
|
||||
|
||||
transport, err := dependencies.connect(ctx, agentnats.Config{
|
||||
URL: settings.NATSURL,
|
||||
Token: settings.NATSToken,
|
||||
URL: settings.NATSURL,
|
||||
Token: settings.NATSToken,
|
||||
StateStoreURL: settings.StateStoreTarget,
|
||||
StateStoreToken: settings.StateStoreToken,
|
||||
}, log)
|
||||
if err != nil {
|
||||
operation := "nats connect failed"
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
@@ -22,6 +23,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/runtime"
|
||||
"google.golang.org/grpc"
|
||||
|
||||
channelruntime "github.com/samcharles93/archie-core/internal/channels"
|
||||
"github.com/samcharles93/archie-core/internal/channels/email"
|
||||
@@ -49,6 +51,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/sessioncurator"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/skillcurator"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/taskactions"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/memory"
|
||||
@@ -1268,6 +1271,55 @@ func (b *boot) buildDaemon() {
|
||||
b.setupForgeWebhook()
|
||||
}
|
||||
|
||||
// startStateStoreServer serves the State Store gRPC service in-process
|
||||
// (multiplexed inside archied), so archie-agent has a gRPC target before the
|
||||
// standalone archie-state-store binary exists (docs/prds/
|
||||
// state-store-contract.md §12 step 3). Listener topology follows §9's single
|
||||
// rule: bind the host-gateway bridge address with mandatory per-task bearer
|
||||
// tokens when agent containers can reach this daemon, or loopback-only with
|
||||
// no token when there is no container pool to serve. Failure degrades
|
||||
// (archie-agent falls back to the legacy NATS storerpc path) rather than
|
||||
// aborting boot -- the State Store's in-process server is additive during
|
||||
// .4.2, not yet load-bearing.
|
||||
func (b *boot) startStateStoreServer(ctx context.Context) {
|
||||
log := b.log
|
||||
deps := staterpc.Deps{
|
||||
Tasks: b.st, Mappings: b.d.Mappings, Bindings: b.d.Bindings,
|
||||
BindingDispatcher: b.d.BindingDispatcher, BindingTaskCreator: b.d.BindingTaskCreator,
|
||||
Log: log,
|
||||
}
|
||||
if cs, ok := b.st.(store.CaptureStore); ok {
|
||||
deps.Captures = cs
|
||||
}
|
||||
|
||||
host := "127.0.0.1"
|
||||
var opts []grpc.ServerOption
|
||||
if b.containerPool != nil {
|
||||
if bridge := b.containerPool.HostGateway(); bridge != "" {
|
||||
host = bridge
|
||||
tokens := daemon.NewStateStoreTokens()
|
||||
b.d.StateStoreTokens = tokens
|
||||
opts = append(opts, grpc.ChainUnaryInterceptor(staterpc.UnaryTokenInterceptor(tokens.Validate)))
|
||||
}
|
||||
}
|
||||
|
||||
listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", net.JoinHostPort(host, "0"))
|
||||
if err != nil {
|
||||
log.Error("state store gRPC listen failed; archie-agent will use the legacy NATS storerpc path", "err", err)
|
||||
return
|
||||
}
|
||||
server := grpc.NewServer(opts...)
|
||||
staterpc.RegisterServer(server, deps)
|
||||
go func() {
|
||||
if err := server.Serve(listener); err != nil {
|
||||
log.Error("state store gRPC server stopped", "err", err)
|
||||
}
|
||||
}()
|
||||
b.addCleanup(server.GracefulStop)
|
||||
b.d.ConnectedStateStore = daemon.StateStoreEndpoint{URL: listener.Addr().String()}
|
||||
log.Info("state store gRPC server running", "addr", listener.Addr().String(), "token_required", host != "127.0.0.1")
|
||||
}
|
||||
|
||||
// setupForgeWebhook starts the forge webhook receiver when intake is "webhook"
|
||||
// or "both". It decodes GitHub issue events into task envelopes and publishes
|
||||
// them through the same path the poller uses, so a labelled or assigned issue
|
||||
|
||||
@@ -421,6 +421,7 @@ func Run() int { //nolint:cyclop // the composition root's setup sequence is del
|
||||
}
|
||||
b.registerStandaloneTools()
|
||||
b.buildDaemon()
|
||||
b.startStateStoreServer(ctx)
|
||||
b.wireConfigPublishing(ctx, args.cfgPath, args.overlayPath)
|
||||
b.installUpdateConfigHandler()
|
||||
b.installUpdateRepoFieldHandler()
|
||||
@@ -1058,13 +1059,18 @@ func startContainers(
|
||||
}
|
||||
|
||||
pool, err := container.NewPool(ctx, container.Config{
|
||||
Image: cfg.Containers.Image,
|
||||
MaxConcurrency: cfg.Containers.MaxConcurrency,
|
||||
MaxUptime: cfg.Containers.MaxUptime.Std(),
|
||||
PullPolicy: cfg.Containers.PullPolicy,
|
||||
Network: cfg.Containers.Network,
|
||||
DockerClient: dockerCli,
|
||||
RequireHostGateway: cfg.NATS.Mode == config.NATSModeEmbedded,
|
||||
Image: cfg.Containers.Image,
|
||||
MaxConcurrency: cfg.Containers.MaxConcurrency,
|
||||
MaxUptime: cfg.Containers.MaxUptime.Std(),
|
||||
PullPolicy: cfg.Containers.PullPolicy,
|
||||
Network: cfg.Containers.Network,
|
||||
DockerClient: dockerCli,
|
||||
// Always resolve the bridge gateway: agent containers need it to
|
||||
// reach embedded NATS (when configured) and, as of Phase 2, the
|
||||
// daemon's in-process State Store gRPC server (docs/prds/
|
||||
// state-store-contract.md §9's single listener-topology rule) --
|
||||
// a container can never reach the host's 127.0.0.1.
|
||||
RequireHostGateway: true,
|
||||
}, log)
|
||||
if err != nil {
|
||||
// A missing image is recoverable by hand. The daemon sends no registry
|
||||
|
||||
@@ -3,6 +3,15 @@ package config
|
||||
// Services selects contract adapters at application composition time.
|
||||
type Services struct {
|
||||
Gateway ServiceConnection `toml:"gateway" yaml:"gateway"`
|
||||
// State selects the State Store contract adapter. Unlike Gateway, an
|
||||
// empty Target means local (the *store.Store in-process adapter): the
|
||||
// State Store service is not yet extracted into its own process. This
|
||||
// is the ratified presence-based [services.state].target surface
|
||||
// (docs/prds/state-store-contract.md §10), consumed by the upcoming
|
||||
// standalone archie-state-store binary (.4.3) -- the daemon does not
|
||||
// read it yet, so it remains dead configuration until that consumer
|
||||
// lands. Setting Target would dial the gRPC StateStoreService.
|
||||
State ServiceConnection `toml:"state" yaml:"state"`
|
||||
}
|
||||
|
||||
// ServiceConnection is the archie-gateway process's gRPC address. It does not
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -5,6 +5,9 @@ package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -62,6 +65,78 @@ type NATSEndpoint struct {
|
||||
Token string
|
||||
}
|
||||
|
||||
// StateStoreEndpoint is the address the daemon's in-process State Store gRPC
|
||||
// server is bound to (docs/prds/state-store-contract.md §6, §12 step 3). The
|
||||
// zero value (empty URL) means the server is not serving -- containerEnv
|
||||
// omits STATE_STORE_URL/STATE_STORE_TOKEN and archie-agent falls back to the
|
||||
// legacy NATS storerpc path.
|
||||
type StateStoreEndpoint struct {
|
||||
URL string
|
||||
}
|
||||
|
||||
// StateStoreTokens issues and validates the per-task bearer tokens the State
|
||||
// Store's bridge-address (agent-consumed) listener topology requires (§9's
|
||||
// token lifecycle). A token is per-incumbence: Generate overwrites any
|
||||
// earlier token for the same task, so a new container acquisition
|
||||
// invalidates the previous one, and Revoke drops a released task's token
|
||||
// entirely. The zero value is ready to use.
|
||||
type StateStoreTokens struct {
|
||||
mu sync.Mutex
|
||||
byTask map[int64]string
|
||||
}
|
||||
|
||||
// NewStateStoreTokens returns a ready-to-use token registry.
|
||||
func NewStateStoreTokens() *StateStoreTokens {
|
||||
return &StateStoreTokens{byTask: make(map[int64]string)}
|
||||
}
|
||||
|
||||
// Generate issues a fresh bearer token for taskID, replacing (and thereby
|
||||
// invalidating) any token previously issued for that task.
|
||||
func (t *StateStoreTokens) Generate(taskID int64) string {
|
||||
token := randomToken()
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.byTask[taskID] = token
|
||||
return token
|
||||
}
|
||||
|
||||
// Revoke invalidates taskID's current token, if any. Called when the
|
||||
// container holding it is released, so a stale token cannot outlive its
|
||||
// container.
|
||||
func (t *StateStoreTokens) Revoke(taskID int64) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
delete(t.byTask, taskID)
|
||||
}
|
||||
|
||||
// Validate reports whether token is any task's currently issued token.
|
||||
// The comparison is constant-time (crypto/subtle) so a timing side channel
|
||||
// cannot tell how many token bytes matched.
|
||||
func (t *StateStoreTokens) Validate(token string) bool {
|
||||
if token == "" {
|
||||
return false
|
||||
}
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
for _, v := range t.byTask {
|
||||
if subtle.ConstantTimeCompare([]byte(v), []byte(token)) == 1 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func randomToken() string {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
// crypto/rand.Read on the standard reader does not fail in practice;
|
||||
// a zero-value token would fail every Validate call, which is a safe
|
||||
// (fail-closed) degradation rather than a panic.
|
||||
return ""
|
||||
}
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
type Daemon struct {
|
||||
// Cfg publishes the running configuration. Read through Cfg() so a
|
||||
// reload swaps the published snapshot atomically. See config.Holder.
|
||||
@@ -72,7 +147,16 @@ type Daemon struct {
|
||||
// broker the daemon is not publishing on. The zero value is invalid in
|
||||
// production composition and remains useful only to fail closed in tests.
|
||||
ConnectedNATS NATSEndpoint
|
||||
Store store.TaskStore
|
||||
// ConnectedStateStore is the address the daemon's in-process State
|
||||
// Store gRPC server bound to at startup, if any. Empty means the
|
||||
// server is not serving (StateStoreTokens is then unused) and
|
||||
// containerEnv omits STATE_STORE_URL/STATE_STORE_TOKEN.
|
||||
ConnectedStateStore StateStoreEndpoint
|
||||
// StateStoreTokens issues and validates the per-task bearer tokens the
|
||||
// State Store's gRPC interceptor checks. Nil when ConnectedStateStore
|
||||
// is empty.
|
||||
StateStoreTokens *StateStoreTokens
|
||||
Store store.TaskStore
|
||||
// Mappings persists payload field mappings (docs/prds/payload-field-mapping.md).
|
||||
// Used by the binding dispatch loop to resolve capture bodies against
|
||||
// the mapping a binding names. Optional: nil disables the binding
|
||||
@@ -589,7 +673,7 @@ func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c st
|
||||
return
|
||||
}
|
||||
|
||||
if err := d.BindingDispatcher.RecordDispatch(ctx, nil, b.ID, int64(b.Version), c.ID, task.ID); err != nil {
|
||||
if err := d.BindingDispatcher.RecordDispatch(ctx, b.ID, int64(b.Version), c.ID, task.ID); err != nil {
|
||||
if errors.Is(err, store.ErrAlreadyDispatched) {
|
||||
// Another cycle or daemon instance raced us and already
|
||||
// recorded the dispatch. The duplicate task remains
|
||||
@@ -1087,6 +1171,9 @@ func (d *Daemon) process(ctx context.Context, task *workflow.Task) {
|
||||
return
|
||||
}
|
||||
defer d.ContainerPool.Release(ctx, ctr)
|
||||
if d.StateStoreTokens != nil {
|
||||
defer d.StateStoreTokens.Revoke(task.ID)
|
||||
}
|
||||
|
||||
// Hand the whole task to archie-agent in one NATS round trip. archie-agent
|
||||
// proxies Store/Forge/worktree-push calls back to archied over storerpc/
|
||||
@@ -1384,6 +1471,14 @@ func (d *Daemon) containerEnv(task *workflow.Task) []string {
|
||||
if token := d.ConnectedNATS.Token; token != "" {
|
||||
env = append(env, "NATS_TOKEN="+token)
|
||||
}
|
||||
// The State Store gRPC target follows the same seam as NATS_URL/
|
||||
// NATS_TOKEN above (docs/prds/state-store-contract.md §6). Omitted
|
||||
// when the daemon is not serving the State Store in-process, so
|
||||
// archie-agent falls back to the legacy NATS storerpc path.
|
||||
if d.ConnectedStateStore.URL != "" && d.StateStoreTokens != nil {
|
||||
env = append(env, "STATE_STORE_URL="+d.ConnectedStateStore.URL)
|
||||
env = append(env, "STATE_STORE_TOKEN="+d.StateStoreTokens.Generate(task.ID))
|
||||
}
|
||||
// The agent process runs as root inside the container (no USER in the
|
||||
// Dockerfile, no userns-remap), so a commit it writes to the bind-mounted
|
||||
// worktree lands owned by UID 0 on the host. The daemon then reads those
|
||||
|
||||
@@ -7,24 +7,37 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
natsio "github.com/nats-io/nats.go"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/forgerpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/storerpc"
|
||||
"github.com/samcharles93/archie-core/internal/taskrun"
|
||||
"github.com/samcharles93/archie-core/internal/worktreerpc"
|
||||
)
|
||||
|
||||
// Config contains the broker endpoint and credential for the worker transport.
|
||||
// Config contains the broker endpoint and credential for the worker
|
||||
// transport, plus the optional State Store gRPC target (docs/prds/
|
||||
// state-store-contract.md §6). An empty StateStoreURL keeps the legacy NATS
|
||||
// storerpc path for workflow.Store; a non-empty one dials the gRPC
|
||||
// StateStoreService instead -- a single agent process is either NATS-backed
|
||||
// or gRPC-backed for its store calls, never both.
|
||||
type Config struct {
|
||||
URL string
|
||||
Token string
|
||||
|
||||
StateStoreURL string
|
||||
StateStoreToken string
|
||||
}
|
||||
|
||||
const (
|
||||
@@ -40,12 +53,21 @@ type sdkSubscription interface {
|
||||
// worker has no JetStream consumer.
|
||||
type Transport struct {
|
||||
conn *natsio.Conn
|
||||
// stateConn is the long-lived gRPC connection to the State Store,
|
||||
// non-nil only when Config.StateStoreURL was set. Store() dials no
|
||||
// per-call connection; it wraps this one connection with the
|
||||
// per-call timeout each caller supplies.
|
||||
stateConn *grpc.ClientConn
|
||||
|
||||
subscribe func(string, natsio.MsgHandler) (sdkSubscription, error)
|
||||
flush func(time.Duration) error
|
||||
}
|
||||
|
||||
// Connect establishes the worker's core-NATS connection.
|
||||
// Connect establishes the worker's core-NATS connection and, when
|
||||
// Config.StateStoreURL is set, a long-lived gRPC connection to the State
|
||||
// Store (docs/prds/state-store-contract.md §6, §9). A non-loopback
|
||||
// StateStoreURL with no token fails closed rather than dialing an
|
||||
// unauthenticated remote store.
|
||||
func Connect(ctx context.Context, config Config, log *slog.Logger) (*Transport, error) {
|
||||
if log == nil {
|
||||
log = slog.New(slog.DiscardHandler)
|
||||
@@ -66,8 +88,20 @@ func Connect(ctx context.Context, config Config, log *slog.Logger) (*Transport,
|
||||
return nil, err
|
||||
}
|
||||
log.Info("worker transport connected", "url", conn.ConnectedUrl())
|
||||
|
||||
var stateConn *grpc.ClientConn
|
||||
if config.StateStoreURL != "" {
|
||||
stateConn, err = dialStateStore(config.StateStoreURL, config.StateStoreToken)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("connect state store: %w", err)
|
||||
}
|
||||
log.Info("worker state store transport connected", "url", config.StateStoreURL)
|
||||
}
|
||||
|
||||
return &Transport{
|
||||
conn: conn,
|
||||
conn: conn,
|
||||
stateConn: stateConn,
|
||||
subscribe: func(subject string, handler natsio.MsgHandler) (sdkSubscription, error) {
|
||||
return conn.Subscribe(subject, handler)
|
||||
},
|
||||
@@ -75,8 +109,32 @@ func Connect(ctx context.Context, config Config, log *slog.Logger) (*Transport,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// dialStateStore dials target, failing closed (rather than connecting
|
||||
// insecurely) when target is not a loopback address and no token was
|
||||
// configured -- §9's "fail-closed on non-loopback" rule.
|
||||
func dialStateStore(target, token string) (*grpc.ClientConn, error) {
|
||||
host, _, err := net.SplitHostPort(target)
|
||||
if err != nil {
|
||||
host = target
|
||||
}
|
||||
loopback := net.ParseIP(host).IsLoopback()
|
||||
if !loopback && token == "" {
|
||||
return nil, fmt.Errorf("state store target %q is not loopback and no token is configured; refusing an unauthenticated remote connection", target)
|
||||
}
|
||||
opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
|
||||
if token != "" {
|
||||
opts = append(opts, grpc.WithUnaryInterceptor(staterpc.UnaryClientTokenInterceptor(token)))
|
||||
}
|
||||
return grpc.NewClient(target, opts...)
|
||||
}
|
||||
|
||||
// Close releases all broker resources.
|
||||
func (t *Transport) Close() { t.conn.Close() }
|
||||
func (t *Transport) Close() {
|
||||
t.conn.Close()
|
||||
if t.stateConn != nil {
|
||||
_ = t.stateConn.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// LogPublisher returns the narrow fire-and-forget capability used by system logs.
|
||||
func (t *Transport) LogPublisher() agentexec.LogPublisher { return t.conn }
|
||||
@@ -100,11 +158,51 @@ func (t *Transport) Forger(identity string, timeout time.Duration) workflow.Forg
|
||||
return &forgerpc.Client{Conn: t.conn, Timeout: timeout, Identity: identity}
|
||||
}
|
||||
|
||||
// Store constructs the workflow store RPC client.
|
||||
// Store constructs the workflow store RPC client: a long-lived gRPC
|
||||
// staterpc.Client over the State Store connection when one was configured,
|
||||
// or the legacy NATS storerpc.Client otherwise (docs/prds/
|
||||
// state-store-contract.md §6). Either way each call is bounded by timeout
|
||||
// when the caller's context carries no deadline of its own.
|
||||
func (t *Transport) Store(timeout time.Duration) workflow.Store {
|
||||
if t.stateConn != nil {
|
||||
return deadlineStore{Store: staterpc.NewClient(t.stateConn), timeout: timeout}
|
||||
}
|
||||
return &storerpc.Client{Conn: t.conn, Timeout: timeout}
|
||||
}
|
||||
|
||||
// deadlineStore applies a default per-call timeout to workflow.Store calls
|
||||
// whose context carries no deadline of its own, matching storerpc.Client's
|
||||
// Timeout field semantics for the gRPC path.
|
||||
type deadlineStore struct {
|
||||
workflow.Store
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
func (d deadlineStore) withDeadline(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
if _, ok := ctx.Deadline(); ok || d.timeout <= 0 {
|
||||
return ctx, func() {}
|
||||
}
|
||||
return context.WithTimeout(ctx, d.timeout)
|
||||
}
|
||||
|
||||
func (d deadlineStore) Update(ctx context.Context, t *workflow.Task) error {
|
||||
ctx, cancel := d.withDeadline(ctx)
|
||||
defer cancel()
|
||||
return d.Store.Update(ctx, t)
|
||||
}
|
||||
|
||||
func (d deadlineStore) Transition(ctx context.Context, taskID int64, from, to, detail string) error {
|
||||
ctx, cancel := d.withDeadline(ctx)
|
||||
defer cancel()
|
||||
return d.Store.Transition(ctx, taskID, from, to, detail)
|
||||
}
|
||||
|
||||
func (d deadlineStore) InsertEvent(ctx context.Context, e events.Event) (int64, error) {
|
||||
ctx, cancel := d.withDeadline(ctx)
|
||||
defer cancel()
|
||||
return d.Store.InsertEvent(ctx, e)
|
||||
}
|
||||
|
||||
// Trees constructs the identity-scoped worktree RPC client.
|
||||
func (t *Transport) Trees(identity, grant string, timeout time.Duration) RemoteTrees {
|
||||
return &worktreerpc.Client{Conn: t.conn, Timeout: timeout, Identity: identity, Grant: grant}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// tokenMetadataKey is the gRPC metadata key the bearer token travels in.
|
||||
// Metadata, never a URL, per docs/prds/state-store-contract.md §9's token
|
||||
// lifecycle note.
|
||||
const tokenMetadataKey = "state-store-token"
|
||||
|
||||
// TokenValidator reports whether token is a currently-issued, unexpired
|
||||
// bearer token for the State Store's bridge-address listener topology. The
|
||||
// caller (the daemon) owns the issued-token set; this package only enforces
|
||||
// the check server-side and attaches the token client-side.
|
||||
type TokenValidator func(token string) bool
|
||||
|
||||
// UnaryTokenInterceptor validates the bearer token carried in each unary
|
||||
// call's metadata, returning codes.Unauthenticated on a missing, unknown, or
|
||||
// expired token. Required on the bridge-address (agent-consumed) listener
|
||||
// topology per §9; not used on the loopback-only, daemon-only topology.
|
||||
func UnaryTokenInterceptor(validate TokenValidator) grpc.UnaryServerInterceptor {
|
||||
return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
|
||||
if err := checkToken(ctx, validate); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return handler(ctx, req)
|
||||
}
|
||||
}
|
||||
|
||||
func checkToken(ctx context.Context, validate TokenValidator) error {
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return status.Error(codes.Unauthenticated, "missing state store token")
|
||||
}
|
||||
values := md.Get(tokenMetadataKey)
|
||||
if len(values) == 0 || values[0] == "" {
|
||||
return status.Error(codes.Unauthenticated, "missing state store token")
|
||||
}
|
||||
if !validate(values[0]) {
|
||||
return status.Error(codes.Unauthenticated, "invalid state store token")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UnaryClientTokenInterceptor attaches token to every outgoing call's
|
||||
// metadata under tokenMetadataKey. One token covers a task's container
|
||||
// lifetime (§9's per-incumbence lifecycle) so it does not need to be
|
||||
// refreshed mid-connection. Used by the agent's long-lived client
|
||||
// connection to the State Store's bridge-address listener.
|
||||
func UnaryClientTokenInterceptor(token string) grpc.UnaryClientInterceptor {
|
||||
return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
|
||||
return invoker(metadata.AppendToOutgoingContext(ctx, tokenMetadataKey, token), method, req, reply, cc, opts...)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
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/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// Client is the single remote adapter wrapping one StateStoreServiceClient,
|
||||
// asserted against whichever narrow Go interfaces its caller needs -- exactly
|
||||
// as gatewayrpc.Client asserts both gateway.ChatContract and
|
||||
// gateway.SessionStore. See docs/prds/state-store-contract.md §2.
|
||||
type Client struct {
|
||||
client pb.StateStoreServiceClient
|
||||
}
|
||||
|
||||
// NewClient wraps conn's generated client. Close is a no-op: the store
|
||||
// service owns its own DB lifecycle (§11).
|
||||
func NewClient(conn grpc.ClientConnInterface) *Client {
|
||||
return &Client{client: pb.NewStateStoreServiceClient(conn)}
|
||||
}
|
||||
|
||||
// Close is a no-op; the remote store service owns its own DB lifecycle.
|
||||
func (c *Client) Close() error { return nil }
|
||||
|
||||
var (
|
||||
_ workflow.Store = (*Client)(nil)
|
||||
_ store.TaskStore = (*Client)(nil)
|
||||
_ store.CaptureStore = (*Client)(nil)
|
||||
_ store.MappingStore = (*Client)(nil)
|
||||
_ store.BindingStore = (*Client)(nil)
|
||||
_ store.BindingDispatcher = (*Client)(nil)
|
||||
_ store.BindingTaskCreator = (*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) EnqueueChatTask(ctx context.Context, owner, repo, title, body, wf, identity string) (*workflow.Task, error) {
|
||||
r, err := c.client.EnqueueChatTask(ctx, &pb.EnqueueChatTaskRequest{Owner: owner, Repo: repo, Title: title, Body: body, Workflow: wf, Identity: identity})
|
||||
if err != nil {
|
||||
return nil, unmapError(err)
|
||||
}
|
||||
return taskValue(r.Task), nil
|
||||
}
|
||||
|
||||
func (c *Client) ClaimNext(ctx context.Context) (*workflow.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) (*workflow.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)
|
||||
}
|
||||
|
||||
func (c *Client) Update(ctx context.Context, t *workflow.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) 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 string) error {
|
||||
_, err := c.client.RetryTask(ctx, &pb.RetryTaskRequest{TaskId: taskID, FromStatus: fromStatus, Workflow: wf})
|
||||
return unmapError(err)
|
||||
}
|
||||
|
||||
// Queries
|
||||
|
||||
func (c *Client) TaskByIssue(ctx context.Context, owner, repo string, number int) (*workflow.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) TaskByID(ctx context.Context, taskID int64) (*workflow.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) ([]workflow.Task, error) {
|
||||
r, err := c.client.OpenPRs(ctx, &pb.OpenPRsRequest{})
|
||||
if err != nil {
|
||||
return nil, unmapError(err)
|
||||
}
|
||||
return derefTasks(r.Tasks), 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
|
||||
}
|
||||
|
||||
func (c *Client) Tasks(ctx context.Context, limit int) ([]workflow.Task, error) {
|
||||
r, err := c.client.Tasks(ctx, &pb.TasksRequest{Limit: int64(limit)})
|
||||
if err != nil {
|
||||
return nil, unmapError(err)
|
||||
}
|
||||
return derefTasks(r.Tasks), 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
|
||||
}
|
||||
|
||||
func (c *Client) IncrementRetryCount(ctx context.Context, taskID int64) error {
|
||||
_, err := c.client.IncrementRetryCount(ctx, &pb.IncrementRetryCountRequest{TaskId: taskID})
|
||||
return unmapError(err)
|
||||
}
|
||||
|
||||
// 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, sinceID int64, limit int) ([]events.Event, error) {
|
||||
r, err := c.client.EventsSince(ctx, &pb.EventsSinceRequest{SinceId: sinceID, 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) ([]store.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) ([]store.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) ([]store.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 store.CapturedEvent, retention time.Duration, maxEvents int) (int64, error) {
|
||||
r, err := c.client.InsertCapture(ctx, &pb.InsertCaptureRequest{Capture: capturedEventProto(ce), RetentionSeconds: int64(retention.Seconds()), MaxEvents: int64(maxEvents)})
|
||||
if err != nil {
|
||||
return 0, unmapError(err)
|
||||
}
|
||||
return r.Id, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListCaptures(ctx context.Context, limit int) ([]store.CapturedEvent, error) {
|
||||
r, err := c.client.ListCaptures(ctx, &pb.ListCapturesRequest{Limit: int64(limit)})
|
||||
if err != nil {
|
||||
return nil, unmapError(err)
|
||||
}
|
||||
return mapValues(r.Captures, capturedEventValue), nil
|
||||
}
|
||||
|
||||
// Mapping
|
||||
|
||||
func (c *Client) InsertMapping(ctx context.Context, m mapping.Mapping) (int64, error) {
|
||||
r, err := c.client.InsertMapping(ctx, &pb.InsertMappingRequest{Mapping: mappingProto(m)})
|
||||
if err != nil {
|
||||
return 0, unmapError(err)
|
||||
}
|
||||
return r.Id, nil
|
||||
}
|
||||
|
||||
func (c *Client) GetMapping(ctx context.Context, id int64) (*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 int64) error {
|
||||
_, err := c.client.DeleteMapping(ctx, &pb.DeleteMappingRequest{Id: id})
|
||||
return unmapError(err)
|
||||
}
|
||||
|
||||
// Binding
|
||||
|
||||
func (c *Client) InsertBinding(ctx context.Context, b binding.Binding) (int64, error) {
|
||||
r, err := c.client.InsertBinding(ctx, &pb.InsertBindingRequest{Binding: bindingProto(b)})
|
||||
if err != nil {
|
||||
return 0, unmapError(err)
|
||||
}
|
||||
return r.Id, nil
|
||||
}
|
||||
|
||||
func (c *Client) GetBinding(ctx context.Context, id int64) (*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) 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 int64) error {
|
||||
_, err := c.client.DeleteBinding(ctx, &pb.DeleteBindingRequest{Id: id})
|
||||
return unmapError(err)
|
||||
}
|
||||
|
||||
func (c *Client) ApproveBinding(ctx context.Context, id int64) error {
|
||||
_, err := c.client.ApproveBinding(ctx, &pb.ApproveBindingRequest{Id: id})
|
||||
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, bindingVersion, captureID, taskID int64) error {
|
||||
_, err := c.client.RecordDispatch(ctx, &pb.RecordDispatchRequest{BindingId: bindingID, BindingVersion: bindingVersion, CaptureId: captureID, TaskId: taskID})
|
||||
return unmapError(err)
|
||||
}
|
||||
|
||||
func (c *Client) ListUndispatchedCaptures(ctx context.Context, sources []string, limit int) ([]store.CapturedEvent, error) {
|
||||
r, err := c.client.ListUndispatchedCaptures(ctx, &pb.ListUndispatchedCapturesRequest{Sources: sources, Limit: int64(limit)})
|
||||
if err != nil {
|
||||
return nil, unmapError(err)
|
||||
}
|
||||
return mapValues(r.Captures, capturedEventValue), nil
|
||||
}
|
||||
|
||||
// BindingTaskCreator
|
||||
|
||||
func (c *Client) EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity string, bindingID int64, bindingVersion int) (*workflow.Task, error) {
|
||||
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)})
|
||||
if err != nil {
|
||||
return nil, unmapError(err)
|
||||
}
|
||||
return taskValue(r.Task), nil
|
||||
}
|
||||
|
||||
func derefTasks(in []*pb.Task) []workflow.Task {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]workflow.Task, len(in))
|
||||
for i, t := range in {
|
||||
out[i] = *taskValue(t)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// contract is the union of every store surface staterpc fronts, so the same
|
||||
// test battery drives both the local *store.Store and the remote *Client
|
||||
// through one interface value, per docs/prds/state-store-contract.md §11's
|
||||
// conformance requirement.
|
||||
type contract interface {
|
||||
store.TaskStore
|
||||
store.CaptureStore
|
||||
store.MappingStore
|
||||
store.BindingStore
|
||||
store.BindingDispatcher
|
||||
store.BindingTaskCreator
|
||||
}
|
||||
|
||||
func remoteContract(t *testing.T, local *store.Store) contract {
|
||||
t.Helper()
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
server := grpc.NewServer()
|
||||
RegisterServer(server, Deps{
|
||||
Tasks: local, Captures: local, Mappings: local, Bindings: local,
|
||||
BindingDispatcher: local, BindingTaskCreator: local,
|
||||
})
|
||||
go func() { _ = server.Serve(listener) }()
|
||||
t.Cleanup(func() { server.Stop(); _ = listener.Close() })
|
||||
conn, err := grpc.NewClient("passthrough:///state",
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) }))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
return NewClient(conn)
|
||||
}
|
||||
|
||||
// TestStateStoreConformance runs the same battery of contract calls through
|
||||
// both the local adapter and a bufconn-backed gRPC client, asserting
|
||||
// identical behaviour including error-sentinel fidelity and the
|
||||
// not-found-as-(nil,nil) convention (§7, §11).
|
||||
func TestStateStoreConformance(t *testing.T) {
|
||||
for _, mode := range []string{"local", "grpc"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
local := store.OpenTest(t)
|
||||
var c contract = local
|
||||
if mode == "grpc" {
|
||||
c = remoteContract(t, local)
|
||||
}
|
||||
|
||||
// workflow.Store view: EnqueueChatTask, Transition, Update, InsertEvent.
|
||||
task, err := c.EnqueueChatTask(ctx, "acme", "widget", "title", "body", "implement", "")
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("EnqueueChatTask: %+v %v", task, err)
|
||||
}
|
||||
if err := c.Transition(ctx, task.ID, task.Status, "running", "started"); err != nil {
|
||||
t.Fatalf("Transition: %v", err)
|
||||
}
|
||||
task.Plan = "the plan"
|
||||
task.Status = "running"
|
||||
if err := c.Update(ctx, task); err != nil {
|
||||
t.Fatalf("Update: %v", err)
|
||||
}
|
||||
eventID, err := c.InsertEvent(ctx, events.Event{Kind: "stage_finish", TaskID: task.ID, Data: map[string]any{"duration_ms": 12.0}})
|
||||
if err != nil || eventID == 0 {
|
||||
t.Fatalf("InsertEvent: %v %v", eventID, err)
|
||||
}
|
||||
|
||||
// Stale transition: from no longer matches current status.
|
||||
err = c.Transition(ctx, task.ID, "queued", "merged", "")
|
||||
if !errors.Is(err, store.ErrStaleTransition) {
|
||||
t.Fatalf("Transition stale = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
|
||||
// TaskQueries: found=false is not an error.
|
||||
missing, err := c.TaskByID(ctx, task.ID+999999)
|
||||
if err != nil || missing != nil {
|
||||
t.Fatalf("TaskByID missing: %+v %v", missing, err)
|
||||
}
|
||||
got, err := c.TaskByID(ctx, task.ID)
|
||||
if err != nil || got == nil || got.Plan != "the plan" {
|
||||
t.Fatalf("TaskByID: %+v %v", got, err)
|
||||
}
|
||||
byIssue, err := c.TaskByIssue(ctx, task.Owner, task.Repo, task.IssueNumber)
|
||||
if err != nil || byIssue == nil || byIssue.ID != task.ID {
|
||||
t.Fatalf("TaskByIssue: %+v %v", byIssue, err)
|
||||
}
|
||||
if _, err := c.Tasks(ctx, 10); err != nil {
|
||||
t.Fatalf("Tasks: %v", err)
|
||||
}
|
||||
if _, err := c.StatusCounts(ctx); err != nil {
|
||||
t.Fatalf("StatusCounts: %v", err)
|
||||
}
|
||||
if _, err := c.OpenPRs(ctx); err != nil {
|
||||
t.Fatalf("OpenPRs: %v", err)
|
||||
}
|
||||
if err := c.IncrementRetryCount(ctx, task.ID); err != nil {
|
||||
t.Fatalf("IncrementRetryCount: %v", err)
|
||||
}
|
||||
|
||||
// TaskEvents / EventsSince / stats.
|
||||
if evs, err := c.TaskEvents(ctx, task.ID); err != nil || len(evs) != 1 || evs[0].Data["duration_ms"] != 12.0 {
|
||||
t.Fatalf("TaskEvents: %+v %v", evs, err)
|
||||
}
|
||||
if _, err := c.EventsSince(ctx, 0, 10); err != nil {
|
||||
t.Fatalf("EventsSince: %v", err)
|
||||
}
|
||||
if _, err := c.WorkflowStats(ctx); err != nil {
|
||||
t.Fatalf("WorkflowStats: %v", err)
|
||||
}
|
||||
if _, err := c.StageStats(ctx); err != nil {
|
||||
t.Fatalf("StageStats: %v", err)
|
||||
}
|
||||
if _, err := c.TokensByDay(ctx, 7); err != nil {
|
||||
t.Fatalf("TokensByDay: %v", err)
|
||||
}
|
||||
|
||||
// Lifecycle: ClaimNext / ClaimByIssue / Requeue / RetryTask / RecoverStale.
|
||||
if _, err := c.EnqueueIssue(ctx, "acme", "widget", 42, "issue title", "body", "bug", ""); err != nil {
|
||||
t.Fatalf("EnqueueIssue: %v", err)
|
||||
}
|
||||
claimed, err := c.ClaimNext(ctx)
|
||||
if err != nil || claimed == nil {
|
||||
t.Fatalf("ClaimNext: %+v %v", claimed, err)
|
||||
}
|
||||
if err := c.Requeue(ctx, claimed.ID, "running", ""); err != nil {
|
||||
t.Fatalf("Requeue: %v", err)
|
||||
}
|
||||
if err := c.RetryTask(ctx, claimed.ID, "queued", ""); err != nil {
|
||||
t.Fatalf("RetryTask: %v", err)
|
||||
}
|
||||
if _, err := c.RecoverStale(ctx); err != nil {
|
||||
t.Fatalf("RecoverStale: %v", err)
|
||||
}
|
||||
byClaim, err := c.ClaimByIssue(ctx, "acme", "widget", 999999)
|
||||
if err != nil || byClaim != nil {
|
||||
t.Fatalf("ClaimByIssue missing: %+v %v", byClaim, err)
|
||||
}
|
||||
|
||||
// Archive. RecoverStale above may have requeued task if it was
|
||||
// still running, so re-fetch its current status rather than
|
||||
// trusting the in-memory snapshot.
|
||||
current, err := c.TaskByID(ctx, task.ID)
|
||||
if err != nil || current == nil {
|
||||
t.Fatalf("TaskByID before archive: %+v %v", current, err)
|
||||
}
|
||||
if _, err := c.ArchiveTask(ctx, task.ID, current.Status, events.Event{Kind: "archived"}); err != nil {
|
||||
t.Fatalf("ArchiveTask: %v", err)
|
||||
}
|
||||
if _, err := c.ClearTerminalTasks(ctx); err != nil {
|
||||
t.Fatalf("ClearTerminalTasks: %v", err)
|
||||
}
|
||||
|
||||
// Mapping: found=false, ErrMappingNotFound.
|
||||
mappingID, err := c.InsertMapping(ctx, mapping.Mapping{Name: "m1", Fields: []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}}})
|
||||
if err != nil || mappingID == 0 {
|
||||
t.Fatalf("InsertMapping: %v %v", mappingID, err)
|
||||
}
|
||||
missingMapping, err := c.GetMapping(ctx, mappingID+999999)
|
||||
if err != nil || missingMapping != nil {
|
||||
t.Fatalf("GetMapping missing: %+v %v", missingMapping, err)
|
||||
}
|
||||
gotMapping, err := c.GetMapping(ctx, mappingID)
|
||||
if err != nil || gotMapping == nil || gotMapping.Name != "m1" {
|
||||
t.Fatalf("GetMapping: %+v %v", gotMapping, err)
|
||||
}
|
||||
if _, err := c.ListMappings(ctx); err != nil {
|
||||
t.Fatalf("ListMappings: %v", err)
|
||||
}
|
||||
gotMapping.Name = "m1-renamed"
|
||||
if err := c.UpdateMapping(ctx, *gotMapping); err != nil {
|
||||
t.Fatalf("UpdateMapping: %v", err)
|
||||
}
|
||||
err = c.UpdateMapping(ctx, mapping.Mapping{ID: mappingID + 999999, Name: "x", Fields: gotMapping.Fields})
|
||||
if !errors.Is(err, store.ErrMappingNotFound) {
|
||||
t.Fatalf("UpdateMapping missing = %v, want ErrMappingNotFound", err)
|
||||
}
|
||||
err = c.DeleteMapping(ctx, mappingID+999999)
|
||||
if !errors.Is(err, store.ErrMappingNotFound) {
|
||||
t.Fatalf("DeleteMapping missing = %v, want ErrMappingNotFound", err)
|
||||
}
|
||||
|
||||
// Binding: found=false, ErrBindingNotFound, ErrBindingOverlap,
|
||||
// ErrBindingTransition, and the dispatch surface incl.
|
||||
// ErrAlreadyDispatched.
|
||||
bindingID, err := c.InsertBinding(ctx, binding.Binding{
|
||||
Name: "b1", Matcher: binding.Matcher{Source: "sentry"}, MappingID: mappingID,
|
||||
Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
|
||||
})
|
||||
if err != nil || bindingID == 0 {
|
||||
t.Fatalf("InsertBinding: %v %v", bindingID, err)
|
||||
}
|
||||
_, err = c.InsertBinding(ctx, binding.Binding{
|
||||
Name: "b2", Matcher: binding.Matcher{Source: "sentry"}, MappingID: mappingID,
|
||||
Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
|
||||
})
|
||||
if !errors.Is(err, store.ErrBindingOverlap) {
|
||||
t.Fatalf("InsertBinding overlap = %v, want ErrBindingOverlap", err)
|
||||
}
|
||||
missingBinding, err := c.GetBinding(ctx, bindingID+999999)
|
||||
if err != nil || missingBinding != nil {
|
||||
t.Fatalf("GetBinding missing: %+v %v", missingBinding, err)
|
||||
}
|
||||
gotBinding, err := c.GetBinding(ctx, bindingID)
|
||||
if err != nil || gotBinding == nil || gotBinding.Name != "b1" {
|
||||
t.Fatalf("GetBinding: %+v %v", gotBinding, err)
|
||||
}
|
||||
if _, err := c.ListBindings(ctx); err != nil {
|
||||
t.Fatalf("ListBindings: %v", err)
|
||||
}
|
||||
err = c.ApproveBinding(ctx, bindingID)
|
||||
if !errors.Is(err, store.ErrBindingTransition) {
|
||||
t.Fatalf("ApproveBinding from draft = %v, want ErrBindingTransition", err)
|
||||
}
|
||||
err = c.DeleteBinding(ctx, bindingID+999999)
|
||||
if !errors.Is(err, store.ErrBindingNotFound) {
|
||||
t.Fatalf("DeleteBinding missing = %v, want ErrBindingNotFound", err)
|
||||
}
|
||||
|
||||
// Capture + dispatch.
|
||||
captureID, err := c.InsertCapture(ctx, store.CapturedEvent{Source: "sentry", Body: `{"id":1}`, Authenticated: true}, 0, 0)
|
||||
if err != nil || captureID == 0 {
|
||||
t.Fatalf("InsertCapture: %v %v", captureID, err)
|
||||
}
|
||||
if _, err := c.ListCaptures(ctx, 10); err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if _, err := c.ArmedBindingsForSource(ctx, "sentry"); err != nil {
|
||||
t.Fatalf("ArmedBindingsForSource: %v", err)
|
||||
}
|
||||
bindingTask, err := c.EnqueueBindingTask(ctx, "acme", "widget", "t", "b", "implement", "", bindingID, 1)
|
||||
if err != nil || bindingTask == nil {
|
||||
t.Fatalf("EnqueueBindingTask: %+v %v", bindingTask, err)
|
||||
}
|
||||
if err := c.RecordDispatch(ctx, bindingID, 1, captureID, bindingTask.ID); err != nil {
|
||||
t.Fatalf("RecordDispatch: %v", err)
|
||||
}
|
||||
err = c.RecordDispatch(ctx, bindingID, 1, captureID, bindingTask.ID)
|
||||
if !errors.Is(err, store.ErrAlreadyDispatched) {
|
||||
t.Fatalf("RecordDispatch dup = %v, want ErrAlreadyDispatched", err)
|
||||
}
|
||||
if _, err := c.ListUndispatchedCaptures(ctx, []string{"sentry"}, 10); err != nil {
|
||||
t.Fatalf("ListUndispatchedCaptures: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestTokenInterceptorRejectsMissingOrInvalidToken exercises the gRPC
|
||||
// interceptor the bridge-address (agent-consumed) listener topology
|
||||
// requires: missing or unrecognised tokens fail closed with
|
||||
// codes.Unauthenticated, per §9's token lifecycle.
|
||||
func TestTokenInterceptorRejectsMissingOrInvalidToken(t *testing.T) {
|
||||
const validToken = "task-42-token"
|
||||
validate := func(token string) bool { return token == validToken }
|
||||
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
local := store.OpenTest(t)
|
||||
server := grpc.NewServer(grpc.UnaryInterceptor(UnaryTokenInterceptor(validate)))
|
||||
RegisterServer(server, Deps{Tasks: local})
|
||||
go func() { _ = server.Serve(listener) }()
|
||||
t.Cleanup(func() { server.Stop(); _ = listener.Close() })
|
||||
|
||||
dial := func(t *testing.T, token string) contract {
|
||||
t.Helper()
|
||||
opts := []grpc.DialOption{
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) }),
|
||||
}
|
||||
if token != "" {
|
||||
opts = append(opts, grpc.WithUnaryInterceptor(UnaryClientTokenInterceptor(token)))
|
||||
}
|
||||
conn, err := grpc.NewClient("passthrough:///state", opts...)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
return NewClient(conn)
|
||||
}
|
||||
|
||||
ctx := t.Context()
|
||||
if _, err := dial(t, "").StatusCounts(ctx); err == nil {
|
||||
t.Fatal("missing token accepted")
|
||||
}
|
||||
if _, err := dial(t, "wrong-token").StatusCounts(ctx); err == nil {
|
||||
t.Fatal("invalid token accepted")
|
||||
}
|
||||
if _, err := dial(t, validToken).StatusCounts(ctx); err != nil {
|
||||
t.Fatalf("valid token rejected: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,509 @@
|
||||
// Package staterpc adapts the State Store contract (internal/store's
|
||||
// producer-owned surfaces plus the consumer-owned workflow.Store) to gRPC.
|
||||
// See docs/prds/state-store-contract.md for the ratified contract this
|
||||
// package implements against.
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
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/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// Unavailable-capability errors, mirroring gatewayrpc's missing-session-store
|
||||
// pattern (docs/prds/state-store-contract.md §7's "capability absent ->
|
||||
// Unavailable" row): a nil optional Deps field maps to codes.Unavailable
|
||||
// rather than a nil-pointer panic.
|
||||
var (
|
||||
errCaptureUnavailable = status.Error(codes.Unavailable, "capture store unavailable")
|
||||
errMappingUnavailable = status.Error(codes.Unavailable, "mapping store unavailable")
|
||||
errBindingUnavailable = status.Error(codes.Unavailable, "binding store unavailable")
|
||||
errBindingDispatchUnavailable = status.Error(codes.Unavailable, "binding dispatcher unavailable")
|
||||
errBindingTaskCreatorUnavailable = status.Error(codes.Unavailable, "binding task creator unavailable")
|
||||
)
|
||||
|
||||
func timeSeconds(s int64) time.Duration { return time.Duration(s) * time.Second }
|
||||
|
||||
// Deps groups the store surfaces the StateStore service fronts. TaskStore is
|
||||
// required; the rest are optional (nil disables that group's RPCs, returning
|
||||
// codes.Unavailable) exactly as their daemon-side consumers already treat a
|
||||
// nil Mappings/Bindings/BindingDispatcher/BindingTaskCreator as "disabled".
|
||||
type Deps struct {
|
||||
Tasks store.TaskStore
|
||||
Captures store.CaptureStore
|
||||
Mappings store.MappingStore
|
||||
Bindings store.BindingStore
|
||||
BindingDispatcher store.BindingDispatcher
|
||||
BindingTaskCreator store.BindingTaskCreator
|
||||
Log *slog.Logger
|
||||
}
|
||||
|
||||
type server struct {
|
||||
pb.UnimplementedStateStoreServiceServer
|
||||
deps Deps
|
||||
}
|
||||
|
||||
// RegisterServer registers the StateStore gRPC service against registrar,
|
||||
// backed by deps. Optionally wrap registrar's interceptor chain with
|
||||
// TokenInterceptor for the bridge-address (agent-consumed) topology; the
|
||||
// caller decides, per docs/prds/state-store-contract.md §9's listener rule.
|
||||
func RegisterServer(registrar grpc.ServiceRegistrar, deps Deps) {
|
||||
if deps.Log == nil {
|
||||
deps.Log = slog.New(slog.DiscardHandler)
|
||||
}
|
||||
pb.RegisterStateStoreServiceServer(registrar, &server{deps: deps})
|
||||
}
|
||||
|
||||
func (s *server) logErr(rpc string, err error) error {
|
||||
if err != nil {
|
||||
s.deps.Log.Error("staterpc call failed", "rpc", rpc, "err", err)
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
// Lifecycle
|
||||
|
||||
func (s *server) EnqueueIssue(ctx context.Context, r *pb.EnqueueIssueRequest) (*pb.EnqueueIssueResponse, error) {
|
||||
inserted, err := s.deps.Tasks.EnqueueIssue(ctx, r.Owner, r.Repo, int(r.Number), r.Title, r.Body, r.Labels, r.Identity)
|
||||
if err != nil {
|
||||
return nil, s.logErr("EnqueueIssue", err)
|
||||
}
|
||||
return &pb.EnqueueIssueResponse{Inserted: inserted}, nil
|
||||
}
|
||||
|
||||
func (s *server) EnqueueChatTask(ctx context.Context, r *pb.EnqueueChatTaskRequest) (*pb.EnqueueChatTaskResponse, error) {
|
||||
t, err := s.deps.Tasks.EnqueueChatTask(ctx, r.Owner, r.Repo, r.Title, r.Body, r.Workflow, r.Identity)
|
||||
if err != nil {
|
||||
return nil, s.logErr("EnqueueChatTask", err)
|
||||
}
|
||||
return &pb.EnqueueChatTaskResponse{Task: taskProto(t)}, nil
|
||||
}
|
||||
|
||||
func (s *server) ClaimNext(ctx context.Context, _ *pb.ClaimNextRequest) (*pb.ClaimNextResponse, error) {
|
||||
t, err := s.deps.Tasks.ClaimNext(ctx)
|
||||
if err != nil {
|
||||
return nil, s.logErr("ClaimNext", err)
|
||||
}
|
||||
return &pb.ClaimNextResponse{Task: taskProto(t), Found: t != nil}, nil
|
||||
}
|
||||
|
||||
func (s *server) ClaimByIssue(ctx context.Context, r *pb.ClaimByIssueRequest) (*pb.ClaimByIssueResponse, error) {
|
||||
t, err := s.deps.Tasks.ClaimByIssue(ctx, r.Owner, r.Repo, int(r.Number))
|
||||
if err != nil {
|
||||
return nil, s.logErr("ClaimByIssue", err)
|
||||
}
|
||||
return &pb.ClaimByIssueResponse{Task: taskProto(t), Found: t != nil}, nil
|
||||
}
|
||||
|
||||
func (s *server) Transition(ctx context.Context, r *pb.TransitionRequest) (*pb.TransitionResponse, error) {
|
||||
if err := s.deps.Tasks.Transition(ctx, r.TaskId, r.From, r.To, r.Detail); err != nil {
|
||||
return nil, s.logErr("Transition", err)
|
||||
}
|
||||
return &pb.TransitionResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *server) Update(ctx context.Context, r *pb.UpdateRequest) (*pb.UpdateResponse, error) {
|
||||
if err := s.deps.Tasks.Update(ctx, taskValue(r.Task)); err != nil {
|
||||
return nil, s.logErr("Update", err)
|
||||
}
|
||||
return &pb.UpdateResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *server) Requeue(ctx context.Context, r *pb.RequeueRequest) (*pb.RequeueResponse, error) {
|
||||
if err := s.deps.Tasks.Requeue(ctx, r.TaskId, r.FromStatus, r.Workflow); err != nil {
|
||||
return nil, s.logErr("Requeue", err)
|
||||
}
|
||||
return &pb.RequeueResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *server) RecoverStale(ctx context.Context, _ *pb.RecoverStaleRequest) (*pb.RecoverStaleResponse, error) {
|
||||
n, err := s.deps.Tasks.RecoverStale(ctx)
|
||||
if err != nil {
|
||||
return nil, s.logErr("RecoverStale", err)
|
||||
}
|
||||
return &pb.RecoverStaleResponse{Count: n}, nil
|
||||
}
|
||||
|
||||
// Archive / Retry
|
||||
|
||||
func (s *server) ArchiveTask(ctx context.Context, r *pb.ArchiveTaskRequest) (*pb.ArchiveTaskResponse, error) {
|
||||
eventID, err := s.deps.Tasks.ArchiveTask(ctx, r.TaskId, r.FromStatus, eventValue(r.Audit))
|
||||
if err != nil {
|
||||
return nil, s.logErr("ArchiveTask", err)
|
||||
}
|
||||
return &pb.ArchiveTaskResponse{EventId: eventID}, nil
|
||||
}
|
||||
|
||||
func (s *server) RetryTask(ctx context.Context, r *pb.RetryTaskRequest) (*pb.RetryTaskResponse, error) {
|
||||
if err := s.deps.Tasks.RetryTask(ctx, r.TaskId, r.FromStatus, r.Workflow); err != nil {
|
||||
return nil, s.logErr("RetryTask", err)
|
||||
}
|
||||
return &pb.RetryTaskResponse{}, nil
|
||||
}
|
||||
|
||||
// Queries
|
||||
|
||||
func (s *server) TaskByIssue(ctx context.Context, r *pb.TaskByIssueRequest) (*pb.TaskByIssueResponse, error) {
|
||||
t, err := s.deps.Tasks.TaskByIssue(ctx, r.Owner, r.Repo, int(r.Number))
|
||||
if err != nil {
|
||||
return nil, s.logErr("TaskByIssue", err)
|
||||
}
|
||||
return &pb.TaskByIssueResponse{Task: taskProto(t), Found: t != nil}, nil
|
||||
}
|
||||
|
||||
func (s *server) TaskByID(ctx context.Context, r *pb.TaskByIDRequest) (*pb.TaskByIDResponse, error) {
|
||||
t, err := s.deps.Tasks.TaskByID(ctx, r.TaskId)
|
||||
if err != nil {
|
||||
return nil, s.logErr("TaskByID", err)
|
||||
}
|
||||
return &pb.TaskByIDResponse{Task: taskProto(t), Found: t != nil}, nil
|
||||
}
|
||||
|
||||
func (s *server) OpenPRs(ctx context.Context, _ *pb.OpenPRsRequest) (*pb.OpenPRsResponse, error) {
|
||||
tasks, err := s.deps.Tasks.OpenPRs(ctx)
|
||||
if err != nil {
|
||||
return nil, s.logErr("OpenPRs", err)
|
||||
}
|
||||
out := make([]*pb.Task, len(tasks))
|
||||
for i := range tasks {
|
||||
out[i] = taskProto(&tasks[i])
|
||||
}
|
||||
return &pb.OpenPRsResponse{Tasks: out}, nil
|
||||
}
|
||||
|
||||
func (s *server) ClearTerminalTasks(ctx context.Context, _ *pb.ClearTerminalTasksRequest) (*pb.ClearTerminalTasksResponse, error) {
|
||||
n, err := s.deps.Tasks.ClearTerminalTasks(ctx)
|
||||
if err != nil {
|
||||
return nil, s.logErr("ClearTerminalTasks", err)
|
||||
}
|
||||
return &pb.ClearTerminalTasksResponse{Count: n}, nil
|
||||
}
|
||||
|
||||
func (s *server) Tasks(ctx context.Context, r *pb.TasksRequest) (*pb.TasksResponse, error) {
|
||||
tasks, err := s.deps.Tasks.Tasks(ctx, int(r.Limit))
|
||||
if err != nil {
|
||||
return nil, s.logErr("Tasks", err)
|
||||
}
|
||||
out := make([]*pb.Task, len(tasks))
|
||||
for i := range tasks {
|
||||
out[i] = taskProto(&tasks[i])
|
||||
}
|
||||
return &pb.TasksResponse{Tasks: out}, nil
|
||||
}
|
||||
|
||||
func (s *server) StatusCounts(ctx context.Context, _ *pb.StatusCountsRequest) (*pb.StatusCountsResponse, error) {
|
||||
counts, err := s.deps.Tasks.StatusCounts(ctx)
|
||||
if err != nil {
|
||||
return nil, s.logErr("StatusCounts", err)
|
||||
}
|
||||
out := make(map[string]int64, len(counts))
|
||||
for k, v := range counts {
|
||||
out[k] = int64(v)
|
||||
}
|
||||
return &pb.StatusCountsResponse{Counts: out}, nil
|
||||
}
|
||||
|
||||
func (s *server) IncrementRetryCount(ctx context.Context, r *pb.IncrementRetryCountRequest) (*pb.IncrementRetryCountResponse, error) {
|
||||
if err := s.deps.Tasks.IncrementRetryCount(ctx, r.TaskId); err != nil {
|
||||
return nil, s.logErr("IncrementRetryCount", err)
|
||||
}
|
||||
return &pb.IncrementRetryCountResponse{}, nil
|
||||
}
|
||||
|
||||
// Events
|
||||
|
||||
func (s *server) InsertEvent(ctx context.Context, r *pb.InsertEventRequest) (*pb.InsertEventResponse, error) {
|
||||
id, err := s.deps.Tasks.InsertEvent(ctx, eventValue(r.Event))
|
||||
if err != nil {
|
||||
return nil, s.logErr("InsertEvent", err)
|
||||
}
|
||||
return &pb.InsertEventResponse{Id: id}, nil
|
||||
}
|
||||
|
||||
func (s *server) EventsSince(ctx context.Context, r *pb.EventsSinceRequest) (*pb.EventsSinceResponse, error) {
|
||||
evs, err := s.deps.Tasks.EventsSince(ctx, r.SinceId, int(r.Limit))
|
||||
if err != nil {
|
||||
return nil, s.logErr("EventsSince", err)
|
||||
}
|
||||
return &pb.EventsSinceResponse{Events: mapValues(evs, eventProto)}, nil
|
||||
}
|
||||
|
||||
func (s *server) TaskEvents(ctx context.Context, r *pb.TaskEventsRequest) (*pb.TaskEventsResponse, error) {
|
||||
evs, err := s.deps.Tasks.TaskEvents(ctx, r.TaskId)
|
||||
if err != nil {
|
||||
return nil, s.logErr("TaskEvents", err)
|
||||
}
|
||||
return &pb.TaskEventsResponse{Events: mapValues(evs, eventProto)}, nil
|
||||
}
|
||||
|
||||
func (s *server) WorkflowStats(ctx context.Context, _ *pb.WorkflowStatsRequest) (*pb.WorkflowStatsResponse, error) {
|
||||
stats, err := s.deps.Tasks.WorkflowStats(ctx)
|
||||
if err != nil {
|
||||
return nil, s.logErr("WorkflowStats", err)
|
||||
}
|
||||
return &pb.WorkflowStatsResponse{Stats: mapValues(stats, workflowStatProto)}, nil
|
||||
}
|
||||
|
||||
func (s *server) StageStats(ctx context.Context, _ *pb.StageStatsRequest) (*pb.StageStatsResponse, error) {
|
||||
stats, err := s.deps.Tasks.StageStats(ctx)
|
||||
if err != nil {
|
||||
return nil, s.logErr("StageStats", err)
|
||||
}
|
||||
return &pb.StageStatsResponse{Stats: mapValues(stats, stageStatProto)}, nil
|
||||
}
|
||||
|
||||
func (s *server) TokensByDay(ctx context.Context, r *pb.TokensByDayRequest) (*pb.TokensByDayResponse, error) {
|
||||
tokens, err := s.deps.Tasks.TokensByDay(ctx, int(r.Days))
|
||||
if err != nil {
|
||||
return nil, s.logErr("TokensByDay", err)
|
||||
}
|
||||
return &pb.TokensByDayResponse{Tokens: mapValues(tokens, dayTokensProto)}, nil
|
||||
}
|
||||
|
||||
// Capture
|
||||
|
||||
func (s *server) capture() (store.CaptureStore, error) {
|
||||
if s.deps.Captures == nil {
|
||||
return nil, errCaptureUnavailable
|
||||
}
|
||||
return s.deps.Captures, nil
|
||||
}
|
||||
|
||||
func (s *server) InsertCapture(ctx context.Context, r *pb.InsertCaptureRequest) (*pb.InsertCaptureResponse, error) {
|
||||
cs, err := s.capture()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id, err := cs.InsertCapture(ctx, capturedEventValue(r.Capture), timeSeconds(r.RetentionSeconds), int(r.MaxEvents))
|
||||
if err != nil {
|
||||
return nil, s.logErr("InsertCapture", err)
|
||||
}
|
||||
return &pb.InsertCaptureResponse{Id: id}, nil
|
||||
}
|
||||
|
||||
func (s *server) ListCaptures(ctx context.Context, r *pb.ListCapturesRequest) (*pb.ListCapturesResponse, error) {
|
||||
cs, err := s.capture()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
captures, err := cs.ListCaptures(ctx, int(r.Limit))
|
||||
if err != nil {
|
||||
return nil, s.logErr("ListCaptures", err)
|
||||
}
|
||||
return &pb.ListCapturesResponse{Captures: mapValues(captures, capturedEventProto)}, nil
|
||||
}
|
||||
|
||||
// Mapping
|
||||
|
||||
func (s *server) mapping() (store.MappingStore, error) {
|
||||
if s.deps.Mappings == nil {
|
||||
return nil, errMappingUnavailable
|
||||
}
|
||||
return s.deps.Mappings, nil
|
||||
}
|
||||
|
||||
func (s *server) InsertMapping(ctx context.Context, r *pb.InsertMappingRequest) (*pb.InsertMappingResponse, error) {
|
||||
ms, err := s.mapping()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id, err := ms.InsertMapping(ctx, mappingValue(r.Mapping))
|
||||
if err != nil {
|
||||
return nil, s.logErr("InsertMapping", err)
|
||||
}
|
||||
return &pb.InsertMappingResponse{Id: id}, nil
|
||||
}
|
||||
|
||||
func (s *server) GetMapping(ctx context.Context, r *pb.GetMappingRequest) (*pb.GetMappingResponse, error) {
|
||||
ms, err := s.mapping()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m, err := ms.GetMapping(ctx, r.Id)
|
||||
if err != nil {
|
||||
return nil, s.logErr("GetMapping", err)
|
||||
}
|
||||
return &pb.GetMappingResponse{Mapping: mappingProtoPtr(m), Found: m != nil}, nil
|
||||
}
|
||||
|
||||
func (s *server) ListMappings(ctx context.Context, _ *pb.ListMappingsRequest) (*pb.ListMappingsResponse, error) {
|
||||
ms, err := s.mapping()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mappings, err := ms.ListMappings(ctx)
|
||||
if err != nil {
|
||||
return nil, s.logErr("ListMappings", err)
|
||||
}
|
||||
return &pb.ListMappingsResponse{Mappings: mapValues(mappings, mappingProto)}, nil
|
||||
}
|
||||
|
||||
func (s *server) UpdateMapping(ctx context.Context, r *pb.UpdateMappingRequest) (*pb.UpdateMappingResponse, error) {
|
||||
ms, err := s.mapping()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ms.UpdateMapping(ctx, mappingValue(r.Mapping)); err != nil {
|
||||
return nil, s.logErr("UpdateMapping", err)
|
||||
}
|
||||
return &pb.UpdateMappingResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *server) DeleteMapping(ctx context.Context, r *pb.DeleteMappingRequest) (*pb.DeleteMappingResponse, error) {
|
||||
ms, err := s.mapping()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ms.DeleteMapping(ctx, r.Id); err != nil {
|
||||
return nil, s.logErr("DeleteMapping", err)
|
||||
}
|
||||
return &pb.DeleteMappingResponse{}, nil
|
||||
}
|
||||
|
||||
// Binding
|
||||
|
||||
func (s *server) binding() (store.BindingStore, error) {
|
||||
if s.deps.Bindings == nil {
|
||||
return nil, errBindingUnavailable
|
||||
}
|
||||
return s.deps.Bindings, nil
|
||||
}
|
||||
|
||||
func (s *server) InsertBinding(ctx context.Context, r *pb.InsertBindingRequest) (*pb.InsertBindingResponse, error) {
|
||||
bs, err := s.binding()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id, err := bs.InsertBinding(ctx, bindingValue(r.Binding))
|
||||
if err != nil {
|
||||
return nil, s.logErr("InsertBinding", err)
|
||||
}
|
||||
return &pb.InsertBindingResponse{Id: id}, nil
|
||||
}
|
||||
|
||||
func (s *server) GetBinding(ctx context.Context, r *pb.GetBindingRequest) (*pb.GetBindingResponse, error) {
|
||||
bs, err := s.binding()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b, err := bs.GetBinding(ctx, r.Id)
|
||||
if err != nil {
|
||||
return nil, s.logErr("GetBinding", err)
|
||||
}
|
||||
return &pb.GetBindingResponse{Binding: bindingProtoPtr(b), Found: b != nil}, nil
|
||||
}
|
||||
|
||||
func (s *server) ListBindings(ctx context.Context, _ *pb.ListBindingsRequest) (*pb.ListBindingsResponse, error) {
|
||||
bs, err := s.binding()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
bindings, err := bs.ListBindings(ctx)
|
||||
if err != nil {
|
||||
return nil, s.logErr("ListBindings", err)
|
||||
}
|
||||
return &pb.ListBindingsResponse{Bindings: mapValues(bindings, bindingProto)}, nil
|
||||
}
|
||||
|
||||
func (s *server) UpdateBinding(ctx context.Context, r *pb.UpdateBindingRequest) (*pb.UpdateBindingResponse, error) {
|
||||
bs, err := s.binding()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := bs.UpdateBinding(ctx, bindingValue(r.Binding)); err != nil {
|
||||
return nil, s.logErr("UpdateBinding", err)
|
||||
}
|
||||
return &pb.UpdateBindingResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *server) DeleteBinding(ctx context.Context, r *pb.DeleteBindingRequest) (*pb.DeleteBindingResponse, error) {
|
||||
bs, err := s.binding()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := bs.DeleteBinding(ctx, r.Id); err != nil {
|
||||
return nil, s.logErr("DeleteBinding", err)
|
||||
}
|
||||
return &pb.DeleteBindingResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *server) ApproveBinding(ctx context.Context, r *pb.ApproveBindingRequest) (*pb.ApproveBindingResponse, error) {
|
||||
bs, err := s.binding()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := bs.ApproveBinding(ctx, r.Id); err != nil {
|
||||
return nil, s.logErr("ApproveBinding", err)
|
||||
}
|
||||
return &pb.ApproveBindingResponse{}, nil
|
||||
}
|
||||
|
||||
// Dispatch
|
||||
|
||||
func (s *server) ArmedBindingsForSource(ctx context.Context, r *pb.ArmedBindingsForSourceRequest) (*pb.ArmedBindingsForSourceResponse, error) {
|
||||
if s.deps.BindingDispatcher == nil {
|
||||
return nil, errBindingDispatchUnavailable
|
||||
}
|
||||
bindings, err := s.deps.BindingDispatcher.ArmedBindingsForSource(ctx, r.Source)
|
||||
if err != nil {
|
||||
return nil, s.logErr("ArmedBindingsForSource", err)
|
||||
}
|
||||
return &pb.ArmedBindingsForSourceResponse{Bindings: mapValues(bindings, bindingProto)}, nil
|
||||
}
|
||||
|
||||
func (s *server) RecordDispatch(ctx context.Context, r *pb.RecordDispatchRequest) (*pb.RecordDispatchResponse, error) {
|
||||
if s.deps.BindingDispatcher == nil {
|
||||
return nil, errBindingDispatchUnavailable
|
||||
}
|
||||
if err := s.deps.BindingDispatcher.RecordDispatch(ctx, r.BindingId, r.BindingVersion, r.CaptureId, r.TaskId); err != nil {
|
||||
return nil, s.logErr("RecordDispatch", err)
|
||||
}
|
||||
return &pb.RecordDispatchResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *server) ListUndispatchedCaptures(ctx context.Context, r *pb.ListUndispatchedCapturesRequest) (*pb.ListUndispatchedCapturesResponse, error) {
|
||||
if s.deps.BindingDispatcher == nil {
|
||||
return nil, errBindingDispatchUnavailable
|
||||
}
|
||||
captures, err := s.deps.BindingDispatcher.ListUndispatchedCaptures(ctx, r.Sources, int(r.Limit))
|
||||
if err != nil {
|
||||
return nil, s.logErr("ListUndispatchedCaptures", err)
|
||||
}
|
||||
return &pb.ListUndispatchedCapturesResponse{Captures: mapValues(captures, capturedEventProto)}, nil
|
||||
}
|
||||
|
||||
// BindingTaskCreator
|
||||
|
||||
func (s *server) EnqueueBindingTask(ctx context.Context, r *pb.EnqueueBindingTaskRequest) (*pb.EnqueueBindingTaskResponse, error) {
|
||||
if s.deps.BindingTaskCreator == nil {
|
||||
return nil, errBindingTaskCreatorUnavailable
|
||||
}
|
||||
t, err := s.deps.BindingTaskCreator.EnqueueBindingTask(ctx, r.Owner, r.Repo, r.Title, r.Body, r.Workflow, r.Identity, r.BindingId, int(r.BindingVersion))
|
||||
if err != nil {
|
||||
return nil, s.logErr("EnqueueBindingTask", err)
|
||||
}
|
||||
return &pb.EnqueueBindingTaskResponse{Task: taskProto(t)}, nil
|
||||
}
|
||||
|
||||
func mappingProtoPtr(m *mapping.Mapping) *pb.Mapping {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
return mappingProto(*m)
|
||||
}
|
||||
|
||||
func bindingProtoPtr(b *binding.Binding) *pb.Binding {
|
||||
if b == nil {
|
||||
return nil
|
||||
}
|
||||
return bindingProto(*b)
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"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/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
func timestamp(t time.Time) *timestamppb.Timestamp {
|
||||
if t.IsZero() {
|
||||
return nil
|
||||
}
|
||||
return timestamppb.New(t)
|
||||
}
|
||||
|
||||
func timeValue(t *timestamppb.Timestamp) time.Time {
|
||||
if t == nil {
|
||||
return time.Time{}
|
||||
}
|
||||
return t.AsTime()
|
||||
}
|
||||
|
||||
func mapValues[A, B any](in []A, f func(A) B) []B {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]B, len(in))
|
||||
for i, v := range in {
|
||||
out[i] = f(v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func taskProto(t *workflow.Task) *pb.Task { //nolint:dupl // mirror-image field-by-field proto<->domain mapping; taskValue below reverses every assignment, so line-level duplication is unavoidable without reflection
|
||||
if t == nil {
|
||||
return nil
|
||||
}
|
||||
return &pb.Task{
|
||||
Id: t.ID, Owner: t.Owner, Repo: t.Repo, IssueNumber: int64(t.IssueNumber),
|
||||
Title: t.Title, Body: t.Body, Labels: t.Labels, Status: t.Status,
|
||||
Workflow: t.Workflow, Stage: t.Stage, Branch: t.Branch, Plan: t.Plan, Notes: t.Notes,
|
||||
PrNumber: int64(t.PRNumber), TokensUsed: int64(t.TokensUsed), Iterations: int64(t.Iterations),
|
||||
Attempt: int64(t.Attempt), ParkReason: t.ParkReason, RetryCount: int64(t.RetryCount),
|
||||
WatchCommentId: t.WatchCommentID, Source: t.Source, Identity: t.Identity,
|
||||
BindingId: t.BindingID, BindingVersion: int64(t.BindingVersion),
|
||||
CreatedAt: timestamp(t.CreatedAt), UpdatedAt: timestamp(t.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func taskValue(t *pb.Task) *workflow.Task { //nolint:dupl // see taskProto above
|
||||
if t == nil {
|
||||
return nil
|
||||
}
|
||||
return &workflow.Task{
|
||||
ID: t.Id, Owner: t.Owner, Repo: t.Repo, IssueNumber: int(t.IssueNumber),
|
||||
Title: t.Title, Body: t.Body, Labels: t.Labels, Status: t.Status,
|
||||
Workflow: t.Workflow, Stage: t.Stage, Branch: t.Branch, Plan: t.Plan, Notes: t.Notes,
|
||||
PRNumber: int(t.PrNumber), TokensUsed: int(t.TokensUsed), Iterations: int(t.Iterations),
|
||||
Attempt: int(t.Attempt), ParkReason: t.ParkReason, RetryCount: int(t.RetryCount),
|
||||
WatchCommentID: t.WatchCommentId, Source: t.Source, Identity: t.Identity,
|
||||
BindingID: t.BindingId, BindingVersion: int(t.BindingVersion),
|
||||
CreatedAt: timeValue(t.CreatedAt), UpdatedAt: timeValue(t.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
// eventDataJSON and eventDataValue convert events.Event.Data (map[string]any)
|
||||
// to/from a JSON object string, mirroring the store's own on-disk column.
|
||||
func eventDataJSON(data map[string]any) string {
|
||||
if data == nil {
|
||||
return ""
|
||||
}
|
||||
b, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func eventDataValue(s string) map[string]any {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
var data map[string]any
|
||||
if err := json.Unmarshal([]byte(s), &data); err != nil {
|
||||
return nil
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func eventProto(e events.Event) *pb.Event {
|
||||
return &pb.Event{
|
||||
Id: e.ID, At: timestamp(e.At), Kind: e.Kind, TaskId: e.TaskID, Repo: e.Repo,
|
||||
Issue: int64(e.Issue), Workflow: e.Workflow, Stage: e.Stage, Detail: e.Detail,
|
||||
DataJson: eventDataJSON(e.Data),
|
||||
}
|
||||
}
|
||||
|
||||
func eventValue(e *pb.Event) events.Event {
|
||||
if e == nil {
|
||||
return events.Event{}
|
||||
}
|
||||
return events.Event{
|
||||
ID: e.Id, At: timeValue(e.At), Kind: e.Kind, TaskID: e.TaskId, Repo: e.Repo,
|
||||
Issue: int(e.Issue), Workflow: e.Workflow, Stage: e.Stage, Detail: e.Detail,
|
||||
Data: eventDataValue(e.DataJson),
|
||||
}
|
||||
}
|
||||
|
||||
func capturedEventProto(c store.CapturedEvent) *pb.CapturedEvent {
|
||||
return &pb.CapturedEvent{
|
||||
Id: c.ID, ReceivedAt: timestamp(c.ReceivedAt), Source: c.Source,
|
||||
RemoteAddr: c.RemoteAddr, ContentType: c.ContentType, Headers: c.Headers,
|
||||
Body: c.Body, Authenticated: c.Authenticated,
|
||||
}
|
||||
}
|
||||
|
||||
func capturedEventValue(c *pb.CapturedEvent) store.CapturedEvent {
|
||||
if c == nil {
|
||||
return store.CapturedEvent{}
|
||||
}
|
||||
return store.CapturedEvent{
|
||||
ID: c.Id, ReceivedAt: timeValue(c.ReceivedAt), Source: c.Source,
|
||||
RemoteAddr: c.RemoteAddr, ContentType: c.ContentType, Headers: c.Headers,
|
||||
Body: c.Body, Authenticated: c.Authenticated,
|
||||
}
|
||||
}
|
||||
|
||||
func mappingFieldProto(f mapping.Field) *pb.MappingField {
|
||||
return &pb.MappingField{Name: f.Name, Path: f.Path, Type: string(f.Type), Required: f.Required}
|
||||
}
|
||||
|
||||
func mappingFieldValue(f *pb.MappingField) mapping.Field {
|
||||
if f == nil {
|
||||
return mapping.Field{}
|
||||
}
|
||||
return mapping.Field{Name: f.Name, Path: f.Path, Type: mapping.FieldType(f.Type), Required: f.Required}
|
||||
}
|
||||
|
||||
func mappingProto(m mapping.Mapping) *pb.Mapping {
|
||||
return &pb.Mapping{
|
||||
Id: m.ID, Name: m.Name, SourceHint: m.SourceHint,
|
||||
Fields: mapValues(m.Fields, mappingFieldProto),
|
||||
CreatedAt: timestamp(m.CreatedAt), UpdatedAt: timestamp(m.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func mappingValue(m *pb.Mapping) mapping.Mapping {
|
||||
if m == nil {
|
||||
return mapping.Mapping{}
|
||||
}
|
||||
return mapping.Mapping{
|
||||
ID: m.Id, Name: m.Name, SourceHint: m.SourceHint,
|
||||
Fields: mapValues(m.Fields, mappingFieldValue),
|
||||
CreatedAt: timeValue(m.CreatedAt), UpdatedAt: timeValue(m.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func bindingProto(b binding.Binding) *pb.Binding {
|
||||
return &pb.Binding{
|
||||
Id: b.ID, Name: b.Name, Matcher: &pb.BindingMatcher{Source: b.Matcher.Source},
|
||||
MappingId: b.MappingID, Workflow: b.Workflow, Owner: b.Owner, Repo: b.Repo,
|
||||
Version: int64(b.Version), Status: string(b.Status), Secret: b.Secret,
|
||||
CreatedAt: timestamp(b.CreatedAt), UpdatedAt: timestamp(b.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func bindingValue(b *pb.Binding) binding.Binding {
|
||||
if b == nil {
|
||||
return binding.Binding{}
|
||||
}
|
||||
var source string
|
||||
if b.Matcher != nil {
|
||||
source = b.Matcher.Source
|
||||
}
|
||||
return binding.Binding{
|
||||
ID: b.Id, Name: b.Name, Matcher: binding.Matcher{Source: source},
|
||||
MappingID: b.MappingId, Workflow: b.Workflow, Owner: b.Owner, Repo: b.Repo,
|
||||
Version: int(b.Version), Status: binding.Status(b.Status), Secret: b.Secret,
|
||||
CreatedAt: timeValue(b.CreatedAt), UpdatedAt: timeValue(b.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func workflowStatProto(w store.WorkflowStat) *pb.WorkflowStat {
|
||||
return &pb.WorkflowStat{
|
||||
Workflow: w.Workflow, Runs: int64(w.Runs), Merged: int64(w.Merged),
|
||||
PrOpen: int64(w.PROpen), Parked: int64(w.Parked), AvgTokens: int64(w.AvgTokens),
|
||||
AvgSteps: w.AvgSteps, TotalTokens: int64(w.TotalToken),
|
||||
}
|
||||
}
|
||||
|
||||
func workflowStatValue(w *pb.WorkflowStat) store.WorkflowStat {
|
||||
if w == nil {
|
||||
return store.WorkflowStat{}
|
||||
}
|
||||
return store.WorkflowStat{
|
||||
Workflow: w.Workflow, Runs: int(w.Runs), Merged: int(w.Merged),
|
||||
PROpen: int(w.PrOpen), Parked: int(w.Parked), AvgTokens: int(w.AvgTokens),
|
||||
AvgSteps: w.AvgSteps, TotalToken: int(w.TotalTokens),
|
||||
}
|
||||
}
|
||||
|
||||
func stageStatProto(s store.StageStat) *pb.StageStat {
|
||||
return &pb.StageStat{Workflow: s.Workflow, Stage: s.Stage, Runs: int64(s.Runs), AvgMs: int64(s.AvgMs), Errors: int64(s.Errors)}
|
||||
}
|
||||
|
||||
func stageStatValue(s *pb.StageStat) store.StageStat {
|
||||
if s == nil {
|
||||
return store.StageStat{}
|
||||
}
|
||||
return store.StageStat{Workflow: s.Workflow, Stage: s.Stage, Runs: int(s.Runs), AvgMs: int(s.AvgMs), Errors: int(s.Errors)}
|
||||
}
|
||||
|
||||
func dayTokensProto(d store.DayTokens) *pb.DayTokens {
|
||||
return &pb.DayTokens{Day: d.Day, Tokens: int64(d.Tokens)}
|
||||
}
|
||||
|
||||
func dayTokensValue(d *pb.DayTokens) store.DayTokens {
|
||||
if d == nil {
|
||||
return store.DayTokens{}
|
||||
}
|
||||
return store.DayTokens{Day: d.Day, Tokens: int(d.Tokens)}
|
||||
}
|
||||
|
||||
// Canonical public phrases for sentinel errors (rev. 2c §7). These strings
|
||||
// are the wire contract for sentinel identity -- the client rehydrates by
|
||||
// matching (code, message), never by parsing free-form text.
|
||||
const (
|
||||
msgStaleTransition = "stale transition"
|
||||
msgBindingNotFound = "binding not found"
|
||||
msgMappingNotFound = "mapping not found"
|
||||
msgBindingOverlap = "binding overlap"
|
||||
msgBindingTransition = "binding transition rejected"
|
||||
msgAlreadyDispatched = "already dispatched"
|
||||
msgInternal = "state store: internal error"
|
||||
)
|
||||
|
||||
// mapError converts a store sentinel error into a structured gRPC status
|
||||
// carrying a short, public, stable message -- never the raw wrapped chain
|
||||
// (which may contain SQL, provider detail, or secrets). Infra errors map to
|
||||
// codes.Internal with a sanitised message; the caller is expected to log the
|
||||
// full error server-side before calling mapError.
|
||||
func mapError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
switch {
|
||||
case errors.Is(err, store.ErrStaleTransition):
|
||||
return status.Error(codes.FailedPrecondition, msgStaleTransition)
|
||||
case errors.Is(err, store.ErrBindingNotFound):
|
||||
return status.Error(codes.NotFound, msgBindingNotFound)
|
||||
case errors.Is(err, store.ErrMappingNotFound):
|
||||
return status.Error(codes.NotFound, msgMappingNotFound)
|
||||
case errors.Is(err, store.ErrBindingOverlap):
|
||||
return status.Error(codes.FailedPrecondition, msgBindingOverlap)
|
||||
case errors.Is(err, store.ErrBindingTransition):
|
||||
return status.Error(codes.FailedPrecondition, msgBindingTransition)
|
||||
case errors.Is(err, store.ErrAlreadyDispatched):
|
||||
return status.Error(codes.AlreadyExists, msgAlreadyDispatched)
|
||||
default:
|
||||
return status.Error(codes.Internal, msgInternal)
|
||||
}
|
||||
}
|
||||
|
||||
// unmapError rehydrates a gRPC status error back to the store sentinel it
|
||||
// came from, so a caller's errors.Is(err, store.ErrX) keeps working across
|
||||
// the wire. A non-status error (e.g. a transport failure, a cancelled or
|
||||
// deadline-exceeded context) is returned unchanged.
|
||||
func unmapError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
st, ok := status.FromError(err)
|
||||
if !ok {
|
||||
return err
|
||||
}
|
||||
switch st.Code() {
|
||||
case codes.FailedPrecondition:
|
||||
switch st.Message() {
|
||||
case msgStaleTransition:
|
||||
return store.ErrStaleTransition
|
||||
case msgBindingOverlap:
|
||||
return store.ErrBindingOverlap
|
||||
case msgBindingTransition:
|
||||
return store.ErrBindingTransition
|
||||
}
|
||||
case codes.NotFound:
|
||||
switch st.Message() {
|
||||
case msgBindingNotFound:
|
||||
return store.ErrBindingNotFound
|
||||
case msgMappingNotFound:
|
||||
return store.ErrMappingNotFound
|
||||
}
|
||||
case codes.AlreadyExists:
|
||||
if st.Message() == msgAlreadyDispatched {
|
||||
return store.ErrAlreadyDispatched
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("state store: %s: %w", st.Message(), err)
|
||||
}
|
||||
@@ -338,33 +338,21 @@ func (s *Store) decryptBindingSecret(b *binding.Binding) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// sqlExecutor is the subset of *sql.DB / *sql.Tx that RecordDispatch needs.
|
||||
// Both satisfy it; nil falls back to the store's own *sql.DB so callers
|
||||
// that don't open an explicit transaction get best-effort semantics.
|
||||
type sqlExecutor interface {
|
||||
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
|
||||
}
|
||||
|
||||
// RecordDispatch writes a (binding, capture) dedup row. The caller may
|
||||
// pass a *sql.Tx to make the dispatch row commit atomically with the
|
||||
// surrounding task insert; pass nil to use the store's own connection
|
||||
// (best-effort, not atomic with the task row). INSERT OR IGNORE +
|
||||
// RecordDispatch writes a (binding, capture) dedup row using the store's
|
||||
// own connection (best-effort, not atomic with the task row -- the
|
||||
// at-most-once guarantee is the INSERT OR IGNORE dedup row itself, which
|
||||
// is already transactionless in production). INSERT OR IGNORE +
|
||||
// RowsAffected is the dedup test: a duplicate (binding_id, capture_id)
|
||||
// is a no-op write and returns ErrAlreadyDispatched rather than a
|
||||
// constraint error.
|
||||
func (s *Store) RecordDispatch(
|
||||
ctx context.Context,
|
||||
tx *sql.Tx,
|
||||
bindingID int64,
|
||||
bindingVersion int64,
|
||||
captureID int64,
|
||||
taskID int64,
|
||||
) error {
|
||||
exec := sqlExecutor(s.db)
|
||||
if tx != nil {
|
||||
exec = tx
|
||||
}
|
||||
res, err := exec.ExecContext(ctx, `
|
||||
res, err := s.db.ExecContext(ctx, `
|
||||
INSERT OR IGNORE INTO binding_dispatches (binding_id, binding_version, capture_id, task_id, dispatched_at)
|
||||
VALUES (?, ?, ?, ?, ?)`,
|
||||
bindingID, bindingVersion, captureID, taskID,
|
||||
|
||||
@@ -381,16 +381,9 @@ func TestDeleteBindingRemovesRowAndLedgerEntries(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding: %v", err)
|
||||
}
|
||||
tx, err := s.db.BeginTx(t.Context(), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("BeginTx: %v", err)
|
||||
}
|
||||
if err := s.RecordDispatch(t.Context(), tx, id, 1, 42, 7); err != nil {
|
||||
if err := s.RecordDispatch(t.Context(), id, 1, 42, 7); err != nil {
|
||||
t.Fatalf("RecordDispatch: %v", err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatalf("Commit: %v", err)
|
||||
}
|
||||
if err := s.DeleteBinding(t.Context(), id); err != nil {
|
||||
t.Fatalf("DeleteBinding: %v", err)
|
||||
}
|
||||
@@ -417,28 +410,14 @@ func TestRecordDispatchIsIdempotent(t *testing.T) {
|
||||
t.Fatalf("InsertBinding: %v", err)
|
||||
}
|
||||
ctx := t.Context()
|
||||
tx1, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("BeginTx 1: %v", err)
|
||||
}
|
||||
if err := s.RecordDispatch(ctx, tx1, id, 1, 42, 7); err != nil {
|
||||
if err := s.RecordDispatch(ctx, id, 1, 42, 7); err != nil {
|
||||
t.Fatalf("first RecordDispatch: %v", err)
|
||||
}
|
||||
if err := tx1.Commit(); err != nil {
|
||||
t.Fatalf("Commit 1: %v", err)
|
||||
}
|
||||
|
||||
tx2, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("BeginTx 2: %v", err)
|
||||
}
|
||||
err = s.RecordDispatch(ctx, tx2, id, 1, 42, 99)
|
||||
err = s.RecordDispatch(ctx, id, 1, 42, 99)
|
||||
if !errors.Is(err, ErrAlreadyDispatched) {
|
||||
t.Fatalf("second RecordDispatch (same binding/capture) = %v, want ErrAlreadyDispatched", err)
|
||||
}
|
||||
if err := tx2.Rollback(); err != nil {
|
||||
t.Fatalf("Rollback 2: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListUndispatchedCapturesExcludesDispatched(t *testing.T) {
|
||||
@@ -474,16 +453,9 @@ func TestListUndispatchedCapturesExcludesDispatched(t *testing.T) {
|
||||
}
|
||||
|
||||
ctx := t.Context()
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("BeginTx: %v", err)
|
||||
}
|
||||
if err := s.RecordDispatch(ctx, tx, id, 1, cap1, 100); err != nil {
|
||||
if err := s.RecordDispatch(ctx, id, 1, cap1, 100); err != nil {
|
||||
t.Fatalf("RecordDispatch: %v", err)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatalf("Commit: %v", err)
|
||||
}
|
||||
|
||||
got, err := s.ListUndispatchedCaptures(ctx, []string{"sentry"}, 10)
|
||||
if err != nil {
|
||||
|
||||
@@ -5,7 +5,6 @@ package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
@@ -122,7 +121,6 @@ type BindingDispatcher interface {
|
||||
ArmedBindingsForSource(ctx context.Context, source string) ([]binding.Binding, error)
|
||||
RecordDispatch(
|
||||
ctx context.Context,
|
||||
tx *sql.Tx,
|
||||
bindingID int64,
|
||||
bindingVersion int64,
|
||||
captureID int64,
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -104,7 +103,6 @@ func (s *stubBindingStore) ApproveBinding(_ context.Context, _ int64) error {
|
||||
|
||||
func (s *stubBindingStore) RecordDispatch(
|
||||
_ context.Context,
|
||||
_ *sql.Tx,
|
||||
_ int64,
|
||||
_ int64,
|
||||
_ int64,
|
||||
|
||||
@@ -0,0 +1,398 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package state.v1;
|
||||
|
||||
import "google/protobuf/timestamp.proto";
|
||||
|
||||
// StateStore is the single gRPC service fronting archie.db (one store, one
|
||||
// file). See docs/prds/state-store-contract.md for the ownership split: the
|
||||
// workflow-domain Store view (Update/Transition/InsertEvent) is consumer-owned
|
||||
// in internal/domain/workflow, while the rest of this surface stays
|
||||
// producer-owned in internal/store. Both are served by the same service and
|
||||
// the same *store.Store implementation; the proto bypasses the Go
|
||||
// interfacebloat cap (max 8), like gateway.v1.ChatService does.
|
||||
service StateStoreService {
|
||||
// Lifecycle
|
||||
rpc EnqueueIssue(EnqueueIssueRequest) returns (EnqueueIssueResponse);
|
||||
rpc EnqueueChatTask(EnqueueChatTaskRequest) returns (EnqueueChatTaskResponse);
|
||||
rpc ClaimNext(ClaimNextRequest) returns (ClaimNextResponse);
|
||||
rpc ClaimByIssue(ClaimByIssueRequest) returns (ClaimByIssueResponse);
|
||||
rpc Transition(TransitionRequest) returns (TransitionResponse);
|
||||
rpc Update(UpdateRequest) returns (UpdateResponse);
|
||||
rpc Requeue(RequeueRequest) returns (RequeueResponse);
|
||||
rpc RecoverStale(RecoverStaleRequest) returns (RecoverStaleResponse);
|
||||
|
||||
// Archive / Retry
|
||||
rpc ArchiveTask(ArchiveTaskRequest) returns (ArchiveTaskResponse);
|
||||
rpc RetryTask(RetryTaskRequest) returns (RetryTaskResponse);
|
||||
|
||||
// Queries
|
||||
rpc TaskByIssue(TaskByIssueRequest) returns (TaskByIssueResponse);
|
||||
rpc TaskByID(TaskByIDRequest) returns (TaskByIDResponse);
|
||||
rpc OpenPRs(OpenPRsRequest) returns (OpenPRsResponse);
|
||||
rpc ClearTerminalTasks(ClearTerminalTasksRequest) returns (ClearTerminalTasksResponse);
|
||||
rpc Tasks(TasksRequest) returns (TasksResponse);
|
||||
rpc StatusCounts(StatusCountsRequest) returns (StatusCountsResponse);
|
||||
rpc IncrementRetryCount(IncrementRetryCountRequest) returns (IncrementRetryCountResponse);
|
||||
|
||||
// Events
|
||||
rpc InsertEvent(InsertEventRequest) returns (InsertEventResponse);
|
||||
rpc EventsSince(EventsSinceRequest) returns (EventsSinceResponse);
|
||||
rpc TaskEvents(TaskEventsRequest) returns (TaskEventsResponse);
|
||||
rpc WorkflowStats(WorkflowStatsRequest) returns (WorkflowStatsResponse);
|
||||
rpc StageStats(StageStatsRequest) returns (StageStatsResponse);
|
||||
rpc TokensByDay(TokensByDayRequest) returns (TokensByDayResponse);
|
||||
|
||||
// Capture
|
||||
rpc InsertCapture(InsertCaptureRequest) returns (InsertCaptureResponse);
|
||||
rpc ListCaptures(ListCapturesRequest) returns (ListCapturesResponse);
|
||||
|
||||
// Mapping
|
||||
rpc InsertMapping(InsertMappingRequest) returns (InsertMappingResponse);
|
||||
rpc GetMapping(GetMappingRequest) returns (GetMappingResponse);
|
||||
rpc ListMappings(ListMappingsRequest) returns (ListMappingsResponse);
|
||||
rpc UpdateMapping(UpdateMappingRequest) returns (UpdateMappingResponse);
|
||||
rpc DeleteMapping(DeleteMappingRequest) returns (DeleteMappingResponse);
|
||||
|
||||
// Binding
|
||||
rpc InsertBinding(InsertBindingRequest) returns (InsertBindingResponse);
|
||||
rpc GetBinding(GetBindingRequest) returns (GetBindingResponse);
|
||||
rpc ListBindings(ListBindingsRequest) returns (ListBindingsResponse);
|
||||
rpc UpdateBinding(UpdateBindingRequest) returns (UpdateBindingResponse);
|
||||
rpc DeleteBinding(DeleteBindingRequest) returns (DeleteBindingResponse);
|
||||
rpc ApproveBinding(ApproveBindingRequest) returns (ApproveBindingResponse);
|
||||
|
||||
// Dispatch
|
||||
rpc ArmedBindingsForSource(ArmedBindingsForSourceRequest) returns (ArmedBindingsForSourceResponse);
|
||||
rpc RecordDispatch(RecordDispatchRequest) returns (RecordDispatchResponse);
|
||||
rpc ListUndispatchedCaptures(ListUndispatchedCapturesRequest) returns (ListUndispatchedCapturesResponse);
|
||||
|
||||
// BindingTaskCreator
|
||||
rpc EnqueueBindingTask(EnqueueBindingTaskRequest) returns (EnqueueBindingTaskResponse);
|
||||
}
|
||||
|
||||
// Task mirrors internal/domain/workflow.Task.
|
||||
message Task {
|
||||
int64 id = 1;
|
||||
string owner = 2;
|
||||
string repo = 3;
|
||||
int64 issue_number = 4;
|
||||
string title = 5;
|
||||
string body = 6;
|
||||
string labels = 7;
|
||||
string status = 8;
|
||||
string workflow = 9;
|
||||
string stage = 10;
|
||||
string branch = 11;
|
||||
string plan = 12;
|
||||
string notes = 13;
|
||||
int64 pr_number = 14;
|
||||
int64 tokens_used = 15;
|
||||
int64 iterations = 16;
|
||||
int64 attempt = 17;
|
||||
string park_reason = 18;
|
||||
int64 retry_count = 19;
|
||||
int64 watch_comment_id = 20;
|
||||
string source = 21;
|
||||
string identity = 22;
|
||||
int64 binding_id = 23;
|
||||
int64 binding_version = 24;
|
||||
google.protobuf.Timestamp created_at = 25;
|
||||
google.protobuf.Timestamp updated_at = 26;
|
||||
}
|
||||
|
||||
// Event mirrors internal/events.Event. Data is carried as a JSON object
|
||||
// string (matching the store's own on-disk representation) rather than
|
||||
// google.protobuf.Struct, to stay a direct mirror of the existing column.
|
||||
message Event {
|
||||
int64 id = 1;
|
||||
google.protobuf.Timestamp at = 2;
|
||||
string kind = 3;
|
||||
int64 task_id = 4;
|
||||
string repo = 5;
|
||||
int64 issue = 6;
|
||||
string workflow = 7;
|
||||
string stage = 8;
|
||||
string detail = 9;
|
||||
string data_json = 10;
|
||||
}
|
||||
|
||||
// CapturedEvent mirrors internal/store.CapturedEvent.
|
||||
message CapturedEvent {
|
||||
int64 id = 1;
|
||||
google.protobuf.Timestamp received_at = 2;
|
||||
string source = 3;
|
||||
string remote_addr = 4;
|
||||
string content_type = 5;
|
||||
string headers = 6;
|
||||
string body = 7;
|
||||
bool authenticated = 8;
|
||||
}
|
||||
|
||||
// MappingField mirrors internal/domain/mapping.Field.
|
||||
message MappingField {
|
||||
string name = 1;
|
||||
string path = 2;
|
||||
string type = 3;
|
||||
bool required = 4;
|
||||
}
|
||||
|
||||
// Mapping mirrors internal/domain/mapping.Mapping.
|
||||
message Mapping {
|
||||
int64 id = 1;
|
||||
string name = 2;
|
||||
string source_hint = 3;
|
||||
repeated MappingField fields = 4;
|
||||
google.protobuf.Timestamp created_at = 5;
|
||||
google.protobuf.Timestamp updated_at = 6;
|
||||
}
|
||||
|
||||
// BindingMatcher mirrors internal/domain/binding.Matcher.
|
||||
message BindingMatcher {
|
||||
string source = 1;
|
||||
}
|
||||
|
||||
// Binding mirrors internal/domain/binding.Binding.
|
||||
message Binding {
|
||||
int64 id = 1;
|
||||
string name = 2;
|
||||
BindingMatcher matcher = 3;
|
||||
int64 mapping_id = 4;
|
||||
string workflow = 5;
|
||||
string owner = 6;
|
||||
string repo = 7;
|
||||
int64 version = 8;
|
||||
string status = 9;
|
||||
string secret = 10;
|
||||
google.protobuf.Timestamp created_at = 11;
|
||||
google.protobuf.Timestamp updated_at = 12;
|
||||
}
|
||||
|
||||
// WorkflowStat mirrors internal/store.WorkflowStat.
|
||||
message WorkflowStat {
|
||||
string workflow = 1;
|
||||
int64 runs = 2;
|
||||
int64 merged = 3;
|
||||
int64 pr_open = 4;
|
||||
int64 parked = 5;
|
||||
int64 avg_tokens = 6;
|
||||
double avg_steps = 7;
|
||||
int64 total_tokens = 8;
|
||||
}
|
||||
|
||||
// StageStat mirrors internal/store.StageStat.
|
||||
message StageStat {
|
||||
string workflow = 1;
|
||||
string stage = 2;
|
||||
int64 runs = 3;
|
||||
int64 avg_ms = 4;
|
||||
int64 errors = 5;
|
||||
}
|
||||
|
||||
// DayTokens mirrors internal/store.DayTokens.
|
||||
message DayTokens {
|
||||
string day = 1;
|
||||
int64 tokens = 2;
|
||||
}
|
||||
|
||||
message EnqueueIssueRequest {
|
||||
string owner = 1;
|
||||
string repo = 2;
|
||||
int64 number = 3;
|
||||
string title = 4;
|
||||
string body = 5;
|
||||
string labels = 6;
|
||||
string identity = 7;
|
||||
}
|
||||
message EnqueueIssueResponse { bool inserted = 1; }
|
||||
|
||||
message EnqueueChatTaskRequest {
|
||||
string owner = 1;
|
||||
string repo = 2;
|
||||
string title = 3;
|
||||
string body = 4;
|
||||
string workflow = 5;
|
||||
string identity = 6;
|
||||
}
|
||||
message EnqueueChatTaskResponse { Task task = 1; }
|
||||
|
||||
message ClaimNextRequest {}
|
||||
message ClaimNextResponse {
|
||||
Task task = 1;
|
||||
bool found = 2;
|
||||
}
|
||||
|
||||
message ClaimByIssueRequest {
|
||||
string owner = 1;
|
||||
string repo = 2;
|
||||
int64 number = 3;
|
||||
}
|
||||
message ClaimByIssueResponse {
|
||||
Task task = 1;
|
||||
bool found = 2;
|
||||
}
|
||||
|
||||
message TransitionRequest {
|
||||
int64 task_id = 1;
|
||||
string from = 2;
|
||||
string to = 3;
|
||||
string detail = 4;
|
||||
}
|
||||
message TransitionResponse {}
|
||||
|
||||
message UpdateRequest { Task task = 1; }
|
||||
message UpdateResponse {}
|
||||
|
||||
message RequeueRequest {
|
||||
int64 task_id = 1;
|
||||
string from_status = 2;
|
||||
string workflow = 3;
|
||||
}
|
||||
message RequeueResponse {}
|
||||
|
||||
message RecoverStaleRequest {}
|
||||
message RecoverStaleResponse { int64 count = 1; }
|
||||
|
||||
message ArchiveTaskRequest {
|
||||
int64 task_id = 1;
|
||||
string from_status = 2;
|
||||
Event audit = 3;
|
||||
}
|
||||
message ArchiveTaskResponse { int64 event_id = 1; }
|
||||
|
||||
message RetryTaskRequest {
|
||||
int64 task_id = 1;
|
||||
string from_status = 2;
|
||||
string workflow = 3;
|
||||
}
|
||||
message RetryTaskResponse {}
|
||||
|
||||
message TaskByIssueRequest {
|
||||
string owner = 1;
|
||||
string repo = 2;
|
||||
int64 number = 3;
|
||||
}
|
||||
message TaskByIssueResponse {
|
||||
Task task = 1;
|
||||
bool found = 2;
|
||||
}
|
||||
|
||||
message TaskByIDRequest { int64 task_id = 1; }
|
||||
message TaskByIDResponse {
|
||||
Task task = 1;
|
||||
bool found = 2;
|
||||
}
|
||||
|
||||
message OpenPRsRequest {}
|
||||
message OpenPRsResponse { repeated Task tasks = 1; }
|
||||
|
||||
message ClearTerminalTasksRequest {}
|
||||
message ClearTerminalTasksResponse { int64 count = 1; }
|
||||
|
||||
message TasksRequest { int64 limit = 1; }
|
||||
message TasksResponse { repeated Task tasks = 1; }
|
||||
|
||||
message StatusCountsRequest {}
|
||||
message StatusCountsResponse { map<string, int64> counts = 1; }
|
||||
|
||||
message IncrementRetryCountRequest { int64 task_id = 1; }
|
||||
message IncrementRetryCountResponse {}
|
||||
|
||||
message InsertEventRequest { Event event = 1; }
|
||||
message InsertEventResponse { int64 id = 1; }
|
||||
|
||||
message EventsSinceRequest {
|
||||
int64 since_id = 1;
|
||||
int64 limit = 2;
|
||||
}
|
||||
message EventsSinceResponse { repeated Event events = 1; }
|
||||
|
||||
message TaskEventsRequest { int64 task_id = 1; }
|
||||
message TaskEventsResponse { repeated Event events = 1; }
|
||||
|
||||
message WorkflowStatsRequest {}
|
||||
message WorkflowStatsResponse { repeated WorkflowStat stats = 1; }
|
||||
|
||||
message StageStatsRequest {}
|
||||
message StageStatsResponse { repeated StageStat stats = 1; }
|
||||
|
||||
message TokensByDayRequest { int64 days = 1; }
|
||||
message TokensByDayResponse { repeated DayTokens tokens = 1; }
|
||||
|
||||
message InsertCaptureRequest {
|
||||
CapturedEvent capture = 1;
|
||||
int64 retention_seconds = 2;
|
||||
int64 max_events = 3;
|
||||
}
|
||||
message InsertCaptureResponse { int64 id = 1; }
|
||||
|
||||
message ListCapturesRequest { int64 limit = 1; }
|
||||
message ListCapturesResponse { repeated CapturedEvent captures = 1; }
|
||||
|
||||
message InsertMappingRequest { Mapping mapping = 1; }
|
||||
message InsertMappingResponse { int64 id = 1; }
|
||||
|
||||
message GetMappingRequest { int64 id = 1; }
|
||||
message GetMappingResponse {
|
||||
Mapping mapping = 1;
|
||||
bool found = 2;
|
||||
}
|
||||
|
||||
message ListMappingsRequest {}
|
||||
message ListMappingsResponse { repeated Mapping mappings = 1; }
|
||||
|
||||
message UpdateMappingRequest { Mapping mapping = 1; }
|
||||
message UpdateMappingResponse {}
|
||||
|
||||
message DeleteMappingRequest { int64 id = 1; }
|
||||
message DeleteMappingResponse {}
|
||||
|
||||
message InsertBindingRequest { Binding binding = 1; }
|
||||
message InsertBindingResponse { int64 id = 1; }
|
||||
|
||||
message GetBindingRequest { int64 id = 1; }
|
||||
message GetBindingResponse {
|
||||
Binding binding = 1;
|
||||
bool found = 2;
|
||||
}
|
||||
|
||||
message ListBindingsRequest {}
|
||||
message ListBindingsResponse { repeated Binding bindings = 1; }
|
||||
|
||||
message UpdateBindingRequest { Binding binding = 1; }
|
||||
message UpdateBindingResponse {}
|
||||
|
||||
message DeleteBindingRequest { int64 id = 1; }
|
||||
message DeleteBindingResponse {}
|
||||
|
||||
message ApproveBindingRequest { int64 id = 1; }
|
||||
message ApproveBindingResponse {}
|
||||
|
||||
message ArmedBindingsForSourceRequest { string source = 1; }
|
||||
message ArmedBindingsForSourceResponse { repeated Binding bindings = 1; }
|
||||
|
||||
message RecordDispatchRequest {
|
||||
int64 binding_id = 1;
|
||||
int64 binding_version = 2;
|
||||
int64 capture_id = 3;
|
||||
int64 task_id = 4;
|
||||
}
|
||||
message RecordDispatchResponse {}
|
||||
|
||||
message ListUndispatchedCapturesRequest {
|
||||
repeated string sources = 1;
|
||||
int64 limit = 2;
|
||||
}
|
||||
message ListUndispatchedCapturesResponse { repeated CapturedEvent captures = 1; }
|
||||
|
||||
message EnqueueBindingTaskRequest {
|
||||
string owner = 1;
|
||||
string repo = 2;
|
||||
string title = 3;
|
||||
string body = 4;
|
||||
string workflow = 5;
|
||||
string identity = 6;
|
||||
int64 binding_id = 7;
|
||||
int64 binding_version = 8;
|
||||
}
|
||||
message EnqueueBindingTaskResponse { Task task = 1; }
|
||||
Reference in new issue
Block a user