deploy / plan (push) Canceled after 0s
deploy / gate (push) Canceled after 0s
deploy / archied-image (push) Canceled after 0s
deploy / agent-image (push) Canceled after 0s
deploy / dist-zip (push) Canceled after 0s
ci/woodpecker/push/deploy Pipeline was canceled
188 lines
6.7 KiB
Go
188 lines
6.7 KiB
Go
package controlplanestore
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"maps"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/samcharles93/archie-core/internal/config"
|
|
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
|
)
|
|
|
|
// telegramPackage is the channel package whose extension settings hold the
|
|
// instance's Telegram connection.
|
|
const telegramPackage = "telegram"
|
|
|
|
// telegramConnection is the instance bot's token reference and allowlist.
|
|
type telegramConnection struct {
|
|
Token config.SecretRef
|
|
Users []int64
|
|
}
|
|
|
|
// extensionSetting renders the connection as the telegram package's settings,
|
|
// in the encoding the package parses.
|
|
func (c telegramConnection) extensionSetting() controlplanerpc.ExtensionSetting {
|
|
settings := map[string]string{}
|
|
if c.Token != (config.SecretRef{}) {
|
|
settings["token_ref"] = c.Token.Engine + ":" + c.Token.Key
|
|
}
|
|
if len(c.Users) > 0 {
|
|
ids := make([]string, len(c.Users))
|
|
for i, id := range c.Users {
|
|
ids[i] = strconv.FormatInt(id, 10)
|
|
}
|
|
settings["allowed_user_ids"] = strings.Join(ids, ",")
|
|
}
|
|
return controlplanerpc.ExtensionSetting{Name: telegramPackage, Enabled: true, Settings: settings}
|
|
}
|
|
|
|
// seedExtensionSettings is the extension-settings seed: the catalogue sources
|
|
// and, when the file's [chat.telegram] names a token, the telegram package
|
|
// enabled with that connection.
|
|
func seedExtensionSettings(cfg config.Config) any {
|
|
doc := controlplanerpc.ExtensionSettings{CatalogueSource: cfg.Distribution.Catalogue, CatalogueKey: cfg.Distribution.CatalogueKey}
|
|
if file := cfg.Chat.Telegram; file.Token != (config.SecretRef{}) {
|
|
doc.Extensions = append(doc.Extensions, telegramConnection{Token: file.Token, Users: file.AllowedUserIDs}.extensionSetting())
|
|
}
|
|
return doc
|
|
}
|
|
|
|
// withTelegramConnection adds the connection to the telegram package's
|
|
// setting. A value the operator already set there wins, and a package entry
|
|
// that exists keeps its enabled state.
|
|
func withTelegramConnection(doc controlplanerpc.ExtensionSettings, c telegramConnection) controlplanerpc.ExtensionSettings {
|
|
moved := c.extensionSetting()
|
|
out := doc
|
|
out.Extensions = append([]controlplanerpc.ExtensionSetting(nil), doc.Extensions...)
|
|
for i, setting := range out.Extensions {
|
|
if setting.Name != telegramPackage {
|
|
continue
|
|
}
|
|
merged := make(map[string]string, len(setting.Settings)+len(moved.Settings))
|
|
maps.Copy(merged, moved.Settings)
|
|
for key, value := range setting.Settings {
|
|
if value != "" {
|
|
merged[key] = value
|
|
}
|
|
}
|
|
setting.Settings = merged
|
|
out.Extensions[i] = setting
|
|
return out
|
|
}
|
|
out.Extensions = append(out.Extensions, moved)
|
|
return out
|
|
}
|
|
|
|
// splitLegacyChannelSettings removes the nested telegram object a
|
|
// channel-settings document used to carry. The instance's token and users are
|
|
// returned for extension-settings; an org keeps its users as the flat
|
|
// allowed_user_ids. changed is false for a document with no such object.
|
|
func splitLegacyChannelSettings(orgID string, stored []byte) (rewritten []byte, moved telegramConnection, changed bool, err error) {
|
|
var doc map[string]json.RawMessage
|
|
if err := json.Unmarshal(stored, &doc); err != nil {
|
|
return nil, telegramConnection{}, false, err
|
|
}
|
|
raw, ok := doc["telegram"]
|
|
if !ok {
|
|
return nil, telegramConnection{}, false, nil
|
|
}
|
|
var legacy struct {
|
|
AllowedUserIDs []int64 `json:"allowed_user_ids"`
|
|
TokenRef config.SecretRef `json:"token_ref"`
|
|
}
|
|
if err := json.Unmarshal(raw, &legacy); err != nil {
|
|
return nil, telegramConnection{}, false, fmt.Errorf("decode telegram: %w", err)
|
|
}
|
|
delete(doc, "telegram")
|
|
// A document old enough to carry telegram can also carry the per-channel
|
|
// models that model aliases replaced, which the current schema rejects.
|
|
delete(doc, "models")
|
|
if orgID == storecontract.DefaultOrgID {
|
|
moved = telegramConnection{Token: legacy.TokenRef, Users: legacy.AllowedUserIDs}
|
|
} else if len(legacy.AllowedUserIDs) > 0 {
|
|
users, err := json.Marshal(legacy.AllowedUserIDs)
|
|
if err != nil {
|
|
return nil, telegramConnection{}, false, err
|
|
}
|
|
doc["allowed_user_ids"] = users
|
|
}
|
|
rewritten, err = json.Marshal(doc)
|
|
return rewritten, moved, true, err
|
|
}
|
|
|
|
// migrateTelegramConnection moves the Telegram connection out of every
|
|
// channel-settings document. The instance's token reference and users go to
|
|
// the telegram package's extension settings first, so a failure between the two
|
|
// writes leaves the legacy object in place to be moved again on the next start.
|
|
func (s *Server) migrateTelegramConnection(ctx context.Context) error {
|
|
resources, err := s.store.ListResources(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, resource := range resources {
|
|
if resource.Kind != ChannelSettingsKind {
|
|
continue
|
|
}
|
|
rewritten, moved, changed, err := splitLegacyChannelSettings(resource.OrgID, resource.Value)
|
|
if err != nil {
|
|
return fmt.Errorf("migrate %s of org %q: %w", ChannelSettingsKind, resource.OrgID, err)
|
|
}
|
|
if !changed {
|
|
continue
|
|
}
|
|
if moved.Token != (config.SecretRef{}) {
|
|
if err := s.addTelegramConnection(ctx, moved); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
value, err := s.definitions[ChannelSettingsKind].Decode(rewritten)
|
|
if err != nil {
|
|
return fmt.Errorf("migrate %s of org %q: %w", ChannelSettingsKind, resource.OrgID, err)
|
|
}
|
|
if err := s.putMigrated(ctx, resource.OrgID, ChannelSettingsKind, value, resource.Version); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Server) addTelegramConnection(ctx context.Context, c telegramConnection) error {
|
|
stored, err := s.store.Resource(ctx, storecontract.DefaultOrgID, ExtensionSettingsKind)
|
|
absent := errors.Is(err, storecontract.ErrResourceNotFound)
|
|
if err != nil && !absent {
|
|
return err
|
|
}
|
|
var doc controlplanerpc.ExtensionSettings
|
|
if !absent {
|
|
if err := json.Unmarshal(stored.Value, &doc); err != nil {
|
|
return fmt.Errorf("decode %s: %w", ExtensionSettingsKind, err)
|
|
}
|
|
}
|
|
encoded, err := json.Marshal(withTelegramConnection(doc, c))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
value, err := s.definitions[ExtensionSettingsKind].Decode(encoded)
|
|
if err != nil {
|
|
return fmt.Errorf("migrate telegram connection: %w", err)
|
|
}
|
|
return s.putMigrated(ctx, storecontract.DefaultOrgID, ExtensionSettingsKind, value, expectedVersion(stored, absent))
|
|
}
|
|
|
|
func (s *Server) putMigrated(ctx context.Context, orgID, kind string, value []byte, expected int64) error {
|
|
_, err := s.store.PutResource(ctx, storecontract.ResourceWrite{
|
|
OrgID: orgID, Kind: kind, Value: value, Actor: seedActor, Source: seedSource,
|
|
RequestID: "migrate:" + orgID + ":" + seedRequestID(kind, value), ExpectedVersion: expected, At: time.Now().UTC(),
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("migrate %s of org %q: %w", kind, orgID, err)
|
|
}
|
|
return nil
|
|
}
|