mirror of
https://github.com/chaitin/MonkeyCode.git
synced 2026-11-30 16:47:16 +08:00
Fix/relay data attach ready (#1596)
* fix(relay): 等待同代次控制通道就绪后附着数据连接 * fix(relay): 拒绝已换代的附着并区分确认读取中断 * fix(relay): 区分 ready_ack 分片中断与消息超限 * fix(endpoint): 读取设备状态失败时保留查询错误 * test(endpoint): 补齐 Nginx 升级夹具的代理路由配置
This commit is contained in:
1 parent
1b48a8ecf8
commit
567a1396e6
13 files changed
+698
-65
No files matched your search
@@ -0,0 +1,18 @@
|
||||
# MonkeyAI 与 MonkeyCode
|
||||
|
||||
MonkeyAI 提供团队 AI 办公工作台。仓库同时包含 MonkeyCode 服务端和客户端。
|
||||
|
||||
## 目录
|
||||
|
||||
- `monkeyai/` 部署 MonkeyAI。Go 1.27 后端提供管理和 Agent API,engine 驱动云端执行环境,web 和 landing 提供管理页面与产品站。设备登记见 [endpoint 模块地图](monkeyai/backend/internal/endpoint/guidelines.md),设备中转见 [relay 模块地图](monkeyai/backend/internal/relay/guidelines.md)。
|
||||
- `backend/` 和 `frontend/` 分别提供 MonkeyCode 的 Go 服务端与 Web 前端。
|
||||
- `desktop/` 使用 Rust 和 Tauri 2 构建桌面客户端。`browser-extension/` 连接桌面内核,按用户授权转发浏览器调试命令。
|
||||
- `mobile/` 使用 Expo 和 React Native 构建移动客户端。
|
||||
- `agent/` 和 `plugins/` 分别接入 OhMyAgent 和 MonkeyCode 官方插件子模块。
|
||||
- `docs/` 保存架构、实施计划和测试文档。
|
||||
|
||||
## 配置与术语
|
||||
|
||||
- `monkeyai/docker-compose.yml` 编排 PostgreSQL、迁移与应用服务。
|
||||
- `.gitmodules` 声明两个子模块的路径和来源。
|
||||
- [领域术语](CONTEXT.md) 与 [后端上下文](monkeyai/backend/CONTEXT.md) 定义身份、资源与授权边界。
|
||||
@@ -1,3 +1,7 @@
|
||||
// [INPUT]: 依赖 PostgreSQL 设备记录、OAuth 设备授权与审计事件。
|
||||
// [OUTPUT]: 提供执行设备状态读取、登记、身份核验与撤销。
|
||||
// [POS]: endpoint 的执行设备持久化入口,为 relay 提供登记版本、授权版本和租约代次。
|
||||
// [PROTOCOL]: 变更时更新此头部,然后检查 guidelines.md
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
@@ -126,19 +130,22 @@ func (e *Execution) Snapshot(ctx context.Context, userID string, executeOnly boo
|
||||
}
|
||||
|
||||
func (e *Execution) ReadState(ctx context.Context, tx pgx.Tx, userID, machineID string) (ExecutionState, error) {
|
||||
row, err := sqlc.New(tx).Get(ctx, sqlc.GetParams{UserID: userID, MachineID: machineID})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ExecutionState{}, executionFailure(404, "device_not_found")
|
||||
}
|
||||
return executionState(row), err
|
||||
return readExecutionState(ctx, tx, userID, machineID)
|
||||
}
|
||||
|
||||
func (e *Execution) State(ctx context.Context, userID, machineID string) (ExecutionState, error) {
|
||||
row, err := sqlc.New(e.pool).Get(ctx, sqlc.GetParams{UserID: userID, MachineID: machineID})
|
||||
return readExecutionState(ctx, e.pool, userID, machineID)
|
||||
}
|
||||
|
||||
func readExecutionState(ctx context.Context, db sqlc.DBTX, userID, machineID string) (ExecutionState, error) {
|
||||
row, err := sqlc.New(db).Get(ctx, sqlc.GetParams{UserID: userID, MachineID: machineID})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ExecutionState{}, executionFailure(http.StatusNotFound, "device_not_found")
|
||||
}
|
||||
return executionState(row), err
|
||||
if err != nil {
|
||||
return ExecutionState{}, err
|
||||
}
|
||||
return executionState(row), nil
|
||||
}
|
||||
|
||||
func KeyID(key []byte) string {
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
// [INPUT]: 依赖 PostgreSQL 测试库、设备登记与 OAuth 授权服务。
|
||||
// [OUTPUT]: 验证执行状态读取、设备绑定、发布、接管、撤销和恢复。
|
||||
// [POS]: endpoint 的执行设备持久化回归,覆盖事务与连接池入口。
|
||||
// [PROTOCOL]: 变更时更新此头部,然后检查 guidelines.md
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -12,9 +18,44 @@ import (
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/identity"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func TestExecutionStateReadErrors(t *testing.T) {
|
||||
pool := testDatabase(t)
|
||||
execution := NewExecution(pool, nil)
|
||||
user, machine := uuid.New().String(), uuid.New().String()
|
||||
tx, err := pool.Begin(t.Context())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = tx.Rollback(context.Background()) })
|
||||
_, err = execution.State(t.Context(), user, machine)
|
||||
requireExecutionError(t, err, "device_not_found")
|
||||
_, err = execution.ReadState(t.Context(), tx, user, machine)
|
||||
requireExecutionError(t, err, "device_not_found")
|
||||
|
||||
var logs bytes.Buffer
|
||||
logger := slog.Default()
|
||||
slog.SetDefault(slog.New(slog.NewTextHandler(&logs, nil)))
|
||||
t.Cleanup(func() { slog.SetDefault(logger) })
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
if _, err := execution.State(ctx, user, machine); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("连接池读取返回 %v,期望 context.Canceled", err)
|
||||
}
|
||||
if err := tx.Rollback(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := execution.ReadState(t.Context(), tx, user, machine); !errors.Is(err, pgx.ErrTxClosed) {
|
||||
t.Fatalf("事务读取返回 %v,期望 pgx.ErrTxClosed", err)
|
||||
}
|
||||
if bytes.Contains(logs.Bytes(), []byte("executionState")) {
|
||||
t.Fatalf("查询失败后仍解析了设备记录:%s", &logs)
|
||||
}
|
||||
}
|
||||
|
||||
func executionPrincipal(t *testing.T, pool *pgxpool.Pool, userID string, scopes []string) identity.Principal {
|
||||
t.Helper()
|
||||
p := identity.Principal{UserID: userID, ClientID: "monkeyai-desktop", Audience: identity.Audience, Purpose: "user", Scopes: scopes, RevocationVersion: 1}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# internal/endpoint/
|
||||
|
||||
> L2 | 父级:[项目地图](../../../../guidelines.md)
|
||||
|
||||
endpoint 保存用户的设备登记,提供设备目录和消息桥接。执行设备通过 relay 发布控制通道时,relay 从本模块读取设备公钥、授权版本和租约代次。查询无记录时返回 `device_not_found`。其他查询错误原样返回,只有读到设备记录才解析其协议字段。
|
||||
|
||||
## 实现
|
||||
|
||||
- `admin.go` 按管理员可见的成员范围查询设备列表和概况。
|
||||
- `connection.go` 读写设备消息,限制待发送队列,定时探活并复核凭据。
|
||||
- `execution.go` 读取执行状态,在设备登记、发布与撤销的事务内更新版本并核验授权。
|
||||
- `handler.go` 暴露 Agent 设备目录、变更和 WebSocket 接入入口。
|
||||
- `names.go` 合并设备别名、独立运行端名称与登记名称,确定目录展示名。
|
||||
- `observe.go` 汇报桥接连接、队列、流量及凭据检查计数。
|
||||
- `postgres.go` 读写设备登记与分页目录,提交设备变更并协调执行授权撤销。
|
||||
- `protocol.go` 校验桥接消息和设备 hello 的字段、标识及边界。
|
||||
- `query.sql` 定义设备登记、状态查询、版本更新及管理端统计所用的 SQL。
|
||||
- `register.go` 解析并校验设备自注册请求,按用户限制登记频率。
|
||||
- `service.go` 维护每用户设备状态,广播目录、路由设备消息并排空连接。
|
||||
- `sqlc/` 保存根据 SQL 生成的查询入口和行类型。
|
||||
|
||||
## 回归
|
||||
|
||||
- `admin_test.go` 核对管理员设备清单的筛选、可见范围和统计。
|
||||
- `connection_test.go` 检查并发队列边界、连接替换、消息路由和用户状态回收。
|
||||
- `contract_test.go` 对照 Agent OpenAPI 文档检查设备入口。
|
||||
- `endpoint_test.go` 提供隔离的 PostgreSQL 与 WebSocket 夹具,验证路由、连接替换、凭据撤销和登记审计。
|
||||
- `execution_test.go` 覆盖连接池及事务读取失败、绑定、发布、并发登记、接管和撤销恢复。
|
||||
- `i18n_test.go` 核对设备错误码使用的共享翻译。
|
||||
- `lifecycle_test.go` 检查来源、凭据轮换、存储故障、超时、探活及消息上限。
|
||||
- `names_test.go` 检查独立运行端设备的显示名称。
|
||||
- `protocol_test.go` 验证消息和 hello 的校验、响应序列化、连接错误和回滚日志。
|
||||
- `proxy_test.go` 加载生产 app.conf,将设备请求指向测试后端,验证 WebSocket 升级后能收到设备目录。
|
||||
- `register_test.go` 检查设备注册参数、平台、频率限制和登记数量。
|
||||
- `unlimited_test.go` 验证执行设备登记不设数量上限。
|
||||
|
||||
[PROTOCOL]: 变更时更新此头部,然后检查 guidelines.md
|
||||
@@ -1,3 +1,7 @@
|
||||
// [INPUT]: 依赖设备桥接夹具、Nginx 容器和生产 app.conf。
|
||||
// [OUTPUT]: 验证经 Nginx 升级的 WebSocket 能完成 hello 并收到设备目录。
|
||||
// [POS]: endpoint 的代理集成回归,使用临时后端接收真实升级请求。
|
||||
// [PROTOCOL]: 变更时更新此头部,然后检查 guidelines.md
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
@@ -25,7 +29,14 @@ func TestNginxUpgrade(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config := fmt.Sprintf("events {}\nhttp { upstream monkeyai_backend { server host.docker.internal:%s; } server { listen 8080; include /etc/nginx/bridge-app.conf; } }\n", upstream.Port())
|
||||
config := fmt.Sprintf(`events {}
|
||||
http {
|
||||
map $uri $monkeyai_target { default monkeyai_backend; }
|
||||
upstream monkeyai_backend { server host.docker.internal:%s; }
|
||||
upstream monkeyai_admin { server 127.0.0.1:1; }
|
||||
server { listen 8080; include /etc/nginx/bridge-app.conf; }
|
||||
}
|
||||
`, upstream.Port())
|
||||
configPath := filepath.Join(t.TempDir(), "nginx.conf")
|
||||
if err = os.WriteFile(configPath, []byte(config), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// [INPUT]: 设备身份、签名握手、WebSocket 与对应通道的 yamux 配置。
|
||||
// [OUTPUT]: 验证设备证明,发布控制路由,按代次附着数据通道。
|
||||
// [INPUT]: 设备身份、签名握手、保留确认读取中断的 bridgeTransport 与对应通道的 yamux 配置。
|
||||
// [OUTPUT]: 发布已验证的控制路由,按代次与授权附着数据通道,区分确认中断、消息超限和内容无效。
|
||||
// [POS]: 设备隧道入口,与 lease 的存活探测共用进程接管窗口。
|
||||
// [PROTOCOL]: 变更时更新此头部,然后检查 guidelines.md
|
||||
package relay
|
||||
@@ -64,7 +64,8 @@ func (s *Service) bridge(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
defer s.workers.Done()
|
||||
defer func() { s.mu.Lock(); s.slots--; s.mu.Unlock() }()
|
||||
ws, err := websocket.Accept(w, r, &websocket.AcceptOptions{InsecureSkipVerify: true, CompressionMode: websocket.CompressionDisabled})
|
||||
var transport bridgeTransport
|
||||
ws, err := transport.accept(w, r)
|
||||
if err != nil {
|
||||
slog.WarnContext(r.Context(), "操作失败", "module", "relay", "operation", "bridge", "error", err)
|
||||
return
|
||||
@@ -146,37 +147,33 @@ func (s *Service) bridge(w http.ResponseWriter, r *http.Request) {
|
||||
s.wsError(handshake, ws, &resource.Error{Status: 403, Code: "invalid_device_proof", Message: "设备证明无效"})
|
||||
return
|
||||
}
|
||||
valid, err := s.identity.VerifyGrant(handshake, p)
|
||||
if err != nil {
|
||||
if err := s.verifyBridgeGrant(handshake, p); err != nil {
|
||||
s.wsError(handshake, ws, err)
|
||||
return
|
||||
}
|
||||
if !valid {
|
||||
s.wsError(handshake, ws, &resource.Error{Status: 403, Code: "permission_denied", Message: "设备授权已失效"})
|
||||
return
|
||||
}
|
||||
gate := s.gate(key)
|
||||
gate.Lock()
|
||||
s.mu.Lock()
|
||||
old := s.routes[key]
|
||||
conflict := channel == "control" && hello.Intent == "publish" && old != nil && time.Since(old.seen) < controlSilenceLimit && old.hello.BootID != hello.BootID
|
||||
s.mu.Unlock()
|
||||
if conflict {
|
||||
gate.Unlock()
|
||||
s.wsError(handshake, ws, &resource.Error{Status: 409, Code: "device_process_conflict", Message: "设备已有活动执行进程"})
|
||||
return
|
||||
}
|
||||
var old, current *route
|
||||
if channel == "data" {
|
||||
s.mu.Lock()
|
||||
attached := old != nil && state.RemoteAccessState == "enabled" && state.ActiveGrantID == p.GrantID && state.GrantVersion == old.state.GrantVersion && state.LeaseEpoch == hello.LeaseEpoch && old.hello.BootID == hello.BootID && old.state.LeaseEpoch == hello.LeaseEpoch && old.principal.GrantID == p.GrantID && old.ready
|
||||
s.mu.Unlock()
|
||||
if !attached {
|
||||
s.wsError(handshake, ws, &resource.Error{Status: 409, Code: "device_registration_changed", Message: "数据通道不能附着当前执行连接"})
|
||||
gate.Unlock()
|
||||
logging.Bind(handshake, slog.Int64("lease_epoch", hello.LeaseEpoch))
|
||||
old, err = s.dataRoute(handshake, key, p, hello, state)
|
||||
if err != nil {
|
||||
if handshake.Err() == nil {
|
||||
s.wsError(handshake, ws, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
state = old.state
|
||||
} else {
|
||||
gate.Lock()
|
||||
s.mu.Lock()
|
||||
old = s.routes[key]
|
||||
conflict := hello.Intent == "publish" && old != nil && time.Since(old.seen) < controlSilenceLimit && old.hello.BootID != hello.BootID
|
||||
s.mu.Unlock()
|
||||
if conflict {
|
||||
gate.Unlock()
|
||||
s.wsError(handshake, ws, &resource.Error{Status: 409, Code: "device_process_conflict", Message: "设备已有活动执行进程"})
|
||||
return
|
||||
}
|
||||
state, err = s.devices.Enroll(handshake, p, endpoint.Enrollment{MachineID: hello.MachineID, PublicKey: public, DisplayName: hello.DisplayName, Platform: hello.Platform, Arch: hello.Arch,
|
||||
Intent: hello.Intent, DeploymentMode: hello.DeploymentMode, RestoreRevoked: hello.RestoreRevoked, Protocols: hello.Protocols, RuntimeVersion: hello.RuntimeVersion, EngineVersion: hello.EngineVersion}, challenge.RegistrationVersion)
|
||||
if err != nil {
|
||||
@@ -184,22 +181,19 @@ func (s *Service) bridge(w http.ResponseWriter, r *http.Request) {
|
||||
s.wsError(handshake, ws, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
if channel == "control" {
|
||||
logging.Event(r.Context(), s.logger, slog.LevelInfo, "relay.bridge.proved", "设备证明已提交", "module", "relay", "operation", "bridge", "server_id", s.config.ServerID, "user_id", p.UserID, "machine_id", hello.MachineID, "boot_id", hello.BootID, "intent", hello.Intent, "registration_version", state.RegistrationVersion, "grant_version", state.GrantVersion, "lease_epoch", state.LeaseEpoch)
|
||||
}
|
||||
var current *route
|
||||
if channel == "control" && hello.Intent == "publish" {
|
||||
if p.IsRuntime() {
|
||||
// 首次握手开始时授权尚未绑定,路由使用登记事务确认的身份。
|
||||
p.MachineID, p.KeyID = state.MachineID, state.KeyID
|
||||
if hello.Intent == "publish" {
|
||||
if p.IsRuntime() {
|
||||
// 首次握手开始时授权尚未绑定,路由使用登记事务确认的身份。
|
||||
p.MachineID, p.KeyID = state.MachineID, state.KeyID
|
||||
}
|
||||
current = &route{publishDone: make(chan struct{}), runtimeStatus: "online", engineHealth: "unknown", controlQueue: make(chan any, 16), target: key, principal: p, hello: hello, state: state, ws: ws, seen: time.Now(), slotsControl: make(chan struct{}, 64), opensControl: make(chan struct{}, 64), streams: make(map[*access]struct{}), connectionVersions: make(map[string]connectionVersion)}
|
||||
s.mu.Lock()
|
||||
s.routes[key] = current
|
||||
s.mu.Unlock()
|
||||
}
|
||||
current = &route{runtimeStatus: "online", engineHealth: "unknown", controlQueue: make(chan any, 16), target: key, principal: p, hello: hello, state: state, ws: ws, seen: time.Now(), slotsControl: make(chan struct{}, 64), opensControl: make(chan struct{}, 64), streams: make(map[*access]struct{}), connectionVersions: make(map[string]connectionVersion)}
|
||||
s.mu.Lock()
|
||||
s.routes[key] = current
|
||||
s.mu.Unlock()
|
||||
gate.Unlock()
|
||||
}
|
||||
gate.Unlock()
|
||||
closeReason := "control_handshake_incomplete"
|
||||
if current != nil {
|
||||
s.closeRoute(old, "epoch_replaced")
|
||||
@@ -215,10 +209,17 @@ func (s *Service) bridge(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
var ack ReadyAck
|
||||
if err := readWS(handshake, ws, &ack); err != nil || ack.Type != "ready_ack" || ack.RegistrationVersion != ready.RegistrationVersion || !identityOnly && ack.LeaseEpoch != ready.LeaseEpoch {
|
||||
if err != nil {
|
||||
slog.WarnContext(r.Context(), "操作失败", "module", "relay", "operation", "bridge", "error", err)
|
||||
}
|
||||
readErr := transport.readAck(handshake, ws, &ack)
|
||||
switch {
|
||||
case errors.Is(readErr, websocket.ErrMessageTooBig):
|
||||
// WebSocket 已发送 1009 关闭帧。
|
||||
logging.Event(handshake, s.logger, slog.LevelWarn, "relay.bridge.rejected", "设备确认消息超限", "reason", "message_too_big", "phase", "ready_ack")
|
||||
return
|
||||
case readErr != nil && !errors.Is(readErr, errProtocol):
|
||||
logging.Event(handshake, s.logger, slog.LevelDebug, "relay.bridge.interrupted", "读取设备确认时连接中断", "phase", "ready_ack", "error", readErr)
|
||||
return
|
||||
}
|
||||
if readErr != nil || ack.Type != "ready_ack" || ack.RegistrationVersion != ready.RegistrationVersion || !identityOnly && ack.LeaseEpoch != ready.LeaseEpoch {
|
||||
s.wsError(handshake, ws, errProtocol)
|
||||
return
|
||||
}
|
||||
@@ -241,9 +242,10 @@ func (s *Service) bridge(w http.ResponseWriter, r *http.Request) {
|
||||
if channel == "data" {
|
||||
gate.Lock()
|
||||
s.mu.Lock()
|
||||
if s.routes[key] != old || !old.ready {
|
||||
if reason := s.dataRouteChange(old); reason != "" {
|
||||
s.mu.Unlock()
|
||||
gate.Unlock()
|
||||
logging.Event(r.Context(), s.logger, slog.LevelWarn, "relay.bridge.rejected", "数据确认时控制路由已失效", "reason", reason, "phase", "ready_ack")
|
||||
return
|
||||
}
|
||||
previous := old.data
|
||||
@@ -285,6 +287,104 @@ func (s *Service) bridge(w http.ResponseWriter, r *http.Request) {
|
||||
s.control(r.Context(), current)
|
||||
}
|
||||
|
||||
func (s *Service) verifyBridgeGrant(ctx context.Context, p identity.Principal) error {
|
||||
valid, err := s.identity.VerifyGrant(ctx, p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !valid {
|
||||
logging.Bind(ctx, slog.String("reason", "grant_invalid"))
|
||||
return &resource.Error{Status: 403, Code: "permission_denied", Message: "设备授权已失效"}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 调用方持有 s.mu。从等待发布到安装数据通道,握手只接受原控制路由。
|
||||
func (s *Service) dataRouteChange(expected *route) string {
|
||||
current := s.routes[expected.target]
|
||||
switch {
|
||||
case current == nil:
|
||||
return "control_missing"
|
||||
case current != expected:
|
||||
return "route_replaced"
|
||||
case !expected.ready || expected.control == nil || expected.control.IsClosed():
|
||||
return "control_closed"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) dataRoute(ctx context.Context, key target, p identity.Principal, hello Hello, state endpoint.ExecutionState) (*route, error) {
|
||||
r, pending, reason := s.matchDataRoute(key, p.GrantID, hello, state)
|
||||
if pending != nil {
|
||||
// 在锁外等待本次发布。超时沿用原错误码,就绪或关闭后重新核验。
|
||||
logging.Event(ctx, s.logger, slog.LevelDebug, "relay.bridge.waiting", "数据通道等待控制就绪", "reason", reason)
|
||||
wait, stop := context.WithTimeout(ctx, time.Second)
|
||||
defer stop()
|
||||
select {
|
||||
case <-wait.Done():
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case <-pending:
|
||||
s.mu.Lock()
|
||||
reason = s.dataRouteChange(r)
|
||||
s.mu.Unlock()
|
||||
if reason != "" {
|
||||
break
|
||||
}
|
||||
fresh, err := s.devices.State(ctx, key.user, key.machine)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.verifyBridgeGrant(ctx, p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r, _, reason = s.matchDataRoute(key, p.GrantID, hello, fresh)
|
||||
if reason == "" && (fresh.RegistrationVersion != state.RegistrationVersion || !bytes.Equal(fresh.PublicKey, state.PublicKey)) {
|
||||
reason = "registration_changed"
|
||||
}
|
||||
}
|
||||
}
|
||||
if reason != "" {
|
||||
logging.Bind(ctx, slog.String("reason", reason))
|
||||
return nil, &resource.Error{Status: 409, Code: "device_registration_changed", Message: "数据通道不能附着当前执行连接"}
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// 只有身份、授权和代次都匹配且控制发布未完成时才返回等待通知。
|
||||
func (s *Service) matchDataRoute(key target, grantID string, hello Hello, state endpoint.ExecutionState) (*route, <-chan struct{}, string) {
|
||||
gate := s.gate(key)
|
||||
gate.Lock()
|
||||
defer gate.Unlock()
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
r := s.routes[key]
|
||||
switch {
|
||||
case state.RemoteAccessState != "enabled":
|
||||
return nil, nil, "remote_access_disabled"
|
||||
case state.ActiveGrantID != grantID:
|
||||
return nil, nil, "grant_mismatch"
|
||||
case r == nil || r.closed:
|
||||
return nil, nil, "control_missing"
|
||||
case state.LeaseEpoch != hello.LeaseEpoch || r.state.LeaseEpoch != hello.LeaseEpoch:
|
||||
return nil, nil, "lease_epoch_mismatch"
|
||||
case r.hello.BootID != hello.BootID:
|
||||
return nil, nil, "boot_id_mismatch"
|
||||
case r.principal.GrantID != grantID:
|
||||
return nil, nil, "grant_mismatch"
|
||||
case r.state.GrantVersion != state.GrantVersion:
|
||||
return nil, nil, "grant_version_mismatch"
|
||||
case !r.ready:
|
||||
return r, r.publishDone, "control_not_ready"
|
||||
case r.control == nil || r.control.IsClosed():
|
||||
return nil, nil, "control_closed"
|
||||
default:
|
||||
return r, nil, ""
|
||||
}
|
||||
}
|
||||
|
||||
func readWS(ctx context.Context, ws *websocket.Conn, out any) error {
|
||||
kind, data, err := ws.Read(ctx)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
// [INPUT]: HTTP 升级连接、coder/websocket 的消息读取与 relay 的确认解码。
|
||||
// [OUTPUT]: 接管设备连接,读取 ready_ack 时保留传输 EOF 与消息结束的区别。
|
||||
// [POS]: bridge 的传输适配层。WebSocket 库负责分帧,bridge 负责确认内容和回包。
|
||||
// [PROTOCOL]: 变更时更新此头部,然后检查 guidelines.md
|
||||
package relay
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
)
|
||||
|
||||
type bridgeTransport struct {
|
||||
net.Conn
|
||||
readingAck bool
|
||||
}
|
||||
|
||||
func (c *bridgeTransport) accept(w http.ResponseWriter, r *http.Request) (*websocket.Conn, error) {
|
||||
// 与 websocket.Accept 一样,沿中间件寻找 Hijacker,保留原响应写入器。
|
||||
for inner := w; ; {
|
||||
if h, ok := inner.(http.Hijacker); ok {
|
||||
w = bridgeUpgrade{w, h, c}
|
||||
break
|
||||
}
|
||||
wrapper, ok := inner.(interface{ Unwrap() http.ResponseWriter })
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
inner = wrapper.Unwrap()
|
||||
}
|
||||
return websocket.Accept(w, r, &websocket.AcceptOptions{InsecureSkipVerify: true, CompressionMode: websocket.CompressionDisabled})
|
||||
}
|
||||
|
||||
type bridgeUpgrade struct {
|
||||
http.ResponseWriter
|
||||
hijacker http.Hijacker
|
||||
transport *bridgeTransport
|
||||
}
|
||||
|
||||
func (w bridgeUpgrade) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
conn, buffers, err := w.hijacker.Hijack()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
w.transport.Conn = conn
|
||||
return w.transport, buffers, nil
|
||||
}
|
||||
|
||||
func (c *bridgeTransport) Read(p []byte) (int, error) {
|
||||
n, err := c.Conn.Read(p)
|
||||
// coder/websocket 会把底层 EOF 当成消息结束。确认必须读到最终分片。
|
||||
if err != nil && c.readingAck && errors.Is(err, io.EOF) {
|
||||
return n, io.ErrUnexpectedEOF
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (c *bridgeTransport) readAck(ctx context.Context, ws *websocket.Conn, ack *ReadyAck) error {
|
||||
// 握手是唯一的读取方,返回后 bridge 才把读取权交给 yamux。
|
||||
c.readingAck = true
|
||||
defer func() { c.readingAck = false }()
|
||||
return readWS(ctx, ws, ack)
|
||||
}
|
||||
@@ -1,20 +1,31 @@
|
||||
// [INPUT]: 双通道测试夹具、真实 yamux 和不回应 Pong 的连接。
|
||||
// [OUTPUT]: 验证失联期限、事件写出边界、反向流预算及数据重连。
|
||||
// [INPUT]: 双通道测试夹具、真实 WebSocket 分片、占满的数据库连接池和可注入读错误的传输连接。
|
||||
// [OUTPUT]: 验证失联期限、反向流预算、数据附着换代与撤销,以及确认中断、超限和内容无效时的回包与诊断。
|
||||
// [POS]: 控制事件协议和传输生命周期回归。
|
||||
// [PROTOCOL]: 变更时更新此头部,然后检查 guidelines.md
|
||||
package relay
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
"uuid"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/endpoint"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/identity"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/logging"
|
||||
"github.com/coder/websocket"
|
||||
"github.com/hashicorp/yamux"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func TestHTTPDataReattachStatus(t *testing.T) {
|
||||
@@ -64,6 +75,306 @@ func TestHTTPDataReattachStatus(t *testing.T) {
|
||||
t.Fatal("数据附着完成后 status 未上线")
|
||||
}
|
||||
|
||||
type attachLog struct {
|
||||
Event, Reason, Code, Phase string
|
||||
Channel string `json:"channel_kind"`
|
||||
}
|
||||
|
||||
type attachLogs chan attachLog
|
||||
|
||||
func (logs attachLogs) Write(data []byte) (int, error) {
|
||||
var event attachLog
|
||||
if json.Unmarshal(data, &event) == nil {
|
||||
switch {
|
||||
case event.Event == "relay.bridge.ready" && event.Channel == "data",
|
||||
event.Event == "relay.bridge.interrupted" && event.Channel == "data" && event.Phase == "ready_ack",
|
||||
event.Event == "relay.bridge.waiting",
|
||||
event.Event == "protocol.response.error",
|
||||
event.Event == "relay.bridge.rejected" && event.Phase == "ready_ack":
|
||||
logs <- event
|
||||
}
|
||||
}
|
||||
return len(data), nil
|
||||
}
|
||||
|
||||
func (logs attachLogs) expect(t *testing.T, event, reason string) {
|
||||
t.Helper()
|
||||
select {
|
||||
case got := <-logs:
|
||||
if got.Event != event || got.Reason != reason {
|
||||
t.Fatalf("收到 %+v,期望 %s / %s", got, event, reason)
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatalf("未收到 %s / %s", event, reason)
|
||||
}
|
||||
}
|
||||
|
||||
// 让服务端的真实 WebSocket 读操作在对端断开时收到指定的底层错误。
|
||||
type ackFaultListener struct {
|
||||
net.Listener
|
||||
cause error
|
||||
}
|
||||
|
||||
func (l ackFaultListener) Accept() (net.Conn, error) {
|
||||
c, err := l.Listener.Accept()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ackFaultConn{c, l.cause}, nil
|
||||
}
|
||||
|
||||
type ackFaultConn struct {
|
||||
net.Conn
|
||||
cause error
|
||||
}
|
||||
|
||||
func (c ackFaultConn) Read(p []byte) (int, error) {
|
||||
n, err := c.Conn.Read(p)
|
||||
if errors.Is(err, io.EOF) {
|
||||
return n, &net.OpError{Op: "read", Net: "tcp", Err: c.cause}
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func TestDataAttachAcrossControlPublish(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
action string
|
||||
reason string
|
||||
}{
|
||||
{"ready", ""},
|
||||
{"timeout", "control_not_ready"},
|
||||
{"stale", "lease_epoch_mismatch"},
|
||||
{"wrong_boot", "boot_id_mismatch"},
|
||||
{"closed", "control_missing"},
|
||||
{"tcp_reset", "control_missing"},
|
||||
{"short_frame", "control_missing"},
|
||||
{"invalid_ack", "control_missing"},
|
||||
{"malformed_ack", "control_missing"},
|
||||
{"replaced", "route_replaced"},
|
||||
{"revoked", "remote_access_disabled"},
|
||||
{"grant_revoked", "grant_invalid"},
|
||||
{"replaced_after_ready", "route_replaced"},
|
||||
} {
|
||||
t.Run(tc.action, func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
logs := make(attachLogs, 16)
|
||||
f.s.logger = logging.New(logs, slog.LevelDebug)
|
||||
server := httptest.NewUnstartedServer(logging.HTTP(f.s.logger)(f.server.Config.Handler))
|
||||
switch tc.action {
|
||||
case "tcp_reset":
|
||||
server.Listener = ackFaultListener{server.Listener, syscall.ECONNRESET}
|
||||
case "short_frame":
|
||||
server.Listener = ackFaultListener{server.Listener, io.ErrUnexpectedEOF}
|
||||
}
|
||||
server.Start()
|
||||
t.Cleanup(server.Close)
|
||||
f.server = server
|
||||
r := f.runtime(t)
|
||||
logs.expect(t, "relay.bridge.ready", "")
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 6*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// 已完成证明,暂缓控制 ready_ack,让数据握手在真实发布窗口抵达。
|
||||
control := f.prove(t, r.hello, r.private, "control", f.token)
|
||||
var published Ready
|
||||
if err := readWS(ctx, control, &published); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ack := ReadyAck{Type: "ready_ack", RegistrationVersion: published.RegistrationVersion, LeaseEpoch: published.LeaseEpoch}
|
||||
h := r.hello
|
||||
h.ChannelKind, h.Intent, h.LeaseEpoch = "data", "attach", published.LeaseEpoch
|
||||
switch tc.action {
|
||||
case "stale":
|
||||
h.LeaseEpoch = r.ready.LeaseEpoch
|
||||
case "wrong_boot":
|
||||
h.BootID = uuid.New().String()
|
||||
}
|
||||
data := f.prove(t, h, r.private, "data", f.token)
|
||||
if tc.action != "stale" && tc.action != "wrong_boot" {
|
||||
logs.expect(t, "relay.bridge.waiting", "control_not_ready")
|
||||
}
|
||||
switch tc.action {
|
||||
case "closed", "tcp_reset", "short_frame":
|
||||
control.CloseNow()
|
||||
case "invalid_ack", "malformed_ack":
|
||||
var err error
|
||||
if tc.action == "malformed_ack" {
|
||||
err = control.Write(ctx, websocket.MessageText, []byte("{"))
|
||||
} else {
|
||||
ack.LeaseEpoch++
|
||||
err = writeWS(ctx, control, ack)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var reply map[string]string
|
||||
if err := readWS(ctx, control, &reply); err != nil || reply["code"] != "invalid_tunnel_message" {
|
||||
t.Fatalf("错误确认未收到协议拒绝: %v %v", reply, err)
|
||||
}
|
||||
logs.expect(t, "protocol.response.error", "")
|
||||
case "replaced":
|
||||
f.handshake(t, r.hello, r.private, "control", f.token)
|
||||
case "ready", "revoked", "grant_revoked", "replaced_after_ready":
|
||||
if tc.action == "revoked" {
|
||||
// 只更新持久状态,验证就绪通知后确实重读了授权。
|
||||
if _, err := f.pool.Exec(ctx, "UPDATE endpoints SET remote_access_state='revoked' WHERE user_id=$1 AND machine_id=$2", f.user, h.MachineID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if tc.action == "grant_revoked" {
|
||||
if _, err := f.pool.Exec(ctx, "UPDATE oauth_grants SET revoked_at=now() WHERE id=$1", f.grant); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := writeWS(ctx, control, ack); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if tc.action == "ready" || tc.action == "replaced_after_ready" {
|
||||
var ready Ready
|
||||
if err := readWS(ctx, data, &ready); err != nil || ready.LeaseEpoch != published.LeaseEpoch {
|
||||
t.Fatalf("数据通道没有附着原代次: %+v %v", ready, err)
|
||||
}
|
||||
if tc.action == "replaced_after_ready" {
|
||||
f.handshake(t, r.hello, r.private, "control", f.token)
|
||||
}
|
||||
if err := writeWS(ctx, data, ack); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tc.action == "replaced_after_ready" {
|
||||
logs.expect(t, "relay.bridge.rejected", tc.reason)
|
||||
} else {
|
||||
logs.expect(t, "relay.bridge.ready", "")
|
||||
}
|
||||
return
|
||||
}
|
||||
var failure struct {
|
||||
Type string `json:"type"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
code := "device_registration_changed"
|
||||
if tc.action == "grant_revoked" {
|
||||
code = "permission_denied"
|
||||
}
|
||||
if err := readWS(ctx, data, &failure); err != nil || failure.Type != "error" || failure.Code != code {
|
||||
t.Fatalf("旧客户端收到非预期错误: %+v %v", failure, err)
|
||||
}
|
||||
logs.expect(t, "protocol.response.error", tc.reason)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDataReadyAckMessageBoundary(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
logs := make(attachLogs, 16)
|
||||
f.s.logger = logging.New(logs, slog.LevelDebug)
|
||||
server := httptest.NewServer(logging.HTTP(f.s.logger)(f.server.Config.Handler))
|
||||
t.Cleanup(server.Close)
|
||||
f.server = server
|
||||
r := f.runtime(t)
|
||||
logs.expect(t, "relay.bridge.ready", "")
|
||||
hello := r.hello
|
||||
hello.ChannelKind, hello.Intent, hello.LeaseEpoch = "data", "attach", r.ready.LeaseEpoch
|
||||
|
||||
for _, mode := range []string{"interrupted_json", "missing_final_frame", "at_limit", "over_limit"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
ws := f.prove(t, hello, r.private, "data", f.token)
|
||||
var ready Ready
|
||||
if err := readWS(ctx, ws, &ready); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ack, err := json.Marshal(ReadyAck{Type: "ready_ack", RegistrationVersion: ready.RegistrationVersion, LeaseEpoch: ready.LeaseEpoch})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
message, err := ws.Writer(ctx, websocket.MessageText)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if mode == "interrupted_json" {
|
||||
ack = ack[:1]
|
||||
}
|
||||
if _, err := message.Write(ack); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
switch mode {
|
||||
case "interrupted_json", "missing_final_frame":
|
||||
// Pong 证明服务端已经读过首个分片,此时断开仍缺少 FIN。
|
||||
ws.CloseRead(ctx)
|
||||
if err := ws.Ping(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ws.CloseNow(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
logs.expect(t, "relay.bridge.interrupted", "")
|
||||
case "at_limit", "over_limit":
|
||||
size := maxControlMessage
|
||||
if mode == "over_limit" {
|
||||
size++
|
||||
}
|
||||
if _, err := message.Write(bytes.Repeat([]byte(" "), size-len(ack))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := message.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if mode == "at_limit" {
|
||||
logs.expect(t, "relay.bridge.ready", "")
|
||||
return
|
||||
}
|
||||
if _, _, err := ws.Read(ctx); websocket.CloseStatus(err) != websocket.StatusMessageTooBig {
|
||||
t.Fatalf("超限确认应收到关闭码 1009,实际为 %v", err)
|
||||
}
|
||||
logs.expect(t, "relay.bridge.rejected", "message_too_big")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplacedDataAttachWithBusyPool(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
cfg := f.pool.Config()
|
||||
cfg.MaxConns = 1
|
||||
pool, err := pgxpool.NewWithConfig(t.Context(), cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
held, err := pool.Acquire(t.Context())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer held.Release()
|
||||
f.s.devices = endpoint.NewExecution(pool, f.ids)
|
||||
logs := make(attachLogs, 8)
|
||||
f.s.logger = logging.New(logs, slog.LevelDebug)
|
||||
key := target{f.user, uuid.New().String()}
|
||||
hello := Hello{BootID: uuid.New().String(), LeaseEpoch: 1}
|
||||
principal := identity.Principal{GrantID: f.grant}
|
||||
state := endpoint.ExecutionState{ActiveGrantID: f.grant, RemoteAccessState: "enabled", LeaseEpoch: 1}
|
||||
old := &route{target: key, hello: hello, state: state, principal: principal, publishDone: make(chan struct{})}
|
||||
f.s.routes[key] = old
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
result := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := f.s.dataRoute(ctx, key, principal, hello, state)
|
||||
result <- err
|
||||
}()
|
||||
logs.expect(t, "relay.bridge.waiting", "control_not_ready")
|
||||
f.s.mu.Lock()
|
||||
f.s.routes[key] = &route{target: key, state: endpoint.ExecutionState{LeaseEpoch: 2}}
|
||||
f.s.mu.Unlock()
|
||||
f.s.closeRoute(old, "epoch_replaced")
|
||||
var rejected *resource.Error
|
||||
if err := <-result; !errors.As(err, &rejected) || rejected.Code != "device_registration_changed" {
|
||||
t.Fatalf("数据库无可用连接时旧代次仍应收到登记变化回包: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestControlBlackholeClosesRoute(t *testing.T) {
|
||||
t.Parallel()
|
||||
left, right := net.Pipe()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// [INPUT]: 隔离 PostgreSQL schema 和真实 WebSocket 握手。
|
||||
// [OUTPUT]: 提供两类通道、运行端替身、访问票据及代理请求测试夹具。
|
||||
// [OUTPUT]: 提供可分步完成证明与确认的双通道握手、运行端替身、访问票据及代理请求测试夹具。
|
||||
// [POS]: relay 集成测试入口,按通道选择与服务端一致的配置。
|
||||
// [PROTOCOL]: 变更时更新此头部,然后检查 guidelines.md
|
||||
package relay
|
||||
@@ -153,7 +153,7 @@ type runtimeFixture struct {
|
||||
sequence atomic.Int64
|
||||
}
|
||||
|
||||
func (f *fixture) handshake(t *testing.T, hello Hello, private ed25519.PrivateKey, channel, token string) (*websocket.Conn, Ready) {
|
||||
func (f *fixture) prove(t *testing.T, hello Hello, private ed25519.PrivateKey, channel, token string) *websocket.Conn {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
@@ -173,11 +173,19 @@ func (f *fixture) handshake(t *testing.T, hello Hello, private ed25519.PrivateKe
|
||||
if err = writeWS(ctx, ws, Proof{Type: "proof", ChallengeID: challenge.ChallengeID, Signature: base64.RawURLEncoding.EncodeToString(ed25519.Sign(private, message))}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ws
|
||||
}
|
||||
|
||||
func (f *fixture) handshake(t *testing.T, hello Hello, private ed25519.PrivateKey, channel, token string) (*websocket.Conn, Ready) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
ws := f.prove(t, hello, private, channel, token)
|
||||
var ready Ready
|
||||
if err = readWS(ctx, ws, &ready); err != nil {
|
||||
if err := readWS(ctx, ws, &ready); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = writeWS(ctx, ws, ReadyAck{Type: "ready_ack", RegistrationVersion: ready.RegistrationVersion, LeaseEpoch: ready.LeaseEpoch}); err != nil {
|
||||
if err := writeWS(ctx, ws, ReadyAck{Type: "ready_ack", RegistrationVersion: ready.RegistrationVersion, LeaseEpoch: ready.LeaseEpoch}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ws, ready
|
||||
|
||||
@@ -1,19 +1,31 @@
|
||||
# internal/relay/
|
||||
|
||||
> L2 | 父级:[MonkeyAI 后端上下文](../../CONTEXT.md)
|
||||
> L2 | 父级:[项目地图](../../../../guidelines.md) · [MonkeyAI 后端上下文](../../CONTEXT.md)
|
||||
|
||||
relay 为运行端发布控制和数据通道,按设备和连接代次向桌面代理请求。控制就绪或收到有效 Pong 后,路由有 45 秒的存活窗口。路由关闭时,用 `relay.route.closed` 的 `machine_id`、`boot_id`、`lease_epoch`、`reason` 和 `last_seen_age_ms` 对照执行端日志。EOF 只能说明本端观察到连接关闭。
|
||||
|
||||
数据通道只能附着在启动标识、授权和代次都匹配的控制路由上。控制发布尚未就绪时,relay 在原数据握手内最多等待 1 秒。等待者被唤醒后先检查原路由。原路由已关闭或被替换时,直接返回 `device_registration_changed`。原路由仍在且就绪时,复核数据库中的设备状态和授权,再确认当前代次。
|
||||
|
||||
查 `protocol.response.error` 的 `reason` 可区分未就绪、代次不匹配、路由替换和授权变化。若数据 ready_ack 到达时路由已被替换,查 `relay.bridge.rejected` 的 `phase=ready_ack`。
|
||||
|
||||
ready_ack 可分片发送,消息上限为 64 KiB。最终分片到达前连接中断时,relay 以调试级别记录 `relay.bridge.interrupted` 并结束握手。消息超限时,WebSocket 发送关闭码 1009,relay 记录 `relay.bridge.rejected` 和 `reason=message_too_big`。消息完整且未超限、但确认内容无效时,回复 `invalid_tunnel_message`。
|
||||
|
||||
## 实现
|
||||
|
||||
- `service.go` 注册 HTTP 入口,维护路由与服务生命周期,按通道配置 yamux,按代次记录首次关闭并释放访问。
|
||||
- `bridge.go` 校验设备身份与握手证明,发布控制路由,按当前代次附着数据通道。
|
||||
- `lease.go` 签发与续验访问租约,推送撤销及控制事件。每 15 秒探测,允许两次 Ping 同时等待应答,按最近有效 Pong 判定失联。
|
||||
- `service.go` 注册 HTTP 入口,维护路由与服务生命周期,按通道配置 yamux,按代次唤醒等待发布的握手,记录首次关闭并释放访问。
|
||||
- `control.go` 通过 Unix socket 查询运行状态、断开连接并传递设备或授权撤销。
|
||||
- `control_peer_darwin.go` 使用 LOCAL_PEERCRED 核对控制 socket 对端的有效用户。
|
||||
- `control_peer_linux.go` 使用 SO_PEERCRED 核对控制 socket 对端的有效用户。
|
||||
- `control_peer_other.go` 在无对端凭据校验实现的平台拒绝控制连接。
|
||||
- `bridge.go` 校验设备身份与握手证明,发布控制路由,按当前代次附着数据通道,限时等待并记录拒绝原因。
|
||||
- `bridgetransport.go` 接管 HTTP 升级连接,在读取 ready_ack 时把底层 EOF 转为意外中断,保留 WebSocket 消息结束边界。
|
||||
- `lease.go` 签发与续验访问租约,通知控制路由就绪,推送撤销及控制事件。每 15 秒探测,允许两次 Ping 同时等待应答,按最近有效 Pong 判定失联。
|
||||
- `directory.go` 组合授权设备与存活路由,生成分页设备目录及运行状态。
|
||||
- `connection.go` 校验业务权限,签发、轮换连接票据并更新访问版本。
|
||||
- `proxy.go` 检查来源、路由与票据,向运行端转发 ACP、HTTP 和终端流量。
|
||||
- `stream.go` 打开代理流,约束取消后的资源回收,复制和计量双向流量。
|
||||
- `budget.go` 分配数据与终端流名额,记录占用与释放。
|
||||
- `overload.go` 按窗口汇总数据通道拒绝次数、占用峰值和最老占用时长。
|
||||
- `terminal.go` 验证终端 WebSocket 升级和响应,协调终端连接接管。
|
||||
- `file.go` 校验独立文件授权并转发读写请求。
|
||||
- `preview.go` 为产物分配隔离来源,校验预览地址和凭据后转发内容。
|
||||
@@ -25,9 +37,14 @@ relay 为运行端发布控制和数据通道,按设备和连接代次向桌
|
||||
|
||||
## 回归
|
||||
|
||||
- `fixture_test.go` 以隔离 PostgreSQL schema、真实 WebSocket 与 yamux 构造设备和桌面连接。
|
||||
- `fixture_test.go` 以隔离 PostgreSQL schema、真实 WebSocket 与 yamux 构造设备和桌面连接;可分别发送设备证明和 ready_ack。
|
||||
- `heartbeat_test.go` 验证原路由在漏回一次 Pong、Pong 迟到或开流 ACK 迟到后恢复。另测过期路由回收和旧代次隔离。
|
||||
- `control_test.go` 验证持续失联、反向控制流限额、事件写超时与同代次数据重连。
|
||||
- `control_socket_test.go` 验证 Unix socket 控制接口。
|
||||
- `firstpublish_test.go` 验证独立 runtime 首次发布后签发票据及撤销后的拒绝。
|
||||
- `management_test.go` 验证设备目录、撤销权限和旧通知对新路由的隔离。
|
||||
- `nginxfixture_test.go` 把测试配置复制到 Nginx 验收容器。
|
||||
- `overload_test.go` 验证满额窗口保留拒绝时的流占用。
|
||||
- `control_test.go` 验证失联期限、反向控制流限额、事件写超时和数据重连。换代测试等待初始数据通道上线,覆盖无效确认、授权撤销及连接池满时拒绝旧代次。真实分片测试区分缺少最终帧、恰好 64 KiB 和超限关闭。
|
||||
- `cleanup_test.go` 验证并发回收只记一次关闭原因,超时可识别。设备与桌面共用授权时,整条路由只发一次撤销通知。
|
||||
- `relay_test.go` 验证票据、授权、文件和代理,覆盖租约宽限、代次切换与通道隔离。
|
||||
- `interop_test.go` 验证桌面来源、票据权限、长连接空闲、签名租约与独立撤销。
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// [INPUT]: 签名租约、授权存储、控制事件流与 yamux Ping。
|
||||
// [OUTPUT]: 核验访问租约,定期探测并按最近有效 Pong 判定失联,传递撤销。
|
||||
// [OUTPUT]: 通知控制发布就绪,核验访问租约,定期探测并按最近有效 Pong 判定失联,传递撤销。
|
||||
// [POS]: 设备控制路由的存活与授权检查,网络读写在服务锁外执行。
|
||||
// [PROTOCOL]: 变更时更新此头部,然后检查 guidelines.md
|
||||
package relay
|
||||
@@ -318,6 +318,7 @@ func (s *Service) control(ctx context.Context, r *route) {
|
||||
return
|
||||
}
|
||||
r.ready = true
|
||||
r.finishPublish()
|
||||
r.seen = time.Now()
|
||||
s.mu.Unlock()
|
||||
logging.Event(ctx, s.logger, slog.LevelInfo, "relay.bridge.ready", "设备控制通道已就绪", "channel_kind", "control")
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
// [INPUT]: JSON 字段定义、Ed25519 公钥和客户端声明的隧道版本。
|
||||
// [OUTPUT]: 定义握手消息与 Version,提供 ProofBytes 构造跨端签名输入。
|
||||
// [POS]: relay 的握手协议。bridge 调用此处校验消息字段和协议版本。
|
||||
// [PROTOCOL]: 变更时更新此头部,然后检查 guidelines.md
|
||||
package relay
|
||||
|
||||
import (
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// [INPUT]: 设备登记、身份授权、yamux 会话与结构化日志。
|
||||
// [OUTPUT]: 组装 relay 服务,按代次回收设备访问并记录首次关闭原因。
|
||||
// [OUTPUT]: 组装 relay 服务,按代次通知发布完成、回收设备访问并记录首次关闭原因。
|
||||
// [POS]: relay 服务入口,按控制或数据通道分配复用器的超时预算。
|
||||
// [PROTOCOL]: 变更时更新此头部,然后检查 guidelines.md
|
||||
package relay
|
||||
@@ -96,6 +96,7 @@ type route struct {
|
||||
control *yamux.Session
|
||||
data *yamux.Session
|
||||
ws *websocket.Conn
|
||||
publishDone chan struct{}
|
||||
ready bool
|
||||
closed bool
|
||||
seen time.Time
|
||||
@@ -294,6 +295,14 @@ func (s *Service) current(key target) *route {
|
||||
return r
|
||||
}
|
||||
|
||||
// 持有服务锁时调用;发布就绪或提前关闭都会唤醒同代次的数据握手。
|
||||
func (r *route) finishPublish() {
|
||||
if r.publishDone != nil {
|
||||
close(r.publishDone)
|
||||
r.publishDone = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) closeRoute(r *route, reason string) {
|
||||
if r == nil {
|
||||
return
|
||||
@@ -308,6 +317,7 @@ func (s *Service) closeRoute(r *route, reason string) {
|
||||
delete(s.routes, r.target)
|
||||
}
|
||||
r.ready = false
|
||||
r.finishPublish()
|
||||
lastSeenAge := time.Since(r.seen)
|
||||
data, control := r.data, r.control
|
||||
accesses := make([]*access, 0, len(r.streams))
|
||||
|
||||
Reference in new issue
Block a user