mirror of
https://github.com/QuantumNous/new-api.git
synced 2026-11-30 19:21:36 +08:00
* feat(plugins): add provider plugins, request plugins and a community marketplace - Provider plugins turn an upstream vendor into a channel type: routes, protocol conversion, models, static keys, sign-in flows with token refresh, balance queries, per-channel config and a scheduled hook. - Request plugins run on requests and replies (ingress, request, outbound, egress, reply, report), with instances by scope, model ranges, dry runs and per-log records. Built-ins: request filter, request redaction, parameter override, auto reasoning effort, image compression and content moderation. Sensitive words move into a request filter instance on first start. - Node sync: a system_sync_topics table lets every node reload settings, channels, plugins and other data within seconds, and the system info page shows each node's state. - Marketplace: a community source next to the official one, lookup by plugin code for official and community plugins, key rules for community plugins, install counts and takedown warnings. * docs(plugins): name request protocols and host-only members in the plugin API - Protocol names: ctx.format and samples use relaykit's protocol names. The spec lists the client paths and body of each name, so every host passes the same names to plugins. - Host-specific members: channel, group, user, token, channelTypes, channelOther and utils.paramOverride exist only on new-api. The types mark them optional. - Relay routes: the spec now writes out the route keys and the converters each incoming path accepts. The schema lists the converter names. * feat(plugins): show recommended plugins from the official list too The site now marks official plugins as recommended in its index. The built-in official and community lists both get a Recommended group; lists added by the administrator still cannot recommend plugins. * feat(plugins): fall back to www.newapi.pro when www.newapi.ai does not answer Plugin lists, plugin files and logos from www.newapi.ai are downloaded from www.newapi.pro, the mainland China site, when newapi.ai gives no answer within 10 seconds; the browser remembers this for a day. The marketplace toolbar has a download site picker: Auto, or Mainland China to always use www.newapi.pro. Saved source addresses stay on newapi.ai, and every file is still checked against its sha256. Community install counts go to newapi.ai first and to newapi.pro when newapi.ai cannot be reached. * fix(plugins): leaving the page does not switch the plugin site to www.newapi.pro Reloading or leaving the marketplace cancels requests still running. That was read as www.newapi.ai not answering, so the browser moved to www.newapi.pro for a day although newapi.ai was reachable. Requests cut off by leaving the page are no longer counted. * feat(plugins): choose the plugin download site by hand The marketplace no longer switches between plugin sites by itself. The toolbar menu lists the main site www.newapi.ai, the backup site www.newapi.pro and the other plugin lists; picking an entry is the only thing that changes where plugins are downloaded from, and the main site can always be picked again. A browser that the earlier automatic switch had moved to www.newapi.pro opens on the main site again. The download site, the source choice and managing sources now share one menu in the list header. * feat(plugins): show plugin usage guides and require README and changelog Every marketplace plugin version now ships a usage guide, README.md, and a changelog, CHANGELOG.md, next to plugin.js. The install dialog shows the guide in the reader's language when a translation is listed, falls back to English, and links to the source file. A guide or changelog that breaks the format is reported with its file, line and rule instead of being shown. The plugin API document describes both formats, the translations they may list, and the checks the community marketplace runs before it accepts a version: readme_missing, readme_invalid, changelog_missing and changelog_invalid. Versions accepted before these checks are not checked again. * fix(plugins): address review findings on plugin parts, limits and access - Only the root user reads request plugin instance configs; an admin who may bind instances to channels gets them without configs. - Outbound hooks that grow the body are held to MAX_REQUEST_BODY_MB, as ingress hooks are, and answer 413 without a retry. - An admin who cannot read plugin options keeps the balance and model list actions on plugin channels; the server answers whether they work. - Reading the parts of a plugin source gives up when the source does not parse or code elsewhere refers to meta, as the meta preview does. * fix(plugins): address review findings on request processing, documents and node sync - PDF checks resolve indirect parameters and bound every value the parser allocates or loops on: predictor columns, object stream counts, nested object streams, cross-reference streams and ToUnicode ranges. Font and CMap work checks the deadline. - A WebP frame must match its declared canvas, and keyword search stops at its match limit. - Request processing treats a body as JSON whenever the gateway parses it as JSON, keeps Gemini reply parts in place, scopes instances by the settled auto group, hides channel header overrides from plugin param overrides, and captures replies only for report instances in scope. - Request processing no longer follows the plugin master switch, which now covers plugin tasks and channels only. - json.patch copies stop at MAX_REQUEST_BODY_MB, and provider prepareRequest effects past it answer 413. - Image billing reads the count from the final upstream body, including the count members of SiliconFlow, Imagen and Replicate and the Imagen default. - Automatic channel status changes no longer reload every node's channel cache. A credential refresh holds no channel lock while it waits on the vendor. A key that needs login is disabled and the request can retry. - Balance requests must go to the channel host or allowedHosts, and provider stream events a plugin drops keep the stream alive. - Node sync: OAuth provider writes bump inside their transaction, a failed startup load is retried, and each node is judged by its own topics. - request-filter checks the text the old sensitive-word check did, request-redact and content-moderation handle large inputs, and image-compress lossless mode leaves JPEG and WebP alone. * fix(plugins): address the second review on balances, egress and routes - Channel other_info writes (status changes, balance queries and manual multi-key actions) only land while other_info is still the value read, and retry otherwise, so a write on one node no longer overwrites another node's balance or status reason. They write only their own columns. - On the Responses path egress reads the body after the channel finalizes it, which is the body sent upstream. - The Vertex AI plugin picks the region by the model the client asked for, as the built-in Vertex AI channel does. - /request-processing and /security are reserved route namespaces, and a test checks that every console page is reserved. - The plugin API docs say what egress reads on a provider plugin channel. * feat(channels): run the balance update as a system task with progress "Update all balances" now queues a channel_balance system task instead of starting a goroutine guarded by an in-process flag. The task row holds the progress (enabled channels queried of total), so any node can answer it, and its active key keeps one run at a time across nodes. The CHANNEL_UPDATE_FREQUENCY schedule becomes the same task's schedule, so manual and scheduled runs no longer overlap. GET /api/channel/update_balance answers with the task id, and with the running one when a run is already queued. GET /api/channel/update_balance/task/:task_id, under the same channel permission, returns the status, progress and failure of balance update tasks only. The channel list follows the task, reloads as more channels are queried and once more at the end, and reports how the run ended. * feat(system): sync nodes through system tasks and clean up task history Node sync no longer needs its own table. A write to synced data adds a pending sync_<topic> system task. Every node polls the newest task of each topic it keeps every 3 s and reloads when that task is newer than the one it applied. Custom OAuth providers still add their task inside the write transaction, and lock the newest task of the topic first, so tasks commit in id order. The master marks a sync task succeeded once every online node that keeps the topic has applied it. Until then the task shows how many nodes have applied it and why the others have not. The system_sync_topics table is gone. A composite (type, id) index answers the newest task of a type from the index. The latest-per-type and earliest-pending queries now read ids first, because MySQL 5.7 scanned the whole table for them. A daily system_task_cleanup task deletes finished system tasks older than system_task_setting.retention_days (default 30, at least 1), in batches. It never deletes active tasks or the newest task of any type. The retention is set under Operations > Log maintenance.
621 lines
18 KiB
Go
621 lines
18 KiB
Go
package model
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"strings"
|
|
|
|
"github.com/QuantumNous/new-api/common"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type SystemTaskStatus string
|
|
|
|
const (
|
|
SystemTaskStatusPending SystemTaskStatus = "pending"
|
|
SystemTaskStatusRunning SystemTaskStatus = "running"
|
|
SystemTaskStatusSucceeded SystemTaskStatus = "succeeded"
|
|
SystemTaskStatusFailed SystemTaskStatus = "failed"
|
|
|
|
SystemTaskTypeLogCleanup = "log_cleanup"
|
|
SystemTaskTypeChannelTest = "channel_test"
|
|
SystemTaskTypeModelUpdate = "model_update"
|
|
SystemTaskTypeMidjourneyPoll = "midjourney_poll"
|
|
SystemTaskTypeAsyncTaskPoll = "async_task_poll"
|
|
SystemTaskTypeChannelBalance = "channel_balance"
|
|
SystemTaskTypeCleanup = "system_task_cleanup"
|
|
|
|
systemTaskCleanupBatchSize = 500
|
|
)
|
|
|
|
var ErrSystemTaskLockLost = errors.New("system task lock lost")
|
|
|
|
// SystemTask is one run of a background job, or one sync task (see
|
|
// SyncTaskType). The (type, id) index answers "newest row of a type" without
|
|
// reading older rows; every node asks it every few seconds.
|
|
type SystemTask struct {
|
|
ID int64 `json:"id" gorm:"primary_key;index:,composite:type_id,priority:2"`
|
|
TaskID string `json:"task_id" gorm:"type:varchar(64);uniqueIndex"`
|
|
Type string `json:"type" gorm:"type:varchar(64);index:,composite:type_id,priority:1"`
|
|
Status SystemTaskStatus `json:"status" gorm:"type:varchar(32);index"`
|
|
ActiveKey *string `json:"active_key,omitempty" gorm:"type:varchar(64);uniqueIndex"`
|
|
Payload string `json:"payload" gorm:"type:text"`
|
|
State string `json:"state" gorm:"type:text"`
|
|
Result string `json:"result" gorm:"type:text"`
|
|
Error string `json:"error" gorm:"type:text"`
|
|
LockedBy string `json:"locked_by" gorm:"type:varchar(128);index"`
|
|
CreatedAt int64 `json:"created_at" gorm:"bigint;index"`
|
|
UpdatedAt int64 `json:"updated_at" gorm:"bigint;index"`
|
|
}
|
|
|
|
type SystemTaskLock struct {
|
|
Type string `json:"type" gorm:"type:varchar(64);primaryKey"`
|
|
TaskID string `json:"task_id" gorm:"type:varchar(64);index"`
|
|
LockedBy string `json:"locked_by" gorm:"type:varchar(128);index"`
|
|
LockedUntil int64 `json:"locked_until" gorm:"bigint;index"`
|
|
UpdatedAt int64 `json:"updated_at" gorm:"bigint;index"`
|
|
}
|
|
|
|
type SystemTaskResponse struct {
|
|
ID int64 `json:"id"`
|
|
TaskID string `json:"task_id"`
|
|
Type string `json:"type"`
|
|
Status SystemTaskStatus `json:"status"`
|
|
ActiveKey *string `json:"active_key,omitempty"`
|
|
Payload any `json:"payload"`
|
|
State any `json:"state"`
|
|
Result any `json:"result"`
|
|
Error string `json:"error"`
|
|
LockedBy string `json:"locked_by"`
|
|
CreatedAt int64 `json:"created_at"`
|
|
UpdatedAt int64 `json:"updated_at"`
|
|
}
|
|
|
|
func (task *SystemTask) BeforeCreate(_ *gorm.DB) error {
|
|
now := common.GetTimestamp()
|
|
if task.CreatedAt == 0 {
|
|
task.CreatedAt = now
|
|
}
|
|
if task.UpdatedAt == 0 {
|
|
task.UpdatedAt = now
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (lock *SystemTaskLock) BeforeCreate(_ *gorm.DB) error {
|
|
if lock.UpdatedAt == 0 {
|
|
lock.UpdatedAt = common.GetTimestamp()
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func GenerateSystemTaskID() (string, error) {
|
|
key, err := common.GenerateRandomCharsKey(32)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return "systask_" + key, nil
|
|
}
|
|
|
|
func CreateSystemTask(taskType string, payload any, state any) (*SystemTask, error) {
|
|
taskID, err := GenerateSystemTaskID()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
payloadText, err := marshalSystemTaskJSON(payload)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
stateText, err := marshalSystemTaskJSON(state)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
task := &SystemTask{
|
|
TaskID: taskID,
|
|
Type: taskType,
|
|
Status: SystemTaskStatusPending,
|
|
ActiveKey: &taskType,
|
|
Payload: payloadText,
|
|
State: stateText,
|
|
}
|
|
|
|
if err := DB.Create(task).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return task, nil
|
|
}
|
|
|
|
func GetSystemTaskByTaskID(taskID string) (*SystemTask, error) {
|
|
var task SystemTask
|
|
if err := DB.Where("task_id = ?", taskID).First(&task).Error; err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
return &task, nil
|
|
}
|
|
|
|
func GetActiveSystemTask(taskType string) (*SystemTask, error) {
|
|
var task SystemTask
|
|
err := DB.Where("type = ? AND status IN ?", taskType, activeSystemTaskStatuses()).
|
|
Order("id desc").
|
|
First(&task).Error
|
|
if err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
return &task, nil
|
|
}
|
|
|
|
func FindPendingSystemTasks(taskType string, limit int) ([]*SystemTask, error) {
|
|
var tasks []*SystemTask
|
|
if limit <= 0 {
|
|
limit = 1
|
|
}
|
|
err := DB.Where("type = ? AND status = ?", taskType, SystemTaskStatusPending).
|
|
Order("id asc").
|
|
Limit(limit).
|
|
Find(&tasks).Error
|
|
return tasks, err
|
|
}
|
|
|
|
func FindEarliestPendingSystemTasks(taskTypes []string) (map[string]*SystemTask, error) {
|
|
tasksByType := map[string]*SystemTask{}
|
|
if len(taskTypes) == 0 {
|
|
return tasksByType, nil
|
|
}
|
|
|
|
// Read the ids first: MySQL 5.7 runs "id IN (grouped subquery)" as a scan
|
|
// of the whole table.
|
|
var ids []int64
|
|
if err := DB.Model(&SystemTask{}).
|
|
Where("type IN ? AND status = ?", taskTypes, SystemTaskStatusPending).
|
|
Group("type").
|
|
Pluck("MIN(id)", &ids).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
if len(ids) == 0 {
|
|
return tasksByType, nil
|
|
}
|
|
var tasks []*SystemTask
|
|
if err := DB.Where("id IN ?", ids).Find(&tasks).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
for _, task := range tasks {
|
|
tasksByType[task.Type] = task
|
|
}
|
|
return tasksByType, nil
|
|
}
|
|
|
|
type SystemTaskFilter struct {
|
|
Scope string `form:"scope" binding:"omitempty,oneof=active history"`
|
|
Type string `form:"type" binding:"max=64"`
|
|
Status SystemTaskStatus `form:"status" binding:"omitempty,oneof=pending running succeeded failed"`
|
|
}
|
|
|
|
func (filter SystemTaskFilter) query() *gorm.DB {
|
|
query := DB.Model(&SystemTask{})
|
|
switch filter.Scope {
|
|
case "active":
|
|
query = query.Where("status IN ?", activeSystemTaskStatuses())
|
|
case "history":
|
|
query = query.Where("status IN ?", []SystemTaskStatus{SystemTaskStatusSucceeded, SystemTaskStatusFailed})
|
|
}
|
|
if filter.Type != "" {
|
|
query = query.Where("type = ?", filter.Type)
|
|
}
|
|
if filter.Status != "" {
|
|
query = query.Where("status = ?", filter.Status)
|
|
}
|
|
return query
|
|
}
|
|
|
|
func ListSystemTasks(filter SystemTaskFilter, offset, limit int) ([]*SystemTask, int64, error) {
|
|
if limit <= 0 {
|
|
limit = 20
|
|
}
|
|
query := filter.query()
|
|
var total int64
|
|
if err := query.Count(&total).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
var tasks []*SystemTask
|
|
err := query.Order("id desc").Offset(max(0, offset)).Limit(min(limit, 100)).Find(&tasks).Error
|
|
return tasks, total, err
|
|
}
|
|
|
|
// DeleteSystemTaskHistory preserves the latest row of every type because the
|
|
// scheduler uses it to determine when the next run is due. Active rows and rows
|
|
// created after this cleanup's snapshot are never removed.
|
|
func DeleteSystemTaskHistory(filter SystemTaskFilter) (int64, error) {
|
|
var latestIDs []int64
|
|
if err := DB.Model(&SystemTask{}).Select("MAX(id)").Group("type").Pluck("MAX(id)", &latestIDs).Error; err != nil {
|
|
return 0, err
|
|
}
|
|
if len(latestIDs) == 0 {
|
|
return 0, nil
|
|
}
|
|
var newestID int64
|
|
for _, id := range latestIDs {
|
|
newestID = max(newestID, id)
|
|
}
|
|
filter.Scope = "history"
|
|
result := filter.query().Where("id < ? AND id NOT IN ?", newestID, latestIDs).Delete(&SystemTask{})
|
|
return result.RowsAffected, result.Error
|
|
}
|
|
|
|
// GetLatestSystemTask returns the most recent task row of the given type
|
|
// (any status) so the scheduler can decide whether enough time has elapsed
|
|
// since the last run. Returns (nil, nil) when no row exists.
|
|
func GetLatestSystemTask(taskType string) (*SystemTask, error) {
|
|
var task SystemTask
|
|
err := DB.Where("type = ?", taskType).Order("id desc").First(&task).Error
|
|
if err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
return &task, nil
|
|
}
|
|
|
|
// GetLatestSystemTaskIDs returns the id of the newest row of each type that
|
|
// has one. Every type is its own MAX(id) subquery, which each database answers
|
|
// from the (type, id) index without reading older rows.
|
|
func GetLatestSystemTaskIDs(taskTypes []string) (map[string]int64, error) {
|
|
ids := make(map[string]int64, len(taskTypes))
|
|
if len(taskTypes) == 0 {
|
|
return ids, nil
|
|
}
|
|
columns := make([]string, len(taskTypes))
|
|
subQueries := make([]any, len(taskTypes))
|
|
for i, taskType := range taskTypes {
|
|
columns[i] = "(?)"
|
|
subQueries[i] = DB.Model(&SystemTask{}).Select("MAX(id)").Where("type = ?", taskType)
|
|
}
|
|
rows, err := DB.Raw("SELECT "+strings.Join(columns, ", "), subQueries...).Rows()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
latest := make([]sql.NullInt64, len(taskTypes))
|
|
dest := make([]any, len(latest))
|
|
for i := range latest {
|
|
dest[i] = &latest[i]
|
|
}
|
|
if rows.Next() {
|
|
if err := rows.Scan(dest...); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
for i, taskType := range taskTypes {
|
|
if latest[i].Valid {
|
|
ids[taskType] = latest[i].Int64
|
|
}
|
|
}
|
|
return ids, nil
|
|
}
|
|
|
|
func GetLatestSystemTasks(taskTypes []string) (map[string]*SystemTask, error) {
|
|
tasksByType := map[string]*SystemTask{}
|
|
latestIDs, err := GetLatestSystemTaskIDs(taskTypes)
|
|
if err != nil || len(latestIDs) == 0 {
|
|
return tasksByType, err
|
|
}
|
|
ids := make([]int64, 0, len(latestIDs))
|
|
for _, id := range latestIDs {
|
|
ids = append(ids, id)
|
|
}
|
|
var tasks []*SystemTask
|
|
if err := DB.Where("id IN ?", ids).Find(&tasks).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
for _, task := range tasks {
|
|
tasksByType[task.Type] = task
|
|
}
|
|
return tasksByType, nil
|
|
}
|
|
|
|
// DeleteFinishedSystemTasks deletes, in batches, the succeeded and failed rows
|
|
// last updated before cutoff. The newest row of every type stays: the
|
|
// scheduler and the node sync read it. A row that becomes the newest later is
|
|
// newer than cutoff.
|
|
func DeleteFinishedSystemTasks(ctx context.Context, cutoff int64) (int64, error) {
|
|
var newestIDs []int64
|
|
if err := DB.Model(&SystemTask{}).Group("type").Pluck("MAX(id)", &newestIDs).Error; err != nil {
|
|
return 0, err
|
|
}
|
|
var deleted int64
|
|
for {
|
|
if err := ctx.Err(); err != nil {
|
|
return deleted, err
|
|
}
|
|
query := DB.Model(&SystemTask{}).Where("status IN ? AND updated_at < ?", []SystemTaskStatus{SystemTaskStatusSucceeded, SystemTaskStatusFailed}, cutoff)
|
|
if len(newestIDs) > 0 {
|
|
query = query.Where("id NOT IN ?", newestIDs)
|
|
}
|
|
// MySQL rejects LIMIT in an IN subquery: read the ids, then delete them.
|
|
var ids []int64
|
|
if err := query.Order("id").Limit(systemTaskCleanupBatchSize).Pluck("id", &ids).Error; err != nil {
|
|
return deleted, err
|
|
}
|
|
if len(ids) == 0 {
|
|
return deleted, nil
|
|
}
|
|
result := DB.Where("id IN ?", ids).Delete(&SystemTask{})
|
|
if result.Error != nil {
|
|
return deleted, result.Error
|
|
}
|
|
deleted += result.RowsAffected
|
|
if len(ids) < systemTaskCleanupBatchSize {
|
|
return deleted, nil
|
|
}
|
|
}
|
|
}
|
|
|
|
func ClaimSystemTask(id int64, taskType string, runnerID string, lockUntil int64) (*SystemTask, bool, error) {
|
|
now := common.GetTimestamp()
|
|
var task SystemTask
|
|
if err := DB.Where("id = ? AND type = ? AND status = ?", id, taskType, SystemTaskStatusPending).First(&task).Error; err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, false, nil
|
|
}
|
|
return nil, false, err
|
|
}
|
|
|
|
acquired, expiredTaskID, err := acquireSystemTaskLock(taskType, task.TaskID, runnerID, now, lockUntil)
|
|
if err != nil || !acquired {
|
|
return nil, acquired, err
|
|
}
|
|
if expiredTaskID != "" && expiredTaskID != task.TaskID {
|
|
if err := MarkSystemTaskLeaseExpired(expiredTaskID); err != nil {
|
|
_ = ReleaseSystemTaskLock(task.TaskID, runnerID)
|
|
return nil, false, err
|
|
}
|
|
}
|
|
|
|
result := DB.Model(&SystemTask{}).
|
|
Where("id = ? AND type = ? AND status = ?", id, taskType, SystemTaskStatusPending).
|
|
Updates(map[string]any{
|
|
"status": SystemTaskStatusRunning,
|
|
"locked_by": runnerID,
|
|
"updated_at": now,
|
|
})
|
|
if result.Error != nil {
|
|
_ = ReleaseSystemTaskLock(task.TaskID, runnerID)
|
|
return nil, false, result.Error
|
|
}
|
|
if result.RowsAffected == 0 {
|
|
_ = ReleaseSystemTaskLock(task.TaskID, runnerID)
|
|
return nil, false, nil
|
|
}
|
|
|
|
if err := DB.Where("id = ?", id).First(&task).Error; err != nil {
|
|
return nil, false, err
|
|
}
|
|
return &task, true, nil
|
|
}
|
|
|
|
func acquireSystemTaskLock(taskType string, taskID string, lockedBy string, now int64, lockUntil int64) (bool, string, error) {
|
|
lock := &SystemTaskLock{
|
|
Type: taskType,
|
|
TaskID: taskID,
|
|
LockedBy: lockedBy,
|
|
LockedUntil: lockUntil,
|
|
UpdatedAt: now,
|
|
}
|
|
if err := DB.Create(lock).Error; err == nil {
|
|
return true, "", nil
|
|
}
|
|
|
|
var existing SystemTaskLock
|
|
err := DB.Where("type = ?", taskType).First(&existing).Error
|
|
if err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return false, "", nil
|
|
}
|
|
return false, "", err
|
|
}
|
|
if existing.LockedUntil >= now {
|
|
return false, "", nil
|
|
}
|
|
|
|
result := DB.Model(&SystemTaskLock{}).
|
|
Where("type = ? AND locked_until < ?", taskType, now).
|
|
Updates(map[string]any{
|
|
"task_id": taskID,
|
|
"locked_by": lockedBy,
|
|
"locked_until": lockUntil,
|
|
"updated_at": now,
|
|
})
|
|
if result.Error != nil {
|
|
return false, "", result.Error
|
|
}
|
|
if result.RowsAffected == 0 {
|
|
return false, "", nil
|
|
}
|
|
return true, existing.TaskID, nil
|
|
}
|
|
|
|
func UpdateSystemTaskState(taskID string, lockedBy string, state any) error {
|
|
stateText, err := marshalSystemTaskJSON(state)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
now := common.GetTimestamp()
|
|
result := DB.Model(&SystemTask{}).
|
|
Where("task_id = ? AND status = ? AND locked_by = ?", taskID, SystemTaskStatusRunning, lockedBy).
|
|
Where("EXISTS (SELECT 1 FROM system_task_locks WHERE system_task_locks.task_id = system_tasks.task_id AND system_task_locks.locked_by = ? AND system_task_locks.locked_until >= ?)", lockedBy, now).
|
|
Updates(map[string]any{
|
|
"state": stateText,
|
|
"updated_at": now,
|
|
})
|
|
if result.Error != nil {
|
|
return result.Error
|
|
}
|
|
if result.RowsAffected > 0 {
|
|
return nil
|
|
}
|
|
// MySQL counts changed rows, not matched rows. A no-op persist of the same
|
|
// state in the same second therefore returns RowsAffected == 0 even while
|
|
// the lease is still held. Confirm the lock before treating this as loss.
|
|
// Reuse `now` from the UPDATE so a clock tick cannot reintroduce false
|
|
// lock-loss; a lease that expires during the write is caught by the next heartbeat.
|
|
var held int64
|
|
err = DB.Model(&SystemTask{}).
|
|
Where("task_id = ? AND status = ? AND locked_by = ?", taskID, SystemTaskStatusRunning, lockedBy).
|
|
Where("EXISTS (SELECT 1 FROM system_task_locks WHERE system_task_locks.task_id = system_tasks.task_id AND system_task_locks.locked_by = ? AND system_task_locks.locked_until >= ?)", lockedBy, now).
|
|
Count(&held).Error
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if held == 0 {
|
|
return ErrSystemTaskLockLost
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func RenewSystemTaskLock(taskID string, lockedBy string, lockUntil int64) error {
|
|
now := common.GetTimestamp()
|
|
result := DB.Model(&SystemTaskLock{}).
|
|
Where("task_id = ? AND locked_by = ? AND locked_until >= ?", taskID, lockedBy, now).
|
|
Updates(map[string]any{
|
|
"locked_until": lockUntil,
|
|
"updated_at": now,
|
|
})
|
|
if result.Error != nil {
|
|
return result.Error
|
|
}
|
|
if result.RowsAffected == 0 {
|
|
return ErrSystemTaskLockLost
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func MarkSystemTaskLeaseExpired(taskID string) error {
|
|
result := DB.Model(&SystemTask{}).
|
|
Where("task_id = ? AND status = ?", taskID, SystemTaskStatusRunning).
|
|
Updates(map[string]any{
|
|
"status": SystemTaskStatusFailed,
|
|
"active_key": nil,
|
|
"error": "task lease expired",
|
|
"updated_at": common.GetTimestamp(),
|
|
})
|
|
return result.Error
|
|
}
|
|
|
|
func ExpireStaleSystemTaskLocks(now int64) error {
|
|
var locks []*SystemTaskLock
|
|
if err := DB.Where("locked_until < ?", now).Find(&locks).Error; err != nil {
|
|
return err
|
|
}
|
|
for _, lock := range locks {
|
|
if err := MarkSystemTaskLeaseExpired(lock.TaskID); err != nil {
|
|
return err
|
|
}
|
|
result := DB.Where("type = ? AND task_id = ? AND locked_by = ? AND locked_until < ?", lock.Type, lock.TaskID, lock.LockedBy, now).
|
|
Delete(&SystemTaskLock{})
|
|
if result.Error != nil {
|
|
return result.Error
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func ReleaseSystemTaskLock(taskID string, lockedBy string) error {
|
|
result := DB.Where("task_id = ? AND locked_by = ?", taskID, lockedBy).Delete(&SystemTaskLock{})
|
|
return result.Error
|
|
}
|
|
|
|
func FinishSystemTask(taskID string, lockedBy string, status SystemTaskStatus, resultPayload any, errorMessage string) error {
|
|
resultText, err := marshalSystemTaskJSON(resultPayload)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
now := common.GetTimestamp()
|
|
result := DB.Model(&SystemTask{}).
|
|
Where("task_id = ? AND status = ? AND locked_by = ?", taskID, SystemTaskStatusRunning, lockedBy).
|
|
Where("EXISTS (SELECT 1 FROM system_task_locks WHERE system_task_locks.task_id = system_tasks.task_id AND system_task_locks.locked_by = ? AND system_task_locks.locked_until >= ?)", lockedBy, now).
|
|
Updates(map[string]any{
|
|
"status": status,
|
|
"active_key": nil,
|
|
"result": resultText,
|
|
"error": errorMessage,
|
|
"updated_at": now,
|
|
})
|
|
if result.Error != nil {
|
|
return result.Error
|
|
}
|
|
if result.RowsAffected == 0 {
|
|
return ErrSystemTaskLockLost
|
|
}
|
|
return ReleaseSystemTaskLock(taskID, lockedBy)
|
|
}
|
|
|
|
func (task *SystemTask) DecodePayload(v any) error {
|
|
return decodeSystemTaskJSONString(task.Payload, v)
|
|
}
|
|
|
|
func (task *SystemTask) DecodeState(v any) error {
|
|
return decodeSystemTaskJSONString(task.State, v)
|
|
}
|
|
|
|
func (task *SystemTask) ToResponse() SystemTaskResponse {
|
|
return SystemTaskResponse{
|
|
ID: task.ID,
|
|
TaskID: task.TaskID,
|
|
Type: task.Type,
|
|
Status: task.Status,
|
|
ActiveKey: task.ActiveKey,
|
|
Payload: decodeSystemTaskJSONValue(task.Payload),
|
|
State: decodeSystemTaskJSONValue(task.State),
|
|
Result: decodeSystemTaskJSONValue(task.Result),
|
|
Error: task.Error,
|
|
LockedBy: task.LockedBy,
|
|
CreatedAt: task.CreatedAt,
|
|
UpdatedAt: task.UpdatedAt,
|
|
}
|
|
}
|
|
|
|
func activeSystemTaskStatuses() []string {
|
|
return []string{string(SystemTaskStatusPending), string(SystemTaskStatusRunning)}
|
|
}
|
|
|
|
func marshalSystemTaskJSON(v any) (string, error) {
|
|
if v == nil {
|
|
return "", nil
|
|
}
|
|
data, err := common.Marshal(v)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return string(data), nil
|
|
}
|
|
|
|
func decodeSystemTaskJSONString(data string, v any) error {
|
|
if data == "" {
|
|
return nil
|
|
}
|
|
return common.UnmarshalJsonStr(data, v)
|
|
}
|
|
|
|
func decodeSystemTaskJSONValue(data string) any {
|
|
if data == "" {
|
|
return nil
|
|
}
|
|
var value any
|
|
if err := common.UnmarshalJsonStr(data, &value); err != nil {
|
|
return data
|
|
}
|
|
return value
|
|
}
|