script

package
v0.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 30, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package script 实现管理员动态 goja 脚本的编译与执行。

Index

Constants

View Source
const (
	HookRequest  = "onRequest"
	HookUpstream = "onUpstreamRequest"
	HookResponse = "onResponse"
)

Variables

This section is empty.

Functions

func MatchScope

func MatchScope(scope models.ScriptScope, channelID uint, model string) bool

MatchScope 报告 scope 是否对目标请求生效。 channelID 为 0 表示尚未路由(入站 onRequest 阶段),此时 channel 作用域不命中。 ChannelIDs 与 ModelNames 均空 => 全局,恒命中。

Types

type Compiled

type Compiled struct {
	ID       uint
	Name     string
	Priority int
	Scope    models.ScriptScope
	Program  *goja.Program
	// contains filtered or unexported fields
}

Compiled 是单个脚本的编译产物 + 元数据 + 复用池。不可变、可被多个请求并发只读共享。

func Compile

func Compile(s models.AdminScript) (*Compiled, error)

Compile 把 AdminScript 编译成 Compiled;语法错误时返回带脚本名的错误。

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine 在 relay 挂点执行脚本。并发安全:每次执行新建独立 *goja.Runtime。

func NewEngine

func NewEngine(provider ScriptProvider, logger *zap.Logger, timeout time.Duration) *Engine

NewEngine 构造引擎。timeout <= 0 时回落到 50ms。

func (*Engine) Run

func (e *Engine) Run(in HookInput) HookResult

Run 按 Priority 顺序对命中脚本执行 in.Hook 钩子。 任一脚本 reject 立即短路;脚本报错/超时 fail-open(跳过其改动,串原 body)。

type HeaderOp

type HeaderOp struct {
	Name   string
	Value  string
	Remove bool
}

HeaderOp 是脚本对请求头的一次写操作。Remove=true 表示删除该头, 否则表示设置(替换)为 Value。

type HookInput

type HookInput struct {
	Hook      string // HookRequest / HookUpstream / HookResponse
	ChannelID uint   // 0 = 尚未路由
	Model     string
	User      map[string]any
	Headers   map[string]string
	Channel   map[string]any // 出站/响应阶段为 {id,name}
	Protocol  string         // 上游协议(出站/响应)
	Body      []byte
}

HookInput 是一次钩子执行的输入。

type HookResult

type HookResult struct {
	Body     []byte
	Changed  bool
	Rejected bool
	Status   int
	Message  string
	// HeaderOps 是脚本通过 ctx.setHeader/removeHeader 累积的请求头改写操作,
	// 按调用顺序排列。仅出站 onUpstreamRequest 挂点会应用它们(见 native backend)。
	HeaderOps []HeaderOp
}

HookResult 是一次(整条脚本链)执行结果。

type ScriptProvider

type ScriptProvider interface {
	MatchScripts(channelID uint, model string) []*Compiled
}

ScriptProvider 返回命中(已按 scope 过滤 + enabled)的已编译脚本,按 Priority 升序。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL