diff --git a/cmd/dobotai/candidate_activation.go b/cmd/dobotai/candidate_activation.go new file mode 100644 index 0000000..e3c3db0 --- /dev/null +++ b/cmd/dobotai/candidate_activation.go @@ -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 +} diff --git a/cmd/dobotai/candidate_activation_test.go b/cmd/dobotai/candidate_activation_test.go new file mode 100644 index 0000000..ec92d88 --- /dev/null +++ b/cmd/dobotai/candidate_activation_test.go @@ -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") + } +} diff --git a/cmd/dobotai/main.go b/cmd/dobotai/main.go index 5caa43c..3b71f73 100644 --- a/cmd/dobotai/main.go +++ b/cmd/dobotai/main.go @@ -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) { diff --git a/cmd/dobotai/settings_wiring.go b/cmd/dobotai/settings_wiring.go index d83fe40..9c1d778 100644 --- a/cmd/dobotai/settings_wiring.go +++ b/cmd/dobotai/settings_wiring.go @@ -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 } diff --git a/cmd/dobotai/support_notifications_test.go b/cmd/dobotai/support_notifications_test.go index 35e568a..af4e81f 100644 --- a/cmd/dobotai/support_notifications_test.go +++ b/cmd/dobotai/support_notifications_test.go @@ -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) diff --git a/internal/adminweb/control.go b/internal/adminweb/control.go index 5fc2e66..77509ff 100644 --- a/internal/adminweb/control.go +++ b/internal/adminweb/control.go @@ -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 { diff --git a/internal/adminweb/control_test.go b/internal/adminweb/control_test.go new file mode 100644 index 0000000..ff0983d --- /dev/null +++ b/internal/adminweb/control_test.go @@ -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) + } +} diff --git a/internal/adminweb/server.go b/internal/adminweb/server.go index 0e7e535..7506f31 100644 --- a/internal/adminweb/server.go +++ b/internal/adminweb/server.go @@ -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 = `DobotAI 设置

DobotAI 配置中心

系统状态:{{.SystemState}}
Client ID:{{.ClientIDMasked}}
Client Secret:{{if .SecretConfigured}}已配置(不可查看){{else}}未配置{{end}}

配置/切换钉钉应用

新凭据会先在线验证,成功后保存;服务重启后加载新应用。

首位管理员

{{range .Components}}
{{.Name}}:{{.State}}
{{.Detail}}
{{end}}` +const settingsPage = `DobotAI 设置

DobotAI 配置中心

系统状态:{{.SystemState}}
Client ID:{{.ClientIDMasked}}
Client Secret:{{if .SecretConfigured}}已配置(不可查看){{else}}未配置{{end}}

配置/切换钉钉应用

新凭据先在线验证并保存为候选。激活后受控重启整组钉钉组件,失败自动回滚。

首位管理员

{{range .Components}}
{{.Name}}:{{.State}}
{{.Detail}}
{{end}}` 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 { diff --git a/internal/runtime/manager.go b/internal/runtime/manager.go new file mode 100644 index 0000000..45ed382 --- /dev/null +++ b/internal/runtime/manager.go @@ -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 +} diff --git a/internal/runtime/manager_test.go b/internal/runtime/manager_test.go new file mode 100644 index 0000000..787bb5f --- /dev/null +++ b/internal/runtime/manager_test.go @@ -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()) + } +} diff --git a/internal/store/postgres/settings.go b/internal/store/postgres/settings.go index 956e5f2..ec00ef3 100644 --- a/internal/store/postgres/settings.go +++ b/internal/store/postgres/settings.go @@ -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(¤tID); 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