feat: switch DingTalk applications with rollback

This commit is contained in:
姚章浩
2026-08-13 13:36:26 +08:00
parent 0fc64ba77d
commit b207ee4089
11 changed files with 645 additions and 19 deletions
+81
View File
@@ -0,0 +1,81 @@
package main
import (
"context"
"errors"
"time"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/dingtalkconfig"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/questiontable"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/secretstore"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings"
)
type candidateConfigRepository interface {
CandidateDingTalkConfig(context.Context, string) (string, string, error)
ActivateDingTalkCandidate(context.Context, string, string) error
}
type candidateCredentialVerifier interface {
Verify(context.Context, string, string) dingtalkconfig.Result
}
var (
candidateTokenURL = ""
candidateTableBaseURL = ""
)
type dingTalkCandidateActivator struct {
tenant string
repo candidateConfigRepository
secrets *secretstore.Store
verifier candidateCredentialVerifier
bindings map[string]settings.ResourceBinding
restart func()
}
func (a *dingTalkCandidateActivator) ActivateCandidate(ctx context.Context) error {
if a == nil || a.repo == nil || a.secrets == nil || a.verifier == nil || a.restart == nil {
return errors.New("candidate_activation_unavailable")
}
clientID, secretRef, err := a.repo.CandidateDingTalkConfig(ctx, a.tenant)
if err != nil {
return errors.New("candidate_not_found")
}
secret, err := a.secrets.Get(secretRef)
if err != nil {
return errors.New("candidate_secret_unavailable")
}
if result := a.verifier.Verify(ctx, clientID, secret); !result.OK {
return errors.New("candidate_oauth_failed")
}
for _, kind := range []string{"question_table", "faq_table"} {
binding, ok := a.bindings[kind]
if !ok {
continue
}
client, err := questiontable.NewClient(questiontable.Config{ClientID: clientID, Secret: secret, BaseID: binding.BaseID, SheetID: binding.SheetID, OperatorID: binding.OperatorID, TokenURL: candidateTokenURL, BaseURL: candidateTableBaseURL}, nil)
if err != nil {
return errors.New("candidate_table_config_failed")
}
fields, err := client.ReadFields(ctx)
if err != nil {
return errors.New("candidate_table_probe_failed")
}
required := questiontable.QuestionSchema()
if kind == "faq_table" {
required = questiontable.FAQSchema()
}
if _, err = questiontable.MapRequiredFields(fields, required); err != nil {
return errors.New("candidate_table_schema_failed")
}
}
if err := a.repo.ActivateDingTalkCandidate(ctx, a.tenant, secretRef); err != nil {
return errors.New("candidate_database_activation_failed")
}
go func() {
time.Sleep(300 * time.Millisecond)
a.restart()
}()
return nil
}
+75
View File
@@ -0,0 +1,75 @@
package main
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/dingtalkconfig"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/secretstore"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings"
)
type candidateRepoStub struct {
activated bool
ref string
}
func (r *candidateRepoStub) CandidateDingTalkConfig(context.Context, string) (string, string, error) {
return "app", r.ref, nil
}
func (r *candidateRepoStub) ActivateDingTalkCandidate(context.Context, string, string) error {
r.activated = true
return nil
}
type candidateVerifierStub struct{ ok bool }
func (v candidateVerifierStub) Verify(context.Context, string, string) dingtalkconfig.Result {
return dingtalkconfig.Result{OK: v.ok}
}
func TestCandidateActivatorRejectsOAuthWithoutActivation(t *testing.T) {
secrets, _ := secretstore.New(t.TempDir())
ref, _ := secrets.Put("dingtalk", "secret")
repo := &candidateRepoStub{ref: ref}
a := &dingTalkCandidateActivator{tenant: "t", repo: repo, secrets: secrets, verifier: candidateVerifierStub{}, bindings: map[string]settings.ResourceBinding{}, restart: func() {}}
if err := a.ActivateCandidate(context.Background()); err == nil {
t.Fatal("expected error")
}
if repo.activated {
t.Fatal("must not activate")
}
}
func TestCandidateActivatorValidatesSchemasThenActivates(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/token", func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"accessToken":"token","expireIn":7200}`))
})
mux.HandleFunc("/v1.0/notable/bases/base/sheets/sheet/fields", func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"value":[{"id":"q","name":"中文问题","type":"text"},{"id":"tm","name":"提问时间","type":"date"},{"id":"u","name":"提问人","type":"user"},{"id":"o","name":"原始问题","type":"text"},{"id":"a","name":"AI答案","type":"text"},{"id":"p","name":"流程触发人员信息","type":"text"},{"id":"l","name":"语言","type":"text"},{"id":"d","name":"部门","type":"text"},{"id":"r","name":"区域","type":"text"}]}`))
})
server := httptest.NewServer(mux)
defer server.Close()
secrets, _ := secretstore.New(t.TempDir())
ref, _ := secrets.Put("dingtalk", "secret")
repo := &candidateRepoStub{ref: ref}
restarted := make(chan struct{}, 1)
a := &dingTalkCandidateActivator{tenant: "t", repo: repo, secrets: secrets, verifier: candidateVerifierStub{ok: true}, bindings: map[string]settings.ResourceBinding{"question_table": {BaseID: "base", SheetID: "sheet", OperatorID: "u"}}, restart: func() { restarted <- struct{}{} }}
oldTokenURL, oldBaseURL := candidateTokenURL, candidateTableBaseURL
candidateTokenURL, candidateTableBaseURL = server.URL+"/token", server.URL
defer func() { candidateTokenURL, candidateTableBaseURL = oldTokenURL, oldBaseURL }()
if err := a.ActivateCandidate(context.Background()); err != nil {
t.Fatal(err)
}
if !repo.activated {
t.Fatal("expected activation")
}
select {
case <-restarted:
case <-time.After(time.Second):
t.Fatal("restart not requested")
}
}
+37 -1
View File
@@ -8,6 +8,7 @@ import (
"os"
"os/signal"
"strings"
"sync/atomic"
"syscall"
"time"
@@ -43,6 +44,7 @@ func runtimeBuildInfo() httpapi.BuildInfo {
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
var restartRequested atomic.Bool
storeCtx, storeCancel := context.WithTimeout(ctx, 10*time.Second)
defer storeCancel()
store, err := postgres.Open(storeCtx, os.Getenv("DATABASE_URL"))
@@ -111,6 +113,12 @@ func main() {
if err != nil {
log.Fatal(err)
}
settingsRuntime.admin.SetCandidateActivator(&dingTalkCandidateActivator{
tenant: dingCfg.TenantKey, repo: settingsRuntime.repository, secrets: settingsRuntime.secrets,
verifier: settingsRuntime.verifier, bindings: activeBindings,
restart: func() { restartRequested.Store(true); cancel() },
})
runtimeReady := make(chan struct{})
faqCfg, err := readFAQConfig()
if err != nil {
log.Fatal(err)
@@ -136,6 +144,11 @@ func main() {
faqWorkflowDone = make(chan struct{})
go func() {
defer close(faqWorkflowDone)
select {
case <-runtimeReady:
case <-ctx.Done():
return
}
runFAQPoller(ctx, faqDispatcher, 5*time.Second)
}()
log.Printf("DingTalk FAQ table dispatcher started")
@@ -156,7 +169,14 @@ func main() {
log.Fatalf("DingTalk support notification init failed: %v", err)
}
if supportDispatcher != nil {
go runSupportDispatcher(ctx, supportDispatcher, 5*time.Second)
go func() {
select {
case <-runtimeReady:
case <-ctx.Done():
return
}
runSupportDispatcher(ctx, supportDispatcher, 5*time.Second)
}()
log.Printf("DingTalk support notification dispatcher started")
}
// Question table dispatcher (optional, fail-closed).
@@ -180,6 +200,11 @@ func main() {
questionTableDone = make(chan struct{})
go func() {
defer close(questionTableDone)
select {
case <-runtimeReady:
case <-ctx.Done():
return
}
runQuestionTablePoller(ctx, qtDispatcher, 5*time.Second)
}()
log.Printf("DingTalk question table dispatcher started")
@@ -270,8 +295,13 @@ func main() {
log.Fatal(err)
}
defer streamClient.Close()
if err := settingsRuntime.repository.MarkDingTalkRuntimeHealthy(context.Background(), dingCfg.TenantKey, settingsRuntime.secretRef); err != nil {
streamClient.Close()
log.Fatal(err)
}
log.Printf("DingTalk Stream ingress started for tenant %s", dingCfg.TenantKey)
}
close(runtimeReady)
rootHandler := http.NewServeMux()
rootHandler.Handle("/", api.Handler())
if strings.TrimSpace(os.Getenv("DOBOTAI_ADMIN_TOKEN")) != "" {
@@ -305,6 +335,12 @@ func main() {
log.Printf("question table poller shutdown timed out")
}
}
if streamClient != nil {
streamClient.Close()
}
if restartRequested.Load() {
os.Exit(75)
}
}
func buildAuditOptions(repo audit.TurnRepository, tenantKey, adminToken, address string) (httpapi.Options, error) {
+16 -7
View File
@@ -29,11 +29,15 @@ func (r *dingTalkSettingsRouter) Handle(ctx context.Context, m dingtalk.Settings
}
type settingsRuntime struct {
repository *postgres.SettingsRepository
controller *settings.Controller
admin *adminweb.ControlService
clientID string
secret string
repository *postgres.SettingsRepository
controller *settings.Controller
admin *adminweb.ControlService
clientID string
secret string
secretRef string
secrets *secretstore.Store
verifier *dingtalkconfig.Verifier
pendingActivation bool
}
func buildSettingsRuntime(ctx context.Context, store *postgres.Store, tenantKey string) (*settingsRuntime, error) {
@@ -57,6 +61,10 @@ func buildSettingsRuntime(ctx context.Context, store *postgres.Store, tenantKey
if err != nil {
return nil, err
}
pendingActivation, err := repo.PrepareDingTalkRuntimeStart(ctx, tenantKey)
if err != nil {
return nil, err
}
clientID, secretRef, _, err := repo.ActiveDingTalkConfig(ctx, tenantKey)
if err != nil {
return nil, err
@@ -79,10 +87,11 @@ func buildSettingsRuntime(ctx context.Context, store *postgres.Store, tenantKey
return nil, err
}
}
control, err := adminweb.NewControlService(tenantKey, repo, secrets, dingtalkconfig.NewVerifier("https://oapi.dingtalk.com/gettoken", nil))
verifier := dingtalkconfig.NewVerifier("https://oapi.dingtalk.com/gettoken", nil)
control, err := adminweb.NewControlService(tenantKey, repo, secrets, verifier)
if err != nil {
return nil, err
}
validatedRepo := &validatedSettingsRepository{SettingsRepository: repo, clientID: clientID, secret: secret}
return &settingsRuntime{repository: repo, controller: settings.NewController(validatedRepo), admin: control, clientID: clientID, secret: secret}, nil
return &settingsRuntime{repository: repo, controller: settings.NewController(validatedRepo), admin: control, clientID: clientID, secret: secret, secretRef: secretRef, secrets: secrets, verifier: verifier, pendingActivation: pendingActivation}, nil
}
+2 -1
View File
@@ -163,7 +163,8 @@ func TestMainWiresCoverageSupportNotifications(t *testing.T) {
`os.Getenv("DINGTALK_SUPPORT_GROUP_OPEN_CONVERSATION_ID")`,
`coverage.NewService(store)`,
`qa.WithSucceededTurnObserver`,
`go runSupportDispatcher(ctx, supportDispatcher, 5*time.Second)`,
`case <-runtimeReady:`,
`runSupportDispatcher(ctx, supportDispatcher, 5*time.Second)`,
} {
if !strings.Contains(source, fragment) {
t.Errorf("main support notification wiring missing %q", fragment)
+28 -5
View File
@@ -13,20 +13,24 @@ import (
type ConfigRepository interface {
ActiveDingTalkConfig(context.Context, string) (string, string, bool, error)
CandidateDingTalkConfig(context.Context, string) (string, string, error)
SaveDingTalkConfig(context.Context, string, string, string, bool) error
MarkDingTalkCandidateFailed(context.Context, string, string, string) error
AdministratorCount(context.Context, string) (int, error)
ActiveBindings(context.Context, string) (map[string]settings.ResourceBinding, error)
CreateBootstrapChallenge(context.Context, string, string, time.Time) error
ConfirmBootstrap(context.Context, string) error
}
type CandidateActivator interface{ ActivateCandidate(context.Context) error }
type CredentialVerifier interface {
Verify(context.Context, string, string) dingtalkconfig.Result
}
type ControlService struct {
tenant string
repo ConfigRepository
secrets *secretstore.Store
verifier CredentialVerifier
tenant string
repo ConfigRepository
secrets *secretstore.Store
verifier CredentialVerifier
activator CandidateActivator
}
func NewControlService(tenant string, repo ConfigRepository, secrets *secretstore.Store, verifier CredentialVerifier) (*ControlService, error) {
@@ -57,14 +61,33 @@ func (s *ControlService) VerifyCredentials(ctx context.Context, id, secret strin
return Verification{OK: r.OK, Code: r.Code, CheckedAt: r.CheckedAt}
}
func (s *ControlService) SaveCredentials(ctx context.Context, id, secret string) error {
_, oldRef, _ := s.repo.CandidateDingTalkConfig(ctx, s.tenant)
ref, err := s.secrets.Put("dingtalk", secret)
if err != nil {
return err
}
if err = s.repo.SaveDingTalkConfig(ctx, s.tenant, strings.TrimSpace(id), ref, true); err != nil {
if err = s.repo.SaveDingTalkConfig(ctx, s.tenant, strings.TrimSpace(id), ref, false); err != nil {
_ = s.secrets.Delete(ref)
return err
}
if oldRef != "" && oldRef != ref {
_ = s.secrets.Delete(oldRef)
}
return nil
}
func (s *ControlService) SetCandidateActivator(activator CandidateActivator) { s.activator = activator }
func (s *ControlService) ActivateCandidate(ctx context.Context) error {
if s.activator == nil {
return errors.New("candidate activator unavailable")
}
_, ref, err := s.repo.CandidateDingTalkConfig(ctx, s.tenant)
if err != nil {
return err
}
if err = s.activator.ActivateCandidate(ctx); err != nil {
_ = s.repo.MarkDingTalkCandidateFailed(ctx, s.tenant, ref, "activation_failed")
return errors.New("candidate activation failed")
}
return nil
}
func (s *ControlService) CreateBootstrap(ctx context.Context, code string) error {
+97
View File
@@ -0,0 +1,97 @@
package adminweb
import (
"context"
"errors"
"testing"
"time"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/dingtalkconfig"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/secretstore"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings"
)
type controlRepo struct {
savedVerified bool
savedRef string
candidateRef string
failedCode string
}
func (*controlRepo) ActiveDingTalkConfig(context.Context, string) (string, string, bool, error) {
return "old", "old-ref", true, nil
}
func (r *controlRepo) CandidateDingTalkConfig(context.Context, string) (string, string, error) {
return "new", r.candidateRef, nil
}
func (r *controlRepo) SaveDingTalkConfig(_ context.Context, _, _, ref string, verified bool) error {
r.savedRef = ref
r.savedVerified = verified
r.candidateRef = ref
return nil
}
func (r *controlRepo) MarkDingTalkCandidateFailed(_ context.Context, _, _, code string) error {
r.failedCode = code
return nil
}
func (*controlRepo) AdministratorCount(context.Context, string) (int, error) { return 1, nil }
func (*controlRepo) ActiveBindings(context.Context, string) (map[string]settings.ResourceBinding, error) {
return map[string]settings.ResourceBinding{}, nil
}
func (*controlRepo) CreateBootstrapChallenge(context.Context, string, string, time.Time) error {
return nil
}
func (*controlRepo) ConfirmBootstrap(context.Context, string) error { return nil }
type verifyOK struct{}
func (verifyOK) Verify(context.Context, string, string) dingtalkconfig.Result {
return dingtalkconfig.Result{OK: true, Code: "oauth_ok"}
}
type activatorStub struct {
err error
calls int
}
func (a *activatorStub) ActivateCandidate(context.Context) error { a.calls++; return a.err }
func TestSaveCredentialsCreatesCandidateNotActive(t *testing.T) {
secrets, err := secretstore.New(t.TempDir())
if err != nil {
t.Fatal(err)
}
repo := &controlRepo{}
service, err := NewControlService("tenant", repo, secrets, verifyOK{})
if err != nil {
t.Fatal(err)
}
if err = service.SaveCredentials(context.Background(), "new", "secret"); err != nil {
t.Fatal(err)
}
if repo.savedVerified {
t.Fatal("candidate must not be active")
}
if repo.savedRef == "" || !secrets.Configured(repo.savedRef) {
t.Fatalf("ref=%q", repo.savedRef)
}
}
func TestActivateCandidateDelegatesAndMarksFailure(t *testing.T) {
secrets, err := secretstore.New(t.TempDir())
if err != nil {
t.Fatal(err)
}
repo := &controlRepo{candidateRef: "candidate-ref"}
activator := &activatorStub{err: errors.New("candidate_start_failed_rolled_back")}
service, err := NewControlService("tenant", repo, secrets, verifyOK{})
if err != nil {
t.Fatal(err)
}
service.SetCandidateActivator(activator)
if err = service.ActivateCandidate(context.Background()); err == nil {
t.Fatal("expected failure")
}
if activator.calls != 1 || repo.failedCode != "activation_failed" {
t.Fatalf("calls=%d code=%q", activator.calls, repo.failedCode)
}
}
+18 -1
View File
@@ -30,6 +30,9 @@ type BootstrapService interface {
CreateBootstrap(context.Context, string) error
ConfirmBootstrap(context.Context) error
}
type CandidateService interface {
ActivateCandidate(context.Context) error
}
type server struct {
service Service
token string
@@ -37,13 +40,14 @@ type server struct {
page *template.Template
}
const settingsPage = `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>DobotAI 设置</title><style>body{font-family:sans-serif;background:#f5f8ff;color:#17324d;max-width:960px;margin:40px auto;padding:0 20px}.card{background:white;border:1px solid #dbe7f4;border-radius:14px;padding:20px;margin:14px 0}input{padding:10px;width:95%;margin:6px 0}button{padding:10px 18px;background:#1677ff;color:white;border:0;border-radius:8px;margin:5px}</style></head><body><h1>DobotAI 配置中心</h1><div class="card"><b>系统状态:</b>{{.SystemState}}<br><b>Client ID:</b>{{.ClientIDMasked}}<br><b>Client Secret:</b>{{if .SecretConfigured}}已配置(不可查看){{else}}未配置{{end}}</div><div class="card"><h2>配置/切换钉钉应用</h2><p>新凭据会先在线验证,成功后保存;服务重启后加载新应用。</p><form method="post" action="/admin/setup/credentials"><label>Client ID / AppKey</label><input name="client_id" required><label>Client Secret / AppSecret</label><input type="password" name="client_secret" required autocomplete="new-password"><button>测试并保存</button></form></div><div class="card"><h2>首位管理员</h2><form method="post" action="/admin/setup/bootstrap"><input name="code" pattern="[0-9]{6}" placeholder="输入任意6位一次性绑定码" required><button>生成绑定码</button></form><form method="post" action="/admin/setup/bootstrap/confirm"><button>确认检测到的管理员</button></form></div>{{range .Components}}<div class="card"><b>{{.Name}}</b>:{{.State}}<br>{{.Detail}}</div>{{end}}</body></html>`
const settingsPage = `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>DobotAI 设置</title><style>body{font-family:sans-serif;background:#f5f8ff;color:#17324d;max-width:960px;margin:40px auto;padding:0 20px}.card{background:white;border:1px solid #dbe7f4;border-radius:14px;padding:20px;margin:14px 0}input{padding:10px;width:95%;margin:6px 0}button{padding:10px 18px;background:#1677ff;color:white;border:0;border-radius:8px;margin:5px}</style></head><body><h1>DobotAI 配置中心</h1><div class="card"><b>系统状态:</b>{{.SystemState}}<br><b>Client ID:</b>{{.ClientIDMasked}}<br><b>Client Secret:</b>{{if .SecretConfigured}}已配置(不可查看){{else}}未配置{{end}}</div><div class="card"><h2>配置/切换钉钉应用</h2><p>新凭据先在线验证并保存为候选。激活后受控重启整组钉钉组件,失败自动回滚。</p><form method="post" action="/admin/setup/credentials"><label>Client ID / AppKey</label><input name="client_id" required><label>Client Secret / AppSecret</label><input type="password" name="client_secret" required autocomplete="new-password"><button>验证并保存候选</button></form><form method="post" action="/admin/setup/candidate/activate"><button>激活候选并重启</button></form></div><div class="card"><h2>首位管理员</h2><form method="post" action="/admin/setup/bootstrap"><input name="code" pattern="[0-9]{6}" placeholder="输入任意6位一次性绑定码" required><button>生成绑定码</button></form><form method="post" action="/admin/setup/bootstrap/confirm"><button>确认检测到的管理员</button></form></div>{{range .Components}}<div class="card"><b>{{.Name}}</b>:{{.State}}<br>{{.Detail}}</div>{{end}}</body></html>`
func New(service Service, token string) http.Handler {
s := &server{service: service, token: strings.TrimSpace(token), mux: http.NewServeMux(), page: template.Must(template.New("settings").Parse(settingsPage))}
s.mux.HandleFunc("GET /admin/settings", s.settings)
s.mux.HandleFunc("GET /admin/setup", s.settings)
s.mux.HandleFunc("POST /admin/setup/credentials", s.saveCredentials)
s.mux.HandleFunc("POST /admin/setup/candidate/activate", s.activateCandidate)
s.mux.HandleFunc("POST /admin/setup/bootstrap", s.createBootstrap)
s.mux.HandleFunc("POST /admin/setup/bootstrap/confirm", s.confirmBootstrap)
return s
@@ -94,6 +98,19 @@ func (s *server) saveCredentials(w http.ResponseWriter, r *http.Request) {
}
http.Redirect(w, r, "/admin/settings", http.StatusSeeOther)
}
func (s *server) activateCandidate(w http.ResponseWriter, r *http.Request) {
service, ok := s.service.(CandidateService)
if !ok {
http.Error(w, "candidate unavailable", http.StatusNotImplemented)
return
}
if err := service.ActivateCandidate(r.Context()); err != nil {
http.Error(w, "candidate activation failed", http.StatusConflict)
return
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
_, _ = w.Write([]byte("候选已激活,DobotAI正在受控重启。\n"))
}
func (s *server) createBootstrap(w http.ResponseWriter, r *http.Request) {
service, ok := s.service.(BootstrapService)
if !ok {
+102
View File
@@ -0,0 +1,102 @@
package runtime
import (
"context"
"errors"
"sync"
"time"
)
type Credentials struct {
ClientID string
Secret string
Ref string
}
type Component interface {
Start(context.Context, Credentials) error
Stop(context.Context) error
}
type Status struct {
State string
ClientID string
LastCode string
UpdatedAt time.Time
}
type Manager struct {
mu sync.Mutex
component Component
active Credentials
status Status
}
func NewManager(component Component) *Manager {
return &Manager{component: component, status: Status{State: "stopped", UpdatedAt: time.Now()}}
}
func (m *Manager) Start(ctx context.Context, credentials Credentials) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.component == nil {
return errors.New("runtime_component_required")
}
if m.status.State == "running" {
return errors.New("runtime_already_running")
}
if err := m.component.Start(ctx, credentials); err != nil {
m.status = Status{State: "error", LastCode: "active_start_failed", UpdatedAt: time.Now()}
return errors.New("active_start_failed")
}
m.active = credentials
m.status = Status{State: "running", ClientID: credentials.ClientID, UpdatedAt: time.Now()}
return nil
}
func (m *Manager) Switch(ctx context.Context, candidate Credentials) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.component == nil {
return errors.New("runtime_component_required")
}
old := m.active
m.status = Status{State: "switching", ClientID: old.ClientID, UpdatedAt: time.Now()}
if err := m.component.Stop(ctx); err != nil {
m.status = Status{State: "running", ClientID: old.ClientID, LastCode: "active_stop_failed", UpdatedAt: time.Now()}
return errors.New("active_stop_failed")
}
if err := m.component.Start(ctx, candidate); err == nil {
m.active = candidate
m.status = Status{State: "running", ClientID: candidate.ClientID, LastCode: "switch_ok", UpdatedAt: time.Now()}
return nil
}
if old.ClientID != "" && m.component.Start(ctx, old) == nil {
m.active = old
m.status = Status{State: "running", ClientID: old.ClientID, LastCode: "candidate_start_failed_rolled_back", UpdatedAt: time.Now()}
return errors.New("candidate_start_failed_rolled_back")
}
m.active = Credentials{}
m.status = Status{State: "error", LastCode: "rollback_failed", UpdatedAt: time.Now()}
return errors.New("rollback_failed")
}
func (m *Manager) Stop(ctx context.Context) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.component == nil || m.status.State == "stopped" {
return nil
}
if err := m.component.Stop(ctx); err != nil {
return errors.New("runtime_stop_failed")
}
m.active = Credentials{}
m.status = Status{State: "stopped", UpdatedAt: time.Now()}
return nil
}
func (m *Manager) Status() Status {
m.mu.Lock()
defer m.mu.Unlock()
return m.status
}
+88
View File
@@ -0,0 +1,88 @@
package runtime
import (
"context"
"errors"
"sync"
"testing"
)
type fakeComponent struct {
mu sync.Mutex
running string
starts []string
stops int
fail map[string]error
}
func (f *fakeComponent) Start(_ context.Context, cfg Credentials) error {
f.mu.Lock()
defer f.mu.Unlock()
if f.running != "" {
return errors.New("already_running")
}
f.starts = append(f.starts, cfg.ClientID)
if err := f.fail[cfg.ClientID]; err != nil {
return err
}
f.running = cfg.ClientID
return nil
}
func (f *fakeComponent) Stop(context.Context) error {
f.mu.Lock()
defer f.mu.Unlock()
f.stops++
f.running = ""
return nil
}
func TestManagerSwitchesWithAtMostOneRuntime(t *testing.T) {
component := &fakeComponent{fail: map[string]error{}}
m := NewManager(component)
if err := m.Start(context.Background(), Credentials{ClientID: "old", Secret: "s1"}); err != nil {
t.Fatal(err)
}
if err := m.Switch(context.Background(), Credentials{ClientID: "new", Secret: "s2"}); err != nil {
t.Fatal(err)
}
if component.running != "new" || component.stops != 1 {
t.Fatalf("running=%q stops=%d", component.running, component.stops)
}
status := m.Status()
if status.ClientID != "new" || status.State != "running" {
t.Fatalf("status=%+v", status)
}
}
func TestManagerRollsBackWhenCandidateFails(t *testing.T) {
component := &fakeComponent{fail: map[string]error{"bad": errors.New("stream_failed")}}
m := NewManager(component)
if err := m.Start(context.Background(), Credentials{ClientID: "old", Secret: "s1"}); err != nil {
t.Fatal(err)
}
if err := m.Switch(context.Background(), Credentials{ClientID: "bad", Secret: "s2"}); err == nil {
t.Fatal("expected failure")
}
if component.running != "old" {
t.Fatalf("running=%q starts=%v", component.running, component.starts)
}
status := m.Status()
if status.State != "running" || status.LastCode != "candidate_start_failed_rolled_back" {
t.Fatalf("status=%+v", status)
}
}
func TestManagerReportsRollbackFailure(t *testing.T) {
component := &fakeComponent{fail: map[string]error{"bad": errors.New("bad"), "old": nil}}
m := NewManager(component)
if err := m.Start(context.Background(), Credentials{ClientID: "old", Secret: "s1"}); err != nil {
t.Fatal(err)
}
component.fail["old"] = errors.New("old_failed")
if err := m.Switch(context.Background(), Credentials{ClientID: "bad", Secret: "s2"}); err == nil {
t.Fatal("expected failure")
}
if m.Status().State != "error" || m.Status().LastCode != "rollback_failed" {
t.Fatalf("status=%+v", m.Status())
}
}
+101 -4
View File
@@ -75,7 +75,7 @@ func (r *SettingsRepository) SaveBinding(ctx context.Context, b settings.Resourc
if err = tx.QueryRow(ctx, `SELECT COALESCE(MAX(revision),0)+1 FROM system_resource_bindings WHERE tenant_key=$1 AND kind=$2`, b.TenantKey, b.Kind).Scan(&rev); err != nil {
return err
}
state := "candidate"
state := "validated"
var validatedAt, activatedAt interface{}
if b.Activate {
state = "active"
@@ -159,11 +159,10 @@ func (r *SettingsRepository) AdministratorCount(ctx context.Context, tenant stri
}
func (r *SettingsRepository) SaveDingTalkConfig(ctx context.Context, tenant, clientID, secretRef string, verified bool) error {
payload, _ := json.Marshal(map[string]string{"client_id": clientID})
state := "draft"
validation := "pending"
state := "validated"
validation := "ok"
if verified {
state = "active"
validation = "ok"
}
tx, err := r.store.pool.Begin(ctx)
if err != nil {
@@ -185,6 +184,104 @@ func (r *SettingsRepository) SaveDingTalkConfig(ctx context.Context, tenant, cli
}
return tx.Commit(ctx)
}
func (r *SettingsRepository) CandidateDingTalkConfig(ctx context.Context, tenant string) (clientID, secretRef string, err error) {
var payload []byte
err = r.store.pool.QueryRow(ctx, `SELECT public_config,secret_ref FROM system_config_revisions WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='validated' AND validation_status='ok' ORDER BY revision DESC LIMIT 1`, tenant).Scan(&payload, &secretRef)
if err != nil {
return
}
var value map[string]string
if json.Unmarshal(payload, &value) != nil {
return "", "", errors.New("decode dingtalk candidate")
}
return value["client_id"], secretRef, nil
}
func (r *SettingsRepository) ActivateDingTalkCandidate(ctx context.Context, tenant, secretRef string) error {
tx, err := r.store.pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
var candidateID string
err = tx.QueryRow(ctx, `SELECT id FROM system_config_revisions WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='validated' AND secret_ref=$2 AND validation_status='ok' FOR UPDATE`, tenant, secretRef).Scan(&candidateID)
if err != nil {
return err
}
if _, err = tx.Exec(ctx, `UPDATE system_config_revisions SET state='retired' WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='active'`, tenant); err != nil {
return err
}
if _, err = tx.Exec(ctx, `UPDATE system_config_revisions SET state='active',validation_code='pending_runtime',activated_at=NOW() WHERE id=$1`, candidateID); err != nil {
return err
}
return tx.Commit(ctx)
}
func (r *SettingsRepository) PrepareDingTalkRuntimeStart(ctx context.Context, tenant string) (bool, error) {
tx, err := r.store.pool.Begin(ctx)
if err != nil {
return false, err
}
defer tx.Rollback(ctx)
var activeID, activeRef, code string
err = tx.QueryRow(ctx, `SELECT id,secret_ref,validation_code FROM system_config_revisions WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='active' FOR UPDATE`, tenant).Scan(&activeID, &activeRef, &code)
if errors.Is(err, pgx.ErrNoRows) {
return false, tx.Commit(ctx)
}
if err != nil {
return false, err
}
switch code {
case "pending_runtime":
if _, err = tx.Exec(ctx, `UPDATE system_config_revisions SET validation_code='runtime_starting' WHERE id=$1`, activeID); err != nil {
return false, err
}
return true, tx.Commit(ctx)
case "runtime_starting":
var oldID string
if err = tx.QueryRow(ctx, `SELECT id FROM system_config_revisions WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='retired' AND validation_status='ok' ORDER BY revision DESC LIMIT 1 FOR UPDATE`, tenant).Scan(&oldID); err != nil {
return false, err
}
if _, err = tx.Exec(ctx, `UPDATE system_config_revisions SET state='failed',validation_status='failed',validation_code='runtime_start_failed' WHERE id=$1`, activeID); err != nil {
return false, err
}
if _, err = tx.Exec(ctx, `UPDATE system_config_revisions SET state='active',validation_code='rollback_restored',activated_at=NOW() WHERE id=$1`, oldID); err != nil {
return false, err
}
return false, tx.Commit(ctx)
default:
_ = activeRef
return false, tx.Commit(ctx)
}
}
func (r *SettingsRepository) MarkDingTalkRuntimeHealthy(ctx context.Context, tenant, secretRef string) error {
_, err := r.store.pool.Exec(ctx, `UPDATE system_config_revisions SET validation_code='runtime_ok' WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='active' AND secret_ref=$2`, tenant, secretRef)
return err
}
func (r *SettingsRepository) RollbackPendingDingTalkActivation(ctx context.Context, tenant, failedRef string) error {
tx, err := r.store.pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
var currentID string
if err = tx.QueryRow(ctx, `SELECT id FROM system_config_revisions WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='active' AND secret_ref=$2 AND validation_code='pending_runtime' FOR UPDATE`, tenant, failedRef).Scan(&currentID); err != nil {
return err
}
var oldID string
if err = tx.QueryRow(ctx, `SELECT id FROM system_config_revisions WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='retired' AND validation_status='ok' ORDER BY revision DESC LIMIT 1 FOR UPDATE`, tenant).Scan(&oldID); err != nil {
return err
}
if _, err = tx.Exec(ctx, `UPDATE system_config_revisions SET state='failed',validation_status='failed',validation_code='runtime_start_failed' WHERE id=$1`, currentID); err != nil {
return err
}
if _, err = tx.Exec(ctx, `UPDATE system_config_revisions SET state='active',validation_code='rollback_restored',activated_at=NOW() WHERE id=$1`, oldID); err != nil {
return err
}
return tx.Commit(ctx)
}
func (r *SettingsRepository) MarkDingTalkCandidateFailed(ctx context.Context, tenant, secretRef, code string) error {
_, err := r.store.pool.Exec(ctx, `UPDATE system_config_revisions SET state='failed',validation_status='failed',validation_code=$3 WHERE tenant_key=$1 AND kind='dingtalk_app' AND state='validated' AND secret_ref=$2`, tenant, secretRef, code)
return err
}
func (r *SettingsRepository) ActiveDingTalkConfig(ctx context.Context, tenant string) (clientID, secretRef string, verified bool, err error) {
var payload []byte
var status string