chore: 初始化仓库(零源工具箱 0.1.0 基线)

- Go 主进程 cmd/zerorigin(托盘常驻 + 触发器/规则/动作引擎)
- Wails v3 设置进程 cmd/settings(独立 module)
- 监督进程 cmd/watchdog(-supervise 异常重启)
- 构建脚本 build.bat / NSIS 安装包 deploy/、便携版 portable/
- 架构与 MVP 计划文档 docs/、阶段 0-4 验收记录 deploy/acceptance-0-4.md
This commit is contained in:
zerorigin2019 committed 2026-08-05 00:42:45 +08:00
commit 0a1c1e82ea
188 files changed
+19926

No files matched your search

+278
View File
@@ -0,0 +1,278 @@
// Package rule 实现规则引擎:事件 → 匹配 → 冷却 → 动作链执行。
// 引擎不依赖 Win32 具体实现;运行时使用内存快照,不读磁盘。
package rule
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"sort"
"sync"
"sync/atomic"
"time"
"zerorigin/internal/action"
"zerorigin/internal/config"
"zerorigin/internal/trigger"
)
// defaultActionTimeout 为单个动作的最大执行时间。
const defaultActionTimeout = 10 * time.Second
// NewActionFunc 按 ID 构造动作实例(测试可注入 fake)。
type NewActionFunc func(id string) (action.Action, error)
// Snapshot 为已校验规则的只读运行时快照。
type Snapshot struct {
Rules []*config.Rule // 按 priority 降序
BadCount int // 被跳过的坏规则数量
GlobalEnabled bool // 全局开关(config.global.enabled)
}
// Engine 为规则引擎。
type Engine struct {
logger *slog.Logger
newAction NewActionFunc
snap atomic.Pointer[Snapshot]
// fullscreen 为全屏状态提供者(由 app 注入,nil 表示不抑制)。
fullscreen func() bool
mu sync.Mutex
lastExec map[string]time.Time // 规则冷却:ID → 上次触发时间
lastLog map[string]time.Time // 触发日志限速:ID → 上次 Info 时间
running map[string]bool // 规则并发保护
wg sync.WaitGroup
}
// New 创建规则引擎。
func New(logger *slog.Logger, newAction NewActionFunc) *Engine {
if newAction == nil {
newAction = action.New
}
return &Engine{
logger: logger,
newAction: newAction,
lastExec: make(map[string]time.Time),
lastLog: make(map[string]time.Time),
running: make(map[string]bool),
}
}
// SetFullscreenProvider 注入全屏状态提供者(返回 true 表示前台窗口全屏)。
// 引擎在规则匹配前查询;提供者为 nil 时不做全屏抑制。
func (e *Engine) SetFullscreenProvider(f func() bool) {
e.fullscreen = f
}
// SetSnapshot 原子替换运行时快照。
func (e *Engine) SetSnapshot(s *Snapshot) {
e.snap.Store(s)
}
// Snapshot 返回当前快照(可能为 nil)。
func (e *Engine) Snapshot() *Snapshot {
return e.snap.Load()
}
// BuildSnapshot 从配置构造快照:逐条校验,坏规则跳过并计数。
// 校验失败仅影响该规则,不阻止其他规则加载。
func BuildSnapshot(cfg *config.Config, newAction NewActionFunc) *Snapshot {
if newAction == nil {
newAction = action.New
}
snap := &Snapshot{GlobalEnabled: cfg.Global.Enabled}
for i := range cfg.Rules {
r := &cfg.Rules[i]
if err := validateRule(r, newAction); err != nil {
snap.BadCount++
continue
}
snap.Rules = append(snap.Rules, r)
}
// 优先级降序,稳定排序保证同优先级按配置顺序。
sort.SliceStable(snap.Rules, func(i, j int) bool {
return snap.Rules[i].Priority > snap.Rules[j].Priority
})
return snap
}
// validateRule 校验单条规则。条件系统 MVP 不支持(非空即坏)。
func validateRule(r *config.Rule, newAction NewActionFunc) error {
if r.ID == "" {
return errors.New("empty rule id")
}
if !trigger.Known(r.Trigger.Type) {
return fmt.Errorf("unknown trigger %q", r.Trigger.Type)
}
if len(r.Actions) == 0 {
return errors.New("rule has no actions")
}
if len(r.Conditions) > 0 {
return errors.New("conditions not supported in MVP")
}
switch r.Fullscreen {
case "", "ignore", "allow":
default:
return fmt.Errorf("invalid fullscreen value %q (want ignore|allow)", r.Fullscreen)
}
for _, a := range r.Actions {
act, err := newAction(a.Type)
if err != nil {
return fmt.Errorf("action %q: %w", a.Type, err)
}
if err := act.Validate(a.Params); err != nil {
return fmt.Errorf("action %q: %w", a.Type, err)
}
}
return nil
}
// TriggerKey 生成触发器去重键(type + 稳定序列化的参数)。
func TriggerKey(tc config.TriggerConfig) string {
b, _ := json.Marshal(tc.Params)
return tc.Type + "|" + string(b)
}
// matches 判断规则触发器是否匹配事件:类型一致且规则声明的
// 参数与事件 payload 一致(事件多余的字段不参与匹配)。
func matches(r *config.Rule, ev trigger.Event) bool {
if r.Trigger.Type != ev.Type {
return false
}
for k, want := range r.Trigger.Params {
got, ok := ev.Payload[k]
if !ok {
continue
}
if fmt.Sprint(got) != fmt.Sprint(want) {
return false
}
}
return true
}
// HandleEvent 处理触发事件:按优先级找到第一条匹配且可执行的规则,
// 在独立 goroutine 中执行其动作链。必须在触发线程快速返回。
func (e *Engine) HandleEvent(ev trigger.Event) {
snap := e.snap.Load()
if snap == nil || !snap.GlobalEnabled {
return // 全局关闭时不匹配任何规则
}
fs := e.fullscreen != nil && e.fullscreen()
for _, r := range snap.Rules {
if !r.Enabled || !matches(r, ev) {
continue
}
if fs && r.Fullscreen != "allow" {
// 全屏前台窗口:默认忽略(allow 规则豁免)。
continue
}
if !e.cooldownOK(r) {
return // 冷却中:该事件已消耗,不再尝试其他规则
}
if !e.tryAcquire(r.ID) {
return // 同规则执行中:丢弃新事件
}
e.wg.Add(1)
go e.runRule(r, ev)
return
}
}
// cooldownOK 检查并预订规则冷却时间戳。
func (e *Engine) cooldownOK(r *config.Rule) bool {
e.mu.Lock()
defer e.mu.Unlock()
now := time.Now()
if last, ok := e.lastExec[r.ID]; ok {
if now.Sub(last) < time.Duration(r.CooldownMs)*time.Millisecond {
return false
}
}
e.lastExec[r.ID] = now
return true
}
func (e *Engine) tryAcquire(id string) bool {
e.mu.Lock()
defer e.mu.Unlock()
if e.running[id] {
return false
}
e.running[id] = true
return true
}
func (e *Engine) release(id string) {
e.mu.Lock()
defer e.mu.Unlock()
delete(e.running, id)
}
// firedLog 输出规则触发日志(高频规则限速采样:每规则每秒至多一条 Info)。
func (e *Engine) firedLog(r *config.Rule, ev trigger.Event) {
e.mu.Lock()
now := time.Now()
rateLimited := false
if last, ok := e.lastLog[r.ID]; ok && now.Sub(last) < time.Second {
rateLimited = true
} else {
e.lastLog[r.ID] = now
}
e.mu.Unlock()
if rateLimited {
e.logger.Debug("rule fired", "rule", r.ID, "event", ev.Type, "actions", len(r.Actions))
return
}
e.logger.Info("rule fired", "rule", r.ID, "event", ev.Type, "actions", len(r.Actions))
}
// runRule 顺序执行规则的动作链,错误隔离:单动作失败记录并继续。
func (e *Engine) runRule(r *config.Rule, ev trigger.Event) {
defer e.wg.Done()
defer e.release(r.ID)
// 动作链 panic 兜底:任何动作实现异常不得拖垮主进程。
defer func() {
if rec := recover(); rec != nil {
e.logger.Error("rule action panic", "rule", r.ID, "panic", rec)
}
}()
ctx, cancel := context.WithTimeout(context.Background(), defaultActionTimeout)
defer cancel()
e.firedLog(r, ev)
failed := 0
for _, ac := range r.Actions {
a, err := e.newAction(ac.Type)
if err != nil {
e.logger.Error("rule action skipped", "rule", r.ID, "action", ac.Type, "err", err)
failed++
continue
}
if err := a.Validate(ac.Params); err != nil {
e.logger.Error("rule action invalid", "rule", r.ID, "action", ac.Type, "err", err)
failed++
continue
}
if err := a.Execute(ctx, ac.Params); err != nil {
e.logger.Error("rule action failed", "rule", r.ID, "action", ac.Type, "err", err)
failed++
continue // 错误隔离:继续后续动作
}
e.logger.Debug("rule action ok", "rule", r.ID, "action", ac.Type)
}
if failed > 0 {
e.logger.Warn("rule completed with errors", "rule", r.ID, "failed", failed)
}
}
// Wait 等待所有进行中的动作链结束(退出前调用)。
func (e *Engine) Wait() {
e.wg.Wait()
}
+314
View File
@@ -0,0 +1,314 @@
package rule
import (
"context"
"errors"
"log/slog"
"sync"
"testing"
"time"
"zerorigin/internal/action"
"zerorigin/internal/config"
"zerorigin/internal/trigger"
)
// fakeAction 记录执行顺序与参数的可编程动作。
type fakeAction struct {
id string
validate func(map[string]any) error
execute func(ctx context.Context) error
executed []string
mu sync.Mutex
block chan struct{} // 非 nil 时 Execute 阻塞等待
}
func (f *fakeAction) ID() string { return f.id }
func (f *fakeAction) Name() string { return f.id }
func (f *fakeAction) Schema() action.ActionSchema {
return action.ActionSchema{}
}
func (f *fakeAction) Validate(p map[string]any) error {
if f.validate != nil {
return f.validate(p)
}
return nil
}
func (f *fakeAction) Execute(ctx context.Context, p map[string]any) error {
f.mu.Lock()
f.executed = append(f.executed, f.id)
f.mu.Unlock()
if f.block != nil {
select {
case <-f.block:
case <-ctx.Done():
return ctx.Err()
}
}
if f.execute != nil {
return f.execute(ctx)
}
return nil
}
func (f *fakeAction) Executed() []string {
f.mu.Lock()
defer f.mu.Unlock()
return append([]string(nil), f.executed...)
}
// fakeRegistry 供测试注入的动作工厂。
type fakeRegistry struct {
acts map[string]*fakeAction
}
func (r *fakeRegistry) newAction(id string) (action.Action, error) {
a, ok := r.acts[id]
if !ok {
return nil, errors.New("no such action")
}
return a, nil
}
func newTestEngine(t *testing.T, reg *fakeRegistry) *Engine {
logger := slog.New(slog.NewTextHandler(discard{}, nil))
e := New(logger, reg.newAction)
t.Cleanup(e.Wait)
return e
}
type discard struct{}
func (discard) Write(p []byte) (int, error) { return len(p), nil }
func testRule(id string, priority int, trType string, trParams map[string]any, actions []config.ActionConfig, cooldown int) *config.Rule {
return &config.Rule{
ID: id,
Name: id,
Enabled: true,
Priority: priority,
Trigger: config.TriggerConfig{Type: trType, Params: trParams},
Actions: actions,
CooldownMs: cooldown,
}
}
func TestMatches(t *testing.T) {
r := testRule("r1", 100, "mouse_corner", map[string]any{"corner": "bottom_left"}, nil, 0)
ev := trigger.Event{Type: "mouse_corner", Payload: map[string]any{"corner": "bottom_left"}}
if !matches(r, ev) {
t.Fatal("should match")
}
ev2 := trigger.Event{Type: "mouse_corner", Payload: map[string]any{"corner": "top_left"}}
if matches(r, ev2) {
t.Fatal("different corner should not match")
}
ev3 := trigger.Event{Type: "mouse_edge_wheel", Payload: map[string]any{"corner": "bottom_left"}}
if matches(r, ev3) {
t.Fatal("different type should not match")
}
// 事件多余字段不参与匹配
ev4 := trigger.Event{Type: "mouse_corner", Payload: map[string]any{"corner": "bottom_left", "direction": "up"}}
if !matches(r, ev4) {
t.Fatal("extra event field should not break match")
}
}
func TestBuildSnapshotSkipsBadRules(t *testing.T) {
reg := &fakeRegistry{acts: map[string]*fakeAction{
"a1": {id: "a1"},
}}
cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{
*testRule("good", 100, "mouse_corner", map[string]any{"corner": "bottom_left"}, []config.ActionConfig{{Type: "a1"}}, 0),
*testRule("bad-action", 100, "mouse_corner", map[string]any{"corner": "top_left"}, []config.ActionConfig{{Type: "nope"}}, 0),
*testRule("bad-trigger", 100, "no_such", nil, []config.ActionConfig{{Type: "a1"}}, 0),
*testRule("bad-conditions", 100, "mouse_corner", map[string]any{"corner": "top_right"},
[]config.ActionConfig{{Type: "a1"}},
0, // 注意:Conditions 手动设置
),
}}
cfg.Rules[3].Conditions = []config.ConditionConfig{{Type: "x"}}
snap := BuildSnapshot(cfg, reg.newAction)
if len(snap.Rules) != 1 {
t.Fatalf("active rules = %d, want 1", len(snap.Rules))
}
if snap.BadCount != 3 {
t.Fatalf("bad count = %d, want 3", snap.BadCount)
}
}
func TestPriorityOrder(t *testing.T) {
reg := &fakeRegistry{acts: map[string]*fakeAction{
"a": {id: "a"},
}}
e := newTestEngine(t, reg)
// 两条规则同触发器:低优先级在前(模拟配置顺序),高优先级应优先执行
cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{
*testRule("low", 10, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "a"}}, 0),
*testRule("high", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "a"}}, 0),
}}
e.SetSnapshot(BuildSnapshot(cfg, reg.newAction))
// 快照应按优先级降序
snap := e.Snapshot()
if snap.Rules[0].ID != "high" || snap.Rules[1].ID != "low" {
t.Fatalf("sort order wrong: %s, %s", snap.Rules[0].ID, snap.Rules[1].ID)
}
e.HandleEvent(trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}})
time.Sleep(50 * time.Millisecond)
// 高优先级执行了一次,低优先级未执行(HandleEvent 只执行第一条匹配)
if got := reg.acts["a"].Executed(); len(got) != 1 {
t.Fatalf("executed = %v, want exactly 1", got)
}
}
func TestCooldown(t *testing.T) {
reg := &fakeRegistry{acts: map[string]*fakeAction{
"a": {id: "a"},
}}
e := newTestEngine(t, reg)
cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{
*testRule("r", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "a"}}, 200),
}}
e.SetSnapshot(BuildSnapshot(cfg, reg.newAction))
ev := trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}}
e.HandleEvent(ev)
e.HandleEvent(ev) // 冷却期内:应丢弃
time.Sleep(50 * time.Millisecond)
if got := reg.acts["a"].Executed(); len(got) != 1 {
t.Fatalf("executed = %v, want 1 (cooldown should drop second)", got)
}
time.Sleep(250 * time.Millisecond)
e.HandleEvent(ev)
time.Sleep(50 * time.Millisecond)
if got := reg.acts["a"].Executed(); len(got) != 2 {
t.Fatalf("executed = %v, want 2 after cooldown", got)
}
}
func TestErrorIsolation(t *testing.T) {
reg := &fakeRegistry{acts: map[string]*fakeAction{
"fail": {id: "fail", execute: func(context.Context) error { return errors.New("boom") }},
"ok": {id: "ok"},
}}
e := newTestEngine(t, reg)
cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{
*testRule("r", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"},
[]config.ActionConfig{{Type: "fail"}, {Type: "ok"}}, 0),
}}
e.SetSnapshot(BuildSnapshot(cfg, reg.newAction))
e.HandleEvent(trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}})
time.Sleep(50 * time.Millisecond)
got := reg.acts["ok"].Executed()
if len(got) != 1 {
t.Fatalf("ok action executed = %v, want 1 (isolation should continue)", got)
}
}
func TestConcurrencyGuard(t *testing.T) {
reg := &fakeRegistry{acts: map[string]*fakeAction{
"slow": {id: "slow", block: make(chan struct{})},
}}
e := newTestEngine(t, reg)
cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{
*testRule("r", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "slow"}}, 0),
}}
e.SetSnapshot(BuildSnapshot(cfg, reg.newAction))
ev := trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}}
e.HandleEvent(ev) // 启动第一个(阻塞)
e.HandleEvent(ev) // 同规则执行中:丢弃
time.Sleep(50 * time.Millisecond)
close(reg.acts["slow"].block) // 放行
time.Sleep(50 * time.Millisecond)
if got := reg.acts["slow"].Executed(); len(got) != 1 {
t.Fatalf("executed = %v, want 1 (concurrent drop)", got)
}
}
// TestGlobalEnabled 验证全局开关:关闭时事件不触发任何规则。
func TestGlobalEnabled(t *testing.T) {
reg := &fakeRegistry{acts: map[string]*fakeAction{
"a": {id: "a"},
}}
e := newTestEngine(t, reg)
cfg := &config.Config{
Global: config.GlobalConfig{Enabled: false},
Rules: []config.Rule{
*testRule("r", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "a"}}, 0),
},
}
snap := BuildSnapshot(cfg, reg.newAction)
if snap.GlobalEnabled {
t.Fatal("GlobalEnabled should be false")
}
e.SetSnapshot(snap)
e.HandleEvent(trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}})
time.Sleep(50 * time.Millisecond)
if got := reg.acts["a"].Executed(); len(got) != 0 {
t.Fatalf("executed = %v, want 0 when globally disabled", got)
}
// 开启后应触发
cfg.Global.Enabled = true
e.SetSnapshot(BuildSnapshot(cfg, reg.newAction))
e.HandleEvent(trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}})
time.Sleep(50 * time.Millisecond)
if got := reg.acts["a"].Executed(); len(got) != 1 {
t.Fatalf("executed = %v, want 1 when enabled", got)
}
}
// TestFullscreenSuppression 验证全屏抑制:默认规则忽略、allow 规则豁免、退出全屏恢复。
func TestFullscreenSuppression(t *testing.T) {
reg := &fakeRegistry{acts: map[string]*fakeAction{
"a": {id: "a"},
"b": {id: "b"},
}}
e := newTestEngine(t, reg)
fs := true
e.SetFullscreenProvider(func() bool { return fs })
// 两条同触发器规则:默认(ignore) + allow
cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{
*testRule("default-rule", 200, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "a"}}, 0),
*testRule("allow-rule", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "b"}}, 0),
}}
cfg.Rules[1].Fullscreen = "allow"
e.SetSnapshot(BuildSnapshot(cfg, reg.newAction))
ev := trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}}
// 全屏:默认规则被忽略,allow 规则触发
fs = true
e.HandleEvent(ev)
time.Sleep(50 * time.Millisecond)
if got := reg.acts["a"].Executed(); len(got) != 0 {
t.Fatalf("default rule executed in fullscreen: %v", got)
}
if got := reg.acts["b"].Executed(); len(got) != 1 {
t.Fatalf("allow rule executed = %v, want 1", got)
}
// 退出全屏:默认规则恢复
fs = false
e.HandleEvent(ev)
time.Sleep(50 * time.Millisecond)
if got := reg.acts["a"].Executed(); len(got) != 1 {
t.Fatalf("default rule executed after fullscreen = %v, want 1", got)
}
}
// TestFullscreenProviderNil 验证未注入提供者时不抑制(默认行为兼容)。
func TestFullscreenProviderNil(t *testing.T) {
reg := &fakeRegistry{acts: map[string]*fakeAction{
"a": {id: "a"},
}}
e := newTestEngine(t, reg) // 不注入 provider
cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{
*testRule("r", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "a"}}, 0),
}}
e.SetSnapshot(BuildSnapshot(cfg, reg.newAction))
e.HandleEvent(trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}})
time.Sleep(50 * time.Millisecond)
if got := reg.acts["a"].Executed(); len(got) != 1 {
t.Fatalf("executed = %v, want 1 (no provider = no suppression)", got)
}
}
+43
View File
@@ -0,0 +1,43 @@
package rule
import (
"io"
"log/slog"
"testing"
"time"
"zerorigin/internal/config"
"zerorigin/internal/trigger"
)
// TestEndToEndWithRealActions 验证"事件 → 引擎匹配 → 真实动作链"完整链路
// (真实 action.New 与真实 SendInput 调用,不 panic、不阻塞)。
// 物理输入注入(鼠标移动/按键)依赖活动桌面会话,由手工验收覆盖。
func TestEndToEndWithRealActions(t *testing.T) {
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
cfg := config.Default()
e := New(logger, nil) // nil → 真实 action.New
e.SetSnapshot(BuildSnapshot(cfg, nil))
// 模拟左下角事件(与 mouse_corner 触发器真实 payload 一致)。
e.HandleEvent(trigger.Event{
Type: "mouse_corner",
Timestamp: time.Now(),
Payload: map[string]any{"corner": "bottom_left", "screen": "all"},
})
// 模拟顶部滚轮事件(与 mouse_edge_wheel 真实 payload 一致)。
e.HandleEvent(trigger.Event{
Type: "mouse_edge_wheel",
Timestamp: time.Now(),
Payload: map[string]any{"edge": "top", "direction": "up", "delta": 120},
})
e.Wait() // 等待动作链完成(含 SendInput 调用)
// 冷却保护下的重复事件不应产生问题。
e.HandleEvent(trigger.Event{
Type: "mouse_corner",
Timestamp: time.Now(),
Payload: map[string]any{"corner": "bottom_left", "screen": "all"},
})
e.Wait()
}