feat(messaging): serve MessagingService.Deliver and deliver chat schedules through it
This commit is contained in:
22 files changed
+689
-46
No files matched your search
@@ -48,6 +48,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/extension"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/messagingrpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/taskactions"
|
||||
@@ -167,14 +168,14 @@ type boot struct {
|
||||
|
||||
chatTasks gateway.TaskCreator
|
||||
defaultChatIdentity string
|
||||
// messaging delivers outbound chat messages through the Messaging Service.
|
||||
messaging *messagingrpc.Client
|
||||
|
||||
startGateways []func()
|
||||
trees *worktree.Manager
|
||||
identityRunners []*daemon.IdentityRunner
|
||||
d *daemon.Daemon
|
||||
// schedulingEngine is the cron/scheduling ticker engine (setupScheduling).
|
||||
// Nil when no chat task creator is configured, in which case startServices
|
||||
// leaves it unstarted rather than running with no reachable job kind.
|
||||
schedulingEngine *scheduling.Engine
|
||||
|
||||
// kindWorkflows/labelWorkflows are the resolved kind/label -> workflow
|
||||
@@ -469,6 +470,12 @@ func (b *boot) setupGatewayClient() error {
|
||||
}
|
||||
b.addCleanup(cleanup)
|
||||
b.chat = &webui.ChatService{Contract: contract}
|
||||
messaging, closeMessaging, err := composeMessaging(b.cfg.Services, b.secrets)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b.addCleanup(closeMessaging)
|
||||
b.messaging = messaging
|
||||
b.setupReadinessProbes()
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/messagingrpc"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
@@ -28,3 +29,13 @@ func composeChatContract(services config.Services, secrets *secret.Registry, opt
|
||||
}
|
||||
return client, cleanup, nil
|
||||
}
|
||||
|
||||
// composeMessaging builds the Messaging Service client. The connection is
|
||||
// lazy, so an absent Messaging Service fails each delivery, not the daemon.
|
||||
func composeMessaging(services config.Services, secrets *secret.Registry) (*messagingrpc.Client, func(), error) {
|
||||
target, err := services.RequireTarget(config.ServiceNameMessaging)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return messagingrpc.Dial(target, services.ResolvedToken(config.ServiceNameMessaging, secrets.Getenv))
|
||||
}
|
||||
@@ -51,30 +51,32 @@ func schedulingConfig(input configuration.SchedulingInput, bus *events.Bus) (sch
|
||||
// subsystem, and the corresponding Stop is registered here via addCleanup so
|
||||
// shutdown ordering matches every other daemon-lifecycle subsystem.
|
||||
//
|
||||
// Only the "workflow" kind is wired: it rides gateway.TaskCreator, the same
|
||||
// non-forge-backed task creation path chat's /spawn uses, which is the one
|
||||
// production capability here that does not require inventing a channel
|
||||
// courier or a synthetic forge owner/repo. A deployment with no chat task
|
||||
// creator configured (no [chat] identity profiles) leaves the engine
|
||||
// unstarted rather than running with no reachable job kind.
|
||||
// The "chat" kind delivers through the Messaging Service. The "workflow" kind
|
||||
// rides gateway.TaskCreator, the path chat's /spawn uses, so it is wired only
|
||||
// when [chat] identity profiles configure one.
|
||||
func (b *boot) setupScheduling() error {
|
||||
cfg, err := schedulingConfig(b.doc.Scheduling, b.bus)
|
||||
if err != nil {
|
||||
return fmt.Errorf("scheduling: %w", err)
|
||||
}
|
||||
|
||||
if b.chatTasks == nil {
|
||||
b.log.Warn("scheduling: no chat task creator configured; ticker engine not started")
|
||||
return nil
|
||||
}
|
||||
|
||||
store := scheduleResourceStore{client: b.controlPlane}
|
||||
|
||||
workflowRunner, err := crondelivery.NewWorkflowTask(store, spawnTaskSubmitter{creator: b.chatTasks, identity: b.defaultChatIdentity})
|
||||
chatRunner, err := crondelivery.NewChatCourier(store, func(ctx context.Context, target scheduling.Target, text string) error {
|
||||
return b.messaging.Deliver(ctx, target.Channel, target.ChatID, text)
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("scheduling: build workflow runner: %w", err)
|
||||
return fmt.Errorf("scheduling: build chat runner: %w", err)
|
||||
}
|
||||
router, err := crondelivery.NewRouter(store, map[string]scheduling.Runner{scheduling.KindWorkflow: workflowRunner}, cfg.Events)
|
||||
runners := map[string]scheduling.Runner{scheduling.KindChat: chatRunner}
|
||||
if b.chatTasks != nil {
|
||||
workflowRunner, err := crondelivery.NewWorkflowTask(store, spawnTaskSubmitter{creator: b.chatTasks, identity: b.defaultChatIdentity})
|
||||
if err != nil {
|
||||
return fmt.Errorf("scheduling: build workflow runner: %w", err)
|
||||
}
|
||||
runners[scheduling.KindWorkflow] = workflowRunner
|
||||
}
|
||||
router, err := crondelivery.NewRouter(store, runners, cfg.Events)
|
||||
if err != nil {
|
||||
return fmt.Errorf("scheduling: build router: %w", err)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package archiemessaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"slices"
|
||||
@@ -17,6 +18,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/health"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/messagingrpc"
|
||||
"github.com/samcharles93/archie-core/internal/sdnotify"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
@@ -263,3 +265,22 @@ func (s *Service) Stop() {
|
||||
}
|
||||
s.log.Info("messaging service stopped")
|
||||
}
|
||||
|
||||
// Deliver sends text to chatID through the named running channel.
|
||||
func (s *Service) Deliver(ctx context.Context, channel, chatID, text string) error {
|
||||
for _, instance := range s.channels {
|
||||
if instance.name != channel {
|
||||
continue
|
||||
}
|
||||
sender, ok := instance.current().(channels.Sender)
|
||||
if !ok {
|
||||
return fmt.Errorf("%w: channel %q cannot send", messagingrpc.ErrUnavailable, channel)
|
||||
}
|
||||
err := sender.Send(ctx, chatID, text)
|
||||
if errors.Is(err, channels.ErrNotRunning) {
|
||||
return fmt.Errorf("%w: channel %q is not running", messagingrpc.ErrUnavailable, channel)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("%w: no channel %q", messagingrpc.ErrUnavailable, channel)
|
||||
}
|
||||
@@ -30,6 +30,7 @@ type ResolvedConfig struct {
|
||||
type projection struct {
|
||||
gateway ServiceTarget
|
||||
stateStore ServiceTarget
|
||||
messaging config.ServiceConnection
|
||||
telegram config.TelegramConfig
|
||||
workDir string
|
||||
botUser string
|
||||
@@ -87,6 +88,7 @@ func project(cfg config.Config) projection {
|
||||
Token: cfg.Services.Get(config.ServiceNameGateway).TargetToken,
|
||||
},
|
||||
stateStore: ServiceTarget{Target: cfg.Services.Get(config.ServiceNameState).Target, Token: cfg.Services.Get(config.ServiceNameState).TargetToken},
|
||||
messaging: cfg.Services.Get(config.ServiceNameMessaging),
|
||||
telegram: cfg.Chat.Telegram,
|
||||
workDir: cfg.WorkDir,
|
||||
botUser: cfg.BotUser,
|
||||
@@ -102,6 +104,9 @@ func withEnvTokens(o Options) Options {
|
||||
if o.StateStore.Token == "" {
|
||||
o.StateStore.Token = os.Getenv("STATE_STORE_TOKEN")
|
||||
}
|
||||
if o.Token == "" {
|
||||
o.Token = os.Getenv("MESSAGING_TOKEN")
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
@@ -118,6 +123,12 @@ func merge(o Options, p projection) Options {
|
||||
if o.StateStore.Token == "" {
|
||||
o.StateStore.Token = p.stateStore.Token
|
||||
}
|
||||
if o.Listen == "" {
|
||||
o.Listen = p.messaging.Listen
|
||||
}
|
||||
if o.Token == "" {
|
||||
o.Token = p.messaging.TargetToken
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
// Process defaults.
|
||||
const (
|
||||
defaultGatewayTarget = "127.0.0.1:8585"
|
||||
defaultListen = "127.0.0.1:8586"
|
||||
defaultDependencyTimeout = 5 * time.Second
|
||||
defaultShutdownTimeout = 5 * time.Second
|
||||
)
|
||||
@@ -29,8 +30,12 @@ type Options struct {
|
||||
Config string
|
||||
Overlay string
|
||||
|
||||
Gateway ServiceTarget
|
||||
StateStore ServiceTarget
|
||||
Gateway ServiceTarget
|
||||
StateStore ServiceTarget
|
||||
// Listen is where MessagingService is served; Token is the bearer token
|
||||
// its callers present on a non-loopback address.
|
||||
Listen string
|
||||
Token string
|
||||
DependencyTimeout time.Duration
|
||||
ShutdownTimeout time.Duration
|
||||
}
|
||||
@@ -39,6 +44,9 @@ func withDefaults(o Options) Options {
|
||||
if o.Gateway.Target == "" {
|
||||
o.Gateway.Target = defaultGatewayTarget
|
||||
}
|
||||
if o.Listen == "" {
|
||||
o.Listen = defaultListen
|
||||
}
|
||||
if o.DependencyTimeout <= 0 {
|
||||
o.DependencyTimeout = defaultDependencyTimeout
|
||||
}
|
||||
@@ -60,7 +68,7 @@ func (o Options) validate() error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return validateServiceTarget("messaging listen", ServiceTarget{Target: o.Listen, Token: o.Token})
|
||||
}
|
||||
|
||||
func validateServiceTarget(serviceName string, target ServiceTarget) error {
|
||||
|
||||
@@ -4,6 +4,9 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/servicekit"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
@@ -14,6 +17,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/extension"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/messagingrpc"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/secretengine"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
@@ -101,7 +105,28 @@ func Run(ctx context.Context, o Options) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return serve(ctx, cfg.Options, srv, log)
|
||||
}
|
||||
|
||||
// serve runs srv and serves MessagingService over it until ctx is cancelled.
|
||||
func serve(ctx context.Context, o Options, srv *Service, log *slog.Logger) error {
|
||||
opts, err := messagingrpc.ServerOptions(o.Listen, o.Token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", o.Listen)
|
||||
if err != nil {
|
||||
return fmt.Errorf("listen messaging (%s): %w", o.Listen, err)
|
||||
}
|
||||
server := grpc.NewServer(opts...)
|
||||
messagingrpc.RegisterServer(server, srv)
|
||||
go func() {
|
||||
if err := server.Serve(listener); err != nil {
|
||||
log.Error("messaging gRPC server stopped", "err", err)
|
||||
}
|
||||
}()
|
||||
defer server.GracefulStop()
|
||||
log.Info("messaging service listening", "listen", o.Listen)
|
||||
return srv.Start(ctx)
|
||||
}
|
||||
|
||||
|
||||
@@ -36,7 +36,13 @@ func validateSchedules(jobs []scheduling.JobSpec) error {
|
||||
return fmt.Errorf("duplicate schedule %q", job.ID)
|
||||
}
|
||||
seen[job.ID] = struct{}{}
|
||||
if job.Kind != scheduling.KindWorkflow {
|
||||
switch job.Kind {
|
||||
case scheduling.KindWorkflow:
|
||||
case scheduling.KindChat:
|
||||
if job.Target.Channel == "" || job.Target.ChatID == "" || strings.TrimSpace(job.Payload.Text) == "" {
|
||||
return fmt.Errorf("chat schedule %q needs a channel, chat ID and message", job.ID)
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("schedule %q has unsupported kind %q", job.ID, job.Kind)
|
||||
}
|
||||
if err := job.Schedule.Validate(); err != nil {
|
||||
|
||||
@@ -6,6 +6,7 @@ package channels
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
@@ -25,3 +26,12 @@ type Channel interface {
|
||||
// ValidateConfig checks that the provided configuration is valid for this channel.
|
||||
ValidateConfig(cfg map[string]any) error
|
||||
}
|
||||
|
||||
// Sender is a channel that can post a message unprompted. Channels that only
|
||||
// reply to inbound messages do not implement it.
|
||||
type Sender interface {
|
||||
Send(ctx context.Context, chatID, text string) error
|
||||
}
|
||||
|
||||
// ErrNotRunning is returned by Send while the channel is stopped.
|
||||
var ErrNotRunning = errors.New("channel is not running")
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -121,6 +122,9 @@ type Gateway struct {
|
||||
log *slog.Logger
|
||||
bot *bot.Bot
|
||||
running bool
|
||||
// outbound is the running bot as Send sees it: Send is called from the
|
||||
// Messaging Service's RPC goroutines, not the update loop that owns bot.
|
||||
outbound atomic.Pointer[bot.Bot]
|
||||
|
||||
// serverURL redirects the Bot API at a test server. Empty in production,
|
||||
// where the library's default endpoint is used. It exists so launch's
|
||||
@@ -313,6 +317,7 @@ func (g *Gateway) launch(ctx context.Context, client messaging.ChatContract, lif
|
||||
return nil, fmt.Errorf("create bot: %w", err)
|
||||
}
|
||||
g.bot = b
|
||||
g.outbound.Store(b)
|
||||
|
||||
g.registerCommandHandlers(b, client)
|
||||
|
||||
@@ -384,6 +389,7 @@ func (g *Gateway) Stop(ctx context.Context) error {
|
||||
}
|
||||
g.log.Info("stopping telegram gateway")
|
||||
g.running = false
|
||||
g.outbound.Store(nil)
|
||||
|
||||
g.abandonAllLive(ctx)
|
||||
|
||||
@@ -824,6 +830,25 @@ func (g *Gateway) sendMessage(ctx context.Context, b *bot.Bot, chatID int64, mes
|
||||
}
|
||||
}
|
||||
|
||||
// Send delivers text to chatID, split like a reply. It fails if the bot is not
|
||||
// running or any part is rejected.
|
||||
func (g *Gateway) Send(ctx context.Context, chatID, text string) error {
|
||||
b := g.outbound.Load()
|
||||
if b == nil {
|
||||
return channels.ErrNotRunning
|
||||
}
|
||||
id, err := strconv.ParseInt(chatID, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("telegram chat id %q: %w", chatID, err)
|
||||
}
|
||||
for _, part := range splitBlocks(markdownToBlocks(text), messageMaxLen) {
|
||||
if g.sendBlocks(ctx, b, id, 0, part, "deliver message failed") == 0 {
|
||||
return fmt.Errorf("telegram rejected a message to chat %d", id)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sendBlocks sends one rich message and returns its ID, or 0. A rejected rich
|
||||
// message is resent as plain text.
|
||||
func (g *Gateway) sendBlocks(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, blocks []models.InputRichBlock, errMsg string) int {
|
||||
|
||||
@@ -44,8 +44,9 @@ type ServiceSpec struct {
|
||||
// spelling a consumer looks up and the spelling that was registered are the
|
||||
// same token, not two string literals that a typo can separate.
|
||||
const (
|
||||
ServiceNameGateway = "gateway"
|
||||
ServiceNameState = "state"
|
||||
ServiceNameGateway = "gateway"
|
||||
ServiceNameState = "state"
|
||||
ServiceNameMessaging = "messaging"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -107,10 +108,11 @@ func RegisteredServices() []ServiceSpec {
|
||||
}
|
||||
|
||||
func init() {
|
||||
// The two services this repository ships. Everything that differs
|
||||
// The services this repository ships. Everything that differs
|
||||
// between them is an argument here, not a branch somewhere else: the
|
||||
// gateway's target is defaulted while the State Store's is supplied by
|
||||
// the operator, and each falls back to its own token variable.
|
||||
RegisterService(ServiceBoth, ServiceNameGateway, "127.0.0.1:8585", "127.0.0.1:8585", "GATEWAY_TOKEN")
|
||||
RegisterService(ServiceClient, ServiceNameState, "", "127.0.0.1:9090", "STATE_STORE_TOKEN")
|
||||
RegisterService(ServiceBoth, ServiceNameMessaging, "127.0.0.1:8586", "127.0.0.1:8586", "MESSAGING_TOKEN")
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.11
|
||||
// protoc (unknown)
|
||||
// source: messaging/v1/messaging.proto
|
||||
|
||||
package messagingv1
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
unsafe "unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type DeliverRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
// channel names the channel, such as "telegram".
|
||||
Channel string `protobuf:"bytes,1,opt,name=channel,proto3" json:"channel,omitempty"`
|
||||
// chat_id is the channel-native chat identifier.
|
||||
ChatId string `protobuf:"bytes,2,opt,name=chat_id,json=chatId,proto3" json:"chat_id,omitempty"`
|
||||
Text string `protobuf:"bytes,3,opt,name=text,proto3" json:"text,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *DeliverRequest) Reset() {
|
||||
*x = DeliverRequest{}
|
||||
mi := &file_messaging_v1_messaging_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *DeliverRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*DeliverRequest) ProtoMessage() {}
|
||||
|
||||
func (x *DeliverRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_messaging_v1_messaging_proto_msgTypes[0]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use DeliverRequest.ProtoReflect.Descriptor instead.
|
||||
func (*DeliverRequest) Descriptor() ([]byte, []int) {
|
||||
return file_messaging_v1_messaging_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *DeliverRequest) GetChannel() string {
|
||||
if x != nil {
|
||||
return x.Channel
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *DeliverRequest) GetChatId() string {
|
||||
if x != nil {
|
||||
return x.ChatId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *DeliverRequest) GetText() string {
|
||||
if x != nil {
|
||||
return x.Text
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type DeliverResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *DeliverResponse) Reset() {
|
||||
*x = DeliverResponse{}
|
||||
mi := &file_messaging_v1_messaging_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *DeliverResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*DeliverResponse) ProtoMessage() {}
|
||||
|
||||
func (x *DeliverResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_messaging_v1_messaging_proto_msgTypes[1]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use DeliverResponse.ProtoReflect.Descriptor instead.
|
||||
func (*DeliverResponse) Descriptor() ([]byte, []int) {
|
||||
return file_messaging_v1_messaging_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
var File_messaging_v1_messaging_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_messaging_v1_messaging_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"\x1cmessaging/v1/messaging.proto\x12\fmessaging.v1\"W\n" +
|
||||
"\x0eDeliverRequest\x12\x18\n" +
|
||||
"\achannel\x18\x01 \x01(\tR\achannel\x12\x17\n" +
|
||||
"\achat_id\x18\x02 \x01(\tR\x06chatId\x12\x12\n" +
|
||||
"\x04text\x18\x03 \x01(\tR\x04text\"\x11\n" +
|
||||
"\x0fDeliverResponse2Z\n" +
|
||||
"\x10MessagingService\x12F\n" +
|
||||
"\aDeliver\x12\x1c.messaging.v1.DeliverRequest\x1a\x1d.messaging.v1.DeliverResponseB\xc4\x01\n" +
|
||||
"\x10com.messaging.v1B\x0eMessagingProtoP\x01ZOgithub.com/samcharles93/archie-core/internal/contracts/messaging/v1;messagingv1\xa2\x02\x03MXX\xaa\x02\fMessaging.V1\xca\x02\fMessaging\\V1\xe2\x02\x18Messaging\\V1\\GPBMetadata\xea\x02\rMessaging::V1b\x06proto3"
|
||||
|
||||
var (
|
||||
file_messaging_v1_messaging_proto_rawDescOnce sync.Once
|
||||
file_messaging_v1_messaging_proto_rawDescData []byte
|
||||
)
|
||||
|
||||
func file_messaging_v1_messaging_proto_rawDescGZIP() []byte {
|
||||
file_messaging_v1_messaging_proto_rawDescOnce.Do(func() {
|
||||
file_messaging_v1_messaging_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_messaging_v1_messaging_proto_rawDesc), len(file_messaging_v1_messaging_proto_rawDesc)))
|
||||
})
|
||||
return file_messaging_v1_messaging_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_messaging_v1_messaging_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
|
||||
var file_messaging_v1_messaging_proto_goTypes = []any{
|
||||
(*DeliverRequest)(nil), // 0: messaging.v1.DeliverRequest
|
||||
(*DeliverResponse)(nil), // 1: messaging.v1.DeliverResponse
|
||||
}
|
||||
var file_messaging_v1_messaging_proto_depIdxs = []int32{
|
||||
0, // 0: messaging.v1.MessagingService.Deliver:input_type -> messaging.v1.DeliverRequest
|
||||
1, // 1: messaging.v1.MessagingService.Deliver:output_type -> messaging.v1.DeliverResponse
|
||||
1, // [1:2] is the sub-list for method output_type
|
||||
0, // [0:1] is the sub-list for method input_type
|
||||
0, // [0:0] is the sub-list for extension type_name
|
||||
0, // [0:0] is the sub-list for extension extendee
|
||||
0, // [0:0] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_messaging_v1_messaging_proto_init() }
|
||||
func file_messaging_v1_messaging_proto_init() {
|
||||
if File_messaging_v1_messaging_proto != nil {
|
||||
return
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_messaging_v1_messaging_proto_rawDesc), len(file_messaging_v1_messaging_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 2,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
GoTypes: file_messaging_v1_messaging_proto_goTypes,
|
||||
DependencyIndexes: file_messaging_v1_messaging_proto_depIdxs,
|
||||
MessageInfos: file_messaging_v1_messaging_proto_msgTypes,
|
||||
}.Build()
|
||||
File_messaging_v1_messaging_proto = out.File
|
||||
file_messaging_v1_messaging_proto_goTypes = nil
|
||||
file_messaging_v1_messaging_proto_depIdxs = nil
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.6.2
|
||||
// - protoc (unknown)
|
||||
// source: messaging/v1/messaging.proto
|
||||
|
||||
package messagingv1
|
||||
|
||||
import (
|
||||
context "context"
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
// Requires gRPC-Go v1.64.0 or later.
|
||||
const _ = grpc.SupportPackageIsVersion9
|
||||
|
||||
const (
|
||||
MessagingService_Deliver_FullMethodName = "/messaging.v1.MessagingService/Deliver"
|
||||
)
|
||||
|
||||
// MessagingServiceClient is the client API for MessagingService service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
//
|
||||
// MessagingService is the Messaging Service's contract: the process that holds
|
||||
// the chat channel transports. Other services send outbound messages through
|
||||
// it rather than holding channel credentials themselves.
|
||||
type MessagingServiceClient interface {
|
||||
// Deliver sends text to one chat on one channel. FAILED_PRECONDITION means
|
||||
// the channel is not running or cannot send; the caller may retry later.
|
||||
Deliver(ctx context.Context, in *DeliverRequest, opts ...grpc.CallOption) (*DeliverResponse, error)
|
||||
}
|
||||
|
||||
type messagingServiceClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewMessagingServiceClient(cc grpc.ClientConnInterface) MessagingServiceClient {
|
||||
return &messagingServiceClient{cc}
|
||||
}
|
||||
|
||||
func (c *messagingServiceClient) Deliver(ctx context.Context, in *DeliverRequest, opts ...grpc.CallOption) (*DeliverResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(DeliverResponse)
|
||||
err := c.cc.Invoke(ctx, MessagingService_Deliver_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// MessagingServiceServer is the server API for MessagingService service.
|
||||
// All implementations must embed UnimplementedMessagingServiceServer
|
||||
// for forward compatibility.
|
||||
//
|
||||
// MessagingService is the Messaging Service's contract: the process that holds
|
||||
// the chat channel transports. Other services send outbound messages through
|
||||
// it rather than holding channel credentials themselves.
|
||||
type MessagingServiceServer interface {
|
||||
// Deliver sends text to one chat on one channel. FAILED_PRECONDITION means
|
||||
// the channel is not running or cannot send; the caller may retry later.
|
||||
Deliver(context.Context, *DeliverRequest) (*DeliverResponse, error)
|
||||
mustEmbedUnimplementedMessagingServiceServer()
|
||||
}
|
||||
|
||||
// UnimplementedMessagingServiceServer must be embedded to have
|
||||
// forward compatible implementations.
|
||||
//
|
||||
// NOTE: this should be embedded by value instead of pointer to avoid a nil
|
||||
// pointer dereference when methods are called.
|
||||
type UnimplementedMessagingServiceServer struct{}
|
||||
|
||||
func (UnimplementedMessagingServiceServer) Deliver(context.Context, *DeliverRequest) (*DeliverResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method Deliver not implemented")
|
||||
}
|
||||
func (UnimplementedMessagingServiceServer) mustEmbedUnimplementedMessagingServiceServer() {}
|
||||
func (UnimplementedMessagingServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
// UnsafeMessagingServiceServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to MessagingServiceServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeMessagingServiceServer interface {
|
||||
mustEmbedUnimplementedMessagingServiceServer()
|
||||
}
|
||||
|
||||
func RegisterMessagingServiceServer(s grpc.ServiceRegistrar, srv MessagingServiceServer) {
|
||||
// If the following call panics, it indicates UnimplementedMessagingServiceServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
|
||||
t.testEmbeddedByValue()
|
||||
}
|
||||
s.RegisterService(&MessagingService_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _MessagingService_Deliver_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(DeliverRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(MessagingServiceServer).Deliver(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: MessagingService_Deliver_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(MessagingServiceServer).Deliver(ctx, req.(*DeliverRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// MessagingService_ServiceDesc is the grpc.ServiceDesc for MessagingService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var MessagingService_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "messaging.v1.MessagingService",
|
||||
HandlerType: (*MessagingServiceServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "Deliver",
|
||||
Handler: _MessagingService_Deliver_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "messaging/v1/messaging.proto",
|
||||
}
|
||||
@@ -67,9 +67,9 @@ type JobSpec struct {
|
||||
// Target identifies where the job's output goes. Empty Target is valid —
|
||||
// the delivery runner chooses a default.
|
||||
type Target struct {
|
||||
// ChatID is the chat channel id (Telegram chat id, email address,
|
||||
// webhook URL — depends on the channel). Empty defers to a default
|
||||
// chosen by the delivery runner.
|
||||
// Channel names the Messaging Service channel, such as "telegram".
|
||||
Channel string `json:"channel,omitempty"`
|
||||
// ChatID is the channel-native chat id.
|
||||
ChatID string `json:"chat_id,omitempty"`
|
||||
}
|
||||
|
||||
|
||||
@@ -34,8 +34,8 @@ type RouterStore interface {
|
||||
RunRecorder
|
||||
}
|
||||
|
||||
// Courier sends one chat message. It must honour ctx.
|
||||
type Courier func(ctx context.Context, chatID, text string) error
|
||||
// Courier sends one chat message to target. It must honour ctx.
|
||||
type Courier func(ctx context.Context, target scheduling.Target, text string) error
|
||||
|
||||
// TaskSubmitter submits one unit of work.
|
||||
type TaskSubmitter interface {
|
||||
|
||||
@@ -38,8 +38,8 @@ func (c *ChatCourier) Run(ctx context.Context, job scheduling.Job) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := c.courier(ctx, spec.Target.ChatID, spec.Payload.Text); err != nil {
|
||||
return fmt.Errorf("crondelivery: deliver job %q to %q: %w", job.ID, spec.Target.ChatID, err)
|
||||
if err := c.courier(ctx, spec.Target, spec.Payload.Text); err != nil {
|
||||
return fmt.Errorf("crondelivery: deliver job %q to %s:%s: %w", job.ID, spec.Target.Channel, spec.Target.ChatID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
// Package messagingrpc is the transport for messaging.v1.MessagingService:
|
||||
// the server the Messaging Service registers and the client other services
|
||||
// dial to deliver outbound chat messages.
|
||||
package messagingrpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/messaging/v1"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
|
||||
)
|
||||
|
||||
const tokenMetadataKey = "messaging-token"
|
||||
|
||||
// ErrUnavailable marks a delivery the channel could not make now: the channel
|
||||
// is unknown, stopped or cannot send. The caller may retry later.
|
||||
var ErrUnavailable = errors.New("messaging: channel unavailable")
|
||||
|
||||
// Deliverer sends text to one chat on a named channel.
|
||||
type Deliverer interface {
|
||||
Deliver(ctx context.Context, channel, chatID, text string) error
|
||||
}
|
||||
|
||||
type server struct {
|
||||
pb.UnimplementedMessagingServiceServer
|
||||
deliverer Deliverer
|
||||
}
|
||||
|
||||
// RegisterServer registers MessagingService over d.
|
||||
func RegisterServer(registrar grpc.ServiceRegistrar, d Deliverer) {
|
||||
pb.RegisterMessagingServiceServer(registrar, &server{deliverer: d})
|
||||
}
|
||||
|
||||
func (s *server) Deliver(ctx context.Context, req *pb.DeliverRequest) (*pb.DeliverResponse, error) {
|
||||
if req.GetChannel() == "" || req.GetChatId() == "" || req.GetText() == "" {
|
||||
return nil, status.Error(codes.InvalidArgument, "channel, chat_id and text are required")
|
||||
}
|
||||
err := s.deliverer.Deliver(ctx, req.GetChannel(), req.GetChatId(), req.GetText())
|
||||
switch {
|
||||
case err == nil:
|
||||
return &pb.DeliverResponse{}, nil
|
||||
case errors.Is(err, ErrUnavailable):
|
||||
return nil, status.Error(codes.FailedPrecondition, err.Error())
|
||||
default:
|
||||
return nil, status.Error(codes.Unavailable, err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// ServerOptions serves a loopback listen address without credentials and
|
||||
// requires token on any other, failing closed when it is empty.
|
||||
func ServerOptions(listen, token string) ([]grpc.ServerOption, error) {
|
||||
loopback, err := gatewayrpc.TargetIsLoopback(listen)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if loopback {
|
||||
return nil, nil
|
||||
}
|
||||
if token == "" {
|
||||
return nil, fmt.Errorf("messaging listen address %q is non-loopback and requires a bearer token", listen)
|
||||
}
|
||||
return []grpc.ServerOption{grpc.ChainUnaryInterceptor(requireToken(token))}, nil
|
||||
}
|
||||
|
||||
func requireToken(token string) grpc.UnaryServerInterceptor {
|
||||
return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
|
||||
values := metadata.ValueFromIncomingContext(ctx, tokenMetadataKey)
|
||||
if len(values) == 0 || subtle.ConstantTimeCompare([]byte(token), []byte(values[0])) != 1 {
|
||||
return nil, status.Error(codes.Unauthenticated, "missing or invalid messaging token")
|
||||
}
|
||||
return handler(ctx, req)
|
||||
}
|
||||
}
|
||||
|
||||
// Client delivers through a dialled MessagingService.
|
||||
type Client struct{ rpc pb.MessagingServiceClient }
|
||||
|
||||
// Dial returns a client for target. A non-loopback target requires token.
|
||||
func Dial(target, token string) (*Client, func(), error) {
|
||||
target = strings.TrimSpace(target)
|
||||
loopback, err := gatewayrpc.TargetIsLoopback(target)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("messaging target must be host:port: %w", err)
|
||||
}
|
||||
if !loopback && token == "" {
|
||||
return nil, nil, fmt.Errorf("messaging target %q is non-loopback and requires a bearer token ([services.messaging].target_token / MESSAGING_TOKEN)", target)
|
||||
}
|
||||
opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
|
||||
if token != "" {
|
||||
opts = append(opts, grpc.WithUnaryInterceptor(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...)
|
||||
}))
|
||||
}
|
||||
conn, err := grpc.NewClient(target, opts...)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("create messaging client: %w", err)
|
||||
}
|
||||
return &Client{rpc: pb.NewMessagingServiceClient(conn)}, func() { _ = conn.Close() }, nil
|
||||
}
|
||||
|
||||
// Deliver sends text to chatID on channel.
|
||||
func (c *Client) Deliver(ctx context.Context, channel, chatID, text string) error {
|
||||
_, err := c.rpc.Deliver(ctx, &pb.DeliverRequest{Channel: channel, ChatId: chatID, Text: text})
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package messagingrpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func TestRequireToken(t *testing.T) {
|
||||
ok := func(context.Context, any) (any, error) { return "served", nil }
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
md metadata.MD
|
||||
want codes.Code
|
||||
}{
|
||||
{"valid", metadata.Pairs(tokenMetadataKey, "secret"), codes.OK},
|
||||
{"wrong", metadata.Pairs(tokenMetadataKey, "secrex"), codes.Unauthenticated},
|
||||
{"missing", metadata.MD{}, codes.Unauthenticated},
|
||||
{"other service's key", metadata.Pairs("gateway-token", "secret"), codes.Unauthenticated},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ctx := metadata.NewIncomingContext(context.Background(), tc.md)
|
||||
_, err := requireToken("secret")(ctx, nil, &grpc.UnaryServerInfo{}, ok)
|
||||
if got := status.Code(err); got != tc.want {
|
||||
t.Fatalf("code = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
if _, err := ServerOptions("0.0.0.0:8586", ""); err == nil {
|
||||
t.Fatal("non-loopback listen with no token was accepted")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user