// Package messagerpc lets archie-agent run a message.send step over NATS // request/reply, so only archied reaches the Messaging Service. package messagerpc import ( "context" "encoding/json" "errors" "fmt" "log/slog" "strings" "time" "github.com/nats-io/nats.go" domainidentity "github.com/samcharles93/archie-core/internal/domain/identity" "github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/natsrpc" ) // SubjectFor returns the subject a task's message.send publishes to, keyed by // the identity's ID as forgerpc.SubjectFor is. func SubjectFor(identity string) string { return "archie.message." + string(domainidentity.StableID(identity)) + ".deliver" } func serverSubject(identity string) string { if identity == "*" { return "archie.message.*.deliver" } return SubjectFor(identity) } // DeliverRequest is one message, with the run credential of the task sending it. type DeliverRequest struct { Credential string Channel string ChatID string Text string } // Response is a bare success/error envelope. type Response struct { natsrpc.Envelope } // Runs resolves a run credential to the task it was issued for. type Runs interface { TaskForCredential(ctx context.Context, token string) (*workflow.Task, error) } // Server delivers authorised requests through Deliver. type Server struct { Runs Runs // Deliver sends through a channel the run's org owns. Deliver func(ctx context.Context, org, channel, chatID, text string) error Log *slog.Logger } // RegisterFor registers the handler under the subject scoped to identity; // "*" answers every identity. func (s *Server) RegisterFor(ctx context.Context, nc *nats.Conn, identity string) (func(), error) { return natsrpc.RegisterAll(ctx, nc, []natsrpc.Registration{{ Subject: serverSubject(identity), Handler: func(ctx context.Context, msg *nats.Msg) { scoped := identity if identity == "*" { scoped = strings.Split(msg.Subject, ".")[2] } s.handleDeliver(ctx, scoped, msg) }, }}) } func (s *Server) handleDeliver(ctx context.Context, identity string, msg *nats.Msg) { var req DeliverRequest if err := json.Unmarshal(msg.Data, &req); err != nil { s.respond(msg, fmt.Errorf("decode deliver request: %w", err)) return } task, err := s.authorize(ctx, identity, req.Credential) if err != nil { s.respond(msg, err) return } if s.Deliver == nil { s.respond(msg, errors.New("messaging service unavailable")) return } s.respond(msg, s.Deliver(ctx, task.OrgOrDefault(), req.Channel, req.ChatID, req.Text)) } // authorize admits a live, non-test run of this server's identity and returns // it. The run's org decides which channels it may send through; a package's // workflow has no accepted authority to message any. func (s *Server) authorize(ctx context.Context, identity, credential string) (*workflow.Task, error) { if s.Runs == nil || credential == "" { return nil, errors.New("message request needs a run credential") } task, err := s.Runs.TaskForCredential(ctx, credential) if err != nil { return nil, fmt.Errorf("message request credential is invalid: %w", err) } switch { case task.Identity != identity && domainidentity.StableID(task.Identity) != domainidentity.IdentityID(identity): return nil, errors.New("message request is outside its run's identity") case task.IsTestRun(): return nil, errors.New("a test run records deliveries instead of performing them") case workflow.PackageOf(task.WorkflowDefinitionYAML) != "": return nil, errors.New("a package's workflow may not send messages") } return task, nil } func (s *Server) respond(msg *nats.Msg, err error) { natsrpc.Respond(msg, s.Log, "messagerpc", Response{Envelope: natsrpc.NewEnvelope(err)}) } // Client sends message.send steps' text from archie-agent's process. type Client struct { Conn *nats.Conn // Timeout bounds each call when ctx has no deadline of its own. Timeout time.Duration Identity string Credential string } var _ workflow.Messenger = (*Client)(nil) // Deliver asks archied to send text to chatID on channel. func (c *Client) Deliver(ctx context.Context, channel, chatID, text string) error { req := DeliverRequest{Credential: c.Credential, Channel: channel, ChatID: chatID, Text: text} resp, err := natsrpc.Call[Response](ctx, &natsrpc.Client{Conn: c.Conn, Timeout: c.Timeout}, SubjectFor(c.Identity), req) if err != nil { return err } return resp.Err() }