sdk

package module
v0.8.2 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2026 License: MIT Imports: 20 Imported by: 0

README

gt-plugin-sdk

GameTrace(Game Traffic Analysis)解码插件的官方 Go SDK。插件是一个独立进程: 启动 gRPC Decoder.DecodeV2 服务、读取 plugin.yaml 清单、向 GameTrace 宿主注册, 然后接收抓包记录并解码为带语义契约的逻辑事件。

package main

import (
    pb "github.com/OwnSecurityGuard/gt-plugin-sdk/proto"
    sdk "github.com/OwnSecurityGuard/gt-plugin-sdk"
)

func main() {
    sdk.RunRegisterLoop(decode) // 注册、心跳、重试、端点选择全部由 SDK 托管
}

func decode(req *pb.DecodeRequest, stream pb.Decoder_DecodeV2Server) error {
    // 解码零或多条事件,最终必须为每个 input_id 回 done=true
    ...
}

快速开始

go get github.com/OwnSecurityGuard/gt-plugin-sdk@latest
  1. 从 examples/http-stream-decoder 复制骨架 (plugin.yaml + 解码回调)。
  2. 实现 DecodeFuncV2:framing.ExtractL7(payload, link_type) → framing.Reassembler 重组 → 解析应用消息 → event.Draft 发送。
  3. go build 后设置 GT_REGISTRY_ADDR 运行,或在 GameTrace 宿主内走 build_plugin → activate_plugin → verify_plugin 闭环。

包结构

包 职责
sdk 根包 RunRegisterLoop / RunRegisterLoopWithOptions(注册/心跳/重试/隧道/认证)、manifest 读写校验、DecodeFuncV2
contract/ 线上契约 SSOT(contract.yaml)+ 分层 PluginChecker(schema 声明 + semantic 规则)
rule/ Protocol Semantic Rule:GJSON 取值 + Predicate + Effect(pair/extract/annotate/name)
schema/ schema 声明层:字段类型/引用/演进/语义校验(v0.7 起恢复)
state/ state 声明层:states 声明、Subject/Change 类型与 _state_changes 投影输入(v0.7 起恢复)
framing/ ExtractL7(按 link_type 剥链路层)、Reassembler(TCP 逐流重组)、FlowKey
event/ Draft(Type/SchemaRef/Value/Meta/Analysis 三段)、Value(MsgPack 编解码)、Split/Merge
proto/ 插件 ↔ 宿主 gRPC 契约(plugin.proto 为 SSOT,仅本仓库生成一份)
examples/http-stream-decoder 完整可运行的参考插件(schemas + semantic_rules 全声明)

plugin.yaml 清单

每个插件需要当前目录下的 plugin.yaml。最小合法清单:

api_version: gt.decoder/v2
name: example-game
protocol: example-game
type: decoder

当前 SDK 校验:api_version 匹配 gt.decoder/v<digit>、name 为小写 kebab-case、 protocol 必填、type 固定 decoder;宿主在注册期按自身大版本(当前 gt.decoder/v2) 复核 api_version。

可选声明段(v0.8.1 现状):

protocol_version: "1.1"
transports:        # v0.8.1 新增:声明能解的 L4 传输层,取值 tcp|udp
  - tcp
hints:
  - example-game

contract:
  name: gt.plugin
  version: 1

# 数据形状声明:宿主注册期校验(字段类型/引用/演进)
schemas:
  - id: example.msg
    version: 1
    strict: true
    fields:
      seq:  { type: int32, queryable: true }

# subject 状态形状声明:宿主据此投影 _state_changes
states:
  - subject: player
    schema: example.player
    version: 1

# Protocol Semantic Rule:插件定义协议语义,平台执行
semantic_rules:
  - id: example.mark_push
    when: [ { path: seq, op: eq, value: 0 } ]
    effect: { type: annotate, semantic: notification }

meta:
  author: example
  description: Decoder for example game protocol

契约层

contract.yaml 是插件与宿主之间线上协议的 SSOT(spec_version: 6), SDK 侧当前承载两个契约层:

  • schema 声明层(LayerSchema,v0.7.1 回归):schemas 声明自洽, 字段类型合法、$ref 可解析、版本号自洽,注册期由 PluginChecker.Check 校验;
  • Protocol Semantic Rule 层(LayerSemantic):semantic_rules 声明在 注册期校验(错误拒绝 Register RPC),规则评估在 plugin.verify 期逐事件执行。

states 声明与 state 包保留(v0.7 恢复):_state_changes 由宿主经 event.ExtractStateChanges 投影到 state_changes 表,是实体/状态变更分析的唯一输入。

注册与解码端点

RunRegisterLoopWithOptions(decodeFuncV2, opts) 支持两种注册模式 (默认与 RunRegisterLoop 完全一致):

  • 标准模式:启动本地 DecodeV2 gRPC server,注册后上报拨号地址,宿主回拨;
  • 隧道模式(opts.Tunnel=true):跳过本地监听,Register(tunnel=true) 后在同一连接上 打开 Connect 双向流,DecodeV2 经隧道帧完成,宿主不回拨。 设置 opts.AuthToken 后所有 RPC 附带 authorization: Bearer <token> metadata。

注册端点发现顺序:GT_REGISTRY_ADDR 环境变量 > --registry= 参数 > 默认 :9091。 注册端点支持 TCP、Unix socket(unix: 或裸路径)与 Windows 命名管道(npipe:)。 心跳默认 10s,注册/心跳失败按指数退避重试(首次 1s,上限 30s)。

平台侧部署在 Docker 时的回连地址

插件注册时会向宿主上报自己的 DecodeV2 拨号地址(Register.socket_path),宿主随后据此回连插件。SDK 的默认行为:

  • 未设置 GT_DECODER_ADDR:监听 TCP :0(随机端口),上报地址自动替换为本机首个非回环 IPv4,而不是通配符地址。
  • 设置了 GT_DECODER_ADDR=0.0.0.0:port:同样在上报时自动带上本机 IP。

之所以不能上报通配符(0.0.0.0 / [::]):当宿主运行在 Docker 容器内时,通配符地址会解析到容器自身的回环,容器永远拨不到运行在宿主机上的插件。

当宿主(pipeline/registry)运行在 Docker、插件运行在宿主机时:

  • 默认行为即可覆盖绝大多数场景(容器经网桥可达宿主机网卡 IP);
  • 多网卡 / VPN / 需要走 Docker 网桥网关等场景,用 GT_DECODER_PUBLIC_ADDR 显式指定平台侧可达的地址(原样上报,优先级最高):
export GT_DECODER_ADDR=0.0.0.0:19001              # 监听所有网卡
export GT_DECODER_PUBLIC_ADDR=192.168.1.10:19001  # 上报给宿主的回连地址(容器可达)

Docker Desktop(Mac/Windows)下也可用 host.docker.internal 作为容器访问宿主机的地址。

文档

宿主(pipeline/MCP 工具链)侧文档见主项目 E:\gametrace 的 pkg/plugin/skills/gametrace-plugin-development.md(MCP get_plugin_dev_guide 可获取)。

版本

当前 v0.8.1。沿革:

  • v0.8.1 — manifest 新增 transports 声明(tcp|udp),插件可声明支持的 L4 传输层。
  • v0.8.0 — Payload/Meta/Analysis 三段分离模型:DecodeResponseV2 新增 meta_msgpack / analysis_msgpack;event.Draft 增加 Meta / Analysis 字段; event.SplitReservedKeys / MergeReservedKeys 兼容旧扁平 payload。业务字段与平台推导从模型层强制分离。
  • v0.7.2 — 注册上报地址:通配符监听地址自动替换为本机非回环 IPv4,适配平台侧 Docker 部署回连; 新增 GT_DECODER_PUBLIC_ADDR 原样上报。
  • v0.7.1 — 回归 schema 声明期校验与 indexable_fields 归一化(升格为 queryable + alias)。
  • v0.7.0 — 恢复 schema/state 声明层,与 Protocol Semantic Rule 并存。
  • v0.6.x — 仅 Protocol Semantic Rule 的瘦身阶段;runtime/event/transport 各层校验 (CheckManifest、CheckDecodeResponse、CheckDecodeRequest 等)已移除不再回归; contract.yaml 自 gametrace 迁入本仓库成为 SSOT。
  • v0.1.0 — 仅 Runtime/Event 的初始快照。

许可

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ReadManifest

func ReadManifest() ([]byte, error)

ReadManifest 读取当前目录的 plugin.yaml 并校验,返回原始 bytes。 用于 Register RPC 的 manifest 参数。 返回 error 当 plugin.yaml 不存在、格式非法或字段校验不通过时。

直接使用本 SDK 内置的 ParseManifest/ValidateManifest,不依赖 gametrace 根模块。

func ResolveRegistryAddr

func ResolveRegistryAddr() string

ResolveRegistryAddr 返回 registry 端点地址。 优先级:GT_REGISTRY_ADDR 环境变量 > --registry= 命令行参数 > 默认 :9091(TCP)。

func RunRegisterLoop

func RunRegisterLoop(decodeFuncV2 DecodeFuncV2)

RunRegisterLoop 是插件 main 的标准入口(非隧道模式,保持原有行为)。

func RunRegisterLoopWithOptions

func RunRegisterLoopWithOptions(decodeFuncV2 DecodeFuncV2, opts RegisterOptions)

RunRegisterLoopWithOptions 是插件 main 的标准入口,支持隧道等可选行为。

工作流程(默认模式,opts 全零值时与旧版行为完全一致):

  1. 创建 Decoder gRPC server,监听 DecodeV2 端点 - 默认:本地 Unix socket(同机部署,路径含 PID 避免冲突) - 跨机器:设置 GT_DECODER_ADDR=host:port 监听 TCP; 并用 GT_DECODER_PUBLIC_ADDR(缺省回退为该 listen 地址)作为注册时上报的拨号地址
  2. 确定 registry 端点地址(GT_REGISTRY_ADDR 环境变量 > --registry flag > 默认 :9091) - 未显式设置时回退到 SDK 默认 :9091(见 ResolveRegistryAddr);显式设置可避免连到非预期地址
  3. 拨号 registry 并调用 Register RPC(传入上报地址和 plugin.yaml manifest bytes)
  4. 按返回的 instance_id 和 heartbeat_interval_sec 启动心跳 goroutine
  5. 心跳断开或 Register 失败时,指数退避重试(首次 1s,上限 30s)

隧道模式(opts.Tunnel=true):跳过第 1 步(不监听本地端点,宿主不回拨), Register(tunnel=true) 成功后打开 Connect 双向流,DecodeV2 经隧道帧完成。 opts.AuthToken 非空时,所有 RPC 附带 `authorization: Bearer <token>` metadata。

func ValidateManifest

func ValidateManifest(m *Manifest) error

ValidateManifest 校验 manifest 必填字段与格式约束。 返回 nil 表示合法,返回 error 描述具体违规字段。

Types

type Capabilities added in v0.7.0

type Capabilities map[Capability]bool

Capabilities 是能力位集合。

type Capability added in v0.7.0

type Capability string

Capability 是插件能力位闭集(§6.1)。

const (
	CapDecode Capability = "decode"
	CapSchema Capability = "schema"
	CapState  Capability = "state"
)

type ContractDecl

type ContractDecl struct {
	Name    string `yaml:"name"`    // gt.plugin
	Version int    `yaml:"version"` // 1
}

ContractDecl 是 manifest 的语义契约版本声明(§3.2)。

type DataSchema

type DataSchema struct {
	Fields map[string]FieldDecl `yaml:"fields"`
}

DataSchema 描述 v1 data 子对象的字段结构。已随 EventSpec 一并废弃。

type DataSpec

type DataSpec struct {
	Schema DataSchema `yaml:"schema"`
}

DataSpec 描述 v1 业务 data 子对象的入口 schema。已随 EventSpec 一并废弃。

type DecodeFuncV2

type DecodeFuncV2 func(req *pb.DecodeRequest, stream pb.Decoder_DecodeV2Server) error

DecodeFuncV2 是 V2 解码回调的签名。 插件通过 stream.Send 发送零个或多个 DecodeResponseV2 结果消息, 最后发送一个 done=true 的消息标记该 input_id 的结果已全部发完。 如果完全没有结果,应至少发送一个 {input_id, done=true} 消息。

type Decoder

type Decoder struct {
	pb.UnimplementedDecoderServer
	// contains filtered or unexported fields
}

Decoder 实现 pb.DecoderServer。 decodeFuncV2 是可选的 V2 解码回调;如果为 nil,则 DecodeV2 返回 Unimplemented。

func (*Decoder) DecodeV2

func (d *Decoder) DecodeV2(stream pb.Decoder_DecodeV2Server) error

DecodeV2 implements pb.DecoderServer.DecodeV2. If decodeFuncV2 is nil, returns Unimplemented.

type EventSpec

type EventSpec struct {
	Fields map[string]FieldDecl `yaml:"fields"` // 遗留:v1 _fields 内字段声明
	Data   DataSpec             `yaml:"data"`   // 遗留:v1 业务 data 子对象 schema
}

EventSpec 是 v1 遗留的事件结构声明。

【已废弃,仅为兼容旧 plugin.yaml 保留解析能力】 v1 时期 payload 是 JSON,平台语义放 _fields 子对象、业务语义放 data 子对象, 本结构就是那套形状的声明。v2 起 payload 改为 MsgPack 编码的 event.Value, 业务字段直接挂根对象,data/_fields 两个约定均已不存在 (见 contract.yaml 的 output_contract)。

新插件无需使用 EventSpec:业务语义请通过 Manifest.SemanticRules 声明 (Protocol Semantic Rule,见 docs/plugin-semantic-rules.md)。

type FieldDecl

type FieldDecl struct {
	Type string   `yaml:"type"`
	Enum []string `yaml:"enum,omitempty"`
}

FieldDecl 是 event.fields 内单个字段的声明。已随 EventSpec 一并废弃。

type Manifest

type Manifest struct {
	APIVersion      string    `yaml:"api_version"`          // gt.decoder/v2
	Name            string    `yaml:"name"`                 // kebab-case
	Protocol        string    `yaml:"protocol"`             // 主协议名(L7)
	Type            string    `yaml:"type"`                 // 固定 decoder
	ProtocolVersion string    `yaml:"protocol_version"`     // 可选,游戏协议版本
	Transports      []string  `yaml:"transports,omitempty"` // 可选,声明能解的 L4 传输层,取值 tcp|udp(缺省由 platform dispatcher 按既有语义处理)
	Hints           []string  `yaml:"hints"`                // 可选,匹配提示
	Event           EventSpec `yaml:"event"`                // 可选,遗留字段声明,见 EventSpec

	Contract      *ContractDecl   `yaml:"contract,omitempty"`       // 语义契约版本块(§3)
	SemanticRules []rule.Rule     `yaml:"semantic_rules,omitempty"` // Protocol Semantic Rule(插件定义协议语义,平台执行)
	Schemas       []schema.Schema `yaml:"schemas"`                  // 完整 schema 声明(宿主实际消费的是这里)
	States        []state.Subject `yaml:"states,omitempty"`         // subject 状态形状声明(capabilities.state 时强制)
	Capabilities  Capabilities    `yaml:"capabilities,omitempty"`   // 能力位(§6)
	Meta          ManifestMeta    `yaml:"meta"`                     // 可选,元数据
}

Manifest 是 plugin.yaml 的 Go 表示。 插件通过 Register RPC 传 plugin.yaml 原文,主程序 ParseManifest 后 ValidateManifest 校验。 字段语义参考 github.com/OwnSecurityGuard/gt-plugin-sdk 内置 contract 的 manifest_schema。

该类型定义与校验逻辑内置于 SDK,使插件模块无需依赖 gametrace 根模块即可完成 manifest 解析与校验(SDK 的 ReadManifest 直接复用本文件函数)。

层次沿革:v1 遗留 event 块(已废弃)→ 语义契约 v1 的 schemas/states 声明层 曾在 spec_version 5/6 短暂移除,v0.7.0 起**恢复**(数据形状声明与语义规则是互补 关系而非取代:schemas 描述数据形状,semantic_rules 描述协议语义)→ Protocol Semantic Rule(semantic_rules,§10):插件定义协议语义,平台执行。 framing/time_authority/state_ordering 等其余各层声明保持移除,不再回归。

func ParseManifest

func ParseManifest(data []byte) (*Manifest, error)

ParseManifest 解析 plugin.yaml 原文返回 Manifest。 不做字段校验,校验由 ValidateManifest 完成。 解析后执行 normalizeSchemas:遗留 indexable_fields 块升格为对应 Field 的 queryable + alias(语义契约 v1 §5,v0.5.0 起的既有行为,v0.7.1 回归)。

type ManifestMeta

type ManifestMeta struct {
	Author      string `yaml:"author"`
	Description string `yaml:"description"`
	Homepage    string `yaml:"homepage"`
}

ManifestMeta 是 manifest 的元数据段。

type RegisterOptions

type RegisterOptions struct {
	// Tunnel 为 true 时走反向隧道模式:Register(tunnel=true) 成功后,
	// 插件在同一连接上打开 Connect 双向流,DecodeV2 经隧道帧完成,
	// 宿主不再回拨 socket_path(此时也不需要启动本地 Decoder server)。
	Tunnel bool

	// AuthToken 非空时,注册/心跳/隧道请求附带
	// `authorization: Bearer <token>` gRPC metadata。
	AuthToken string
}

RegisterOptions 是注册行为的可选项,全部为零值时行为与旧版完全一致。

Directories

Path Synopsis
Package contract 承载 GameTrace Decoder Plugin API 契约(contract.yaml)。
Package contract 承载 GameTrace Decoder Plugin API 契约(contract.yaml)。
examples
http-stream-decoder command
Command http-stream-decoder is a complete, runnable GameTrace decoder plugin for HTTP over TCP.
Command http-stream-decoder is a complete, runnable GameTrace decoder plugin for HTTP over TCP.
Package framing turns a captured DecodeRequest.payload into L7 application bytes.
Package framing turns a captured DecodeRequest.payload into L7 application bytes.
Package rule 实现 Protocol Semantic Rule(协议语义规则)。
Package rule 实现 Protocol Semantic Rule(协议语义规则)。
Package schema defines the gt semantic schema model: declared types, fields, refs, references, and the validation/evolution rules that turn a plugin's schema declaration into a contract the host can enforce.
Package schema defines the gt semantic schema model: declared types, fields, refs, references, and the validation/evolution rules that turn a plugin's schema declaration into a contract the host can enforce.
Package state 实现 Layer 4 — State Contract(§9)。
Package state 实现 Layer 4 — State Contract(§9)。

Jump to

Keyboard shortcuts

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