Compare commits

...
3 Commits
5 changed files with 89 additions and 7 deletions

No files matched your search

+7
View File
@@ -140,6 +140,13 @@ func (m *Module) Notify(ctx context.Context, n Notification) error {
})
}
// Reaches reports whether channel is a running connector that declares the
// delivery to one chat.
func (m *Module) Reaches(channel string) bool {
c, ok := m.channels.Get(channel)
return ok && c.Delivers(deliveryChat)
}
// Send delivers text to one chat on the named channel, and returns when the
// channel has accepted it. The key makes the delivery idempotent on the
// channel, so a step that is replayed after a crash does not send twice.
+21 -5
View File
@@ -295,7 +295,8 @@ type execer interface {
// if it is waiting. Only an ending an operator or the caller must act on
// counts: a run waiting for approval has not ended, and its caller keeps
// waiting. The first ending wins, so a later retry of a parked child does not
// change what the parent was told.
// change what the parent was told. A parent that has already ended is not told
// at all: nothing reads the signal, and a cancelled parent must stay cancelled.
func signalParent(ctx context.Context, q execer, id uuid.UUID) error {
if _, err := q.ExecContext(ctx, `
WITH ended AS (
@@ -307,7 +308,9 @@ func signalParent(ctx context.Context, q execer, id uuid.UUID) error {
AND state IN ('succeeded', 'failed', 'cancelled', 'parked', 'declined')),
sent AS (
INSERT INTO runs.signals (run_id, key, payload)
SELECT parent_run_id, parent_signal, payload FROM ended
SELECT e.parent_run_id, e.parent_signal, e.payload FROM ended e
JOIN runs.runs p ON p.id = e.parent_run_id
WHERE p.state NOT IN ('succeeded', 'failed', 'cancelled', 'declined')
ON CONFLICT (run_id, key) DO NOTHING)
UPDATE runs.runs r SET state = 'queued', wake_at = NULL, updated_at = now()
FROM ended e
@@ -420,8 +423,15 @@ func (s *Store) Signalled(ctx context.Context, id uuid.UUID, key string) (jsonte
return payload, true, nil
}
// Cancel asks a run to stop. A run not currently held ends at once and tells
// the run waiting on it; a running one sees the request at its next step.
// cancelDepth bounds how far Cancel follows workflow.call children. It matches
// the call depth limit a call chain is started under.
const cancelDepth = 5
// Cancel asks a run, and every run it started through workflow.call, to stop.
// A run not currently held ends at once; a held one sees the request at its
// next step and its worker ends it. Runs that have already ended are left
// alone. Only the named run tells its own caller: the descendants' callers are
// being cancelled in the same transaction.
func (s *Store) Cancel(ctx context.Context, id uuid.UUID) error {
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
@@ -429,11 +439,17 @@ func (s *Store) Cancel(ctx context.Context, id uuid.UUID) error {
}
defer func() { _ = tx.Rollback() }()
if _, err := tx.ExecContext(ctx, `
WITH RECURSIVE tree(id, depth) AS (
SELECT id, 0 FROM runs.runs WHERE id = $1
UNION ALL
SELECT c.id, t.depth + 1 FROM runs.runs c JOIN tree t ON c.parent_run_id = t.id
WHERE t.depth < $2)
UPDATE runs.runs
SET cancel_requested = true, updated_at = now(),
state = CASE WHEN state IN ('queued', 'waiting', 'parked', 'waiting_approval') THEN 'cancelled' ELSE state END,
finished_at = CASE WHEN state IN ('queued', 'waiting', 'parked', 'waiting_approval') THEN now() ELSE finished_at END
WHERE id = $1 AND state NOT IN ('succeeded', 'failed', 'cancelled', 'declined')`, id); err != nil {
WHERE id IN (SELECT id FROM tree) AND state NOT IN ('succeeded', 'failed', 'cancelled', 'declined')`,
id, cancelDepth); err != nil {
return fmt.Errorf("cancel run: %w", err)
}
if err := signalParent(ctx, tx, id); err != nil {
+3
View File
@@ -9,6 +9,9 @@ import (
// Messenger delivers text to one chat on a messaging channel.
type Messenger interface {
// Reaches reports whether channel is running and can send to a chat. A
// workflow that sends through any other channel can't be saved.
Reaches(channel string) bool
Send(ctx context.Context, channel, chatID, text, key string) error
}
+21
View File
@@ -144,6 +144,9 @@ func (e *Engine) validateDocument(ctx context.Context, body string) (Document, e
}
var problems []Problem
for i, step := range doc.Steps {
if step.Type == typeMessage {
problems = append(problems, e.checkMessageChannel(i, step)...)
}
if step.Type != typeAgent {
continue
}
@@ -171,6 +174,24 @@ func (e *Engine) validateDocument(ctx context.Context, body string) (Document, e
return doc, nil
}
// checkMessageChannel refuses a message.send step whose channel can't send to
// a chat, so the workflow fails when it is saved instead of when it runs. A
// step with invalid settings is already reported by the document check.
func (e *Engine) checkMessageChannel(index int, step Step) []Problem {
var s messageSettings
if decodeSettings(step.Settings, &s) != nil || strings.TrimSpace(s.Channel) == "" {
return nil
}
deps, err := e.steps()
if err == nil && deps.Messenger != nil && deps.Messenger.Reaches(s.Channel) {
return nil
}
return []Problem{{
Path: fmt.Sprintf("steps[%d].settings.channel", index),
Message: fmt.Sprintf("channel %q isn't an accepted connector that sends messages to a chat", s.Channel),
}}
}
// Has reports whether a workflow is stored under name.
func (e *Engine) Has(ctx context.Context, orgID, name string) (bool, error) {
_, err := e.db.Workflow(ctx, orgID, name, 0)
+37 -2
View File
@@ -6,6 +6,8 @@ import (
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"fmt"
"log/slog"
"slices"
"strings"
"testing"
@@ -107,10 +109,16 @@ func (n *notices) Notify(_ context.Context, msg deliveries.Notification) error {
return nil
}
// chats records the messages a workflow sends.
// chats records the messages a workflow sends. Its only channel that can send
// to a chat is "chat", as a connector declaring the chat delivery would be.
type chats struct{ sent []string }
func (*chats) Reaches(channel string) bool { return channel == "chat" }
func (c *chats) Send(_ context.Context, channel, chatID, text, _ string) error {
if channel != "chat" {
return fmt.Errorf("connector %q declares no chat delivery", channel)
}
c.sent = append(c.sent, channel+"/"+chatID+": "+text)
return nil
}
@@ -418,7 +426,7 @@ steps:
told := &notices{}
sent := &chats{}
wf := Deps{Settings: onePersonPath{}, Toolbox: anyBox{}, Judge: judge, Approver: ask, Notifier: told, Messenger: sent}.Compile(doc)
work := &callWork{signalAfter: signalAfter{arrives: 1}}
work := &callWork{arrives: 1}
work.bodies = tt.bodies
run := store.Run{ID: uuid.New(), Dry: tt.dry}
rc := newContext(t.Context(), work, run, uuid.New(), nil)
@@ -509,6 +517,33 @@ steps:
}
}
// TestSavingChecksMessageChannel guards the message.send contract: a workflow
// that sends through a channel no accepted connector declares the chat
// delivery for is refused when it is saved, not when it runs.
func TestSavingChecksMessageChannel(t *testing.T) {
tests := []struct {
name string
channel string
want string
}{
{name: "a channel that sends to a chat is accepted", channel: "chat"},
{name: "a channel with no chat delivery is refused", channel: "mail", want: `steps[0].settings.channel: channel "mail" isn't an accepted connector that sends messages to a chat`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
engine := newEngine(nil, &fakeWork{}, slog.New(slog.DiscardHandler), Options{})
engine.Use(Deps{Settings: onePersonPath{}, Messenger: &chats{}})
_, err := engine.validateDocument(t.Context(), "steps:\n - {type: message.send, settings: {channel: "+tt.channel+", chat_id: ops, text: hi}}\n")
switch {
case tt.want == "" && err != nil:
t.Fatalf("validateDocument: %v", err)
case tt.want != "" && (err == nil || !strings.Contains(err.Error(), tt.want)):
t.Fatalf("validateDocument error = %v, want %q", err, tt.want)
}
})
}
}
// stepsBeforeRetry is what a retry from the named step keeps: the steps
// recorded before it began, and the markers written before it was entered. It
// mirrors store.Retry.