- 迁移 043 一次到位:runtime_instance/environment_binding 并入 browser_env(账号即环境)、 credential_reference 并入 social_account、work_source/metric_plan 并入 creator_work、 sync 租约并入 creator_collection_checkpoint(kind='sync')、audit_event 瘦列、 creator_settings 去转写列、TRUNCATE 账号域(竞品采集数据无损保留) - 统一迁移 runner:environment.Open 串起 001 账号基座 + hub 链 + 038 creator 版本回填 (v+1000) + creator 1017-1042 + 043;account/creator Open 不再迁移 - 三域 store SQL 全量适配:CreateBoundEnv 就绪门禁、SetRuntimeCleanupPending fence 语义(未知代 MissingRuntimeID 允许登记并释放活跃实例)、metric_plan 列并入 work、 checkpoint sync 租约、deletion 链路重写 - api 适配:envView 去 runtime_instance_id、audit filter 去任务列、browser_env 单表查询 - 测试:迁移 043 形态探针、迁移不可变映射新路径、legacy 迁移重放子测试重写、 fence/出口生命周期/单来源 upsert 语义覆盖;CREATORHUB_POSTGRES_TEST_URL 全绿, environment 70%/creator 67.5% 覆盖率,tsc 通过
246 lines
8.0 KiB
Go
246 lines
8.0 KiB
Go
package api
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
accountdomain "git.ipao.vip/rogee/creator-hub/internal/account"
|
|
hub "git.ipao.vip/rogee/creator-hub/internal/environment"
|
|
"github.com/gofiber/fiber/v3"
|
|
)
|
|
|
|
type accountRequest struct {
|
|
Name string `json:"name"`
|
|
Platform string `json:"platform"`
|
|
PlatformAccountKey string `json:"platform_account_key"`
|
|
Tags []string `json:"tags"`
|
|
Cookies string `json:"cookies"`
|
|
}
|
|
|
|
// RegisterAccountRoutes exposes account lifecycle routes (create/list/detail/pause/resume/revoke + audit).
|
|
func RegisterAccountRoutes(app *fiber.App, store *accountdomain.Store, runtimeStore RuntimeStopStore, credentials accountdomain.CredentialBridge) {
|
|
app.Post("/api/phase-a/accounts", func(c fiber.Ctx) error {
|
|
var input accountRequest
|
|
if err := decodePhaseA(c, &input); err != nil {
|
|
return phaseAError(c, err)
|
|
}
|
|
tags := input.Tags
|
|
if tags == nil {
|
|
tags = []string{}
|
|
}
|
|
for index := range tags {
|
|
tags[index] = strings.TrimSpace(tags[index])
|
|
}
|
|
accountID := accountdomain.NewAccountID()
|
|
account := accountdomain.Account{
|
|
ID: accountID, Name: strings.TrimSpace(input.Name), Platform: strings.TrimSpace(input.Platform),
|
|
PlatformAccountKey: strings.TrimSpace(input.PlatformAccountKey), Tags: tags, Cookies: strings.TrimSpace(input.Cookies),
|
|
CredentialReference: accountdomain.CredentialReference{ID: accountID + "-cookies", Provider: "os_keyring"},
|
|
CredentialKey: "creatorhub/" + accountID + "/cookies",
|
|
AuthorizationStatus: "authorized", RuntimeStatus: "paused", Version: 1,
|
|
}
|
|
if err := store.CreateAccount(c.Context(), account, credentials); err != nil {
|
|
if errors.Is(err, accountdomain.ErrAccountCreationUnknown) {
|
|
return c.Status(fiber.StatusServiceUnavailable).JSON(map[string]string{
|
|
"error": "account creation result is unknown", "reason_code": "account_creation_result_unknown", "account_id": accountID,
|
|
})
|
|
}
|
|
return phaseAError(c, err)
|
|
}
|
|
return c.Status(fiber.StatusCreated).JSON(account)
|
|
})
|
|
|
|
app.Get("/api/phase-a/accounts", func(c fiber.Ctx) error {
|
|
accounts, err := store.ListAccounts(c.Context())
|
|
if err != nil {
|
|
return phaseAError(c, err)
|
|
}
|
|
return c.JSON(accounts)
|
|
})
|
|
|
|
app.Get("/api/phase-a/accounts/:id", func(c fiber.Ctx) error {
|
|
account, err := store.GetAccount(c.Context(), c.Params("id"))
|
|
if err != nil {
|
|
return phaseAError(c, err)
|
|
}
|
|
return c.JSON(account)
|
|
})
|
|
|
|
app.Post("/api/phase-a/accounts/:id/pause", func(c fiber.Ctx) error {
|
|
unlock, err := lockAccountResources(c.Context(), runtimeStore, c.Params("id"))
|
|
if err != nil {
|
|
return hubError(c, err)
|
|
}
|
|
defer unlock()
|
|
if err := store.PauseAccount(c.Context(), c.Params("id")); err != nil {
|
|
return phaseAError(c, err)
|
|
}
|
|
if runtimeStore != nil {
|
|
if err := stopAccountRuntime(c.Context(), runtimeStore, c.Params("id")); err != nil {
|
|
return hubError(c, err)
|
|
}
|
|
}
|
|
return c.SendStatus(fiber.StatusNoContent)
|
|
})
|
|
|
|
app.Post("/api/phase-a/accounts/:id/resume", func(c fiber.Ctx) error {
|
|
unlock, err := lockAccountResources(c.Context(), runtimeStore, c.Params("id"))
|
|
if err != nil {
|
|
return hubError(c, err)
|
|
}
|
|
defer unlock()
|
|
if err := store.ResumeAccount(c.Context(), c.Params("id")); err != nil {
|
|
if errors.Is(err, accountdomain.ErrConflict) {
|
|
return accountResumeConflict(c, store, runtimeStore, c.Params("id"))
|
|
}
|
|
return phaseAError(c, err)
|
|
}
|
|
return c.SendStatus(fiber.StatusNoContent)
|
|
})
|
|
|
|
app.Post("/api/phase-a/accounts/:id/revoke", func(c fiber.Ctx) error {
|
|
unlock, err := lockAccountResources(c.Context(), runtimeStore, c.Params("id"))
|
|
if err != nil {
|
|
return hubError(c, err)
|
|
}
|
|
defer unlock()
|
|
if err := store.RevokeAccount(c.Context(), c.Params("id")); err != nil {
|
|
return phaseAError(c, err)
|
|
}
|
|
if runtimeStore != nil {
|
|
if err := stopAccountRuntime(c.Context(), runtimeStore, c.Params("id")); err != nil {
|
|
return hubError(c, err)
|
|
}
|
|
}
|
|
return c.SendStatus(fiber.StatusNoContent)
|
|
})
|
|
|
|
app.Get("/api/phase-a/audit", func(c fiber.Ctx) error {
|
|
filter, err := auditFilter(c)
|
|
if err != nil {
|
|
return phaseAError(c, err)
|
|
}
|
|
events, err := store.ListAudit(c.Context(), filter)
|
|
if err != nil {
|
|
return phaseAError(c, err)
|
|
}
|
|
return c.JSON(events)
|
|
})
|
|
}
|
|
|
|
func auditFilter(c fiber.Ctx) (accountdomain.AuditFilter, error) {
|
|
filter := accountdomain.AuditFilter{
|
|
AccountID: c.Query("account_id"),
|
|
BrowserEnvAlias: c.Query("browser_env_alias"), NetworkExitID: c.Query("network_exit_id"),
|
|
EventType: c.Query("event_type"), Page: 1, PageSize: 25,
|
|
}
|
|
for _, field := range []struct {
|
|
value string
|
|
target *int
|
|
}{{c.Query("page"), &filter.Page}, {c.Query("page_size"), &filter.PageSize}} {
|
|
value, target := field.value, field.target
|
|
if value == "" {
|
|
continue
|
|
}
|
|
parsed, err := strconv.Atoi(value)
|
|
if err != nil {
|
|
return accountdomain.AuditFilter{}, accountdomain.ErrInvalid
|
|
}
|
|
*target = parsed
|
|
}
|
|
for _, field := range []struct {
|
|
value string
|
|
target **time.Time
|
|
}{{c.Query("from"), &filter.From}, {c.Query("to"), &filter.To}} {
|
|
value, target := field.value, field.target
|
|
if value == "" {
|
|
continue
|
|
}
|
|
parsed, err := time.Parse(time.RFC3339, value)
|
|
if err != nil {
|
|
return accountdomain.AuditFilter{}, accountdomain.ErrInvalid
|
|
}
|
|
*target = &parsed
|
|
}
|
|
return filter, nil
|
|
}
|
|
|
|
func resumeBlockReason(account accountdomain.Account, environment hub.EnvironmentContext, bindingFound bool) string {
|
|
switch {
|
|
case account.AuthorizationStatus != "authorized":
|
|
return "account_revoked"
|
|
case !bindingFound:
|
|
return "binding_missing"
|
|
case environment.Exit.ID != "" && environment.Exit.HealthStatus != "healthy":
|
|
return "network_exit_unhealthy"
|
|
case environment.RuntimeCleanupPending:
|
|
return "runtime_stop_pending"
|
|
case environment.RuntimeID != "":
|
|
return "runtime_active"
|
|
default:
|
|
return "account_conflict"
|
|
}
|
|
}
|
|
|
|
func accountResumeConflict(c fiber.Ctx, store *accountdomain.Store, runtimeStore RuntimeStopStore, accountID string) error {
|
|
account, err := store.GetAccount(c.Context(), accountID)
|
|
if err != nil {
|
|
return phaseAError(c, err)
|
|
}
|
|
var environment hub.EnvironmentContext
|
|
bindingFound := false
|
|
if runtimeStore != nil {
|
|
environment, err = runtimeStore.GetEnvironmentContextForAccount(c.Context(), accountID)
|
|
bindingFound = err == nil
|
|
if err != nil && !errors.Is(err, hub.ErrNotFound) {
|
|
return phaseAError(c, err)
|
|
}
|
|
}
|
|
return c.Status(fiber.StatusConflict).JSON(map[string]string{
|
|
"error": accountdomain.ErrConflict.Error(), "reason_code": resumeBlockReason(account, environment, bindingFound), "readiness": "blocked",
|
|
})
|
|
}
|
|
|
|
func decodePhaseA(c fiber.Ctx, destination any) error {
|
|
decoder := json.NewDecoder(bytes.NewReader(c.Body()))
|
|
decoder.DisallowUnknownFields()
|
|
if err := decoder.Decode(destination); err != nil {
|
|
return accountdomain.ErrInvalid
|
|
}
|
|
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
|
return accountdomain.ErrInvalid
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func phaseAError(c fiber.Ctx, err error) error {
|
|
status := fiber.StatusInternalServerError
|
|
message := "phase A operation failed"
|
|
var readiness *accountdomain.ReadinessError
|
|
switch {
|
|
case errors.As(err, &readiness):
|
|
status, message = fiber.StatusConflict, "phase A version or account state changed"
|
|
if readiness.Unavailable {
|
|
status, message = fiber.StatusServiceUnavailable, "phase A resources are not ready"
|
|
}
|
|
return c.Status(status).JSON(map[string]string{"error": message, "reason_code": readiness.Reason})
|
|
case errors.Is(err, accountdomain.ErrInvalid):
|
|
status, message = fiber.StatusBadRequest, accountdomain.ErrInvalid.Error()
|
|
case errors.Is(err, accountdomain.ErrConflict):
|
|
status, message = fiber.StatusConflict, accountdomain.ErrConflict.Error()
|
|
case errors.Is(err, accountdomain.ErrNotFound):
|
|
status, message = fiber.StatusNotFound, accountdomain.ErrNotFound.Error()
|
|
}
|
|
return c.Status(status).JSON(map[string]string{"error": message})
|
|
}
|
|
|
|
// PhaseAError maps account errors to the existing HTTP contract.
|
|
func PhaseAError(c fiber.Ctx, err error) error {
|
|
return phaseAError(c, err)
|
|
}
|