feat: add config overlay and shared RPC/Yaegi packages
- Introduce `-config-overlay` flag and `config.LoadOverlay()` to merge a base config with an overlay file, only overriding fields the overlay sets. This enables docker-compose to mount the base config from the host and apply only deployment-specific overrides. - Create `internal/natsrpc` package with reusable NATS request/reply primitives (Envelope, Client, Call, RegisterAll, Respond). Migrate storerpc, worktreerpc, and forgerpc to use it, eliminating duplicated marshal/unmarshal and error handling. - Create `internal/yaegiutil` package with shared interpreter construction (stdlib + extra symbols), generic export resolution (Resolve), and panic recovery (Safe). Migrate all Yaegi-based surfaces (gate scripts, daemon plugins, skill plugins, workflow stages, skill scripts) to use it, reducing boilerplate and centralizing panic safety. - Simplify `config.docker.toml` to contain only overlay fields (paths, container config) and remove the duplicated repos list – the base config is now the single source of truth. - Update docker-compose.yml to pass both -config and -config-overlay flags and mount the base config from the host. - Add tests for LoadOverlay, DockerConfigOverlaysExampleConfig, Envelope, and yaegiutil utilities.
This commit is contained in:
1 parent
4573ed125a
commit
d80401d595
18 files changed
+580
-506
No files matched your search
+2
-1
@@ -45,13 +45,14 @@ func main() {
|
||||
func run() int {
|
||||
defaultCfg := filepath.Join(configHome(), "archie", "config.toml")
|
||||
cfgPath := flag.String("config", defaultCfg, "path to config.toml")
|
||||
overlayPath := flag.String("config-overlay", "", "path to a config.toml overlay applied on top of -config (only the fields it sets are overridden)")
|
||||
once := flag.Bool("once", false, "run a single poll+process cycle and exit (systemd timer / testing)")
|
||||
requeue := flag.Int64("requeue", 0, "requeue a parked/waiting task by id (keeps its workflow), then exit unless -once is also set")
|
||||
flag.Parse()
|
||||
|
||||
log := slog.New(slog.NewJSONHandler(os.Stderr, nil))
|
||||
|
||||
cfg, err := config.Load(*cfgPath)
|
||||
cfg, err := config.LoadOverlay(*cfgPath, *overlayPath)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return 1
|
||||
|
||||
+6
-38
@@ -1,11 +1,9 @@
|
||||
# Docker Compose overrides for the inprocess config.
|
||||
# Only set fields that differ: paths (container filesystem) and
|
||||
# container-specific configuration. Everything else inherits from
|
||||
# config.toml (inprocess config), which is the single source of truth.
|
||||
#
|
||||
# Mount this at /etc/archie/config.toml AND the base config so TOML
|
||||
# merging works. Or better: the daemon loads both — base first, then
|
||||
# this overlay.
|
||||
# Docker Compose overlay: only fields that differ from the base config.
|
||||
# The daemon loads both — base config.toml first, then this file on top
|
||||
# (config.LoadOverlay) — so config.toml (the same file inprocess mode
|
||||
# reads) stays the single source of truth for bot_user, forge, dispatch,
|
||||
# models, providers, budgets, and repos. See docker-compose.yml's
|
||||
# `-config` / `-config-overlay` flags and volume mounts.
|
||||
|
||||
work_dir = "/var/lib/archie/work"
|
||||
db_path = "/var/lib/archie/archie.db"
|
||||
@@ -25,33 +23,3 @@ pull_policy = "missing"
|
||||
|
||||
[web]
|
||||
listen = "0.0.0.0:8484"
|
||||
|
||||
# Repos: same as inprocess config — keep in sync with config.toml.
|
||||
# TODO: support `include` directive so repos list is not duplicated.
|
||||
|
||||
[[repos]]
|
||||
owner = "sam"
|
||||
name = "archie-core"
|
||||
base = "main"
|
||||
ecosystem = "go"
|
||||
gate = [
|
||||
["gofumpt", "-w", "."],
|
||||
["go", "fix", "./..."],
|
||||
["go", "vet", "./..."],
|
||||
["go", "build", "./..."],
|
||||
["go", "test", "./...", "-count=1"],
|
||||
]
|
||||
|
||||
[[repos]]
|
||||
owner = "sam"
|
||||
name = "tau"
|
||||
base = "main"
|
||||
ecosystem = "go"
|
||||
gate = [
|
||||
["gofumpt", "-w", "."],
|
||||
["go", "fix", "./..."],
|
||||
["go", "vet", "./..."],
|
||||
["golangci-lint", "run"],
|
||||
["go", "test", "./...", "-count=1"],
|
||||
]
|
||||
protect = ["_templ.go"]
|
||||
+3
-2
@@ -24,7 +24,7 @@ services:
|
||||
# ── archie daemon ──────────────────────────────────────────────────
|
||||
archied:
|
||||
image: git.catlow.cloud/sam/archied:latest
|
||||
command: -config /etc/archie/config.toml
|
||||
command: -config /etc/archie/config.toml -config-overlay /etc/archie/config.docker.toml
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
ports:
|
||||
@@ -33,7 +33,8 @@ services:
|
||||
- ARCHIE_GITEA_TOKEN
|
||||
- DEEPSEEK_API_KEY
|
||||
volumes:
|
||||
- ./config.docker.toml:/etc/archie/config.toml:ro
|
||||
- ${HOME}/.config/archie/config.toml:/etc/archie/config.toml:ro
|
||||
- ./config.docker.toml:/etc/archie/config.docker.toml:ro
|
||||
- /var/lib/archie/work:/var/lib/archie/work
|
||||
- /var/lib/archie/db:/var/lib/archie
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
|
||||
@@ -391,6 +391,30 @@ func Load(path string) (Config, error) {
|
||||
if _, err := toml.DecodeFile(path, &cfg); err != nil {
|
||||
return cfg, fmt.Errorf("config %s: %w", path, err)
|
||||
}
|
||||
return finalize(cfg)
|
||||
}
|
||||
|
||||
// LoadOverlay reads basePath, then re-decodes overlayPath into the same
|
||||
// struct so only the fields overlayPath sets are overridden — every field
|
||||
// it omits keeps the value from basePath. This lets a deployment-specific
|
||||
// file (e.g. config.docker.toml) declare only what differs from the base
|
||||
// config instead of duplicating the whole schema. overlayPath == "" is
|
||||
// equivalent to Load(basePath).
|
||||
func LoadOverlay(basePath, overlayPath string) (Config, error) {
|
||||
var cfg Config
|
||||
if _, err := toml.DecodeFile(basePath, &cfg); err != nil {
|
||||
return cfg, fmt.Errorf("config %s: %w", basePath, err)
|
||||
}
|
||||
if overlayPath != "" {
|
||||
if _, err := toml.DecodeFile(overlayPath, &cfg); err != nil {
|
||||
return cfg, fmt.Errorf("config %s: %w", overlayPath, err)
|
||||
}
|
||||
}
|
||||
return finalize(cfg)
|
||||
}
|
||||
|
||||
// finalize applies defaults and validates a decoded configuration.
|
||||
func finalize(cfg Config) (Config, error) {
|
||||
if cfg.WorkDir == "" {
|
||||
cfg.WorkDir = filepath.Join(dataHome(), "archie", "work")
|
||||
}
|
||||
|
||||
@@ -485,6 +485,78 @@ func TestExampleConfigLoads(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadOverlay(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
basePath := filepath.Join(dir, "config.toml")
|
||||
base := "bot_user = \"archie\"\nwork_dir = \"/base/work\"\n" +
|
||||
"[agent]\nmode = \"inprocess\"\n" +
|
||||
"[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(basePath, []byte(base), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
overlayPath := filepath.Join(dir, "config.docker.toml")
|
||||
overlay := "work_dir = \"/var/lib/archie/work\"\n[agent]\nmode = \"nats\"\n" +
|
||||
"[nats]\nurl = \"nats://nats:4222\"\n" +
|
||||
"[containers]\nenabled = true\nimage = \"archie-agent:latest\"\n"
|
||||
if err := os.WriteFile(overlayPath, []byte(overlay), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := LoadOverlay(basePath, overlayPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Overlay-set fields win.
|
||||
if cfg.WorkDir != "/var/lib/archie/work" {
|
||||
t.Errorf("WorkDir: got %q, want overlay value", cfg.WorkDir)
|
||||
}
|
||||
if cfg.Agent.Mode != "nats" {
|
||||
t.Errorf("Agent.Mode: got %q, want %q", cfg.Agent.Mode, "nats")
|
||||
}
|
||||
// Fields the overlay omits keep the base value.
|
||||
if cfg.BotUser != "archie" {
|
||||
t.Errorf("BotUser: got %q, want base value", cfg.BotUser)
|
||||
}
|
||||
if len(cfg.Repos) != 1 || cfg.Repos[0].Owner != "acme" {
|
||||
t.Errorf("Repos: got %+v, want base repos", cfg.Repos)
|
||||
}
|
||||
|
||||
// No overlay path behaves like Load(basePath).
|
||||
baseOnly, err := LoadOverlay(basePath, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if baseOnly.Agent.Mode != "inprocess" {
|
||||
t.Errorf("Agent.Mode with empty overlay: got %q, want %q", baseOnly.Agent.Mode, "inprocess")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDockerConfigOverlaysExampleConfig(t *testing.T) {
|
||||
cfg, err := LoadOverlay(
|
||||
filepath.Join("..", "..", "config.example.toml"),
|
||||
filepath.Join("..", "..", "config.docker.toml"),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Agent.Mode != "nats" {
|
||||
t.Errorf("Agent.Mode: got %q, want %q", cfg.Agent.Mode, "nats")
|
||||
}
|
||||
if cfg.Containers.Image == "" {
|
||||
t.Error("Containers.Image: want docker overlay image, got empty")
|
||||
}
|
||||
// bot_user and repos are not set by the docker overlay — they must
|
||||
// come from the base config, proving the overlay isn't a standalone
|
||||
// config that silently drops required fields.
|
||||
if cfg.BotUser == "" {
|
||||
t.Error("BotUser: want value from base config.example.toml, got empty")
|
||||
}
|
||||
if len(cfg.Repos) == 0 {
|
||||
t.Error("Repos: want repos from base config.example.toml, got none")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEcosystemDefaults(t *testing.T) {
|
||||
// Empty ecosystem → "go" (backward compat).
|
||||
r := Repo{}
|
||||
|
||||
+36
-123
@@ -13,7 +13,6 @@ package forgerpc
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
@@ -21,6 +20,7 @@ import (
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/natsrpc"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -37,8 +37,8 @@ type CommentRequest struct {
|
||||
}
|
||||
|
||||
type CommentResponse struct {
|
||||
ID int64 `json:"id"`
|
||||
Error string `json:"error,omitempty"`
|
||||
ID int64 `json:"id"`
|
||||
natsrpc.Envelope
|
||||
}
|
||||
|
||||
type CloseIssueRequest struct {
|
||||
@@ -52,8 +52,8 @@ type CreatePRRequest struct {
|
||||
}
|
||||
|
||||
type CreatePRResponse struct {
|
||||
Number int `json:"number"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Number int `json:"number"`
|
||||
natsrpc.Envelope
|
||||
}
|
||||
|
||||
type SetStateLabelRequest struct {
|
||||
@@ -65,7 +65,7 @@ type SetStateLabelRequest struct {
|
||||
|
||||
// Response is a bare success/error envelope for calls with no return value.
|
||||
type Response struct {
|
||||
Error string `json:"error,omitempty"`
|
||||
natsrpc.Envelope
|
||||
}
|
||||
|
||||
// Server proxies forgerpc requests to a real forge.Forge implementation.
|
||||
@@ -77,77 +77,48 @@ type Server struct {
|
||||
// Register subscribes all four handlers on nc. The returned func
|
||||
// unsubscribes all of them.
|
||||
func (s *Server) Register(nc *nats.Conn) (unsubscribe func(), err error) {
|
||||
type registration struct {
|
||||
subject string
|
||||
handler nats.MsgHandler
|
||||
}
|
||||
regs := []registration{
|
||||
{SubjectComment, s.handleComment},
|
||||
{SubjectCloseIssue, s.handleCloseIssue},
|
||||
{SubjectCreatePR, s.handleCreatePR},
|
||||
{SubjectSetStateLabel, s.handleSetStateLabel},
|
||||
}
|
||||
|
||||
var subs []*nats.Subscription
|
||||
for _, r := range regs {
|
||||
sub, err := nc.Subscribe(r.subject, r.handler)
|
||||
if err != nil {
|
||||
for _, s := range subs {
|
||||
s.Unsubscribe()
|
||||
}
|
||||
return nil, fmt.Errorf("subscribe %s: %w", r.subject, err)
|
||||
}
|
||||
subs = append(subs, sub)
|
||||
}
|
||||
return func() {
|
||||
for _, s := range subs {
|
||||
s.Unsubscribe()
|
||||
}
|
||||
}, nil
|
||||
return natsrpc.RegisterAll(nc, []natsrpc.Registration{
|
||||
{Subject: SubjectComment, Handler: s.handleComment},
|
||||
{Subject: SubjectCloseIssue, Handler: s.handleCloseIssue},
|
||||
{Subject: SubjectCreatePR, Handler: s.handleCreatePR},
|
||||
{Subject: SubjectSetStateLabel, Handler: s.handleSetStateLabel},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleComment(msg *nats.Msg) {
|
||||
var req CommentRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.respond(msg, CommentResponse{Error: fmt.Sprintf("decode comment request: %v", err)})
|
||||
s.respond(msg, CommentResponse{Envelope: natsrpc.NewEnvelope(fmt.Errorf("decode comment request: %w", err))})
|
||||
return
|
||||
}
|
||||
id, err := s.Forge.Comment(context.Background(), req.Owner, req.Repo, req.Number, req.Body)
|
||||
resp := CommentResponse{ID: id}
|
||||
if err != nil {
|
||||
resp.Error = err.Error()
|
||||
}
|
||||
s.respond(msg, resp)
|
||||
s.respond(msg, CommentResponse{ID: id, Envelope: natsrpc.NewEnvelope(err)})
|
||||
}
|
||||
|
||||
func (s *Server) handleCloseIssue(msg *nats.Msg) {
|
||||
var req CloseIssueRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.respond(msg, Response{Error: fmt.Sprintf("decode close_issue request: %v", err)})
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(fmt.Errorf("decode close_issue request: %w", err))})
|
||||
return
|
||||
}
|
||||
err := s.Forge.CloseIssue(context.Background(), req.Owner, req.Repo, req.Number, req.Comment)
|
||||
s.respond(msg, errResponse(err))
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(err)})
|
||||
}
|
||||
|
||||
func (s *Server) handleCreatePR(msg *nats.Msg) {
|
||||
var req CreatePRRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.respond(msg, CreatePRResponse{Error: fmt.Sprintf("decode create_pr request: %v", err)})
|
||||
s.respond(msg, CreatePRResponse{Envelope: natsrpc.NewEnvelope(fmt.Errorf("decode create_pr request: %w", err))})
|
||||
return
|
||||
}
|
||||
num, err := s.Forge.CreatePR(context.Background(), req.Owner, req.Repo, req.Title, req.Head, req.Base, req.Body)
|
||||
resp := CreatePRResponse{Number: num}
|
||||
if err != nil {
|
||||
resp.Error = err.Error()
|
||||
}
|
||||
s.respond(msg, resp)
|
||||
s.respond(msg, CreatePRResponse{Number: num, Envelope: natsrpc.NewEnvelope(err)})
|
||||
}
|
||||
|
||||
func (s *Server) handleSetStateLabel(msg *nats.Msg) {
|
||||
var req SetStateLabelRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.respond(msg, Response{Error: fmt.Sprintf("decode set_state_label request: %v", err)})
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(fmt.Errorf("decode set_state_label request: %w", err))})
|
||||
return
|
||||
}
|
||||
// SetStateLabel has no error return in forge.Forge — nothing to propagate.
|
||||
@@ -155,24 +126,8 @@ func (s *Server) handleSetStateLabel(msg *nats.Msg) {
|
||||
s.respond(msg, Response{})
|
||||
}
|
||||
|
||||
func errResponse(err error) Response {
|
||||
if err == nil {
|
||||
return Response{}
|
||||
}
|
||||
return Response{Error: err.Error()}
|
||||
}
|
||||
|
||||
func (s *Server) respond(msg *nats.Msg, v any) {
|
||||
data, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
if s.Log != nil {
|
||||
s.Log.Error("forgerpc: encode response failed", "err", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err := msg.Respond(data); err != nil && s.Log != nil {
|
||||
s.Log.Error("forgerpc: respond failed", "err", err)
|
||||
}
|
||||
natsrpc.Respond(msg, s.Log, "forgerpc", v)
|
||||
}
|
||||
|
||||
// Client calls the forgerpc Server from archie-agent's process. It
|
||||
@@ -184,48 +139,37 @@ type Client struct {
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
func (c *Client) rpc() *natsrpc.Client { return &natsrpc.Client{Conn: c.Conn, Timeout: c.Timeout} }
|
||||
|
||||
func (c *Client) Comment(ctx context.Context, owner, repo string, number int, body string) (int64, error) {
|
||||
data, err := json.Marshal(CommentRequest{Owner: owner, Repo: repo, Number: number, Body: body})
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("encode comment request: %w", err)
|
||||
}
|
||||
reply, err := c.call(ctx, SubjectComment, data)
|
||||
req := CommentRequest{Owner: owner, Repo: repo, Number: number, Body: body}
|
||||
resp, err := natsrpc.Call[CommentResponse](ctx, c.rpc(), SubjectComment, req)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var resp CommentResponse
|
||||
if err := json.Unmarshal(reply, &resp); err != nil {
|
||||
return 0, fmt.Errorf("forgerpc %s: decode response: %w", SubjectComment, err)
|
||||
}
|
||||
if resp.Error != "" {
|
||||
return 0, errors.New(resp.Error)
|
||||
if err := resp.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return resp.ID, nil
|
||||
}
|
||||
|
||||
func (c *Client) CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error {
|
||||
data, err := json.Marshal(CloseIssueRequest{Owner: owner, Repo: repo, Number: number, Comment: comment})
|
||||
req := CloseIssueRequest{Owner: owner, Repo: repo, Number: number, Comment: comment}
|
||||
resp, err := natsrpc.Call[Response](ctx, c.rpc(), SubjectCloseIssue, req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode close_issue request: %w", err)
|
||||
return err
|
||||
}
|
||||
return c.callErr(ctx, SubjectCloseIssue, data)
|
||||
return resp.Err()
|
||||
}
|
||||
|
||||
func (c *Client) CreatePR(ctx context.Context, owner, repo, title, head, base, body string) (int, error) {
|
||||
data, err := json.Marshal(CreatePRRequest{Owner: owner, Repo: repo, Title: title, Head: head, Base: base, Body: body})
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("encode create_pr request: %w", err)
|
||||
}
|
||||
reply, err := c.call(ctx, SubjectCreatePR, data)
|
||||
req := CreatePRRequest{Owner: owner, Repo: repo, Title: title, Head: head, Base: base, Body: body}
|
||||
resp, err := natsrpc.Call[CreatePRResponse](ctx, c.rpc(), SubjectCreatePR, req)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var resp CreatePRResponse
|
||||
if err := json.Unmarshal(reply, &resp); err != nil {
|
||||
return 0, fmt.Errorf("forgerpc %s: decode response: %w", SubjectCreatePR, err)
|
||||
}
|
||||
if resp.Error != "" {
|
||||
return 0, errors.New(resp.Error)
|
||||
if err := resp.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return resp.Number, nil
|
||||
}
|
||||
@@ -234,37 +178,6 @@ func (c *Client) CreatePR(ctx context.Context, owner, repo, title, head, base, b
|
||||
// server-side failures are logged by the server; the daemon still owns
|
||||
// SetStateLabel's fire-and-forget semantics.
|
||||
func (c *Client) SetStateLabel(ctx context.Context, owner, repo string, number int, label string, knownLabels []string) {
|
||||
data, err := json.Marshal(SetStateLabelRequest{Owner: owner, Repo: repo, Number: number, Label: label, KnownLabels: knownLabels})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_ = c.callErr(ctx, SubjectSetStateLabel, data)
|
||||
}
|
||||
|
||||
func (c *Client) callErr(ctx context.Context, subject string, data []byte) error {
|
||||
reply, err := c.call(ctx, subject, data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var resp Response
|
||||
if err := json.Unmarshal(reply, &resp); err != nil {
|
||||
return fmt.Errorf("forgerpc %s: decode response: %w", subject, err)
|
||||
}
|
||||
if resp.Error != "" {
|
||||
return errors.New(resp.Error)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) call(ctx context.Context, subject string, data []byte) ([]byte, error) {
|
||||
if _, hasDeadline := ctx.Deadline(); !hasDeadline && c.Timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, c.Timeout)
|
||||
defer cancel()
|
||||
}
|
||||
reply, err := c.Conn.RequestWithContext(ctx, subject, data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("forgerpc %s: %w", subject, err)
|
||||
}
|
||||
return reply.Data, nil
|
||||
req := SetStateLabelRequest{Owner: owner, Repo: repo, Number: number, Label: label, KnownLabels: knownLabels}
|
||||
_, _ = natsrpc.Call[Response](ctx, c.rpc(), SubjectSetStateLabel, req)
|
||||
}
|
||||
@@ -11,10 +11,10 @@ import (
|
||||
"path/filepath"
|
||||
|
||||
"github.com/traefik/yaegi/interp"
|
||||
"github.com/traefik/yaegi/stdlib"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/gate"
|
||||
"github.com/samcharles93/archie-core/internal/gate/gateextract"
|
||||
"github.com/samcharles93/archie-core/internal/yaegiutil"
|
||||
)
|
||||
|
||||
// scriptPath is the per-repo custom gate script, relative to the
|
||||
@@ -27,7 +27,7 @@ const scriptPath = ".archie/gate.go"
|
||||
// (interpreted, not sandboxed), so a panic inside it — nil dereference,
|
||||
// out-of-range index — is recovered and returned as an error rather than
|
||||
// taking down the daemon.
|
||||
func Evaluate(gctx gate.GateContext) (findings []gate.Finding, err error) {
|
||||
func Evaluate(gctx gate.GateContext) ([]gate.Finding, error) {
|
||||
src, err := os.ReadFile(filepath.Join(gctx.Dir, scriptPath))
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
@@ -36,32 +36,15 @@ func Evaluate(gctx gate.GateContext) (findings []gate.Finding, err error) {
|
||||
return nil, fmt.Errorf("read %s: %w", scriptPath, err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
findings, err = nil, fmt.Errorf("yaegi: %s panicked: %v", scriptPath, r)
|
||||
return yaegiutil.Safe(scriptPath, func() ([]gate.Finding, error) {
|
||||
i, err := yaegiutil.New(interp.Options{}, gateextract.Symbols)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}()
|
||||
|
||||
i := interp.New(interp.Options{})
|
||||
if err := i.Use(stdlib.Symbols); err != nil {
|
||||
return nil, fmt.Errorf("yaegi: load stdlib symbols: %w", err)
|
||||
}
|
||||
if err := i.Use(gateextract.Symbols); err != nil {
|
||||
return nil, fmt.Errorf("yaegi: load gate symbols: %w", err)
|
||||
}
|
||||
|
||||
if _, err := i.Eval(string(src)); err != nil {
|
||||
return nil, fmt.Errorf("yaegi: evaluate %s: %w", scriptPath, err)
|
||||
}
|
||||
|
||||
v, err := i.Eval("gate.Check")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("yaegi: %s does not export func Check(GateContext) []Finding: %w", scriptPath, err)
|
||||
}
|
||||
check, ok := v.Interface().(func(gate.GateContext) []gate.Finding)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("yaegi: %s Check has the wrong signature (want func(gate.GateContext) []gate.Finding)", scriptPath)
|
||||
}
|
||||
|
||||
return check(gctx), nil
|
||||
check, err := yaegiutil.Resolve[func(gate.GateContext) []gate.Finding](i, string(src), "gate.Check")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", scriptPath, err)
|
||||
}
|
||||
return check(gctx), nil
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
// Package natsrpc holds the request/reply plumbing shared by
|
||||
// archie-core's three core-NATS RPC surfaces (storerpc, worktreerpc,
|
||||
// forgerpc): a timeout-bounded client call, multi-subject server
|
||||
// registration with rollback on partial failure, and a JSON error
|
||||
// envelope so handlers don't each reimplement "marshal error, log
|
||||
// encode/respond failures."
|
||||
package natsrpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
)
|
||||
|
||||
// Envelope is the error half of an RPC response. Embed it in a
|
||||
// response type (it flattens into the same JSON object via
|
||||
// encoding/json's anonymous-field promotion) to get Err/NewEnvelope for
|
||||
// free instead of hand-rolling an `Error string` field and its checks.
|
||||
type Envelope struct {
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// NewEnvelope builds an Envelope from err, leaving Error empty on nil.
|
||||
func NewEnvelope(err error) Envelope {
|
||||
if err == nil {
|
||||
return Envelope{}
|
||||
}
|
||||
return Envelope{Error: err.Error()}
|
||||
}
|
||||
|
||||
// Err converts a populated Error string back into an error, or nil.
|
||||
func (e Envelope) Err() error {
|
||||
if e.Error == "" {
|
||||
return nil
|
||||
}
|
||||
return errors.New(e.Error)
|
||||
}
|
||||
|
||||
// Client sends timeout-bounded NATS request/reply calls.
|
||||
type Client struct {
|
||||
Conn *nats.Conn
|
||||
// Timeout bounds each call when ctx has no deadline of its own.
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Request sends data to subject and returns the reply payload.
|
||||
func (c *Client) Request(ctx context.Context, subject string, data []byte) ([]byte, error) {
|
||||
if _, hasDeadline := ctx.Deadline(); !hasDeadline && c.Timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, c.Timeout)
|
||||
defer cancel()
|
||||
}
|
||||
reply, err := c.Conn.RequestWithContext(ctx, subject, data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", subject, err)
|
||||
}
|
||||
return reply.Data, nil
|
||||
}
|
||||
|
||||
// Call marshals req, sends it to subject, and unmarshals the reply
|
||||
// into a Resp. It does not inspect Resp's error envelope — callers
|
||||
// that embed Envelope should check Err() themselves, since natsrpc
|
||||
// has no way to know a bare Resp type embeds one.
|
||||
func Call[Resp any](ctx context.Context, c *Client, subject string, req any) (Resp, error) {
|
||||
var zero Resp
|
||||
data, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
return zero, fmt.Errorf("encode %s request: %w", subject, err)
|
||||
}
|
||||
reply, err := c.Request(ctx, subject, data)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
var resp Resp
|
||||
if err := json.Unmarshal(reply, &resp); err != nil {
|
||||
return zero, fmt.Errorf("%s: decode response: %w", subject, err)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// Registration pairs a subject with its handler for RegisterAll.
|
||||
type Registration struct {
|
||||
Subject string
|
||||
Handler nats.MsgHandler
|
||||
}
|
||||
|
||||
// RegisterAll subscribes every registration on nc. If any subscribe
|
||||
// call fails, every subscription made so far is unsubscribed before
|
||||
// returning the error — a server never ends up half-registered. The
|
||||
// returned func unsubscribes all of them.
|
||||
func RegisterAll(nc *nats.Conn, regs []Registration) (unsubscribe func(), err error) {
|
||||
subs := make([]*nats.Subscription, 0, len(regs))
|
||||
for _, r := range regs {
|
||||
sub, err := nc.Subscribe(r.Subject, r.Handler)
|
||||
if err != nil {
|
||||
for _, s := range subs {
|
||||
s.Unsubscribe()
|
||||
}
|
||||
return nil, fmt.Errorf("subscribe %s: %w", r.Subject, err)
|
||||
}
|
||||
subs = append(subs, sub)
|
||||
}
|
||||
return func() {
|
||||
for _, s := range subs {
|
||||
s.Unsubscribe()
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Respond marshals v and replies to msg, logging (rather than
|
||||
// returning) any encode or transport failure — a handler has no
|
||||
// meaningful way to retry or propagate a respond failure to its caller.
|
||||
// pkg prefixes the log message (e.g. "storerpc") to identify the
|
||||
// surface a failure came from.
|
||||
func Respond(msg *nats.Msg, log *slog.Logger, pkg string, v any) {
|
||||
data, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
if log != nil {
|
||||
log.Error(pkg+": encode response failed", "err", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err := msg.Respond(data); err != nil && log != nil {
|
||||
log.Error(pkg+": respond failed", "err", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package natsrpc_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/natsrpc"
|
||||
)
|
||||
|
||||
func TestEnvelopeRoundTrip(t *testing.T) {
|
||||
if err := natsrpc.NewEnvelope(nil).Err(); err != nil {
|
||||
t.Errorf("NewEnvelope(nil).Err() = %v, want nil", err)
|
||||
}
|
||||
|
||||
want := "boom"
|
||||
env := natsrpc.NewEnvelope(errBoom{want})
|
||||
if env.Error != want {
|
||||
t.Errorf("Error = %q, want %q", env.Error, want)
|
||||
}
|
||||
if got := env.Err(); got == nil || got.Error() != want {
|
||||
t.Errorf("Err() = %v, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
type errBoom struct{ msg string }
|
||||
|
||||
func (e errBoom) Error() string { return e.msg }
|
||||
@@ -14,7 +14,8 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/traefik/yaegi/interp"
|
||||
"github.com/traefik/yaegi/stdlib"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/yaegiutil"
|
||||
)
|
||||
|
||||
// Plugin is a core plugin loaded by the daemon at startup. Each .go file
|
||||
@@ -74,34 +75,14 @@ func LoadDir(dir string, extraSymbols ...map[string]map[string]reflect.Value) ([
|
||||
}
|
||||
// Each plugin file is package main — must use a fresh interpreter
|
||||
// to avoid symbol collisions between files.
|
||||
i := interp.New(interp.Options{})
|
||||
if err := i.Use(stdlib.Symbols); err != nil {
|
||||
slog.Default().Warn("skipping plugin — stdlib load failed", "file", name, "err", err)
|
||||
continue
|
||||
}
|
||||
symbolLoadFailed := false
|
||||
for j, s := range extraSymbols {
|
||||
if err := i.Use(s); err != nil {
|
||||
slog.Default().Warn("skipping plugin — symbol table load failed", "file", name, "symbolIndex", j, "err", err)
|
||||
symbolLoadFailed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if symbolLoadFailed {
|
||||
continue
|
||||
}
|
||||
if _, err := i.Eval(string(src)); err != nil {
|
||||
slog.Default().Warn("skipping plugin — compile failed", "file", name, "err", err)
|
||||
continue
|
||||
}
|
||||
v, err := i.Eval("main.Plugin")
|
||||
i, err := yaegiutil.New(interp.Options{}, extraSymbols...)
|
||||
if err != nil {
|
||||
slog.Default().Warn("skipping plugin — no Plugin export", "file", name, "err", err)
|
||||
slog.Default().Warn("skipping plugin — interpreter setup failed", "file", name, "err", err)
|
||||
continue
|
||||
}
|
||||
p, ok := v.Interface().(Plugin)
|
||||
if !ok {
|
||||
slog.Default().Warn("skipping plugin — wrong Plugin type", "file", name, "type", fmt.Sprintf("%T", v.Interface()))
|
||||
p, err := yaegiutil.Resolve[Plugin](i, string(src), "main.Plugin")
|
||||
if err != nil {
|
||||
slog.Default().Warn("skipping plugin", "file", name, "err", err)
|
||||
continue
|
||||
}
|
||||
plugins = append(plugins, p)
|
||||
|
||||
@@ -8,7 +8,8 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/traefik/yaegi/interp"
|
||||
"github.com/traefik/yaegi/stdlib"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/yaegiutil"
|
||||
)
|
||||
|
||||
// Plugin is a discovered Yaegi-interpreted .go file in a skill's plugins/
|
||||
@@ -24,21 +25,14 @@ type Plugin struct {
|
||||
// Run interprets the plugin source via Yaegi and calls its Run function
|
||||
// with the given input. The plugin runs with full standard library access.
|
||||
func (p *Plugin) Run(input string) (string, error) {
|
||||
i := interp.New(interp.Options{})
|
||||
if err := i.Use(stdlib.Symbols); err != nil {
|
||||
return "", fmt.Errorf("plugin %s: stdlib: %w", p.Name, err)
|
||||
}
|
||||
if _, err := i.Eval(p.Src); err != nil {
|
||||
return "", fmt.Errorf("plugin %s: eval: %w", p.Name, err)
|
||||
i, err := yaegiutil.New(interp.Options{})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("plugin %s: %w", p.Name, err)
|
||||
}
|
||||
// Plugins must use package main — the convention for runnable Yaegi scripts.
|
||||
v, err := i.Eval("main.Run")
|
||||
fn, err := yaegiutil.Resolve[func(string) string](i, p.Src, "main.Run")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("plugin %s: resolve Run: %w", p.Name, err)
|
||||
}
|
||||
fn, ok := v.Interface().(func(string) string)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("plugin %s: Run is %T, want func(string) string", p.Name, v.Interface())
|
||||
return "", fmt.Errorf("plugin %s: %w", p.Name, err)
|
||||
}
|
||||
return fn(input), nil
|
||||
}
|
||||
|
||||
@@ -11,8 +11,9 @@ import (
|
||||
"os"
|
||||
|
||||
"github.com/traefik/yaegi/interp"
|
||||
"github.com/traefik/yaegi/stdlib"
|
||||
"github.com/traefik/yaegi/stdlib/unrestricted"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/yaegiutil"
|
||||
)
|
||||
|
||||
// Run interprets the Go script at path and executes its main function,
|
||||
@@ -21,33 +22,25 @@ import (
|
||||
// (os/exec included — these scripts wrap external tools the way a shell
|
||||
// script would), so a panic inside it is recovered and returned as an
|
||||
// error rather than taking down the daemon.
|
||||
func Run(path string) (output string, err error) {
|
||||
func Run(path string) (string, error) {
|
||||
if _, statErr := os.Stat(path); statErr != nil {
|
||||
return "", statErr
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
err = fmt.Errorf("yaegi: %s panicked: %v", path, r)
|
||||
return yaegiutil.Safe(path, func() (string, error) {
|
||||
var buf bytes.Buffer
|
||||
i, err := yaegiutil.New(interp.Options{Stdout: &buf, Stderr: &buf}, unrestricted.Symbols)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}()
|
||||
|
||||
var buf bytes.Buffer
|
||||
i := interp.New(interp.Options{Stdout: &buf, Stderr: &buf})
|
||||
if err := i.Use(stdlib.Symbols); err != nil {
|
||||
return "", fmt.Errorf("yaegi: load stdlib symbols: %w", err)
|
||||
}
|
||||
if err := i.Use(unrestricted.Symbols); err != nil {
|
||||
return "", fmt.Errorf("yaegi: load unrestricted symbols: %w", err)
|
||||
}
|
||||
|
||||
// EvalPath treats a package-main source file the way `go run` does:
|
||||
// evaluating it executes its main() directly. Unlike `go build`, it
|
||||
// does not complain about a missing main() — such a script simply
|
||||
// produces no output.
|
||||
if _, err := i.EvalPath(path); err != nil {
|
||||
return "", fmt.Errorf("yaegi: run %s: %w", path, err)
|
||||
}
|
||||
|
||||
return buf.String(), nil
|
||||
// EvalPath treats a package-main source file the way `go run` does:
|
||||
// evaluating it executes its main() directly. Unlike `go build`, it
|
||||
// does not complain about a missing main() — such a script simply
|
||||
// produces no output.
|
||||
if _, err := i.EvalPath(path); err != nil {
|
||||
return "", fmt.Errorf("yaegi: run %s: %w", path, err)
|
||||
}
|
||||
return buf.String(), nil
|
||||
})
|
||||
}
|
||||
@@ -7,13 +7,12 @@ package storerpc
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/natsrpc"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
@@ -38,7 +37,7 @@ type TransitionRequest struct {
|
||||
|
||||
// Response carries the result of an RPC. Error is empty on success.
|
||||
type Response struct {
|
||||
Error string `json:"error,omitempty"`
|
||||
natsrpc.Envelope
|
||||
}
|
||||
|
||||
// Server handles storerpc requests against the daemon's Store.
|
||||
@@ -50,25 +49,16 @@ type Server struct {
|
||||
// Register subscribes the update and transition handlers on nc. The
|
||||
// returned func unsubscribes both.
|
||||
func (s *Server) Register(nc *nats.Conn) (unsubscribe func(), err error) {
|
||||
updateSub, err := nc.Subscribe(SubjectUpdate, s.handleUpdate)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("subscribe %s: %w", SubjectUpdate, err)
|
||||
}
|
||||
transitionSub, err := nc.Subscribe(SubjectTransition, s.handleTransition)
|
||||
if err != nil {
|
||||
updateSub.Unsubscribe()
|
||||
return nil, fmt.Errorf("subscribe %s: %w", SubjectTransition, err)
|
||||
}
|
||||
return func() {
|
||||
updateSub.Unsubscribe()
|
||||
transitionSub.Unsubscribe()
|
||||
}, nil
|
||||
return natsrpc.RegisterAll(nc, []natsrpc.Registration{
|
||||
{Subject: SubjectUpdate, Handler: s.handleUpdate},
|
||||
{Subject: SubjectTransition, Handler: s.handleTransition},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleUpdate(msg *nats.Msg) {
|
||||
var req UpdateRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.reply(msg, fmt.Errorf("decode update request: %w", err))
|
||||
s.reply(msg, err)
|
||||
return
|
||||
}
|
||||
s.reply(msg, s.Store.Update(context.Background(), req.Task))
|
||||
@@ -77,27 +67,14 @@ func (s *Server) handleUpdate(msg *nats.Msg) {
|
||||
func (s *Server) handleTransition(msg *nats.Msg) {
|
||||
var req TransitionRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.reply(msg, fmt.Errorf("decode transition request: %w", err))
|
||||
s.reply(msg, err)
|
||||
return
|
||||
}
|
||||
s.reply(msg, s.Store.Transition(context.Background(), req.TaskID, req.From, req.To, req.Detail))
|
||||
}
|
||||
|
||||
func (s *Server) reply(msg *nats.Msg, err error) {
|
||||
resp := Response{}
|
||||
if err != nil {
|
||||
resp.Error = err.Error()
|
||||
}
|
||||
data, encErr := json.Marshal(resp)
|
||||
if encErr != nil {
|
||||
if s.Log != nil {
|
||||
s.Log.Error("storerpc: encode response failed", "err", encErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err := msg.Respond(data); err != nil && s.Log != nil {
|
||||
s.Log.Error("storerpc: respond failed", "err", err)
|
||||
}
|
||||
natsrpc.Respond(msg, s.Log, "storerpc", Response{Envelope: natsrpc.NewEnvelope(err)})
|
||||
}
|
||||
|
||||
// Client calls the storerpc Server from archie-agent's process.
|
||||
@@ -107,40 +84,23 @@ type Client struct {
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
func (c *Client) rpc() *natsrpc.Client { return &natsrpc.Client{Conn: c.Conn, Timeout: c.Timeout} }
|
||||
|
||||
// Update calls store.Store.Update on the daemon over NATS request/reply.
|
||||
func (c *Client) Update(ctx context.Context, task *store.Task) error {
|
||||
data, err := json.Marshal(UpdateRequest{Task: task})
|
||||
resp, err := natsrpc.Call[Response](ctx, c.rpc(), SubjectUpdate, UpdateRequest{Task: task})
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode update request: %w", err)
|
||||
return err
|
||||
}
|
||||
return c.call(ctx, SubjectUpdate, data)
|
||||
return resp.Err()
|
||||
}
|
||||
|
||||
// Transition calls store.Store.Transition on the daemon over NATS request/reply.
|
||||
func (c *Client) Transition(ctx context.Context, taskID int64, from, to, detail string) error {
|
||||
data, err := json.Marshal(TransitionRequest{TaskID: taskID, From: from, To: to, Detail: detail})
|
||||
req := TransitionRequest{TaskID: taskID, From: from, To: to, Detail: detail}
|
||||
resp, err := natsrpc.Call[Response](ctx, c.rpc(), SubjectTransition, req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode transition request: %w", err)
|
||||
return err
|
||||
}
|
||||
return c.call(ctx, SubjectTransition, data)
|
||||
}
|
||||
|
||||
func (c *Client) call(ctx context.Context, subject string, data []byte) error {
|
||||
if _, hasDeadline := ctx.Deadline(); !hasDeadline && c.Timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, c.Timeout)
|
||||
defer cancel()
|
||||
}
|
||||
reply, err := c.Conn.RequestWithContext(ctx, subject, data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("storerpc %s: %w", subject, err)
|
||||
}
|
||||
var resp Response
|
||||
if err := json.Unmarshal(reply.Data, &resp); err != nil {
|
||||
return fmt.Errorf("storerpc %s: decode response: %w", subject, err)
|
||||
}
|
||||
if resp.Error != "" {
|
||||
return errors.New(resp.Error)
|
||||
}
|
||||
return nil
|
||||
return resp.Err()
|
||||
}
|
||||
@@ -13,11 +13,11 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/traefik/yaegi/interp"
|
||||
"github.com/traefik/yaegi/stdlib"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/skill"
|
||||
"github.com/samcharles93/archie-core/internal/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/workflow/wfextract"
|
||||
"github.com/samcharles93/archie-core/internal/yaegiutil"
|
||||
)
|
||||
|
||||
// builtins returns the hardcoded fallback workflows. These are used when
|
||||
@@ -39,41 +39,10 @@ func builtins() workflow.Registry {
|
||||
//
|
||||
// Skills define workflows. Plugins define stages. The daemon composes them.
|
||||
func BuildRegistry(worktree string) (workflow.Registry, error) {
|
||||
catalog, err := skill.Catalog(worktree)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("skill catalog: %w", err)
|
||||
}
|
||||
|
||||
reg := builtins()
|
||||
|
||||
for _, entry := range catalog {
|
||||
if entry.Workflow == "" {
|
||||
continue
|
||||
}
|
||||
sw := SkillWorkflow{Workflow: entry.Workflow, Dir: entry.Dir}
|
||||
wf, err := BuildWorkflow(worktree, sw)
|
||||
if err != nil {
|
||||
slog.Default().Warn("skipping broken skill workflow",
|
||||
"workflow", entry.Workflow,
|
||||
"skill", entry.Dir,
|
||||
"err", err,
|
||||
)
|
||||
continue
|
||||
}
|
||||
// Only override the built-in when the skill actually has stages —
|
||||
// an empty workflow means the skill declared intent but has no
|
||||
// plugins yet, so keep the built-in.
|
||||
if len(wf.Stages) > 0 {
|
||||
if _, dup := reg[entry.Workflow]; dup {
|
||||
slog.Default().Warn("duplicate workflow name — overriding",
|
||||
"workflow", entry.Workflow,
|
||||
"skill", entry.Dir,
|
||||
)
|
||||
}
|
||||
reg[entry.Workflow] = wf
|
||||
}
|
||||
if err := mergeSkillWorkflows(worktree, reg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return reg, nil
|
||||
}
|
||||
|
||||
@@ -95,15 +64,26 @@ type SkillWorkflow struct {
|
||||
// specific cloned worktree so that per-repo skills are discovered
|
||||
// without restarting the daemon.
|
||||
func AugmentRegistry(worktree string, base workflow.Registry) (workflow.Registry, error) {
|
||||
// Copy base — never mutate the caller's registry.
|
||||
reg := make(workflow.Registry, len(base))
|
||||
maps.Copy(reg, base)
|
||||
if err := mergeSkillWorkflows(worktree, reg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return reg, nil
|
||||
}
|
||||
|
||||
// mergeSkillWorkflows scans worktree for skill catalog entries that
|
||||
// declare a workflow, builds each from its stage plugins, and merges the
|
||||
// result into reg in place. A skill whose workflow has no stages yet
|
||||
// (declared intent, no plugins/ directory) leaves reg's existing entry
|
||||
// (built-in or base) untouched.
|
||||
func mergeSkillWorkflows(worktree string, reg workflow.Registry) error {
|
||||
catalog, err := skill.Catalog(worktree)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("skill catalog: %w", err)
|
||||
return fmt.Errorf("skill catalog: %w", err)
|
||||
}
|
||||
|
||||
// Copy base — never mutate the caller's registry.
|
||||
reg := make(workflow.Registry, len(base)+len(catalog))
|
||||
maps.Copy(reg, base)
|
||||
|
||||
for _, entry := range catalog {
|
||||
if entry.Workflow == "" {
|
||||
continue
|
||||
@@ -111,16 +91,13 @@ func AugmentRegistry(worktree string, base workflow.Registry) (workflow.Registry
|
||||
sw := SkillWorkflow{Workflow: entry.Workflow, Dir: entry.Dir}
|
||||
wf, err := BuildWorkflow(worktree, sw)
|
||||
if err != nil {
|
||||
slog.Default().Warn("skipping broken skill workflow in worktree",
|
||||
slog.Default().Warn("skipping broken skill workflow",
|
||||
"workflow", entry.Workflow,
|
||||
"skill", entry.Dir,
|
||||
"err", err,
|
||||
)
|
||||
continue
|
||||
}
|
||||
// Only override the base entry when the skill actually has stages.
|
||||
// An empty workflow means the skill declared intent but has no
|
||||
// plugins yet — keep the base (or built-in) definition.
|
||||
if len(wf.Stages) > 0 {
|
||||
if _, dup := reg[entry.Workflow]; dup {
|
||||
slog.Default().Warn("duplicate workflow name — overriding",
|
||||
@@ -132,7 +109,7 @@ func AugmentRegistry(worktree string, base workflow.Registry) (workflow.Registry
|
||||
}
|
||||
}
|
||||
|
||||
return reg, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// BuildWorkflow loads stage plugins from a skill's plugins/ directory
|
||||
@@ -168,8 +145,7 @@ func BuildWorkflow(worktree string, entry SkillWorkflow) (workflow.Workflow, err
|
||||
slog.Default().Warn("skipping unreadable stage plugin", "plugin", name, "err", err)
|
||||
continue
|
||||
}
|
||||
i := newStageInterpreter()
|
||||
stage, err := loadStage(i, name, string(src))
|
||||
stage, err := loadStage(name, string(src))
|
||||
if err != nil {
|
||||
slog.Default().Warn("skipping broken stage plugin", "plugin", name, "err", err)
|
||||
continue
|
||||
@@ -180,44 +156,32 @@ func BuildWorkflow(worktree string, entry SkillWorkflow) (workflow.Workflow, err
|
||||
return workflow.Workflow{Name: entry.Workflow, Stages: stages}, nil
|
||||
}
|
||||
|
||||
// newStageInterpreter returns a Yaegi interpreter pre-loaded with stdlib
|
||||
// and workflow symbols. Each plugin file still needs its own interpreter
|
||||
// because files use package main with duplicate Stage() symbols — they
|
||||
// cannot be co-evaluated in a single interpreter without collisions.
|
||||
func newStageInterpreter() *interp.Interpreter {
|
||||
i := interp.New(interp.Options{})
|
||||
_ = i.Use(stdlib.Symbols)
|
||||
_ = i.Use(wfextract.Symbols)
|
||||
return i
|
||||
}
|
||||
|
||||
// loadStage interprets a single .go plugin source via Yaegi. Prefer
|
||||
// passing a pre-configured interpreter from newStageInterpreter() to
|
||||
// avoid redundant stdlib loading across multiple files.
|
||||
func loadStage(interp *interp.Interpreter, filename string, src string) (workflow.Stage, error) {
|
||||
i := interp
|
||||
if i == nil {
|
||||
i = newStageInterpreter()
|
||||
}
|
||||
if _, err := i.Eval(src); err != nil {
|
||||
return workflow.Stage{}, fmt.Errorf("eval: %w", err)
|
||||
}
|
||||
v, err := i.Eval("main.Stage")
|
||||
if err != nil {
|
||||
return workflow.Stage{}, fmt.Errorf("resolve Stage: %w", err)
|
||||
}
|
||||
fn, ok := v.Interface().(func() workflow.Stage)
|
||||
if !ok {
|
||||
// loadStage interprets a single .go plugin source via Yaegi and calls its
|
||||
// exported Stage(). filename is used only for interpreter panic messages.
|
||||
func loadStage(filename, src string) (workflow.Stage, error) {
|
||||
return yaegiutil.Safe(filename, func() (workflow.Stage, error) {
|
||||
i, err := yaegiutil.New(interp.Options{}, wfextract.Symbols)
|
||||
if err != nil {
|
||||
return workflow.Stage{}, err
|
||||
}
|
||||
if _, err := i.Eval(src); err != nil {
|
||||
return workflow.Stage{}, fmt.Errorf("evaluate: %w", err)
|
||||
}
|
||||
v, err := i.Eval("main.Stage")
|
||||
if err != nil {
|
||||
return workflow.Stage{}, fmt.Errorf("does not export main.Stage: %w", err)
|
||||
}
|
||||
if fn, ok := v.Interface().(func() workflow.Stage); ok {
|
||||
return fn(), nil
|
||||
}
|
||||
// Fallback for test plugins: func() (string, func(...) error).
|
||||
// NOTE: this constructs Stage with positional fields. If Stage
|
||||
// gains new fields in the future, this path will silently zero-
|
||||
// value them. Prefer func() workflow.Stage in production plugins.
|
||||
rawFn, rawOk := v.Interface().(func() (string, func(context.Context, *workflow.TaskContext) error))
|
||||
if rawOk {
|
||||
if rawFn, ok := v.Interface().(func() (string, func(context.Context, *workflow.TaskContext) error)); ok {
|
||||
name, run := rawFn()
|
||||
return workflow.Stage{Name: name, Run: run}, nil
|
||||
}
|
||||
return workflow.Stage{}, fmt.Errorf("Stage is %T, want func() workflow.Stage", v.Interface())
|
||||
}
|
||||
return fn(), nil
|
||||
return workflow.Stage{}, fmt.Errorf("main.Stage is %T, want func() workflow.Stage", v.Interface())
|
||||
})
|
||||
}
|
||||
@@ -12,10 +12,10 @@ import (
|
||||
"sort"
|
||||
|
||||
"github.com/traefik/yaegi/interp"
|
||||
"github.com/traefik/yaegi/stdlib"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/workflow/wfextract"
|
||||
"github.com/samcharles93/archie-core/internal/yaegiutil"
|
||||
)
|
||||
|
||||
// stagesDir is where a repo's custom stage scripts live, relative to
|
||||
@@ -58,38 +58,21 @@ func Discover(dir string) ([]workflow.Stage, error) {
|
||||
// Stage() function. The script runs in-process (interpreted, not
|
||||
// sandboxed), so a panic inside it is recovered and returned as an error
|
||||
// rather than taking down the daemon.
|
||||
func loadStage(path string) (stage workflow.Stage, err error) {
|
||||
func loadStage(path string) (workflow.Stage, error) {
|
||||
src, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return workflow.Stage{}, err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
stage, err = workflow.Stage{}, fmt.Errorf("panicked: %v", r)
|
||||
return yaegiutil.Safe(path, func() (workflow.Stage, error) {
|
||||
i, err := yaegiutil.New(interp.Options{}, wfextract.Symbols)
|
||||
if err != nil {
|
||||
return workflow.Stage{}, err
|
||||
}
|
||||
}()
|
||||
|
||||
i := interp.New(interp.Options{})
|
||||
if err := i.Use(stdlib.Symbols); err != nil {
|
||||
return workflow.Stage{}, fmt.Errorf("yaegi: load stdlib symbols: %w", err)
|
||||
}
|
||||
if err := i.Use(wfextract.Symbols); err != nil {
|
||||
return workflow.Stage{}, fmt.Errorf("yaegi: load workflow symbols: %w", err)
|
||||
}
|
||||
|
||||
if _, err := i.Eval(string(src)); err != nil {
|
||||
return workflow.Stage{}, fmt.Errorf("yaegi: evaluate: %w", err)
|
||||
}
|
||||
|
||||
v, err := i.Eval("stages.Stage")
|
||||
if err != nil {
|
||||
return workflow.Stage{}, fmt.Errorf("yaegi: does not export func Stage() workflow.Stage: %w", err)
|
||||
}
|
||||
factory, ok := v.Interface().(func() workflow.Stage)
|
||||
if !ok {
|
||||
return workflow.Stage{}, fmt.Errorf("yaegi: Stage has the wrong signature (want func() workflow.Stage)")
|
||||
}
|
||||
|
||||
return factory(), nil
|
||||
factory, err := yaegiutil.Resolve[func() workflow.Stage](i, string(src), "stages.Stage")
|
||||
if err != nil {
|
||||
return workflow.Stage{}, fmt.Errorf("yaegi: %w", err)
|
||||
}
|
||||
return factory(), nil
|
||||
})
|
||||
}
|
||||
@@ -14,13 +14,12 @@ package worktreerpc
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/natsrpc"
|
||||
"github.com/samcharles93/archie-core/internal/worktree"
|
||||
)
|
||||
|
||||
@@ -40,7 +39,7 @@ type PushRequest struct {
|
||||
}
|
||||
|
||||
type Response struct {
|
||||
Error string `json:"error,omitempty"`
|
||||
natsrpc.Envelope
|
||||
}
|
||||
|
||||
// PrepareRequest mirrors worktree.Manager.Prepare's arguments.
|
||||
@@ -57,7 +56,7 @@ type PrepareRequest struct {
|
||||
type PrepareResponse struct {
|
||||
Dir string `json:"dir"`
|
||||
Branch string `json:"branch"`
|
||||
Error string `json:"error,omitempty"`
|
||||
natsrpc.Envelope
|
||||
}
|
||||
|
||||
// Server proxies push requests to a real worktree.Manager holding the
|
||||
@@ -70,25 +69,16 @@ type Server struct {
|
||||
// Register subscribes the push and prepare handlers on nc. The returned
|
||||
// func unsubscribes both.
|
||||
func (s *Server) Register(nc *nats.Conn) (unsubscribe func(), err error) {
|
||||
pushSub, err := nc.Subscribe(SubjectPush, s.handlePush)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("subscribe %s: %w", SubjectPush, err)
|
||||
}
|
||||
prepareSub, err := nc.Subscribe(SubjectPrepare, s.handlePrepare)
|
||||
if err != nil {
|
||||
pushSub.Unsubscribe()
|
||||
return nil, fmt.Errorf("subscribe %s: %w", SubjectPrepare, err)
|
||||
}
|
||||
return func() {
|
||||
pushSub.Unsubscribe()
|
||||
prepareSub.Unsubscribe()
|
||||
}, nil
|
||||
return natsrpc.RegisterAll(nc, []natsrpc.Registration{
|
||||
{Subject: SubjectPush, Handler: s.handlePush},
|
||||
{Subject: SubjectPrepare, Handler: s.handlePrepare},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handlePush(msg *nats.Msg) {
|
||||
var req PushRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.respond(msg, fmt.Errorf("decode push request: %w", err))
|
||||
s.respond(msg, err)
|
||||
return
|
||||
}
|
||||
dir := s.Trees.Dir(req.Owner, req.Repo, req.Issue)
|
||||
@@ -98,7 +88,7 @@ func (s *Server) handlePush(msg *nats.Msg) {
|
||||
func (s *Server) handlePrepare(msg *nats.Msg) {
|
||||
var req PrepareRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.respondPrepare(msg, "", "", fmt.Errorf("decode prepare request: %w", err))
|
||||
s.respondPrepare(msg, "", "", err)
|
||||
return
|
||||
}
|
||||
dir, branch, err := s.Trees.Prepare(context.Background(), req.Owner, req.Repo, req.Base, req.Issue, req.Title, req.Body, req.Labels)
|
||||
@@ -106,37 +96,12 @@ func (s *Server) handlePrepare(msg *nats.Msg) {
|
||||
}
|
||||
|
||||
func (s *Server) respondPrepare(msg *nats.Msg, dir, branch string, err error) {
|
||||
resp := PrepareResponse{Dir: dir, Branch: branch}
|
||||
if err != nil {
|
||||
resp.Error = err.Error()
|
||||
}
|
||||
data, encErr := json.Marshal(resp)
|
||||
if encErr != nil {
|
||||
if s.Log != nil {
|
||||
s.Log.Error("worktreerpc: encode response failed", "err", encErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err := msg.Respond(data); err != nil && s.Log != nil {
|
||||
s.Log.Error("worktreerpc: respond failed", "err", err)
|
||||
}
|
||||
resp := PrepareResponse{Dir: dir, Branch: branch, Envelope: natsrpc.NewEnvelope(err)}
|
||||
natsrpc.Respond(msg, s.Log, "worktreerpc", resp)
|
||||
}
|
||||
|
||||
func (s *Server) respond(msg *nats.Msg, err error) {
|
||||
resp := Response{}
|
||||
if err != nil {
|
||||
resp.Error = err.Error()
|
||||
}
|
||||
data, encErr := json.Marshal(resp)
|
||||
if encErr != nil {
|
||||
if s.Log != nil {
|
||||
s.Log.Error("worktreerpc: encode response failed", "err", encErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err := msg.Respond(data); err != nil && s.Log != nil {
|
||||
s.Log.Error("worktreerpc: respond failed", "err", err)
|
||||
}
|
||||
natsrpc.Respond(msg, s.Log, "worktreerpc", Response{Envelope: natsrpc.NewEnvelope(err)})
|
||||
}
|
||||
|
||||
// Client calls the worktreerpc Server from archie-agent's process.
|
||||
@@ -146,58 +111,30 @@ type Client struct {
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
func (c *Client) rpc() *natsrpc.Client { return &natsrpc.Client{Conn: c.Conn, Timeout: c.Timeout} }
|
||||
|
||||
// Push requests that archied push branch for owner/repo/issue's worktree
|
||||
// using its held forge credential.
|
||||
func (c *Client) Push(ctx context.Context, owner, repo string, issue int, branch string) error {
|
||||
data, err := json.Marshal(PushRequest{Owner: owner, Repo: repo, Issue: issue, Branch: branch})
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode push request: %w", err)
|
||||
}
|
||||
reply, err := c.request(ctx, SubjectPush, data)
|
||||
req := PushRequest{Owner: owner, Repo: repo, Issue: issue, Branch: branch}
|
||||
resp, err := natsrpc.Call[Response](ctx, c.rpc(), SubjectPush, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var resp Response
|
||||
if err := json.Unmarshal(reply, &resp); err != nil {
|
||||
return fmt.Errorf("worktreerpc %s: decode response: %w", SubjectPush, err)
|
||||
}
|
||||
if resp.Error != "" {
|
||||
return errors.New(resp.Error)
|
||||
}
|
||||
return nil
|
||||
return resp.Err()
|
||||
}
|
||||
|
||||
// Prepare requests that archied clone/fetch the worktree for
|
||||
// owner/repo/issue using its held forge credential, matching
|
||||
// worktree.Manager.Prepare's signature.
|
||||
func (c *Client) Prepare(ctx context.Context, owner, repo, base string, issue int, title, body, labels string) (dir, branch string, err error) {
|
||||
data, err := json.Marshal(PrepareRequest{Owner: owner, Repo: repo, Base: base, Issue: issue, Title: title, Body: body, Labels: labels})
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("encode prepare request: %w", err)
|
||||
}
|
||||
reply, err := c.request(ctx, SubjectPrepare, data)
|
||||
req := PrepareRequest{Owner: owner, Repo: repo, Base: base, Issue: issue, Title: title, Body: body, Labels: labels}
|
||||
resp, err := natsrpc.Call[PrepareResponse](ctx, c.rpc(), SubjectPrepare, req)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
var resp PrepareResponse
|
||||
if err := json.Unmarshal(reply, &resp); err != nil {
|
||||
return "", "", fmt.Errorf("worktreerpc %s: decode response: %w", SubjectPrepare, err)
|
||||
}
|
||||
if resp.Error != "" {
|
||||
return "", "", errors.New(resp.Error)
|
||||
if err := resp.Err(); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
return resp.Dir, resp.Branch, nil
|
||||
}
|
||||
|
||||
func (c *Client) request(ctx context.Context, subject string, data []byte) ([]byte, error) {
|
||||
if _, hasDeadline := ctx.Deadline(); !hasDeadline && c.Timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, c.Timeout)
|
||||
defer cancel()
|
||||
}
|
||||
reply, err := c.Conn.RequestWithContext(ctx, subject, data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("worktreerpc %s: %w", subject, err)
|
||||
}
|
||||
return reply.Data, nil
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// Package yaegiutil holds the interpreter-construction and safe-eval
|
||||
// helpers shared by every Yaegi-interpreted extension surface in
|
||||
// archie-core (gate scripts, workflow stages, skill plugins, daemon
|
||||
// plugins, skill scripts). Each surface differs in what symbol tables it
|
||||
// loads, what export it resolves, and how it invokes that export, but
|
||||
// all of them build an interpreter the same way and must recover a
|
||||
// panic from interpreted code — including a panic during the call
|
||||
// itself, not just during eval — rather than let it take down the
|
||||
// daemon.
|
||||
package yaegiutil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
|
||||
"github.com/traefik/yaegi/interp"
|
||||
"github.com/traefik/yaegi/stdlib"
|
||||
)
|
||||
|
||||
// New returns a Yaegi interpreter with the standard library and any
|
||||
// extraSymbols loaded. Each interpreted file must get its own
|
||||
// interpreter when it declares package main — Yaegi cannot co-evaluate
|
||||
// two package-main files with colliding symbols (e.g. two Stage()
|
||||
// functions) in the same interpreter.
|
||||
func New(opts interp.Options, extraSymbols ...map[string]map[string]reflect.Value) (*interp.Interpreter, error) {
|
||||
i := interp.New(opts)
|
||||
if err := i.Use(stdlib.Symbols); err != nil {
|
||||
return nil, fmt.Errorf("yaegi: load stdlib symbols: %w", err)
|
||||
}
|
||||
for _, s := range extraSymbols {
|
||||
if err := i.Use(s); err != nil {
|
||||
return nil, fmt.Errorf("yaegi: load symbols: %w", err)
|
||||
}
|
||||
}
|
||||
return i, nil
|
||||
}
|
||||
|
||||
// Resolve evaluates src in i and type-asserts exportPath's value
|
||||
// (e.g. "main.Stage", "gate.Check") to T. It does not itself recover
|
||||
// panics — wrap the call that invokes the returned T in Safe, since a
|
||||
// panic can happen either during Eval (e.g. an init()) or during the
|
||||
// caller's later invocation of the resolved function.
|
||||
func Resolve[T any](i *interp.Interpreter, src, exportPath string) (result T, err error) {
|
||||
if _, err := i.Eval(src); err != nil {
|
||||
return result, fmt.Errorf("evaluate: %w", err)
|
||||
}
|
||||
v, err := i.Eval(exportPath)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("does not export %s: %w", exportPath, err)
|
||||
}
|
||||
fn, ok := v.Interface().(T)
|
||||
if !ok {
|
||||
return result, fmt.Errorf("%s is %T, want %T", exportPath, v.Interface(), result)
|
||||
}
|
||||
return fn, nil
|
||||
}
|
||||
|
||||
// Safe runs fn and recovers any panic — interpreted code is untrusted
|
||||
// relative to the daemon's own logic, so a nil dereference or
|
||||
// out-of-range index inside it must become an error, not a crash.
|
||||
// label identifies the interpreted source in the resulting error.
|
||||
func Safe[R any](label string, fn func() (R, error)) (result R, err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
var zero R
|
||||
result, err = zero, fmt.Errorf("yaegi: %s panicked: %v", label, r)
|
||||
}
|
||||
}()
|
||||
return fn()
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package yaegiutil_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/traefik/yaegi/interp"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/yaegiutil"
|
||||
)
|
||||
|
||||
func TestResolve(t *testing.T) {
|
||||
i, err := yaegiutil.New(interp.Options{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fn, err := yaegiutil.Resolve[func() string](i, `package main
|
||||
func Greet() string { return "hi" }`, "main.Greet")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := fn(); got != "hi" {
|
||||
t.Errorf("got %q, want %q", got, "hi")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveWrongType(t *testing.T) {
|
||||
i, err := yaegiutil.New(interp.Options{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = yaegiutil.Resolve[func() int](i, `package main
|
||||
func Greet() string { return "hi" }`, "main.Greet")
|
||||
if err == nil {
|
||||
t.Fatal("want error for wrong type, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveMissingExport(t *testing.T) {
|
||||
i, err := yaegiutil.New(interp.Options{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = yaegiutil.Resolve[func() string](i, `package main
|
||||
func Other() string { return "hi" }`, "main.Greet")
|
||||
if err == nil {
|
||||
t.Fatal("want error for missing export, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeRecoversPanic(t *testing.T) {
|
||||
_, err := yaegiutil.Safe("test", func() (string, error) {
|
||||
panic("boom")
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("want error from recovered panic, got nil")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "boom") {
|
||||
t.Errorf("error %q does not mention panic value", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafePassesThroughResult(t *testing.T) {
|
||||
got, err := yaegiutil.Safe("test", func() (int, error) {
|
||||
return 42, nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != 42 {
|
||||
t.Errorf("got %d, want 42", got)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user