feat(messaging): run a channel per organisation and deliver only through the owner's

This commit is contained in:
sam committed 2026-10-27 10:38:00 +11:00
1 parent 3ea929cbdc
commit 4f2d0e964a
37 files changed
+1108 -277

No files matched your search

+2 -2
View File
@@ -550,11 +550,11 @@ func (b *boot) registerNATSRPC() error {
return daemon.RepositoryAccess{}, errors.New("repository connections starting")
}
return b.d.Repository(ctx, t, op)
}, func(ctx context.Context, channel, chatID, text string) error {
}, func(ctx context.Context, org, channel, chatID, text string) error {
if b.messaging == nil {
return errors.New("messaging service not configured")
}
return b.messaging.Deliver(ctx, channel, chatID, text)
return b.messaging.Deliver(ctx, org, channel, chatID, text)
}, b.stateStoreGrants.Client, installedAuthorities{b.stateStoreGrants.Client}, log)
if err != nil {
log.Error("task RPC server registration failed", "err", err)
+1 -1
View File
@@ -349,7 +349,7 @@ func subscribeAgentEvents(nc *natsio.Conn, bus *events.Bus, log *slog.Logger) (u
// registerTaskRPCServers routes each request through the current task binding.
// Wildcard subjects serve identities created after daemon startup; credentials
// and repository bounds are checked before the connection is resolved.
func registerTaskRPCServers(nc *natsio.Conn, resolve func(context.Context, *workflow.Task, string) (daemon.RepositoryAccess, error), deliver func(ctx context.Context, channel, chatID, text string) error, runs worktreerpc.Runs, authorities forgerpc.Authorities, log *slog.Logger) (func(), error) {
func registerTaskRPCServers(nc *natsio.Conn, resolve func(context.Context, *workflow.Task, string) (daemon.RepositoryAccess, error), deliver func(ctx context.Context, org, channel, chatID, text string) error, runs worktreerpc.Runs, authorities forgerpc.Authorities, log *slog.Logger) (func(), error) {
var unsubs []func()
unsubscribe := func() {
for _, stop := range unsubs {
+5 -5
View File
@@ -18,7 +18,7 @@ import (
const outcomePostInterval = 15 * time.Second
type outcomeDeliverer func(ctx context.Context, origin, text string) error
type outcomeDeliverer func(ctx context.Context, org, origin, text string) error
// conversationPoster appends a message to a Gateway conversation.
type conversationPoster interface {
@@ -27,21 +27,21 @@ type conversationPoster interface {
// channelDeliverer sends text to a Messaging Service channel.
type channelDeliverer interface {
Deliver(ctx context.Context, channel, chatID, text string) error
Deliver(ctx context.Context, org, channel, chatID, text string) error
}
// deliverOutcome sends a dashboard conversation's outcome into its Gateway
// session, where the dashboard reads it, and every other channel's through
// the Messaging Service.
func deliverOutcome(chats conversationPoster, channels channelDeliverer) outcomeDeliverer {
return func(ctx context.Context, origin, text string) error {
return func(ctx context.Context, org, origin, text string) error {
channel, conversation, _ := strings.Cut(origin, ":")
if channel == "web" {
channelID, threadID, _ := strings.Cut(conversation, "/")
return chats.PostToConversation(ctx, channel, messaging.ConversationID{ChannelID: channelID, ThreadID: threadID}, text)
}
chatID, _, _ := strings.Cut(conversation, "/")
return channels.Deliver(ctx, channel, chatID, text)
return channels.Deliver(ctx, org, channel, chatID, text)
}
}
@@ -73,7 +73,7 @@ func postPendingOutcomes(ctx context.Context, tasks storecontract.OutcomePoster,
// posted keeps it from being retried forever.
delivered := false
if validOrigin(t.Origin) {
err := deliver(ctx, t.Origin, outcomeText(t))
err := deliver(ctx, t.OrgOrDefault(), t.Origin, outcomeText(t))
delivered = err == nil
switch {
case status.Code(err) == codes.NotFound:
+1 -1
View File
@@ -68,7 +68,7 @@ func TestPostPendingOutcomes(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
store := &outcomeStore{}
deliver := func(context.Context, string, string) error { return tt.err }
deliver := func(context.Context, string, string, string) error { return tt.err }
postPendingOutcomes(context.Background(), store, deliver, func(int64) {}, slog.New(slog.DiscardHandler))
if got := len(store.posted) == 1; got != tt.posted {
t.Fatalf("posted = %v, want %v", got, tt.posted)
@@ -49,7 +49,7 @@ func channelReloadable(ch channels.Channel) bool {
// ReloadChannel asks one channel to reload its configuration, refusing
// channels that cannot.
func (s *Service) ReloadChannel(_ context.Context, id string) error {
for _, instance := range s.channels {
for _, instance := range s.instances() {
if instance.name != id {
continue
}
+44 -13
View File
@@ -49,6 +49,8 @@ type deps struct {
// AppliedVersion is the channel-settings version already running when the
// service starts, so the first reconcile tick does not re-apply it.
AppliedVersion int64
// OrgChannels enables a channel per org. Nil runs the instance's alone.
OrgChannels *orgChannelDeps
// ReconcileInterval overrides applystatus.RestampInterval, so a test can
// drive the loop without waiting 30 seconds.
ReconcileInterval time.Duration
@@ -57,8 +59,18 @@ type deps struct {
// channelInstance is one composed channel and what is needed to restart it.
// mu guards every field below.
type channelInstance struct {
name string
name string
// kind is the channel name a delivery or chat addresses, and owner the org
// whose channel it is. The instance's built-in and extension channels belong
// to the system org.
kind string
owner string
rebuild func(ResolvedConfig) (channels.Channel, error)
// chat, when set, is the contract this channel speaks to the Gateway
// through; an org's channel acts as its agent. Nil uses the service's.
chat messaging.ChatContract
// plan is what an org's channel was built from.
plan *orgChannelPlan
mu sync.Mutex
channel channels.Channel
@@ -90,12 +102,16 @@ type Service struct {
statusWriter storecontract.ChannelStatusStore
// publish coalesces a burst of transitions into one write: a reader only ever
// wants the latest state of every channel.
publish chan struct{}
cfg ResolvedConfig
secrets *secret.Registry
log *slog.Logger
chat messaging.ChatContract
publish chan struct{}
cfg ResolvedConfig
secrets *secret.Registry
log *slog.Logger
chat messaging.ChatContract
// chMu guards channels, which grows as orgs gain channels.
chMu sync.RWMutex
channels []*channelInstance
// orgs enables a channel per org. Nil runs the instance's alone.
orgs *orgChannelDeps
// runningSignal carries a channel's name each time it reports Running, so
// startup can announce readiness only once every channel has bound.
runningSignal chan string
@@ -133,6 +149,7 @@ func compose(ctx context.Context, d deps) (*Service, error) {
chat: d.Chat,
settingsSource: d.SettingsSource,
reporter: d.ApplyReporter,
orgs: d.OrgChannels,
reconcileInterval: d.ReconcileInterval,
}
srv.appliedVersion.Store(d.AppliedVersion)
@@ -177,6 +194,13 @@ func composeChannels(ctx context.Context, d deps) ([]*channelInstance, error) {
}
for _, instance := range instances {
instance.notify = make(chan struct{}, 1)
// The instance's own channels are the system org's.
if instance.kind == "" {
instance.kind = instance.name
}
if instance.owner == "" {
instance.owner = storecontract.DefaultOrgID
}
}
return instances, nil
}
@@ -202,7 +226,7 @@ func composeTelegram(ctx context.Context, d deps) (*channelInstance, error) {
if err != nil {
return nil, err
}
return &channelInstance{name: "telegram", channel: ch, rebuild: build}, nil
return &channelInstance{name: "telegram", kind: "telegram", owner: storecontract.DefaultOrgID, channel: ch, rebuild: build}, nil
}
// telegramValidateConfigMap builds the map Gateway.ValidateConfig expects
@@ -227,7 +251,7 @@ func (s *Service) Start(ctx context.Context) error {
s.stop = cancel
s.mu.Unlock()
s.log.InfoContext(ctx, "messaging service started", "gateway_target", s.cfg.Options.Gateway.Target, "channels", len(s.channels))
s.log.InfoContext(ctx, "messaging service started", "gateway_target", s.cfg.Options.Gateway.Target, "channels", len(s.instances()))
if s.statusWriter != nil {
go s.publishLoop(ctx)
@@ -239,7 +263,7 @@ func (s *Service) Start(ctx context.Context) error {
go s.reconcileLoop(ctx)
}
for _, ch := range s.channels {
for _, ch := range s.instances() {
c := ch
c.mu.Lock()
c.supervised = true
@@ -249,6 +273,9 @@ func (s *Service) Start(ctx context.Context) error {
}
s.announceReady(ctx, s.awaitedChannels())
if s.orgs != nil {
go s.orgChannelLoop(ctx)
}
<-ctx.Done()
@@ -280,10 +307,14 @@ 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 {
// Deliver sends text to chatID through org's running channel of that name. A
// channel is its owner's alone: another org's channel is reported as absent.
func (s *Service) Deliver(ctx context.Context, owner, channel, chatID, text string) error {
if owner == "" {
owner = storecontract.DefaultOrgID
}
for _, instance := range s.instances() {
if instance.kind != channel || instance.owner != owner {
continue
}
sender, ok := instance.current().(channels.Sender)
@@ -0,0 +1,310 @@
package archiemessaging
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"time"
"github.com/samcharles93/archie-core/internal/channels"
"github.com/samcharles93/archie-core/internal/channels/telegram"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
"github.com/samcharles93/archie-core/internal/secret"
"github.com/samcharles93/archie-core/internal/taskstate"
)
// telegramCredential is the credential binding service an org's Telegram bot
// token is bound under.
const telegramCredential = "telegram"
// credentialBindingsKind is the control-plane resource holding the bindings.
const credentialBindingsKind = "credential-bindings"
// orgChannelSource is where the Messaging Service learns which orgs run a
// channel and how they are bound. *controlplanerpc.Client satisfies the first
// two; the principals come from the State Store's access contract.
type orgChannelSource interface {
ChannelOrgs(ctx context.Context) ([]controlplanerpc.OrgChannel, error)
Query(ctx context.Context, kind string, decode func([]byte) error) (int64, bool, error)
}
// orgChannelDeps is everything an org's channels need beyond the instance's.
type orgChannelDeps struct {
Source orgChannelSource
Principals access.PrincipalSource
}
// orgChannelPlan is one org's channel as its settings, binding and agent
// currently resolve.
type orgChannelPlan struct {
org string
token string
allowed []int64
show bool
agent access.Principal
}
// same reports whether next needs no rebuild of the running channel.
func (p orgChannelPlan) same(next orgChannelPlan) bool {
return p.token == next.token && slices.Equal(p.allowed, next.allowed) && p.agent.IdentityID == next.agent.IdentityID
}
// orgChannelLoop keeps one channel per org that has settings, a bound bot token
// and an agent of its own, until ctx ends.
func (s *Service) orgChannelLoop(ctx context.Context) {
ticker := time.NewTicker(s.reconcileInterval)
defer ticker.Stop()
for {
if err := s.syncOrgChannels(ctx); err != nil {
s.log.WarnContext(ctx, "org channels not synced", "err", err)
}
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}
// syncOrgChannels builds, replaces or stops each org's channel to match what
// the orgs currently hold. A channel that no longer resolves is stopped: an org
// whose binding or agent went away must not keep a bot running.
func (s *Service) syncOrgChannels(ctx context.Context) error {
orgs, err := s.orgs.Source.ChannelOrgs(ctx)
if err != nil {
return err
}
bindings, err := s.telegramBindings(ctx)
if err != nil {
return err
}
wanted := map[string]orgChannelPlan{}
for _, entry := range orgs {
plan, err := s.planOrgChannel(ctx, entry, bindings[entry.Org])
if err != nil {
s.log.WarnContext(ctx, "org channel not run", "org", entry.Org, "reason", err)
continue
}
wanted[entry.Org] = plan
}
for owner, plan := range wanted {
s.applyOrgChannel(ctx, owner, plan)
}
for _, instance := range s.instances() {
if _, still := wanted[instance.owner]; instance.owner != storecontract.DefaultOrgID && !still {
if err := s.setChannelState(instance, nil); err != nil {
s.log.WarnContext(ctx, "org channel not stopped", "org", instance.owner, "err", err)
}
s.status.Declare(instance.name, false, false)
}
}
s.signalPublish()
return nil
}
// planOrgChannel resolves one org's settings to a channel it may run. The
// agent must belong to the org: the settings are the org's to write, so the
// identity they name is checked here rather than trusted.
func (s *Service) planOrgChannel(ctx context.Context, entry controlplanerpc.OrgChannel, binding secret.SecretRef) (orgChannelPlan, error) {
settings := entry.Settings
switch {
case settings.Agent == "":
return orgChannelPlan{}, errors.New("no agent named")
case len(settings.Telegram.AllowedUserIDs) == 0:
return orgChannelPlan{}, errors.New("no allowed telegram users")
case binding == (secret.SecretRef{}):
return orgChannelPlan{}, fmt.Errorf("no credential binding %q", telegramCredential)
}
principal, err := s.orgs.Principals.PrincipalFor(ctx, identity.IdentityID(settings.Agent))
if err != nil {
return orgChannelPlan{}, fmt.Errorf("resolve agent: %w", err)
}
if string(principal.Org) != entry.Org || !principal.Kind.Agent() {
return orgChannelPlan{}, errors.New("agent is not an agent of this org")
}
token, err := s.secrets.Resolve(binding)
if err != nil {
return orgChannelPlan{}, fmt.Errorf("resolve token: %w", err)
}
if token == "" {
return orgChannelPlan{}, errors.New("token resolved empty")
}
return orgChannelPlan{org: entry.Org, token: token, allowed: settings.Telegram.AllowedUserIDs, show: settings.ShowToolCalls, agent: principal}, nil
}
// telegramBindings maps each org to the secret its Telegram bot token is bound
// to. Bindings are the instance's to grant, so they are read from the system
// org's document.
func (s *Service) telegramBindings(ctx context.Context) (map[string]secret.SecretRef, error) {
var documents []struct {
Service string `json:"service"`
Org string `json:"org"`
Secret struct {
Engine string `json:"engine"`
Key string `json:"key"`
} `json:"secret"`
}
if _, _, err := s.orgs.Source.Query(ctx, credentialBindingsKind, func(value []byte) error { return json.Unmarshal(value, &documents) }); err != nil {
return nil, err
}
out := map[string]secret.SecretRef{}
for _, document := range documents {
if document.Service == telegramCredential {
out[document.Org] = secret.SecretRef{Engine: document.Secret.Engine, Key: document.Secret.Key}
}
}
return out, nil
}
// applyOrgChannel starts owner's channel, or replaces it when its plan changed.
func (s *Service) applyOrgChannel(ctx context.Context, owner string, plan orgChannelPlan) {
if instance := s.orgInstance(owner); instance != nil {
s.applyExistingOrgChannel(ctx, instance, plan)
return
}
instance := &channelInstance{
name: owner + "/" + telegramCredential, kind: telegramCredential, owner: owner,
chat: actingChat{ChatContract: s.chat, as: plan.agent}, plan: &plan,
notify: make(chan struct{}, 1),
}
instance.channel = s.buildOrgTelegram(plan)
s.addChannel(ctx, instance)
}
func (s *Service) applyExistingOrgChannel(ctx context.Context, instance *channelInstance, plan orgChannelPlan) {
previous := instance.currentPlan()
instance.mu.Lock()
running := instance.channel != nil
instance.mu.Unlock()
if running && previous.same(plan) {
if previous.show != plan.show {
s.setOrgShowToolCalls(instance, plan.show)
instance.setPlan(plan, s.chat)
}
return
}
instance.setPlan(plan, s.chat)
if err := s.setChannelState(instance, s.buildOrgTelegram(plan)); err != nil {
s.log.WarnContext(ctx, "org channel not restarted", "org", plan.org, "err", err)
return
}
s.status.Declare(instance.name, true, false)
}
func (s *Service) setOrgShowToolCalls(instance *channelInstance, show bool) {
if g, ok := instance.current().(*telegram.Gateway); ok {
g.SetShowToolCalls(show)
}
}
// buildOrgTelegram builds an org's bot. It carries none of the instance
// operator's seams: no settings command, update service or version report, so
// an org's chat users reach nothing but chat.
func (s *Service) buildOrgTelegram(plan orgChannelPlan) channels.Channel {
tg := telegram.New(plan.token, plan.allowed, s.log.With("org", plan.org))
tg.SetShowToolCalls(plan.show)
return tg
}
func (c *channelInstance) currentPlan() orgChannelPlan {
c.mu.Lock()
defer c.mu.Unlock()
if c.plan == nil {
return orgChannelPlan{}
}
return *c.plan
}
// setPlan records the plan the instance runs and the chat it speaks through.
func (c *channelInstance) setPlan(plan orgChannelPlan, gateway messaging.ChatContract) {
c.mu.Lock()
defer c.mu.Unlock()
c.plan = &plan
c.chat = actingChat{ChatContract: gateway, as: plan.agent}
}
func (s *Service) orgInstance(owner string) *channelInstance {
for _, instance := range s.instances() {
if instance.owner == owner && instance.kind == telegramCredential {
return instance
}
}
return nil
}
// addChannel registers a channel composed after startup and supervises it.
func (s *Service) addChannel(ctx context.Context, instance *channelInstance) {
s.chMu.Lock()
s.channels = append(s.channels, instance)
s.chMu.Unlock()
s.status.Add(instance.name, instance.name, instance.current() != nil)
instance.mu.Lock()
instance.supervised = true
instance.mu.Unlock()
s.wg.Add(1)
go s.runChannel(ctx, instance)
}
// instances returns the composed channels, including those added since start.
func (s *Service) instances() []*channelInstance {
s.chMu.RLock()
defer s.chMu.RUnlock()
return slices.Clone(s.channels)
}
// actingChat speaks to the Gateway as an org's agent, so every call lands in
// that org. Every method of the contract is wrapped: one left bare would act
// for no one, which the Gateway reads as the system org.
type actingChat struct {
messaging.ChatContract
as access.Principal
}
func (a actingChat) act(ctx context.Context) context.Context { return access.WithPrincipal(ctx, a.as) }
func (a actingChat) Snapshot(ctx context.Context) (messaging.ChatSnapshot, error) {
return a.ChatContract.Snapshot(a.act(ctx))
}
func (a actingChat) GetSession(ctx context.Context, id string) (messaging.SessionContext, bool, error) {
return a.ChatContract.GetSession(a.act(ctx), id)
}
func (a actingChat) RecentMessages(ctx context.Context, id string, limit int) ([]messaging.Message, error) {
return a.ChatContract.RecentMessages(a.act(ctx), id, limit)
}
func (a actingChat) RecentTurns(ctx context.Context, id string, limit int) ([]messaging.TurnRecord, error) {
return a.ChatContract.RecentTurns(a.act(ctx), id, limit)
}
func (a actingChat) Route(ctx context.Context, in messaging.Inbound) (messaging.ChatReply, error) {
return a.ChatContract.Route(a.act(ctx), in)
}
func (a actingChat) Stream(ctx context.Context, in messaging.Inbound) (<-chan messaging.ChatEvent, error) {
return a.ChatContract.Stream(a.act(ctx), in)
}
func (a actingChat) Cancel(ctx context.Context, id string) (messaging.ChatCancellation, error) {
return a.ChatContract.Cancel(a.act(ctx), id)
}
func (a actingChat) StopTasks(ctx context.Context, origin string, taskID int64) ([]int64, error) {
return a.ChatContract.StopTasks(a.act(ctx), origin, taskID)
}
func (a actingChat) ApplyTaskAction(ctx context.Context, origin string, taskID int64, action taskstate.Action, payload taskactions.ActionPayload) (messaging.TaskActionResult, error) {
return a.ChatContract.ApplyTaskAction(a.act(ctx), origin, taskID, action, payload)
}
func (a actingChat) ApplyOperatorTaskAction(ctx context.Context, actor taskactions.Actor, taskID int64, action taskstate.Action, payload taskactions.ActionPayload) (messaging.TaskActionResult, error) {
return a.ChatContract.ApplyOperatorTaskAction(a.act(ctx), actor, taskID, action, payload)
}
@@ -0,0 +1,82 @@
package archiemessaging
import (
"context"
"errors"
"testing"
"github.com/samcharles93/archie-core/internal/channels"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/infrastructure/messagingrpc"
)
// sendingChannel records what it was asked to send.
type sendingChannel struct {
fakeChannel
sent []string
}
func (c *sendingChannel) Send(_ context.Context, chatID, text string) error {
c.sent = append(c.sent, chatID+":"+text)
return nil
}
var _ channels.Sender = (*sendingChannel)(nil)
func TestDeliverReachesOnlyTheOwnersChannel(t *testing.T) {
instance, acme := &sendingChannel{}, &sendingChannel{}
srv := &Service{channels: []*channelInstance{
{name: "telegram", kind: "telegram", owner: storecontract.DefaultOrgID, channel: instance},
{name: "acme/telegram", kind: "telegram", owner: "acme", channel: acme},
}}
tests := []struct {
name, org, channel string
want *sendingChannel
wantErr error
}{
{"the system org sends through the instance channel", storecontract.DefaultOrgID, "telegram", instance, nil},
{"an empty org is the system org", "", "telegram", instance, nil},
{"an org sends through its own channel", "acme", "telegram", acme, nil},
{"an org with no channel finds none", "beta", "telegram", nil, messagingrpc.ErrNoChannel},
{"an org cannot name another org's channel", "acme", "slack", nil, messagingrpc.ErrNoChannel},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
instance.sent, acme.sent = nil, nil
err := srv.Deliver(t.Context(), tt.org, tt.channel, "1", "hi")
if !errors.Is(err, tt.wantErr) {
t.Fatalf("err = %v, want %v", err, tt.wantErr)
}
for _, ch := range []*sendingChannel{instance, acme} {
if got := len(ch.sent) == 1; got != (ch == tt.want) {
t.Fatalf("channel %p sent %v, want delivery to %p only", ch, ch.sent, tt.want)
}
}
})
}
}
// recordingChat remembers the principal each call carried.
type recordingChat struct {
messaging.ChatContract
seen []access.Principal
}
func (c *recordingChat) Snapshot(ctx context.Context) (messaging.ChatSnapshot, error) {
p, _ := access.PrincipalFromContext(ctx)
c.seen = append(c.seen, p)
return messaging.ChatSnapshot{}, nil
}
func TestActingChatCarriesTheOrgsAgent(t *testing.T) {
inner := &recordingChat{}
chat := actingChat{ChatContract: inner, as: access.Principal{IdentityID: "agent-acme", Org: "acme"}}
if _, err := chat.Snapshot(t.Context()); err != nil {
t.Fatal(err)
}
if len(inner.seen) != 1 || inner.seen[0].Org != "acme" || inner.seen[0].IdentityID != "agent-acme" {
t.Fatalf("call carried %+v, want the acme agent", inner.seen)
}
}
+1 -1
View File
@@ -40,7 +40,7 @@ func (s *Service) signalRunning(id string) {
// channel has nothing to run and is not waited for.
func (s *Service) awaitedChannels() map[string]bool {
awaited := map[string]bool{}
for _, c := range s.channels {
for _, c := range s.instances() {
c.mu.Lock()
if c.channel != nil {
awaited[c.name] = true
+1 -1
View File
@@ -139,7 +139,7 @@ func (s *Service) applyChannelEnablement(current, next ResolvedConfig) []string
// applyShowToolCalls updates the running Telegram gateways in place. Nothing
// else consumes the setting, and it is read per reply, so it needs no restart.
func (s *Service) applyShowToolCalls(show bool) {
for _, c := range s.channels {
for _, c := range s.instances() {
if g, ok := c.current().(*telegram.Gateway); ok {
g.SetShowToolCalls(show)
}
+3 -1
View File
@@ -69,6 +69,7 @@ func Run(ctx context.Context, o Options) error {
var settingsSource chatSettingsSource
var applyReporter *applystatus.Reporter
var appliedVersion int64
var orgChannels *orgChannelDeps
var updates *releaseupdate.Service
var extensionChannels []*channelInstance
if cfg.Options.StateStore.Target != "" {
@@ -98,7 +99,7 @@ func Run(ctx context.Context, o Options) error {
extensionChannels = openExtensionChannels(ctx, extensions, secrets, log)
settings = messaging.NewSettingsCommand(controlplanerpc.NewSettingsClient(stateStore.ControlPlane())).WithIdentities(stateStore)
channelStatusStore, presenceStore = stateStore, stateStore
settingsSource, applyReporter, appliedVersion = controlPlaneClient, reporter, channelVersion
settingsSource, applyReporter, appliedVersion, orgChannels = controlPlaneClient, reporter, channelVersion, &orgChannelDeps{Source: controlPlaneClient, Principals: stateStore}
updates = controlplanerpc.UpdateService(controlPlaneClient, filepath.Join(cfg.WorkDir, "telegram-update-deferrals.json"))
}
@@ -117,6 +118,7 @@ func Run(ctx context.Context, o Options) error {
Chat: chat,
Settings: settings,
SettingsSource: settingsSource,
OrgChannels: orgChannels,
ApplyReporter: applyReporter,
AppliedVersion: appliedVersion,
Updates: updates,
+6 -2
View File
@@ -35,10 +35,14 @@ func (s *Service) runChannel(ctx context.Context, c *channelInstance) {
}
runCtx, cancel := context.WithCancel(ctx)
c.cancel = cancel
chat := s.chat
if c.chat != nil {
chat = c.chat
}
c.mu.Unlock()
s.log.InfoContext(ctx, "starting channel", "name", c.name)
err := ch.Start(runCtx, s.chat, s.lifecycleFor(c.name))
err := ch.Start(runCtx, chat, s.lifecycleFor(c.name))
attempts++
// Decide the next state under the same lock a restart takes, so a
@@ -373,7 +377,7 @@ func (s *Service) stopChannel(ctx context.Context, name string, ch channels.Chan
}
func (s *Service) instanceByID(id string) *channelInstance {
for _, c := range s.channels {
for _, c := range s.instances() {
if c.name == id {
return c
}
+18
View File
@@ -74,6 +74,24 @@ func (m *Manager) MarkDegraded(id, detail string) {
func (m *Manager) MarkFailed(id, detail string) { m.set(id, StateFailed, detail) }
func (m *Manager) MarkStopped(id, detail string) { m.set(id, StateStopped, detail) }
// Add registers a channel composed after the manager was built.
func (m *Manager) Add(id, name string, configured bool) {
if m == nil {
return
}
m.mu.Lock()
defer m.mu.Unlock()
if _, ok := m.index[id]; ok {
return
}
state := StateStopped
if configured {
state = StateConfigured
}
m.index[id] = len(m.channels)
m.channels = append(m.channels, Status{ID: id, Name: name, Configured: configured, State: state})
}
// Declare records whether a composed channel is currently configured and
// reloadable. A live enable or disable changes both without changing the
// channel's identity, so the operator-facing declaration follows the channel
@@ -22,6 +22,86 @@ const (
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type ChannelOrgsRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ChannelOrgsRequest) Reset() {
*x = ChannelOrgsRequest{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ChannelOrgsRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ChannelOrgsRequest) ProtoMessage() {}
func (x *ChannelOrgsRequest) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_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 ChannelOrgsRequest.ProtoReflect.Descriptor instead.
func (*ChannelOrgsRequest) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{0}
}
type ChannelOrgsResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Resources []*Resource `protobuf:"bytes,1,rep,name=resources,proto3" json:"resources,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ChannelOrgsResponse) Reset() {
*x = ChannelOrgsResponse{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ChannelOrgsResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ChannelOrgsResponse) ProtoMessage() {}
func (x *ChannelOrgsResponse) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_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 ChannelOrgsResponse.ProtoReflect.Descriptor instead.
func (*ChannelOrgsResponse) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{1}
}
func (x *ChannelOrgsResponse) GetResources() []*Resource {
if x != nil {
return x.Resources
}
return nil
}
type ResourceDescriptor struct {
state protoimpl.MessageState `protogen:"open.v1"`
Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"`
@@ -43,7 +123,7 @@ type ResourceDescriptor struct {
func (x *ResourceDescriptor) Reset() {
*x = ResourceDescriptor{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[0]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -55,7 +135,7 @@ func (x *ResourceDescriptor) String() string {
func (*ResourceDescriptor) ProtoMessage() {}
func (x *ResourceDescriptor) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[0]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -68,7 +148,7 @@ func (x *ResourceDescriptor) ProtoReflect() protoreflect.Message {
// Deprecated: Use ResourceDescriptor.ProtoReflect.Descriptor instead.
func (*ResourceDescriptor) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{0}
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{2}
}
func (x *ResourceDescriptor) GetKind() string {
@@ -135,7 +215,7 @@ type CatalogRequest struct {
func (x *CatalogRequest) Reset() {
*x = CatalogRequest{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[1]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -147,7 +227,7 @@ func (x *CatalogRequest) String() string {
func (*CatalogRequest) ProtoMessage() {}
func (x *CatalogRequest) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[1]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[3]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -160,7 +240,7 @@ func (x *CatalogRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use CatalogRequest.ProtoReflect.Descriptor instead.
func (*CatalogRequest) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{1}
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{3}
}
type CatalogResponse struct {
@@ -172,7 +252,7 @@ type CatalogResponse struct {
func (x *CatalogResponse) Reset() {
*x = CatalogResponse{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[2]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -184,7 +264,7 @@ func (x *CatalogResponse) String() string {
func (*CatalogResponse) ProtoMessage() {}
func (x *CatalogResponse) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[2]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[4]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -197,7 +277,7 @@ func (x *CatalogResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use CatalogResponse.ProtoReflect.Descriptor instead.
func (*CatalogResponse) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{2}
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{4}
}
func (x *CatalogResponse) GetResources() []*ResourceDescriptor {
@@ -220,7 +300,7 @@ type Resource struct {
func (x *Resource) Reset() {
*x = Resource{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[3]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -232,7 +312,7 @@ func (x *Resource) String() string {
func (*Resource) ProtoMessage() {}
func (x *Resource) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[3]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[5]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -245,7 +325,7 @@ func (x *Resource) ProtoReflect() protoreflect.Message {
// Deprecated: Use Resource.ProtoReflect.Descriptor instead.
func (*Resource) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{3}
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{5}
}
func (x *Resource) GetKind() string {
@@ -294,7 +374,7 @@ type QueryRequest struct {
func (x *QueryRequest) Reset() {
*x = QueryRequest{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[4]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -306,7 +386,7 @@ func (x *QueryRequest) String() string {
func (*QueryRequest) ProtoMessage() {}
func (x *QueryRequest) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[4]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[6]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -319,7 +399,7 @@ func (x *QueryRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use QueryRequest.ProtoReflect.Descriptor instead.
func (*QueryRequest) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{4}
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{6}
}
func (x *QueryRequest) GetKind() string {
@@ -338,7 +418,7 @@ type QueryResponse struct {
func (x *QueryResponse) Reset() {
*x = QueryResponse{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[5]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[7]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -350,7 +430,7 @@ func (x *QueryResponse) String() string {
func (*QueryResponse) ProtoMessage() {}
func (x *QueryResponse) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[5]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[7]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -363,7 +443,7 @@ func (x *QueryResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use QueryResponse.ProtoReflect.Descriptor instead.
func (*QueryResponse) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{5}
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{7}
}
func (x *QueryResponse) GetResource() *Resource {
@@ -389,7 +469,7 @@ type Revision struct {
func (x *Revision) Reset() {
*x = Revision{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[6]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[8]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -401,7 +481,7 @@ func (x *Revision) String() string {
func (*Revision) ProtoMessage() {}
func (x *Revision) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[6]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[8]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -414,7 +494,7 @@ func (x *Revision) ProtoReflect() protoreflect.Message {
// Deprecated: Use Revision.ProtoReflect.Descriptor instead.
func (*Revision) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{6}
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{8}
}
func (x *Revision) GetVersion() int64 {
@@ -471,7 +551,7 @@ type HistoryRequest struct {
func (x *HistoryRequest) Reset() {
*x = HistoryRequest{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[7]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[9]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -483,7 +563,7 @@ func (x *HistoryRequest) String() string {
func (*HistoryRequest) ProtoMessage() {}
func (x *HistoryRequest) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[7]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[9]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -496,7 +576,7 @@ func (x *HistoryRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use HistoryRequest.ProtoReflect.Descriptor instead.
func (*HistoryRequest) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{7}
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{9}
}
func (x *HistoryRequest) GetKind() string {
@@ -522,7 +602,7 @@ type HistoryResponse struct {
func (x *HistoryResponse) Reset() {
*x = HistoryResponse{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[8]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[10]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -534,7 +614,7 @@ func (x *HistoryResponse) String() string {
func (*HistoryResponse) ProtoMessage() {}
func (x *HistoryResponse) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[8]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[10]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -547,7 +627,7 @@ func (x *HistoryResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use HistoryResponse.ProtoReflect.Descriptor instead.
func (*HistoryResponse) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{8}
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{10}
}
func (x *HistoryResponse) GetRevisions() []*Revision {
@@ -574,7 +654,7 @@ type CommandRequest struct {
func (x *CommandRequest) Reset() {
*x = CommandRequest{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[9]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[11]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -586,7 +666,7 @@ func (x *CommandRequest) String() string {
func (*CommandRequest) ProtoMessage() {}
func (x *CommandRequest) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[9]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[11]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -599,7 +679,7 @@ func (x *CommandRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use CommandRequest.ProtoReflect.Descriptor instead.
func (*CommandRequest) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{9}
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{11}
}
func (x *CommandRequest) GetKind() string {
@@ -660,7 +740,7 @@ type CommandResponse struct {
func (x *CommandResponse) Reset() {
*x = CommandResponse{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[10]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[12]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -672,7 +752,7 @@ func (x *CommandResponse) String() string {
func (*CommandResponse) ProtoMessage() {}
func (x *CommandResponse) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[10]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[12]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -685,7 +765,7 @@ func (x *CommandResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use CommandResponse.ProtoReflect.Descriptor instead.
func (*CommandResponse) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{10}
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{12}
}
func (x *CommandResponse) GetResource() *Resource {
@@ -705,7 +785,7 @@ type WatchRequest struct {
func (x *WatchRequest) Reset() {
*x = WatchRequest{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[11]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[13]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -717,7 +797,7 @@ func (x *WatchRequest) String() string {
func (*WatchRequest) ProtoMessage() {}
func (x *WatchRequest) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[11]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[13]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -730,7 +810,7 @@ func (x *WatchRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use WatchRequest.ProtoReflect.Descriptor instead.
func (*WatchRequest) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{11}
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{13}
}
func (x *WatchRequest) GetKind() string {
@@ -757,7 +837,7 @@ type WatchResponse struct {
func (x *WatchResponse) Reset() {
*x = WatchResponse{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[12]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[14]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -769,7 +849,7 @@ func (x *WatchResponse) String() string {
func (*WatchResponse) ProtoMessage() {}
func (x *WatchResponse) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[12]
mi := &file_controlplane_v1_controlplane_proto_msgTypes[14]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -782,7 +862,7 @@ func (x *WatchResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use WatchResponse.ProtoReflect.Descriptor instead.
func (*WatchResponse) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{12}
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{14}
}
func (x *WatchResponse) GetResource() *Resource {
@@ -803,7 +883,10 @@ var File_controlplane_v1_controlplane_proto protoreflect.FileDescriptor
const file_controlplane_v1_controlplane_proto_rawDesc = "" +
"\n" +
"\"controlplane/v1/controlplane.proto\x12\x0fcontrolplane.v1\x1a\x1fgoogle/protobuf/timestamp.proto\"\x8d\x02\n" +
"\"controlplane/v1/controlplane.proto\x12\x0fcontrolplane.v1\x1a\x1fgoogle/protobuf/timestamp.proto\"\x14\n" +
"\x12ChannelOrgsRequest\"N\n" +
"\x13ChannelOrgsResponse\x127\n" +
"\tresources\x18\x01 \x03(\v2\x19.controlplane.v1.ResourceR\tresources\"\x8d\x02\n" +
"\x12ResourceDescriptor\x12\x12\n" +
"\x04kind\x18\x01 \x01(\tR\x04kind\x12\x14\n" +
"\x05title\x18\x02 \x01(\tR\x05title\x12\x1f\n" +
@@ -861,13 +944,14 @@ const file_controlplane_v1_controlplane_proto_rawDesc = "" +
"\rafter_version\x18\x02 \x01(\x03R\fafterVersionJ\x04\b\x03\x10\x04R\x06org_id\"\\\n" +
"\rWatchResponse\x125\n" +
"\bresource\x18\x01 \x01(\v2\x19.controlplane.v1.ResourceR\bresource\x12\x14\n" +
"\x05error\x18\x02 \x01(\tR\x05error2\x91\x03\n" +
"\x05error\x18\x02 \x01(\tR\x05error2\xeb\x03\n" +
"\x13ControlPlaneService\x12L\n" +
"\aCatalog\x12\x1f.controlplane.v1.CatalogRequest\x1a .controlplane.v1.CatalogResponse\x12F\n" +
"\x05Query\x12\x1d.controlplane.v1.QueryRequest\x1a\x1e.controlplane.v1.QueryResponse\x12L\n" +
"\aHistory\x12\x1f.controlplane.v1.HistoryRequest\x1a .controlplane.v1.HistoryResponse\x12L\n" +
"\aCommand\x12\x1f.controlplane.v1.CommandRequest\x1a .controlplane.v1.CommandResponse\x12H\n" +
"\x05Watch\x12\x1d.controlplane.v1.WatchRequest\x1a\x1e.controlplane.v1.WatchResponse0\x01B\xdc\x01\n" +
"\x05Watch\x12\x1d.controlplane.v1.WatchRequest\x1a\x1e.controlplane.v1.WatchResponse0\x01\x12X\n" +
"\vChannelOrgs\x12#.controlplane.v1.ChannelOrgsRequest\x1a$.controlplane.v1.ChannelOrgsResponseB\xdc\x01\n" +
"\x13com.controlplane.v1B\x11ControlplaneProtoP\x01ZUgithub.com/samcharles93/archie-core/internal/contracts/controlplane/v1;controlplanev1\xa2\x02\x03CXX\xaa\x02\x0fControlplane.V1\xca\x02\x0fControlplane\\V1\xe2\x02\x1bControlplane\\V1\\GPBMetadata\xea\x02\x10Controlplane::V1b\x06proto3"
var (
@@ -882,46 +966,51 @@ func file_controlplane_v1_controlplane_proto_rawDescGZIP() []byte {
return file_controlplane_v1_controlplane_proto_rawDescData
}
var file_controlplane_v1_controlplane_proto_msgTypes = make([]protoimpl.MessageInfo, 13)
var file_controlplane_v1_controlplane_proto_msgTypes = make([]protoimpl.MessageInfo, 15)
var file_controlplane_v1_controlplane_proto_goTypes = []any{
(*ResourceDescriptor)(nil), // 0: controlplane.v1.ResourceDescriptor
(*CatalogRequest)(nil), // 1: controlplane.v1.CatalogRequest
(*CatalogResponse)(nil), // 2: controlplane.v1.CatalogResponse
(*Resource)(nil), // 3: controlplane.v1.Resource
(*QueryRequest)(nil), // 4: controlplane.v1.QueryRequest
(*QueryResponse)(nil), // 5: controlplane.v1.QueryResponse
(*Revision)(nil), // 6: controlplane.v1.Revision
(*HistoryRequest)(nil), // 7: controlplane.v1.HistoryRequest
(*HistoryResponse)(nil), // 8: controlplane.v1.HistoryResponse
(*CommandRequest)(nil), // 9: controlplane.v1.CommandRequest
(*CommandResponse)(nil), // 10: controlplane.v1.CommandResponse
(*WatchRequest)(nil), // 11: controlplane.v1.WatchRequest
(*WatchResponse)(nil), // 12: controlplane.v1.WatchResponse
(*timestamppb.Timestamp)(nil), // 13: google.protobuf.Timestamp
(*ChannelOrgsRequest)(nil), // 0: controlplane.v1.ChannelOrgsRequest
(*ChannelOrgsResponse)(nil), // 1: controlplane.v1.ChannelOrgsResponse
(*ResourceDescriptor)(nil), // 2: controlplane.v1.ResourceDescriptor
(*CatalogRequest)(nil), // 3: controlplane.v1.CatalogRequest
(*CatalogResponse)(nil), // 4: controlplane.v1.CatalogResponse
(*Resource)(nil), // 5: controlplane.v1.Resource
(*QueryRequest)(nil), // 6: controlplane.v1.QueryRequest
(*QueryResponse)(nil), // 7: controlplane.v1.QueryResponse
(*Revision)(nil), // 8: controlplane.v1.Revision
(*HistoryRequest)(nil), // 9: controlplane.v1.HistoryRequest
(*HistoryResponse)(nil), // 10: controlplane.v1.HistoryResponse
(*CommandRequest)(nil), // 11: controlplane.v1.CommandRequest
(*CommandResponse)(nil), // 12: controlplane.v1.CommandResponse
(*WatchRequest)(nil), // 13: controlplane.v1.WatchRequest
(*WatchResponse)(nil), // 14: controlplane.v1.WatchResponse
(*timestamppb.Timestamp)(nil), // 15: google.protobuf.Timestamp
}
var file_controlplane_v1_controlplane_proto_depIdxs = []int32{
0, // 0: controlplane.v1.CatalogResponse.resources:type_name -> controlplane.v1.ResourceDescriptor
13, // 1: controlplane.v1.Resource.updated_at:type_name -> google.protobuf.Timestamp
3, // 2: controlplane.v1.QueryResponse.resource:type_name -> controlplane.v1.Resource
13, // 3: controlplane.v1.Revision.at:type_name -> google.protobuf.Timestamp
6, // 4: controlplane.v1.HistoryResponse.revisions:type_name -> controlplane.v1.Revision
3, // 5: controlplane.v1.CommandResponse.resource:type_name -> controlplane.v1.Resource
3, // 6: controlplane.v1.WatchResponse.resource:type_name -> controlplane.v1.Resource
1, // 7: controlplane.v1.ControlPlaneService.Catalog:input_type -> controlplane.v1.CatalogRequest
4, // 8: controlplane.v1.ControlPlaneService.Query:input_type -> controlplane.v1.QueryRequest
7, // 9: controlplane.v1.ControlPlaneService.History:input_type -> controlplane.v1.HistoryRequest
9, // 10: controlplane.v1.ControlPlaneService.Command:input_type -> controlplane.v1.CommandRequest
11, // 11: controlplane.v1.ControlPlaneService.Watch:input_type -> controlplane.v1.WatchRequest
2, // 12: controlplane.v1.ControlPlaneService.Catalog:output_type -> controlplane.v1.CatalogResponse
5, // 13: controlplane.v1.ControlPlaneService.Query:output_type -> controlplane.v1.QueryResponse
8, // 14: controlplane.v1.ControlPlaneService.History:output_type -> controlplane.v1.HistoryResponse
10, // 15: controlplane.v1.ControlPlaneService.Command:output_type -> controlplane.v1.CommandResponse
12, // 16: controlplane.v1.ControlPlaneService.Watch:output_type -> controlplane.v1.WatchResponse
12, // [12:17] is the sub-list for method output_type
7, // [7:12] is the sub-list for method input_type
7, // [7:7] is the sub-list for extension type_name
7, // [7:7] is the sub-list for extension extendee
0, // [0:7] is the sub-list for field type_name
5, // 0: controlplane.v1.ChannelOrgsResponse.resources:type_name -> controlplane.v1.Resource
2, // 1: controlplane.v1.CatalogResponse.resources:type_name -> controlplane.v1.ResourceDescriptor
15, // 2: controlplane.v1.Resource.updated_at:type_name -> google.protobuf.Timestamp
5, // 3: controlplane.v1.QueryResponse.resource:type_name -> controlplane.v1.Resource
15, // 4: controlplane.v1.Revision.at:type_name -> google.protobuf.Timestamp
8, // 5: controlplane.v1.HistoryResponse.revisions:type_name -> controlplane.v1.Revision
5, // 6: controlplane.v1.CommandResponse.resource:type_name -> controlplane.v1.Resource
5, // 7: controlplane.v1.WatchResponse.resource:type_name -> controlplane.v1.Resource
3, // 8: controlplane.v1.ControlPlaneService.Catalog:input_type -> controlplane.v1.CatalogRequest
6, // 9: controlplane.v1.ControlPlaneService.Query:input_type -> controlplane.v1.QueryRequest
9, // 10: controlplane.v1.ControlPlaneService.History:input_type -> controlplane.v1.HistoryRequest
11, // 11: controlplane.v1.ControlPlaneService.Command:input_type -> controlplane.v1.CommandRequest
13, // 12: controlplane.v1.ControlPlaneService.Watch:input_type -> controlplane.v1.WatchRequest
0, // 13: controlplane.v1.ControlPlaneService.ChannelOrgs:input_type -> controlplane.v1.ChannelOrgsRequest
4, // 14: controlplane.v1.ControlPlaneService.Catalog:output_type -> controlplane.v1.CatalogResponse
7, // 15: controlplane.v1.ControlPlaneService.Query:output_type -> controlplane.v1.QueryResponse
10, // 16: controlplane.v1.ControlPlaneService.History:output_type -> controlplane.v1.HistoryResponse
12, // 17: controlplane.v1.ControlPlaneService.Command:output_type -> controlplane.v1.CommandResponse
14, // 18: controlplane.v1.ControlPlaneService.Watch:output_type -> controlplane.v1.WatchResponse
1, // 19: controlplane.v1.ControlPlaneService.ChannelOrgs:output_type -> controlplane.v1.ChannelOrgsResponse
14, // [14:20] is the sub-list for method output_type
8, // [8:14] is the sub-list for method input_type
8, // [8:8] is the sub-list for extension type_name
8, // [8:8] is the sub-list for extension extendee
0, // [0:8] is the sub-list for field type_name
}
func init() { file_controlplane_v1_controlplane_proto_init() }
@@ -935,7 +1024,7 @@ func file_controlplane_v1_controlplane_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_controlplane_v1_controlplane_proto_rawDesc), len(file_controlplane_v1_controlplane_proto_rawDesc)),
NumEnums: 0,
NumMessages: 13,
NumMessages: 15,
NumExtensions: 0,
NumServices: 1,
},
@@ -19,11 +19,12 @@ import (
const _ = grpc.SupportPackageIsVersion9
const (
ControlPlaneService_Catalog_FullMethodName = "/controlplane.v1.ControlPlaneService/Catalog"
ControlPlaneService_Query_FullMethodName = "/controlplane.v1.ControlPlaneService/Query"
ControlPlaneService_History_FullMethodName = "/controlplane.v1.ControlPlaneService/History"
ControlPlaneService_Command_FullMethodName = "/controlplane.v1.ControlPlaneService/Command"
ControlPlaneService_Watch_FullMethodName = "/controlplane.v1.ControlPlaneService/Watch"
ControlPlaneService_Catalog_FullMethodName = "/controlplane.v1.ControlPlaneService/Catalog"
ControlPlaneService_Query_FullMethodName = "/controlplane.v1.ControlPlaneService/Query"
ControlPlaneService_History_FullMethodName = "/controlplane.v1.ControlPlaneService/History"
ControlPlaneService_Command_FullMethodName = "/controlplane.v1.ControlPlaneService/Command"
ControlPlaneService_Watch_FullMethodName = "/controlplane.v1.ControlPlaneService/Watch"
ControlPlaneService_ChannelOrgs_FullMethodName = "/controlplane.v1.ControlPlaneService/ChannelOrgs"
)
// ControlPlaneServiceClient is the client API for ControlPlaneService service.
@@ -35,6 +36,10 @@ type ControlPlaneServiceClient interface {
History(ctx context.Context, in *HistoryRequest, opts ...grpc.CallOption) (*HistoryResponse, error)
Command(ctx context.Context, in *CommandRequest, opts ...grpc.CallOption) (*CommandResponse, error)
Watch(ctx context.Context, in *WatchRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[WatchResponse], error)
// ChannelOrgs answers every org's stored channel settings except the system
// org's, for the Messaging Service alone: it builds one channel per org, and
// its other reads are confined to the system org.
ChannelOrgs(ctx context.Context, in *ChannelOrgsRequest, opts ...grpc.CallOption) (*ChannelOrgsResponse, error)
}
type controlPlaneServiceClient struct {
@@ -104,6 +109,16 @@ func (c *controlPlaneServiceClient) Watch(ctx context.Context, in *WatchRequest,
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type ControlPlaneService_WatchClient = grpc.ServerStreamingClient[WatchResponse]
func (c *controlPlaneServiceClient) ChannelOrgs(ctx context.Context, in *ChannelOrgsRequest, opts ...grpc.CallOption) (*ChannelOrgsResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ChannelOrgsResponse)
err := c.cc.Invoke(ctx, ControlPlaneService_ChannelOrgs_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// ControlPlaneServiceServer is the server API for ControlPlaneService service.
// All implementations must embed UnimplementedControlPlaneServiceServer
// for forward compatibility.
@@ -113,6 +128,10 @@ type ControlPlaneServiceServer interface {
History(context.Context, *HistoryRequest) (*HistoryResponse, error)
Command(context.Context, *CommandRequest) (*CommandResponse, error)
Watch(*WatchRequest, grpc.ServerStreamingServer[WatchResponse]) error
// ChannelOrgs answers every org's stored channel settings except the system
// org's, for the Messaging Service alone: it builds one channel per org, and
// its other reads are confined to the system org.
ChannelOrgs(context.Context, *ChannelOrgsRequest) (*ChannelOrgsResponse, error)
mustEmbedUnimplementedControlPlaneServiceServer()
}
@@ -138,6 +157,9 @@ func (UnimplementedControlPlaneServiceServer) Command(context.Context, *CommandR
func (UnimplementedControlPlaneServiceServer) Watch(*WatchRequest, grpc.ServerStreamingServer[WatchResponse]) error {
return status.Error(codes.Unimplemented, "method Watch not implemented")
}
func (UnimplementedControlPlaneServiceServer) ChannelOrgs(context.Context, *ChannelOrgsRequest) (*ChannelOrgsResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ChannelOrgs not implemented")
}
func (UnimplementedControlPlaneServiceServer) mustEmbedUnimplementedControlPlaneServiceServer() {}
func (UnimplementedControlPlaneServiceServer) testEmbeddedByValue() {}
@@ -242,6 +264,24 @@ func _ControlPlaneService_Watch_Handler(srv interface{}, stream grpc.ServerStrea
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type ControlPlaneService_WatchServer = grpc.ServerStreamingServer[WatchResponse]
func _ControlPlaneService_ChannelOrgs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ChannelOrgsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ControlPlaneServiceServer).ChannelOrgs(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ControlPlaneService_ChannelOrgs_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ControlPlaneServiceServer).ChannelOrgs(ctx, req.(*ChannelOrgsRequest))
}
return interceptor(ctx, in, info, handler)
}
// ControlPlaneService_ServiceDesc is the grpc.ServiceDesc for ControlPlaneService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
@@ -265,6 +305,10 @@ var ControlPlaneService_ServiceDesc = grpc.ServiceDesc{
MethodName: "Command",
Handler: _ControlPlaneService_Command_Handler,
},
{
MethodName: "ChannelOrgs",
Handler: _ControlPlaneService_ChannelOrgs_Handler,
},
},
Streams: []grpc.StreamDesc{
{
@@ -27,8 +27,11 @@ type DeliverRequest struct {
// 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"`
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"`
// org_id is the org whose channel sends. A channel belongs to one org, and
// delivery through another org's channel is refused as no such channel.
OrgId string `protobuf:"bytes,4,opt,name=org_id,json=orgId,proto3" json:"org_id,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -84,6 +87,13 @@ func (x *DeliverRequest) GetText() string {
return ""
}
func (x *DeliverRequest) GetOrgId() string {
if x != nil {
return x.OrgId
}
return ""
}
type DeliverResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
@@ -212,11 +222,12 @@ var File_messaging_v1_messaging_proto protoreflect.FileDescriptor
const file_messaging_v1_messaging_proto_rawDesc = "" +
"\n" +
"\x1cmessaging/v1/messaging.proto\x12\fmessaging.v1\x1a\x18logging/v1/logging.proto\"W\n" +
"\x1cmessaging/v1/messaging.proto\x12\fmessaging.v1\x1a\x18logging/v1/logging.proto\"n\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" +
"\x04text\x18\x03 \x01(\tR\x04text\x12\x15\n" +
"\x06org_id\x18\x04 \x01(\tR\x05orgId\"\x11\n" +
"\x0fDeliverResponse\"?\n" +
"\x11RecentLogsRequest\x12*\n" +
"\x05query\x18\x01 \x01(\v2\x14.logging.v1.LogQueryR\x05query\"I\n" +
+1 -1
View File
@@ -43,7 +43,7 @@ var dashboardPages = []DashboardPage{
{Path: "/settings/curators", Label: "Curators", Description: "Scheduled memory and capture curation."},
{Path: "/events", Label: "Events", Description: "Captured events, field mappings, workflow bindings."},
{Path: "/logs", Label: "Logs", Description: "Daemon log by level and component."},
{Path: "/settings/channels", Label: "Channels", Description: "Chat and notification channels."},
{Path: "/org/channels", Label: "Channels", Description: "Chat and notification channels."},
{Path: "/settings/status", Label: "Status", Description: "Update state, config sources, listen address."},
{Path: "/settings/appearance", Label: "Appearance", Description: "Theme, density, motion."},
{Path: "/settings/task-execution", Label: "Task execution", Description: "Statuses, operator actions, budgets."},
+10 -1
View File
@@ -16,6 +16,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/presence"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
@@ -889,9 +890,17 @@ func (s *postgresSessionStore) mayWrite(ctx context.Context, sessionID string) e
// Service-owned curation has no person principal. Signed-in callers only
// see their own web conversations, including through tools and slash commands.
// The Messaging Service speaks for an org's agent and sees that org's channel
// conversations, never a person's web ones.
func sessionVisible(ctx context.Context, session SessionContext) bool {
p, ok := access.PrincipalFromContext(ctx)
return !ok || (session.Source.Platform == "web" && session.Source.ThreadID == string(p.IdentityID))
if !ok {
return true
}
if access.SourceFromContext(ctx) == presence.Messaging {
return session.Source.Platform != "web"
}
return session.Source.Platform == "web" && session.Source.ThreadID == string(p.IdentityID)
}
func visibleSessions(ctx context.Context, sessions []SessionContext) []SessionContext {
+12 -5
View File
@@ -5,26 +5,33 @@ import (
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/domain/presence"
)
func TestSessionVisibility(t *testing.T) {
for _, tc := range []struct {
name string
service bool
caller string
platform, owner string
want bool
}{
{"own history", false, "web", "alice", true},
{"another user in the same org", false, "web", "bob", false},
{"anonymous history is not assigned to a person", false, "web", "", false},
{"other channel history", false, "telegram", "alice", false},
{"curator service", true, "web", "bob", true},
{"own history", false, "", "web", "alice", true},
{"another user in the same org", false, "", "web", "bob", false},
{"anonymous history is not assigned to a person", false, "", "web", "", false},
{"other channel history", false, "", "telegram", "alice", false},
{"curator service", true, "", "web", "bob", true},
{"messaging acting for an org agent sees channel history", false, presence.Messaging, "telegram", "alice", true},
{"messaging acting for an org agent never sees web history", false, presence.Messaging, "web", "bob", false},
} {
t.Run(tc.name, func(t *testing.T) {
ctx := t.Context()
if !tc.service {
ctx = access.WithPrincipal(ctx, access.Principal{IdentityID: "alice"})
}
if tc.caller != "" {
ctx = access.WithSource(ctx, tc.caller)
}
session := SessionContext{Source: messaging.SessionSource{Platform: tc.platform, ThreadID: tc.owner}}
if got := sessionVisible(ctx, session); got != tc.want {
t.Fatalf("visible=%v want=%v", got, tc.want)
@@ -92,6 +92,31 @@ func RuntimeChatConfigFrom(ctx context.Context, reader ResourceReader, base conf
return out, version, nil
}
// OrgChannel is one org's stored channel settings.
type OrgChannel struct {
Org string
Version int64
Settings ChannelSettings
}
// ChannelOrgs lists every other org's channel settings. Only the Messaging
// Service may ask.
func (c *Client) ChannelOrgs(ctx context.Context) ([]OrgChannel, error) {
response, err := c.rpc.ChannelOrgs(ctx, &pb.ChannelOrgsRequest{})
if err != nil {
return nil, ClientError(err)
}
out := make([]OrgChannel, 0, len(response.GetResources()))
for _, resource := range response.GetResources() {
var settings ChannelSettings
if err := json.Unmarshal(resource.GetValueJson(), &settings); err != nil {
return nil, fmt.Errorf("decode %s of %s: %w", ChannelSettingsKind, resource.GetOrgId(), err)
}
out = append(out, OrgChannel{Org: resource.GetOrgId(), Version: resource.GetVersion(), Settings: settings})
}
return out, nil
}
// ClientError maps a gRPC status onto the wire sentinels both sides match on.
// It is exported because the store-backed server's own client methods need the
// same mapping, and a second copy would be a second contract.
@@ -22,6 +22,9 @@ type ChannelSettings struct {
RateLimit RateLimitSettings `json:"rate_limit"`
UnrestrictedFilesystem bool `json:"unrestricted_filesystem"`
Workspace string `json:"workspace"`
// Agent is the identity an org's channel chats as. The system org's
// channel acts for no one and leaves it empty.
Agent string `json:"agent"`
}
type TelegramSettings struct {
@@ -0,0 +1,34 @@
package controlplanestore
import (
"context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/presence"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// ChannelOrgs answers every other org's channel settings to the Messaging
// Service, which builds one channel per org. Its ordinary reads are confined to
// the system org, and no other caller may enumerate orgs' settings.
func (s *Server) ChannelOrgs(ctx context.Context, _ *pb.ChannelOrgsRequest) (*pb.ChannelOrgsResponse, error) {
if access.SourceFromContext(ctx) != presence.Messaging {
return nil, status.Error(codes.PermissionDenied, "only the messaging service lists org channels")
}
stored, err := s.store.ListResources(ctx)
if err != nil {
return nil, mapError(err)
}
var out []*pb.Resource
for _, resource := range stored {
if resource.Kind != ChannelSettingsKind || resource.OrgID == storecontract.DefaultOrgID {
continue
}
out = append(out, resourceProto(resource))
}
return &pb.ChannelOrgsResponse{Resources: out}, nil
}
@@ -5,6 +5,7 @@ import (
"fmt"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
)
@@ -46,3 +47,27 @@ func normalizeChannels(input []byte) ([]byte, error) {
}
return json.Marshal(settings)
}
// checkChannelWrite keeps an org to the settings its own channel consumes.
// The workspace, filesystem, step, rate-limit and operator settings configure
// the instance's gateway, and the bot token resolves against the instance's
// secret engines, so an org's bot takes its token from the org's credential
// binding named telegram instead. The system org's channel acts for no one, so
// it names no agent.
func checkChannelWrite(orgID string, value []byte) error {
var doc channelSettings
if err := json.Unmarshal(value, &doc); err != nil {
return err
}
if orgID == storecontract.DefaultOrgID {
if doc.Agent != "" {
return fmt.Errorf("%w: the instance channel acts for no agent", ErrValidation)
}
return nil
}
if doc.Operator != "" || doc.Workspace != "" || doc.UnrestrictedFilesystem || doc.MaxSteps != 0 ||
doc.RateLimit != (rateLimitSettings{}) || doc.Telegram.Token != (config.SecretRef{}) {
return fmt.Errorf("%w: operator, workspace, filesystem, step, rate-limit and token settings are the instance's; an org sets its Telegram users, tool-call display and agent, and binds its bot token as the credential telegram", ErrValidation)
}
return nil
}
@@ -0,0 +1,83 @@
package controlplanestore
import (
"context"
"errors"
"testing"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/presence"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
func TestChannelSettingsWritesStayWithinTheirOrg(t *testing.T) {
tests := []struct {
name, org, value string
refused bool
}{
{"system org sets the instance channel", storecontract.DefaultOrgID, `{"operator":"sam","workspace":"/srv","telegram":{"allowed_user_ids":[1]}}`, false},
{"system org names an agent", storecontract.DefaultOrgID, `{"agent":"a1"}`, true},
{"another org sets its users and agent", "acme", `{"agent":"a1","show_tool_calls":true,"telegram":{"allowed_user_ids":[7]}}`, false},
{"another org sets the host workspace", "acme", `{"workspace":"/srv"}`, true},
{"another org lifts the filesystem limit", "acme", `{"unrestricted_filesystem":true}`, true},
{"another org names a token secret", "acme", `{"telegram":{"token_ref":{"engine":"env","key":"INSTANCE_BOT"}}}`, true},
{"another org sets the instance rate limit", "acme", `{"rate_limit":{"max_requests":5}}`, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := (&Server{}).checkOrgWrite(t.Context(), tt.org, ChannelSettingsKind, []byte(tt.value))
if refused := errors.Is(err, ErrValidation); refused != tt.refused {
t.Fatalf("refused = %v, want %v (err %v)", refused, tt.refused, err)
}
})
}
}
type listingStore struct {
ResourceStore
resources []storecontract.Resource
}
func (s listingStore) ListResources(context.Context) ([]storecontract.Resource, error) {
return s.resources, nil
}
func TestChannelOrgsServesOnlyMessagingAndOnlyOtherOrgs(t *testing.T) {
server := &Server{store: listingStore{resources: []storecontract.Resource{
{OrgID: storecontract.DefaultOrgID, Kind: ChannelSettingsKind},
{OrgID: "acme", Kind: ChannelSettingsKind},
{OrgID: "acme", Kind: SoulKind},
}}}
tests := []struct {
name, caller string
wantOrgs []string
wantCode codes.Code
}{
{"messaging lists other orgs' channel settings", presence.Messaging, []string{"acme"}, codes.OK},
{"the gateway is refused", presence.Gateway, nil, codes.PermissionDenied},
{"an unattributed caller is refused", "", nil, codes.PermissionDenied},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := t.Context()
if tt.caller != "" {
ctx = access.WithSource(ctx, tt.caller)
}
response, err := server.ChannelOrgs(ctx, &pb.ChannelOrgsRequest{})
if status.Code(err) != tt.wantCode {
t.Fatalf("code = %v, want %v (err %v)", status.Code(err), tt.wantCode, err)
}
var got []string
for _, resource := range response.GetResources() {
got = append(got, resource.GetOrgId())
}
if len(got) != len(tt.wantOrgs) || (len(got) == 1 && got[0] != tt.wantOrgs[0]) {
t.Fatalf("orgs = %v, want %v", got, tt.wantOrgs)
}
})
}
}
@@ -202,6 +202,7 @@ var orgSeededKinds = map[string]bool{
// instance's, so nothing is stored for it and the instance's values are not
// copied in.
var orgEmptyDocuments = map[string]string{
ChannelSettingsKind: `{"operator":"","show_tool_calls":false,"max_steps":0,"telegram":{"allowed_user_ids":[],"token_ref":{},"credential_configured":false},"rate_limit":{"window":0,"max_requests":0},"unrestricted_filesystem":false,"workspace":"","agent":""}`,
TaskPolicyKind: `{"notify_webhook":"","notify_min_severity":"","notify_secret":{}}`,
SchedulingPolicyKind: `{"poll_interval":"","max_retries":0,"dispatch":{"trigger":"","ack_reaction":""}}`,
}
@@ -182,12 +182,9 @@ func (s *Server) readResource(ctx context.Context, orgID, kind string, into any)
// limits): ToolSettings, PluginSettings, ContainerRuntimePolicies,
// AgentProfile, WorkflowExecutionSettings, ExtensionSettings, UpdateSettings,
// AuditRetention, ScheduleSettings (the zone every cron schedule reads in).
// Pending an org owner of the channels they configure:
// ChannelSettings.
var instanceOnlyKinds = map[string]bool{
ChannelSettingsKind: true,
ToolSettingsKind: true,
PluginSettingsKind: true, ContainerRuntimePoliciesKind: true, AgentProfileKind: true,
ToolSettingsKind: true,
PluginSettingsKind: true, ContainerRuntimePoliciesKind: true, AgentProfileKind: true,
ExtensionSettingsKind: true, UpdateSettingsKind: true, WorkflowExecutionSettingsKind: true,
AuditRetentionKind: true, ScheduleSettingsKind: true,
}
@@ -209,6 +206,8 @@ func (s *Server) checkOrgWrite(ctx context.Context, orgID, kind string, value []
if orgID != storecontract.DefaultOrgID {
return s.checkOrgProviders(ctx, orgID, value)
}
case ChannelSettingsKind:
return checkChannelWrite(orgID, value)
case TaskPolicyKind:
return checkTaskPolicyWrite(orgID, value)
case SchedulingPolicyKind:
@@ -28,9 +28,10 @@ var ErrUnavailable = errors.New("messaging: channel unavailable")
// Retrying cannot succeed.
var ErrNoChannel = errors.New("messaging: no such channel")
// Deliverer sends text to one chat on a named channel.
// Deliverer sends text to one chat on a named channel of an org. An empty org
// is the system org's.
type Deliverer interface {
Deliver(ctx context.Context, channel, chatID, text string) error
Deliver(ctx context.Context, org, channel, chatID, text string) error
}
type server struct {
@@ -48,7 +49,7 @@ func (s *server) Deliver(ctx context.Context, req *pb.DeliverRequest) (*pb.Deliv
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())
err := s.deliverer.Deliver(ctx, req.GetOrgId(), req.GetChannel(), req.GetChatId(), req.GetText())
switch {
case err == nil:
return &pb.DeliverResponse{}, nil
@@ -87,8 +88,8 @@ func Dial(target string, id *rpctls.Identity) (*Client, func(), error) {
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})
// Deliver sends text to chatID on org's channel.
func (c *Client) Deliver(ctx context.Context, org, channel, chatID, text string) error {
_, err := c.rpc.Deliver(ctx, &pb.DeliverRequest{OrgId: org, Channel: channel, ChatId: chatID, Text: text})
return err
}
+16 -17
View File
@@ -14,7 +14,6 @@ import (
"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"
)
@@ -58,8 +57,9 @@ type Runs interface {
// Server delivers authorized requests through Deliver.
type Server struct {
Runs Runs
Deliver func(ctx context.Context, channel, chatID, text string) error
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
}
@@ -84,7 +84,8 @@ func (s *Server) handleDeliver(ctx context.Context, identity string, msg *nats.M
s.respond(msg, fmt.Errorf("decode deliver request: %w", err))
return
}
if err := s.authorize(ctx, identity, req.Credential); err != nil {
task, err := s.authorize(ctx, identity, req.Credential)
if err != nil {
s.respond(msg, err)
return
}
@@ -92,31 +93,29 @@ func (s *Server) handleDeliver(ctx context.Context, identity string, msg *nats.M
s.respond(msg, errors.New("messaging service unavailable"))
return
}
s.respond(msg, s.Deliver(ctx, req.Channel, req.ChatID, req.Text))
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 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 {
// 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 errors.New("message request needs a run credential")
return nil, 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)
return nil, 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")
return nil, 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")
return nil, errors.New("a test run records deliveries instead of performing them")
case workflow.PackageOf(task.WorkflowDefinitionYAML) != "":
return errors.New("a package's workflow may not send messages")
return nil, errors.New("a package's workflow may not send messages")
}
return nil
return task, nil
}
func (s *Server) respond(msg *nats.Msg, err error) {
+2 -2
View File
@@ -33,14 +33,14 @@ func TestAuthorize(t *testing.T) {
{"no credential", "archie", "", false},
{"unknown credential", "archie", "nope", false},
{"other identity", "someone-else", "sys", false},
{"non-system org", "archie", "org", false},
{"non-system org", "archie", "org", true},
{"test run", "archie", "test", false},
{"package workflow", "archie", "package", false},
}
s := &Server{Runs: runs}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := s.authorize(context.Background(), tt.identity, tt.credential)
_, err := s.authorize(context.Background(), tt.identity, tt.credential)
if (err == nil) != tt.ok {
t.Fatalf("authorize() err = %v, want ok %v", err, tt.ok)
}
+1 -1
View File
@@ -46,7 +46,7 @@ func (s *Server) handleSetup(w http.ResponseWriter, r *http.Request) {
Title: "Chat channel",
Detail: "Chat and approvals.",
Done: view.Chat.ChannelConfigured,
Path: "/settings/channels",
Path: "/org/channels",
})
// Only meaningful once there is somewhere to run work.