// 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/org" "github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/natsrpc" ) // SubjectDeliver is the root subject a task's message.send publishes to. const SubjectDeliver = "archie.message.deliver" // SubjectFor returns SubjectDeliver scoped to identity, or the root subject // when identity is empty. Keyed by the identity's ID, as forgerpc.SubjectFor is. func SubjectFor(identity string) string { if identity == "" { return SubjectDeliver } 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 authorized requests through Deliver. type Server struct { Runs Runs Deliver func(ctx context.Context, 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(nc *nats.Conn, identity string) (func(), error) { return natsrpc.RegisterAll(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 } if err := s.authorize(ctx, identity, req.Credential); 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, req.Channel, req.ChatID, req.Text)) } // authorize admits a live, non-test run of this server's identity in the // system org. Channels are instance-owned, and a package's workflow has no // accepted authority to message them. func (s *Server) authorize(ctx context.Context, identity, credential string) error { if s.Runs == nil || credential == "" { return errors.New("message request needs a run credential") } task, err := s.Runs.TaskForCredential(ctx, credential) if err != nil { return fmt.Errorf("message request credential is invalid: %w", err) } switch { case identity != "" && task.Identity != identity && domainidentity.StableID(task.Identity) != domainidentity.IdentityID(identity): return errors.New("message request is outside its run's identity") case task.IsTestRun(): return errors.New("a test run records deliveries instead of performing them") case task.OrgOrDefault() != string(org.DefaultOrgID): return errors.New("messaging channels belong to the instance; only system organisation workflows may send") case workflow.PackageOf(task.WorkflowDefinitionYAML) != "": return errors.New("a package's workflow may not send messages") } return 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() }