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.
355 lines
12 KiB
Go
355 lines
12 KiB
Go
package model
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"slices"
|
|
"sort"
|
|
"time"
|
|
|
|
"github.com/QuantumNous/new-api/common"
|
|
"github.com/QuantumNous/new-api/constant"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
"gorm.io/gorm/schema"
|
|
)
|
|
|
|
type TaskPluginChannelRef struct {
|
|
Id int `json:"id"`
|
|
Name string `json:"name"`
|
|
Type int `json:"type"`
|
|
}
|
|
|
|
func GetTaskPluginUsage(key string) ([]TaskPluginChannelRef, int64, error) {
|
|
var channels []Channel
|
|
boundTypes := []int{constant.ChannelTypeTaskPlugin, constant.ChannelTypeNewAPI}
|
|
if err := DB.Where("type IN ? AND status = ?", boundTypes, common.ChannelStatusEnabled).Find(&channels).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
refs := make([]TaskPluginChannelRef, 0)
|
|
for _, channel := range channels {
|
|
if channel.GetSetting().BindsTaskPlugin(key) {
|
|
refs = append(refs, TaskPluginChannelRef{Id: channel.Id, Name: channel.Name, Type: channel.Type})
|
|
}
|
|
}
|
|
var inFlight int64
|
|
err := DB.Model(&Task{}).Where("platform = ? AND status NOT IN ?", key, []TaskStatus{TaskStatusSuccess, TaskStatusFailure}).Count(&inFlight).Error
|
|
return refs, inFlight, err
|
|
}
|
|
|
|
// UnbindTaskPlugin removes one plugin from a channel's bindings and reports
|
|
// whether the channel changed. A New API gateway channel keeps serving its other
|
|
// plugins and its ordinary traffic.
|
|
func UnbindTaskPlugin(channelID int, key string) (bool, error) {
|
|
channel, err := GetChannelById(channelID, false)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
setting := channel.GetSetting()
|
|
if !setting.BindsTaskPlugin(key) {
|
|
return false, nil
|
|
}
|
|
if setting.TaskPluginKey == key {
|
|
setting.TaskPluginKey = ""
|
|
}
|
|
setting.TaskExtendPluginKeys = slices.DeleteFunc(setting.TaskExtendPluginKeys, func(bound string) bool { return bound == key })
|
|
channel.SetSetting(setting)
|
|
if err = DB.Model(&Channel{}).Where("id = ?", channelID).Update("setting", channel.Setting).Error; err != nil {
|
|
return true, err
|
|
}
|
|
BumpSyncTopic(SyncTopicChannels)
|
|
return true, nil
|
|
}
|
|
|
|
// LongText is a string column sized for plugin payloads on every supported
|
|
// database: longtext on MySQL, text on PostgreSQL and SQLite. A bare
|
|
// `type:text` tag stops at 64 KiB on MySQL. A `size:` tag above that becomes
|
|
// varchar(N) on PostgreSQL, which rejects sizes past 10485760, and a NOT NULL
|
|
// column declared that way is re-altered by AutoMigrate on every MySQL start
|
|
// because the reported column length never equals N. Neither type chosen here
|
|
// carries a length, so an up-to-date column is left alone, and MySQL widens a
|
|
// shipped text column once, without data loss.
|
|
type LongText string
|
|
|
|
func (LongText) GormDBDataType(db *gorm.DB, _ *schema.Field) string {
|
|
if db.Dialector.Name() == string(common.DatabaseTypeMySQL) {
|
|
return "longtext"
|
|
}
|
|
return "text"
|
|
}
|
|
|
|
type TaskPlugin struct {
|
|
Id int64 `json:"id"`
|
|
Key string `json:"key" gorm:"size:128;not null;uniqueIndex:uk_task_plugin_key_version,priority:1"`
|
|
APIVersion int `json:"api_version" gorm:"not null"`
|
|
Version string `json:"version" gorm:"size:64;not null;uniqueIndex:uk_task_plugin_key_version,priority:2"`
|
|
Source LongText `json:"source" gorm:"not null"`
|
|
SourceHash string `json:"source_hash" gorm:"size:64;not null"`
|
|
// Icon is the plugin logo shipped as a sidecar icon.svg / icon.png next to
|
|
// plugin.js, stored as a data URI so one column carries both the media
|
|
// type and the bytes. It never travels inside list or detail JSON; the UI
|
|
// loads it through GET /api/plugin/task/:key/icon. LongText keeps the
|
|
// 512 KiB icon cap storable on MySQL, where a bare TEXT holds only 64 KiB.
|
|
Icon LongText `json:"-"`
|
|
Enabled bool `json:"enabled" gorm:"not null"`
|
|
Active bool `json:"active" gorm:"not null;index"`
|
|
CreatedAt int64 `json:"created_at" gorm:"not null"`
|
|
Remark string `json:"remark" gorm:"type:text"`
|
|
}
|
|
|
|
// HasIcon reports whether this version ships a logo.
|
|
func (plugin TaskPlugin) HasIcon() bool {
|
|
return plugin.Icon != ""
|
|
}
|
|
|
|
func SaveTaskPlugin(plugin *TaskPlugin) error {
|
|
err := DB.Transaction(func(tx *gorm.DB) error {
|
|
var existing TaskPlugin
|
|
err := tx.Where(&TaskPlugin{Key: plugin.Key, Version: plugin.Version}).First(&existing).Error
|
|
if err == nil {
|
|
if existing.SourceHash != plugin.SourceHash {
|
|
return errors.New("plugin key and version already exist with different source")
|
|
}
|
|
updates := map[string]any{"enabled": plugin.Enabled, "remark": plugin.Remark}
|
|
if plugin.Icon != "" {
|
|
updates["icon"] = plugin.Icon
|
|
existing.Icon = plugin.Icon
|
|
}
|
|
if err = tx.Model(&existing).Updates(updates).Error; err != nil {
|
|
return err
|
|
}
|
|
existing.Enabled = plugin.Enabled
|
|
existing.Remark = plugin.Remark
|
|
*plugin = existing
|
|
return nil
|
|
}
|
|
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return err
|
|
}
|
|
plugin.CreatedAt = time.Now().Unix()
|
|
var count int64
|
|
if err = tx.Model(&TaskPlugin{}).Where(&TaskPlugin{Key: plugin.Key, Active: true}).Count(&count).Error; err != nil {
|
|
return err
|
|
}
|
|
plugin.Active = count == 0
|
|
return tx.Create(plugin).Error
|
|
})
|
|
if err == nil {
|
|
BumpSyncTopic(SyncTopicPlugins)
|
|
}
|
|
return err
|
|
}
|
|
|
|
func ListTaskPluginVersions(key string) ([]TaskPlugin, error) {
|
|
var plugins []TaskPlugin
|
|
err := DB.Where(&TaskPlugin{Key: key}).Order("created_at DESC, id DESC").Find(&plugins).Error
|
|
return plugins, err
|
|
}
|
|
|
|
func ListTaskPlugins() ([]TaskPlugin, error) {
|
|
var plugins []TaskPlugin
|
|
err := DB.
|
|
Order(clause.OrderByColumn{Column: clause.Column{Name: "key"}}).
|
|
Order(clause.OrderByColumn{Column: clause.Column{Name: "created_at"}, Desc: true}).
|
|
Order(clause.OrderByColumn{Column: clause.Column{Name: "id"}, Desc: true}).
|
|
Find(&plugins).Error
|
|
return plugins, err
|
|
}
|
|
|
|
func GetTaskPluginVersion(key, version string) (*TaskPlugin, error) {
|
|
var plugin TaskPlugin
|
|
query := DB.Where(&TaskPlugin{Key: key})
|
|
if version == "" {
|
|
query = query.Where(&TaskPlugin{Active: true})
|
|
} else {
|
|
query = query.Where(&TaskPlugin{Version: version})
|
|
}
|
|
if err := query.First(&plugin).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return &plugin, nil
|
|
}
|
|
|
|
// ListActiveTaskPlugins returns the enabled override rows without their
|
|
// source and icon payloads; see GetTaskPluginSyncSnapshot.
|
|
func ListActiveTaskPlugins() ([]TaskPlugin, error) {
|
|
snapshot, err := GetTaskPluginSyncSnapshot()
|
|
return snapshot.Plugins, err
|
|
}
|
|
|
|
type TaskPluginSyncSnapshot struct {
|
|
// Plugins are the enabled active overrides with Source and Icon left
|
|
// empty. Sync compares SourceHash against what it already compiled and
|
|
// loads source through GetTaskPluginSource only for the rows that changed.
|
|
Plugins []TaskPlugin
|
|
Revision string
|
|
}
|
|
|
|
// GetTaskPluginSyncSnapshot returns the enabled override set together with a
|
|
// deterministic revision of every active database override. Nodes can compare
|
|
// the revision even though their local routing-generation counters differ.
|
|
// The query skips the source and icon columns: every node polls this every
|
|
// 30 seconds, and plugin sources may be several MiB each.
|
|
func GetTaskPluginSyncSnapshot() (TaskPluginSyncSnapshot, error) {
|
|
var activePlugins []TaskPlugin
|
|
if err := DB.Omit("source", "icon").Where(&TaskPlugin{Active: true}).
|
|
Order(clause.OrderByColumn{Column: clause.Column{Name: "key"}}).
|
|
Order(clause.OrderByColumn{Column: clause.Column{Name: "version"}}).
|
|
Order(clause.OrderByColumn{Column: clause.Column{Name: "id"}}).
|
|
Find(&activePlugins).Error; err != nil {
|
|
return TaskPluginSyncSnapshot{}, err
|
|
}
|
|
|
|
type revisionEntry struct {
|
|
Key string `json:"key"`
|
|
APIVersion int `json:"api_version"`
|
|
Version string `json:"version"`
|
|
SourceHash string `json:"source_hash"`
|
|
Enabled bool `json:"enabled"`
|
|
}
|
|
entries := make([]revisionEntry, 0, len(activePlugins))
|
|
enabledPlugins := make([]TaskPlugin, 0, len(activePlugins))
|
|
for _, plugin := range activePlugins {
|
|
entries = append(entries, revisionEntry{
|
|
Key: plugin.Key,
|
|
APIVersion: plugin.APIVersion,
|
|
Version: plugin.Version,
|
|
SourceHash: plugin.SourceHash,
|
|
Enabled: plugin.Enabled,
|
|
})
|
|
if plugin.Enabled {
|
|
enabledPlugins = append(enabledPlugins, plugin)
|
|
}
|
|
}
|
|
sort.Slice(entries, func(i, j int) bool {
|
|
if entries[i].Key != entries[j].Key {
|
|
return entries[i].Key < entries[j].Key
|
|
}
|
|
return entries[i].Version < entries[j].Version
|
|
})
|
|
payload, err := common.Marshal(entries)
|
|
if err != nil {
|
|
return TaskPluginSyncSnapshot{}, err
|
|
}
|
|
digest := sha256.Sum256(payload)
|
|
return TaskPluginSyncSnapshot{
|
|
Plugins: enabledPlugins,
|
|
Revision: hex.EncodeToString(digest[:]),
|
|
}, nil
|
|
}
|
|
|
|
// GetTaskPluginSource loads one override's JavaScript by row id. Rows never
|
|
// change source in place (SaveTaskPlugin rejects a different source for the
|
|
// same key and version), so the id from a sync snapshot identifies exactly the
|
|
// text whose SourceHash that snapshot reported.
|
|
func GetTaskPluginSource(id int64) (LongText, error) {
|
|
var plugin TaskPlugin
|
|
err := DB.Select("source").Where(&TaskPlugin{Id: id}).Take(&plugin).Error
|
|
return plugin.Source, err
|
|
}
|
|
|
|
func ActivateTaskPlugin(key, version string) error {
|
|
err := DB.Transaction(func(tx *gorm.DB) error {
|
|
var target TaskPlugin
|
|
if err := tx.Where(&TaskPlugin{Key: key, Version: version}).First(&target).Error; err != nil {
|
|
return err
|
|
}
|
|
if err := tx.Model(&TaskPlugin{}).Where(&TaskPlugin{Key: key}).Update("active", false).Error; err != nil {
|
|
return err
|
|
}
|
|
return tx.Model(&target).Updates(map[string]any{"active": true, "enabled": true}).Error
|
|
})
|
|
if err == nil {
|
|
BumpSyncTopic(SyncTopicPlugins)
|
|
}
|
|
return err
|
|
}
|
|
|
|
func SetTaskPluginEnabled(key string, enabled bool) error {
|
|
result := DB.Model(&TaskPlugin{}).Where(&TaskPlugin{Key: key, Active: true}).Update("enabled", enabled)
|
|
if result.Error != nil {
|
|
return result.Error
|
|
}
|
|
if result.RowsAffected == 0 {
|
|
return gorm.ErrRecordNotFound
|
|
}
|
|
BumpSyncTopic(SyncTopicPlugins)
|
|
return nil
|
|
}
|
|
|
|
type TaskPluginDeleteResult struct {
|
|
DeletedActive bool
|
|
Promoted *TaskPlugin
|
|
}
|
|
|
|
func DeleteTaskPluginVersion(key, version string) (TaskPluginDeleteResult, error) {
|
|
result := TaskPluginDeleteResult{}
|
|
err := DB.Transaction(func(tx *gorm.DB) error {
|
|
var plugin TaskPlugin
|
|
if err := lockForUpdate(tx).Where(&TaskPlugin{Key: key, Version: version}).First(&plugin).Error; err != nil {
|
|
return err
|
|
}
|
|
result.DeletedActive = plugin.Active
|
|
if err := tx.Delete(&plugin).Error; err != nil {
|
|
return err
|
|
}
|
|
if !plugin.Active {
|
|
return nil
|
|
}
|
|
|
|
var promoted TaskPlugin
|
|
err := lockForUpdate(tx).
|
|
Where(&TaskPlugin{Key: key}).
|
|
Order("created_at DESC, id DESC").
|
|
First(&promoted).Error
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err = tx.Model(&promoted).Update("active", true).Error; err != nil {
|
|
return err
|
|
}
|
|
promoted.Active = true
|
|
result.Promoted = &promoted
|
|
return nil
|
|
})
|
|
if err == nil {
|
|
BumpSyncTopic(SyncTopicPlugins)
|
|
}
|
|
return result, err
|
|
}
|
|
|
|
// TaskPluginGatewayIDKey names the option row holding the random gateway id
|
|
// sent with community plugin install counts.
|
|
const TaskPluginGatewayIDKey = "TaskPluginGatewayID"
|
|
|
|
// GetTaskPluginGatewayID returns the gateway id, creating it on first use. The
|
|
// first node to insert the row wins, so every node reads the same value.
|
|
func GetTaskPluginGatewayID() (string, error) {
|
|
var option Option
|
|
err := DB.Where(&Option{Key: TaskPluginGatewayIDKey}).First(&option).Error
|
|
if err == nil {
|
|
return option.Value, nil
|
|
}
|
|
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return "", err
|
|
}
|
|
random := make([]byte, 32)
|
|
if _, err = rand.Read(random); err != nil {
|
|
return "", err
|
|
}
|
|
candidate := Option{Key: TaskPluginGatewayIDKey, Value: hex.EncodeToString(random)}
|
|
if err = DB.Clauses(clause.OnConflict{DoNothing: true}).Create(&candidate).Error; err != nil {
|
|
return "", err
|
|
}
|
|
option = Option{}
|
|
if err = DB.Where(&Option{Key: TaskPluginGatewayIDKey}).First(&option).Error; err != nil {
|
|
return "", err
|
|
}
|
|
return option.Value, nil
|
|
}
|