mirror of
https://github.com/QuantumNous/new-api.git
synced 2026-12-05 16:04:03 +00:00
插件 API v1 的元数据校验、utils、moejs 执行层和任务钩子的结果解析搬到 嵌套模块 github.com/QuantumNous/new-api/pluginkit,按 pluginkit/vX.Y.Z 打标签发布,其他宿主可以直接引用同一份实现。 - pkg/jsplugin 只留注册表、路由和 CLI,现有导出名通过别名保留,行为不变 - 文档 v1.md、v1.d.ts、v1.schema.json 移到 pluginkit/,schema 和类型由模块内嵌 - 请求处理钩子新增宿主专有的 ctx.client、ctx.session,new-api 不提供 - 导出 MaxPluginKeyLength、NewAPIReservedKeys 和 CallPathJSONInto - CI、Makefile、Dockerfile 和 AGENTS.md 按 relaykit 的方式加上 pluginkit
349 lines
12 KiB
Go
349 lines
12 KiB
Go
package pluginkit
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/MoeForge/moejs"
|
|
)
|
|
|
|
// Fetcher sends one utils.fetch request with the network deadline in ctx.
|
|
// It reads at most request.ResponseBodyLimit()+1 bytes and returns any
|
|
// bytes it read before an error so the engine can count them.
|
|
type Fetcher func(ctx context.Context, request FetchRequest) (FetchResponse, error)
|
|
|
|
type FetchRequest struct {
|
|
Hook string // the calling hook, filled by the engine for logs and errors
|
|
URL string
|
|
Method string
|
|
Headers map[string]string
|
|
// Body is the text a POST sends; only postFetchHooks may POST.
|
|
Body string
|
|
// BodyStream, when set, is what the POST sends instead of Body: Body
|
|
// with the media refs it names replaced by their data URLs, BodySize
|
|
// bytes long.
|
|
BodyStream io.Reader
|
|
BodySize int64
|
|
// priorResponseBytes counts the bytes read by earlier fetches in this hook.
|
|
priorResponseBytes int64
|
|
}
|
|
|
|
// ResponseBodyLimit is the number of response bytes this fetch can accept.
|
|
func (r FetchRequest) ResponseBodyLimit() int64 {
|
|
return min(maxFetchResponseBytes, maxFetchResponseBytesPerCall-r.priorResponseBytes)
|
|
}
|
|
|
|
type FetchResponse struct {
|
|
Status int
|
|
Headers map[string]string
|
|
Body []byte
|
|
}
|
|
|
|
// The utils.fetch limits are part of the published plugin contract
|
|
// (v1.md). MaxFetchBodyBytes applies to the POST body
|
|
// before the host expands media references.
|
|
const (
|
|
maxFetchesPerCall = 4
|
|
fetchTimeout = 15 * time.Second
|
|
maxFetchTimePerCall = 30 * time.Second
|
|
MaxFetchBodyBytes = 1 << 20
|
|
maxFetchResponseBytes = 4 << 20
|
|
maxFetchResponseBytesPerCall = 8 << 20
|
|
maxFetchURLBytes = 64 << 10
|
|
)
|
|
|
|
var errFetchResponseBudget = fmt.Errorf("utils.fetch allows at most %d response bytes per hook call", maxFetchResponseBytesPerCall)
|
|
|
|
type fetcherContextKey struct{}
|
|
|
|
// postFetchHooks may POST through utils.fetch for credential exchanges,
|
|
// scheduled account maintenance and calls to request processing services.
|
|
var postFetchHooks = map[string]bool{"login": true, "refresh": true, "revoke": true, "exchangeKey": true, "scheduled": true, "ingress": true, "egress": true, ReplyHook: true, ReportHook: true}
|
|
|
|
// WithFetcher makes utils.fetch available to the hook called with ctx.
|
|
func WithFetcher(ctx context.Context, fetcher Fetcher) context.Context {
|
|
return context.WithValue(ctx, fetcherContextKey{}, fetcher)
|
|
}
|
|
|
|
// runtimeCall is the hook call a runtime is running, as its host functions
|
|
// see it. The engine sets it for one call and clears it when the call ends,
|
|
// so an idle pooled runtime keeps no request data.
|
|
type runtimeCall struct {
|
|
engine *Engine
|
|
runtime *moejs.Runtime
|
|
ctx context.Context
|
|
hook string
|
|
fetcher Fetcher
|
|
// transform is the context of a stage hook call, nil for other hooks.
|
|
transform *TransformContext
|
|
watchdog *runtimeWatchdog
|
|
// holdsSlot and parked are what the call holds of the engine's
|
|
// semaphore and parked tokens; release returns exactly that.
|
|
holdsSlot bool
|
|
parked bool
|
|
fetches int
|
|
fetchTime time.Duration
|
|
fetchResponseBytes int64
|
|
}
|
|
|
|
func (c *runtimeCall) release() {
|
|
if c.holdsSlot {
|
|
<-c.engine.semaphore
|
|
c.holdsSlot = false
|
|
}
|
|
if c.parked {
|
|
<-c.engine.parked
|
|
c.parked = false
|
|
}
|
|
}
|
|
|
|
// fetch is utils.fetch. While the fetcher waits on the network the call's
|
|
// JavaScript clock is stopped and its execution slot is lent to other calls.
|
|
// Errors name the host only: hook errors reach API callers, and paths and
|
|
// queries can carry credentials.
|
|
func (c *runtimeCall) fetch(r *moejs.Realm, argument moejs.Value) (moejs.Value, error) {
|
|
if c.fetcher == nil {
|
|
return moejs.Undefined(), fmt.Errorf("utils.fetch is not available in %s", c.hook)
|
|
}
|
|
request, host, wantBytes, err := fetchRequest(r, argument, postFetchHooks[c.hook])
|
|
if err != nil {
|
|
return moejs.Undefined(), err
|
|
}
|
|
request.Hook = c.hook
|
|
if c.fetches >= maxFetchesPerCall {
|
|
return moejs.Undefined(), fmt.Errorf("utils.fetch allows at most %d requests per hook call", maxFetchesPerCall)
|
|
}
|
|
remainingBytes := maxFetchResponseBytesPerCall - c.fetchResponseBytes
|
|
if remainingBytes == 0 {
|
|
return moejs.Undefined(), errFetchResponseBudget
|
|
}
|
|
request.priorResponseBytes = c.fetchResponseBytes
|
|
remaining := maxFetchTimePerCall - c.fetchTime
|
|
if remaining <= 0 {
|
|
return moejs.Undefined(), fmt.Errorf("utils.fetch requests used up their %s per hook call", maxFetchTimePerCall)
|
|
}
|
|
c.fetches++
|
|
timeout, timeoutCause := fetchTimeout, fmt.Errorf("utils.fetch to %s timed out after %s", host, fetchTimeout)
|
|
if remaining < fetchTimeout {
|
|
timeout, timeoutCause = remaining, fmt.Errorf("utils.fetch to %s ran past the %s of requests per hook call", host, maxFetchTimePerCall)
|
|
}
|
|
|
|
if source := c.mediaSource(); source != nil && request.Body != "" {
|
|
// The media refs of the request go out as data URLs, streamed from
|
|
// the request body.
|
|
if request.BodyStream, request.BodySize, err = source.FetchBody(request.Body); err != nil {
|
|
return moejs.Undefined(), r.TypeError("utils.fetch: %s", err)
|
|
}
|
|
}
|
|
|
|
var response FetchResponse
|
|
if interrupted := c.offSlot(r, "utils.fetch", func() {
|
|
fetchContext, cancel := context.WithTimeoutCause(c.ctx, timeout, timeoutCause)
|
|
started := time.Now()
|
|
response, err = c.fetcher(fetchContext, request)
|
|
c.fetchTime += time.Since(started)
|
|
if err != nil && fetchContext.Err() != nil {
|
|
err = context.Cause(fetchContext)
|
|
}
|
|
cancel()
|
|
}); interrupted != nil {
|
|
return moejs.Undefined(), interrupted
|
|
}
|
|
|
|
// Partial and oversized responses also consume the hook's byte budget.
|
|
size := int64(len(response.Body))
|
|
c.fetchResponseBytes += min(size, remainingBytes)
|
|
if err != nil {
|
|
var transportErr *url.Error
|
|
if errors.As(err, &transportErr) {
|
|
err = transportErr.Err
|
|
}
|
|
return moejs.Undefined(), fmt.Errorf("utils.fetch to %s failed: %v", host, err)
|
|
}
|
|
if size > maxFetchResponseBytes {
|
|
return moejs.Undefined(), fmt.Errorf("utils.fetch response from %s exceeds %d bytes", host, maxFetchResponseBytes)
|
|
}
|
|
if size > remainingBytes {
|
|
return moejs.Undefined(), errFetchResponseBudget
|
|
}
|
|
// The result is built from JavaScript objects, not a host map: a hook may
|
|
// return it, or part of it, as it is.
|
|
headers := r.NewObject()
|
|
for name, value := range response.Headers {
|
|
if err = headers.CreateDataPropertyOrThrow(r, r.KeyFromGoString(name), moejs.String(value)); err != nil {
|
|
return moejs.Undefined(), err
|
|
}
|
|
}
|
|
headersValue, err := r.FromGo(headers)
|
|
if err != nil {
|
|
return moejs.Undefined(), err
|
|
}
|
|
body := moejs.String("")
|
|
if wantBytes {
|
|
// An ArrayBuffer over the response bytes, which belong to this call.
|
|
if response.Body == nil {
|
|
response.Body = []byte{}
|
|
}
|
|
if body, err = r.FromGo(response.Body); err != nil {
|
|
return moejs.Undefined(), err
|
|
}
|
|
} else if request.Method != http.MethodHead {
|
|
text := string(response.Body)
|
|
if body, err = c.runtime.ParseJSONString(text); err != nil {
|
|
body = moejs.String(text)
|
|
}
|
|
}
|
|
result := r.NewObject()
|
|
for _, member := range []struct {
|
|
name string
|
|
value moejs.Value
|
|
}{{"status", moejs.Int(int64(response.Status))}, {"headers", headersValue}, {"body", body}} {
|
|
if err = result.CreateDataPropertyOrThrow(r, r.KeyFromGoString(member.name), member.value); err != nil {
|
|
return moejs.Undefined(), err
|
|
}
|
|
}
|
|
return r.FromGo(result)
|
|
}
|
|
|
|
// fetchRequest reads the utils.fetch argument: {url, method?, headers?,
|
|
// responseType?}, plus body when allowPost is set. wantBytes is a
|
|
// responseType of "bytes": the body is returned as an ArrayBuffer instead of
|
|
// parsed JSON or text.
|
|
func fetchRequest(r *moejs.Realm, argument moejs.Value, allowPost bool) (request FetchRequest, host string, wantBytes bool, err error) {
|
|
if !argument.IsObject() {
|
|
return FetchRequest{}, "", false, r.TypeError("utils.fetch request must be an object")
|
|
}
|
|
exported, err := r.ToGoStrict(argument)
|
|
if err != nil {
|
|
return FetchRequest{}, "", false, err
|
|
}
|
|
members, ok := exported.(map[string]any)
|
|
if !ok {
|
|
return FetchRequest{}, "", false, r.TypeError("utils.fetch request must be an object")
|
|
}
|
|
request = FetchRequest{Method: http.MethodGet}
|
|
hasBody := false
|
|
for name, value := range members {
|
|
switch name {
|
|
case "url":
|
|
if request.URL, ok = value.(string); !ok {
|
|
return FetchRequest{}, "", false, r.TypeError("utils.fetch url must be a string")
|
|
}
|
|
case "method":
|
|
if value == nil {
|
|
continue
|
|
}
|
|
method, isString := value.(string)
|
|
if !isString {
|
|
return FetchRequest{}, "", false, r.TypeError("utils.fetch method must be a string")
|
|
}
|
|
if method = strings.ToUpper(strings.TrimSpace(method)); method != "" {
|
|
request.Method = method
|
|
}
|
|
case "headers":
|
|
if value == nil {
|
|
continue
|
|
}
|
|
headers, isObject := value.(map[string]any)
|
|
if !isObject {
|
|
return FetchRequest{}, "", false, r.TypeError("utils.fetch headers must be an object")
|
|
}
|
|
request.Headers = make(map[string]string, len(headers))
|
|
for headerName, headerValue := range headers {
|
|
text, isString := headerValue.(string)
|
|
if !isString {
|
|
return FetchRequest{}, "", false, r.TypeError("utils.fetch header %q must be a string", headerName)
|
|
}
|
|
request.Headers[strings.TrimSpace(headerName)] = text
|
|
}
|
|
case "responseType":
|
|
if value == nil {
|
|
continue
|
|
}
|
|
responseType, isString := value.(string)
|
|
if !isString || (responseType != "json" && responseType != "bytes") {
|
|
return FetchRequest{}, "", false, r.TypeError(`utils.fetch responseType must be "json" or "bytes"`)
|
|
}
|
|
wantBytes = responseType == "bytes"
|
|
case "body":
|
|
if !allowPost {
|
|
return FetchRequest{}, "", false, r.TypeError("utils.fetch request has unsupported member %q", name)
|
|
}
|
|
if value == nil {
|
|
continue
|
|
}
|
|
text, isString := value.(string)
|
|
if !isString {
|
|
return FetchRequest{}, "", false, r.TypeError("utils.fetch body must be a string")
|
|
}
|
|
request.Body, hasBody = text, true
|
|
default:
|
|
return FetchRequest{}, "", false, r.TypeError("utils.fetch request has unsupported member %q", name)
|
|
}
|
|
}
|
|
switch {
|
|
case request.Method == http.MethodGet || request.Method == http.MethodHead:
|
|
if hasBody {
|
|
return FetchRequest{}, "", false, r.TypeError("utils.fetch body requires method POST")
|
|
}
|
|
case request.Method == http.MethodPost && allowPost:
|
|
if len(request.Body) > MaxFetchBodyBytes {
|
|
return FetchRequest{}, "", false, r.TypeError("utils.fetch body exceeds %d bytes", MaxFetchBodyBytes)
|
|
}
|
|
case allowPost:
|
|
return FetchRequest{}, "", false, r.TypeError("utils.fetch supports only GET, HEAD and POST")
|
|
default:
|
|
return FetchRequest{}, "", false, r.TypeError("utils.fetch supports only GET and HEAD")
|
|
}
|
|
if len(request.URL) > maxFetchURLBytes {
|
|
return FetchRequest{}, "", false, r.TypeError("utils.fetch url exceeds %d bytes", maxFetchURLBytes)
|
|
}
|
|
parsed, err := url.Parse(request.URL)
|
|
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
|
|
return FetchRequest{}, "", false, r.TypeError("utils.fetch url must be an absolute http(s) URL")
|
|
}
|
|
if err = ValidateRequestHeaders(request.Headers); err != nil {
|
|
return FetchRequest{}, "", false, r.TypeError("utils.fetch: %s", err)
|
|
}
|
|
return request, parsed.Host, wantBytes, nil
|
|
}
|
|
|
|
// yieldSlot lends the call's execution slot to other calls while it waits on
|
|
// the network. Parked runtimes are bounded by the engine's parked tokens;
|
|
// without one the call keeps its slot and waits holding it.
|
|
func (c *runtimeCall) yieldSlot() {
|
|
select {
|
|
case c.engine.parked <- struct{}{}:
|
|
default:
|
|
return
|
|
}
|
|
c.parked = true
|
|
<-c.engine.semaphore
|
|
c.holdsSlot = false
|
|
}
|
|
|
|
// reclaimSlot takes an execution slot back for the call's JavaScript, waiting
|
|
// no longer than the caller and fetchTimeout allow.
|
|
func (c *runtimeCall) reclaimSlot() bool {
|
|
if c.holdsSlot {
|
|
return true
|
|
}
|
|
timer := time.NewTimer(fetchTimeout)
|
|
defer timer.Stop()
|
|
select {
|
|
case c.engine.semaphore <- struct{}{}:
|
|
c.holdsSlot = true
|
|
case <-c.ctx.Done():
|
|
case <-timer.C:
|
|
}
|
|
<-c.engine.parked
|
|
c.parked = false
|
|
return c.holdsSlot
|
|
}
|