account.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. // Package schema 定义 Ent ORM 的数据库 schema。
  2. // 每个文件对应一个数据库实体(表),定义其字段、边(关联)和索引。
  3. package schema
  4. import (
  5. "github.com/Wei-Shaw/sub2api/ent/schema/mixins"
  6. "github.com/Wei-Shaw/sub2api/internal/domain"
  7. "entgo.io/ent"
  8. "entgo.io/ent/dialect"
  9. "entgo.io/ent/dialect/entsql"
  10. "entgo.io/ent/schema"
  11. "entgo.io/ent/schema/edge"
  12. "entgo.io/ent/schema/field"
  13. "entgo.io/ent/schema/index"
  14. )
  15. // Account 定义 AI API 账户实体的 schema。
  16. //
  17. // 账户是系统的核心资源,代表一个可用于调用 AI API 的凭证。
  18. // 例如:一个 Claude API 账户、一个 Gemini OAuth 账户等。
  19. //
  20. // 主要功能:
  21. // - 存储不同平台(Claude、Gemini、OpenAI 等)的 API 凭证
  22. // - 支持多种认证类型(api_key、oauth、cookie 等)
  23. // - 管理账户的调度状态(可调度、速率限制、过载等)
  24. // - 通过分组机制实现账户的灵活分配
  25. type Account struct {
  26. ent.Schema
  27. }
  28. // Annotations 返回 schema 的注解配置。
  29. // 这里指定数据库表名为 "accounts"。
  30. func (Account) Annotations() []schema.Annotation {
  31. return []schema.Annotation{
  32. entsql.Annotation{Table: "accounts"},
  33. }
  34. }
  35. // Mixin 返回该 schema 使用的混入组件。
  36. // - TimeMixin: 自动管理 created_at 和 updated_at 时间戳
  37. // - SoftDeleteMixin: 提供软删除功能(deleted_at)
  38. func (Account) Mixin() []ent.Mixin {
  39. return []ent.Mixin{
  40. mixins.TimeMixin{},
  41. mixins.SoftDeleteMixin{},
  42. }
  43. }
  44. // Fields 定义账户实体的所有字段。
  45. func (Account) Fields() []ent.Field {
  46. return []ent.Field{
  47. // name: 账户显示名称,用于在界面中标识账户
  48. field.String("name").
  49. MaxLen(100).
  50. NotEmpty(),
  51. // notes: 管理员备注(可为空)
  52. field.String("notes").
  53. Optional().
  54. Nillable().
  55. SchemaType(map[string]string{dialect.Postgres: "text"}),
  56. // platform: 所属平台,如 "claude", "gemini", "openai" 等
  57. field.String("platform").
  58. MaxLen(50).
  59. NotEmpty(),
  60. // type: 认证类型,如 "api_key", "oauth", "cookie" 等
  61. // 不同类型决定了 credentials 中存储的数据结构
  62. field.String("type").
  63. MaxLen(20).
  64. NotEmpty(),
  65. // credentials: 认证凭证,以 JSONB 格式存储
  66. // 结构取决于 type 字段:
  67. // - api_key: {"api_key": "sk-xxx"}
  68. // - oauth: {"access_token": "...", "refresh_token": "...", "expires_at": "..."}
  69. // - cookie: {"session_key": "..."}
  70. field.JSON("credentials", map[string]any{}).
  71. Default(func() map[string]any { return map[string]any{} }).
  72. SchemaType(map[string]string{dialect.Postgres: "jsonb"}),
  73. // extra: 扩展数据,存储平台特定的额外信息
  74. // 如 CRS 账户的 crs_account_id、组织信息等
  75. field.JSON("extra", map[string]any{}).
  76. Default(func() map[string]any { return map[string]any{} }).
  77. SchemaType(map[string]string{dialect.Postgres: "jsonb"}),
  78. // proxy_id: 关联的代理配置 ID(可选)
  79. // 用于需要通过特定代理访问 API 的场景
  80. field.Int64("proxy_id").
  81. Optional().
  82. Nillable(),
  83. field.Int64("proxy_fallback_origin_id").
  84. Optional().Nillable().
  85. Comment("Original proxy id replaced by expiry-fallback; for manual revert. NULL = not in fallback."),
  86. // concurrency: 账户最大并发请求数
  87. // 用于限制同一时间对该账户发起的请求数量
  88. field.Int("concurrency").
  89. Default(3),
  90. field.Int("load_factor").Optional().Nillable(),
  91. // priority: 账户优先级,数值越小优先级越高
  92. // 调度器会优先使用高优先级的账户
  93. field.Int("priority").
  94. Default(50),
  95. // rate_multiplier: 账号计费倍率(>=0,允许 0 表示该账号计费为 0)
  96. // 仅影响账号维度计费口径,不影响用户/API Key 扣费(分组倍率)
  97. field.Float("rate_multiplier").
  98. SchemaType(map[string]string{dialect.Postgres: "decimal(10,4)"}).
  99. Default(1.0),
  100. // status: 账户状态,如 "active", "error", "disabled"
  101. field.String("status").
  102. MaxLen(20).
  103. Default(domain.StatusActive),
  104. // error_message: 错误信息,记录账户异常时的详细信息
  105. field.String("error_message").
  106. Optional().
  107. Nillable().
  108. SchemaType(map[string]string{dialect.Postgres: "text"}),
  109. // last_used_at: 最后使用时间,用于统计和调度
  110. field.Time("last_used_at").
  111. Optional().
  112. Nillable().
  113. SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
  114. // expires_at: 账户过期时间(可为空)
  115. field.Time("expires_at").
  116. Optional().
  117. Nillable().
  118. Comment("Account expiration time (NULL means no expiration).").
  119. SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
  120. // auto_pause_on_expired: 过期后自动暂停调度
  121. field.Bool("auto_pause_on_expired").
  122. Default(true).
  123. Comment("Auto pause scheduling when account expires."),
  124. // ========== 调度和速率限制相关字段 ==========
  125. // 这些字段在 migrations/005_schema_parity.sql 中添加
  126. // schedulable: 是否可被调度器选中
  127. // false 表示账户暂时不参与请求分配(如正在刷新 token)
  128. field.Bool("schedulable").
  129. Default(true),
  130. // rate_limited_at: 触发速率限制的时间
  131. // 当收到 429 错误时记录
  132. field.Time("rate_limited_at").
  133. Optional().
  134. Nillable().
  135. SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
  136. // rate_limit_reset_at: 速率限制预计解除的时间
  137. // 调度器会在此时间之前避免使用该账户
  138. field.Time("rate_limit_reset_at").
  139. Optional().
  140. Nillable().
  141. SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
  142. // overload_until: 过载状态解除时间
  143. // 当收到 529 错误(API 过载)时设置
  144. field.Time("overload_until").
  145. Optional().
  146. Nillable().
  147. SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
  148. // temp_unschedulable_until: 临时不可调度状态解除时间
  149. // 当命中临时不可调度规则时设置,在此时间前调度器应跳过该账号
  150. field.Time("temp_unschedulable_until").
  151. Optional().
  152. Nillable().
  153. SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
  154. // temp_unschedulable_reason: 临时不可调度原因,便于排障审计
  155. field.String("temp_unschedulable_reason").
  156. Optional().
  157. Nillable().
  158. SchemaType(map[string]string{dialect.Postgres: "text"}),
  159. // session_window_*: 会话窗口相关字段
  160. // 用于管理某些需要会话时间窗口的 API(如 Claude Pro)
  161. field.Time("session_window_start").
  162. Optional().
  163. Nillable().
  164. SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
  165. field.Time("session_window_end").
  166. Optional().
  167. Nillable().
  168. SchemaType(map[string]string{dialect.Postgres: "timestamptz"}),
  169. field.String("session_window_status").
  170. Optional().
  171. Nillable().
  172. MaxLen(20),
  173. field.Int64("parent_account_id").Optional().Nillable().
  174. Comment("Parent account id for a linked spark shadow (NULL = normal)."),
  175. field.Enum("quota_dimension").Values("global", "spark").Default("global").
  176. Comment("'global' (default) or 'spark' (shadow reads codex_bengalfox)."),
  177. }
  178. }
  179. // Edges 定义账户实体的关联关系。
  180. func (Account) Edges() []ent.Edge {
  181. return []ent.Edge{
  182. // groups: 账户所属的分组(多对多关系)
  183. // 通过 account_groups 中间表实现
  184. // 一个账户可以属于多个分组,一个分组可以包含多个账户
  185. edge.To("groups", Group.Type).
  186. Through("account_groups", AccountGroup.Type),
  187. // proxy: 账户使用的代理配置(可选的一对一关系)
  188. // 使用已有的 proxy_id 外键字段
  189. edge.To("proxy", Proxy.Type).
  190. Field("proxy_id").
  191. Unique(),
  192. // children/parent: linked spark shadow relationship.
  193. // parent_account_id is nullable, and the active one-shadow-per-parent rule
  194. // is enforced by the partial unique index in migration 154a.
  195. edge.To("children", Account.Type).
  196. Annotations(entsql.OnDelete(entsql.Restrict)).
  197. From("parent").
  198. Field("parent_account_id").
  199. Unique(),
  200. // usage_logs: 该账户的使用日志
  201. edge.To("usage_logs", UsageLog.Type),
  202. }
  203. }
  204. // Indexes 定义数据库索引,优化查询性能。
  205. // 每个索引对应一个常用的查询条件。
  206. func (Account) Indexes() []ent.Index {
  207. return []ent.Index{
  208. index.Fields("platform"), // 按平台筛选
  209. index.Fields("type"), // 按认证类型筛选
  210. index.Fields("status"), // 按状态筛选
  211. index.Fields("proxy_id"), // 按代理筛选
  212. index.Fields("priority"), // 按优先级排序
  213. index.Fields("last_used_at"), // 按最后使用时间排序
  214. index.Fields("schedulable"), // 筛选可调度账户
  215. index.Fields("rate_limited_at"), // 筛选速率限制账户
  216. index.Fields("rate_limit_reset_at"), // 筛选速率限制解除时间
  217. index.Fields("overload_until"), // 筛选过载账户
  218. // 调度热路径复合索引(线上由 SQL 迁移创建部分索引,schema 仅用于模型可读性对齐)
  219. index.Fields("platform", "priority"),
  220. index.Fields("priority", "status"),
  221. index.Fields("deleted_at"), // 软删除查询优化
  222. index.Fields("parent_account_id"),
  223. }
  224. }