protocol

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jul 13, 2026 License: Apache-2.0 Imports: 9 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package protocol 存放信令 JSON 消息、普通转发与终局转发的 sessionId 包裹 类型(执行计划 §6.2/§6.7)。纯类型零依赖:transport/relay 客户端与 relay 服务端共同 import;不得引入第三方依赖,也不得反向依赖任何实现包。 线协议版本位(/v1/ws/<shareId> 的 v1)覆盖信令 JSON 与数据面帧布局。

Index

Constants

View Source
const (
	// BinTypeManifest:清单帧,`0x01 ‖ sealedManifest`。紧随所属 JSON 消息
	// (register 上行 / manifest 下行),同连接 WS 有序,天然关联(§6.7)。
	BinTypeManifest byte = 0x01
	// BinTypeForward:回退数据面转发帧,`0x02 ‖ sessionId(8B) ‖ 内层数据面帧`。
	// 包裹只为路由;内层 REQUEST/BLOCK/ERROR 布局归 core/session,中转不解析。
	BinTypeForward byte = 0x02
	// BinTypeTerminalForward carries the final opaque inner frame. Its distinct
	// envelope lets every hop prioritize and tombstone the session without
	// inspecting encrypted block traffic or the inner ERROR payload.
	BinTypeTerminalForward byte = 0x03
)

二进制 WS 帧的类型前缀(§6.7)。同一 WS 复用文本(信令 JSON)与二进制帧, 二进制帧以首字节区分用途;中转对帧体原样搬运、零解析。

View Source
const (
	TypeRegister   = "register"
	TypeRegistered = "registered"
	TypeKeepalive  = "keepalive"
	TypeJoin       = "join"
	TypeManifest   = "manifest"
	TypeNotFound   = "not_found"
	TypeSignal     = "signal"
	TypeBye        = "bye"
	TypeError      = "error"
)

信令 JSON 消息类型标签(§6.7)。

View Source
const (
	// KeepaliveInterval 是发送端 WS 保活间隔(§8);中转对 keepalive 原样回显,
	// 兼作应用层 pong。
	KeepaliveInterval = 20 * time.Second

	// SenderReconnectGrace:发送端断开后 shareId 会话挂起的宽限期,期内凭
	// resumeToken 原像 + sealedManifest 字节一致重注册恢复,期满回收(§6.8)。
	SenderReconnectGrace = 60 * time.Second

	// ResumeTokenBytes 是发送端会话续接令牌长度(crypto/rand 生成的本地秘密,
	// 不经链接/清单流出;每中转独立,§6.8)。register 提交其 SHA-256。
	ResumeTokenBytes = 16

	// SessionIDBytes:中转在 join 时分配的接收会话标识长度。值在线上保持
	// opaque;中转可在内部使用结构化发行来识别连接生命周期内的旧会话。
	SessionIDBytes = 8

	// MaxSignalingMessageBytes 是单条信令 JSON 文本帧的上限。信令只承载控制
	// 字段与 SDP/ICE(几 KiB 量级),64 KiB 已远超正常需要;设上限防止
	// 恶意超长 JSON 撑爆中转解析缓冲。
	MaxSignalingMessageBytes = 64 * 1024

	// MaxSignalingJSONDepth counts nested JSON objects and arrays, including the
	// top-level signaling object. A protocol-owned bound avoids inheriting the
	// different and unstable recursion ceilings of Go and JavaScript parsers.
	MaxSignalingJSONDepth = 64
)
View Source
const (
	SignalKindOffer     = "offer"
	SignalKindAnswer    = "answer"
	SignalKindCandidate = "candidate"
)

WebRTC 协商消息的 kind 取值(§6.7)。中转不解析、原样转发;常量供两端 客户端使用。

View Source
const (
	// ErrCodeProtocol:消息违反线协议(未知类型、字段缺失、时序错误等),
	// 连接级致命。
	ErrCodeProtocol = "protocol_error"
	// ErrCodeShareIDMismatch:register/join 消息内 shareId 与 WS 路径不一致(§6.7)。
	ErrCodeShareIDMismatch = "share_id_mismatch"
	// ErrCodeShareIDCollision:shareId 已有活跃发送端;客户端应重生成(D13)。
	ErrCodeShareIDCollision = "share_id_collision"
	// ErrCodeResumeRejected:宽限期重注册的 token 原像校验失败或
	// sealedManifest 字节不一致(§6.8)。
	ErrCodeResumeRejected = "resume_rejected"
	// ErrCodeManifestTooLarge:清单帧超 MaxManifestSize。
	ErrCodeManifestTooLarge = "manifest_too_large"
	// ErrCodeManifestBudget:节点清单驻留内存预算耗尽,拒新 register(§6.8)。
	ErrCodeManifestBudget = "manifest_budget_exceeded"
	// ErrCodeRateLimited:join 命中每 shareId 或每 IP 限速(§6.8)。
	ErrCodeRateLimited = "rate_limited"
	// ErrCodeFrameTooLarge:二进制帧超限(转发帧超 MaxFrameSize+包裹头,
	// 或清单帧超 MaxManifestSize)。
	ErrCodeFrameTooLarge = "frame_too_large"
	// ErrCodeSessionOverflow:该会话的有界转发队列已满(慢接收端/恶意),
	// 中转断会话以保发送端 WS 不被队头阻塞(§6.8)。
	ErrCodeSessionOverflow = "session_overflow"
	// ErrCodeUnknownSession:sessionId 不存在或已随会话结束失效。
	ErrCodeUnknownSession = "unknown_session"
	// ErrCodeSenderGone:发送端断开,会话终结;接收端应指数退避 rejoin(§6.8)。
	ErrCodeSenderGone = "sender_gone"
)

信令 error 消息的 code 值域。取自描述字符串而非数字:信令面是 JSON, 可读的 code 让客户端分支与人工排障都不必查表。

View Source
const ForwardOverheadBytes = 1 + SessionIDBytes

ForwardOverheadBytes 是转发帧包裹头长度(类型前缀 + sessionId); 中转的二进制帧限额 = MaxFrameSize + 此值。

View Source
const HealthOK = "ok"

HealthOK 是健康响应的唯一正常值;不健康的节点直接不回 200。

View Source
const ManifestOverheadBytes = 1

ManifestOverheadBytes 是清单帧头长度(仅类型前缀)。

View Source
const MaxShareIDChars = 64

MaxShareIDChars 限定 shareId 字符串长度。shareId 对中转是不透明路由句柄 (D13,长度由客户端版本决定),但它入 URL 路径与注册表键,须限制字符集 与长度防注入/滥用;64 字符已容纳数倍于当前 9 字节句柄的演进空间。

View Source
const ProtocolVersion = "v1"

ProtocolVersion 是线协议版本位(§6.7):覆盖信令 JSON 与数据面帧布局, 体现在 WS 端点路径 /v1/ws/<shareId> 与 health/config 的版本通告。 suiteByte 只版本化加密套件,管不到线协议。

View Source
const TerminalForwardOverheadBytes = 1 + SessionIDBytes

TerminalForwardOverheadBytes intentionally matches the ordinary envelope; the type byte alone carries lifecycle semantics.

Variables

This section is empty.

Functions

func BinType

func BinType(frame []byte) byte

BinType 返回二进制帧的类型前缀;空帧返回 0(非法值,两个已定义类型都非 0)。

func DecodeManifestFrame

func DecodeManifestFrame(frame []byte) ([]byte, error)

DecodeManifestFrame 取出清单帧内的 sealedManifest 字节(共享底层数组, 不拷贝——中转按"原样字节"存储与回放,拷贝由调用方按需决定)。

func Encode

func Encode(m Message) ([]byte, error)

Encode 序列化一条信令消息;先校验,坏消息不出门。

func EncodeForwardFrame

func EncodeForwardFrame(id SessionID, inner []byte) []byte

EncodeForwardFrame 用 sessionId 包裹一条内层数据面帧。

func EncodeManifestFrame

func EncodeManifestFrame(sealed []byte) []byte

EncodeManifestFrame 构造清单二进制帧。

func EncodeResumeToken

func EncodeResumeToken(token []byte) string

EncodeResumeToken 把 resumeToken 原像编码为线格式(base64url 无填充)。

func EncodeTerminalForwardFrame

func EncodeTerminalForwardFrame(id SessionID, inner []byte) []byte

func HashResumeToken

func HashResumeToken(token []byte) string

HashResumeToken 计算 register 提交的 resumeTokenHash 线格式: base64url 无填充的 SHA-256(token)(§6.8)。

func ValidateShareID

func ValidateShareID(s string) error

ValidateShareID 校验 shareId 为非空、不超长的 base64url 字符串。 只做路由句柄的卫生检查,不钉死具体长度——语义家在 core/link(§8)。

func VerifyResumeToken

func VerifyResumeToken(tokenB64, wantHashB64 string) bool

VerifyResumeToken 校验宽限期重注册出示的原像与注册时提交的哈希匹配。 常数时间比较:token 是会话所有权凭证,不给旁路留时序信道。

Types

type AdmissionLimits

type AdmissionLimits struct {
	MaxConnections            int       `json:"maxConnections"`
	MaxConcurrentShares       int       `json:"maxConcurrentShares"`
	MaxSharesPerSource        int       `json:"maxSharesPerSource"`
	MaxManifestBytesPerSource int64     `json:"maxManifestBytesPerSource"`
	MaxTotalManifestBytes     int64     `json:"maxTotalManifestBytes"`
	RegisterPerSource         RateLimit `json:"registerPerSource"`
	JoinPerSource             RateLimit `json:"joinPerSource"`
	JoinPerShare              RateLimit `json:"joinPerShare"`
}

type Bye

type Bye struct {
	Type      string `json:"type"`
	SessionID string `json:"sessionId"`
}

Bye:结束会话,双向(§6.7)。接收端断连时中转也会代其向发送端合成 Bye, 使发送端无需区分"对端主动告别"与"对端消失"。

func NewBye

func NewBye(sessionID string) *Bye

type Error

type Error struct {
	Type      string `json:"type"`
	Code      string `json:"code"`
	Message   string `json:"message,omitempty"`
	SessionID string `json:"sessionId,omitempty"`
}

Error:中转→客户端的错误通报。SessionID 非空表示会话级错误(该会话 已终结、连接仍可用),为空表示连接级错误(随后连接关闭)。

func NewError

func NewError(code, message string) *Error

func NewSessionError

func NewSessionError(sessionID, code, message string) *Error

type Health

type Health struct {
	Status string `json:"status"`
}

Health 是 GET /healthz 的响应体。

type Join

type Join struct {
	Type    string `json:"type"`
	ShareID string `json:"shareId"`
}

Join:接收端→中转,加入分享(§6.7)。

func NewJoin

func NewJoin(shareID string) *Join

type Keepalive

type Keepalive struct {
	Type string `json:"type"`
}

Keepalive:发送端↔中转保活;中转原样回显兼作应用层 pong(§6.7)。

func NewKeepalive

func NewKeepalive() *Keepalive

type Manifest

type Manifest struct {
	Type      string `json:"type"`
	SessionID string `json:"sessionId"`
}

Manifest:中转→接收端,join 成功;清单二进制帧紧随其后。SessionID 由 中转分配、标识该接收会话,随会话结束失效(§6.7)。

func NewManifest

func NewManifest(sessionID string) *Manifest

type Message

type Message interface {
	// contains filtered or unexported methods
}

Message 是信令消息的封闭集合:每个具体类型自带 Type 标签与字段校验。 Encode/Decode 是唯一出入口,保证两端(transport/relay 客户端与中转) 对 schema 的理解逐字节一致。

func Decode

func Decode(data []byte) (Message, error)

Decode 解析一条信令 JSON 消息为具体类型;未知 type 与字段校验失败都在 此处拦下,调用方拿到的消息保证结构完整。

type NotFound

type NotFound struct {
	Type string `json:"type"`
}

NotFound:中转→接收端,shareId 无活跃分享;接收端短窗指数退避重试(§6.7)。

func NewNotFound

func NewNotFound() *NotFound

type RateLimit

type RateLimit struct {
	PerSecond float64 `json:"perSecond"`
	Burst     int     `json:"burst"`
}

type Register

type Register struct {
	Type            string `json:"type"`
	ShareID         string `json:"shareId"`
	ResumeTokenHash string `json:"resumeTokenHash"`       // base64url 无填充的 SHA-256(resumeToken)
	ResumeToken     string `json:"resumeToken,omitempty"` // 宽限期重注册出示的原像(base64url 无填充)
}

Register:发送端→中转,注册分享;清单二进制帧紧随其后(§6.7)。 ResumeToken 仅在断线宽限期重注册时出示(原像,§6.8),首次注册留空。

func NewRegister

func NewRegister(shareID, resumeTokenHash string) *Register

func NewResumeRegister

func NewResumeRegister(shareID, resumeTokenHash, resumeToken string) *Register

type Registered

type Registered struct {
	Type    string `json:"type"`
	ShareID string `json:"shareId"`
}

Registered:中转→发送端,注册(含清单入库)成功确认。发送端收到它才可 打印链接(§6.9)——没有 ack 就只能以"未收到 error"猜测成功,测试与 客户端都得靠 sleep,违背最小惊讶。

func NewRegistered

func NewRegistered(shareID string) *Registered

type ServerConfig

type ServerConfig struct {
	ProtocolVersions []string     `json:"protocolVersions"`
	Limits           ServerLimits `json:"limits"`
}

ServerConfig 是 GET /v1/config 的响应体(§6.7/§6.8):通告支持的线协议 版本列表与限额,供客户端预检——中转是第三方长期部署的基础设施, 客户端↔中转版本错配必然发生,错配即明确拒绝优于神秘失败。

type ServerLimits

type ServerLimits struct {
	// MaxFrameSize:数据面单帧上限(含内层帧头,不含转发包裹头)。
	MaxFrameSize int64 `json:"maxFrameSize"`
	// MaxManifestSize:清单帧内 sealedManifest 的上限;发送端出链接前预检(§6.9)。
	MaxManifestSize int64 `json:"maxManifestSize"`
	// MaxSignalingMessageBytes:单条信令 JSON 的上限。
	MaxSignalingMessageBytes int64 `json:"maxSignalingMessageBytes"`
	// MaxHeaderBytes bounds the HTTP request headers before WebSocket upgrade.
	MaxHeaderBytes int `json:"maxHeaderBytes"`
	// Admission exposes effective static policy. Live remaining capacity is
	// intentionally not advertised because it races every request.
	Admission AdmissionLimits `json:"admission"`
	// Timeouts are milliseconds to avoid language-specific duration encodings.
	Timeouts ServerTimeouts `json:"timeouts"`
}

ServerLimits publishes deployment policy that clients can use for preflight. Live capacity and internal protocol-abuse/queue guards are omitted because they are neither stable client budgets nor actionable before dialing.

type ServerTimeouts

type ServerTimeouts struct {
	HTTPReadHeaderMilliseconds       int64 `json:"httpReadHeaderMilliseconds"`
	HTTPReadMilliseconds             int64 `json:"httpReadMilliseconds"`
	HTTPIdleMilliseconds             int64 `json:"httpIdleMilliseconds"`
	WebSocketRoleMilliseconds        int64 `json:"webSocketRoleMilliseconds"`
	WebSocketKeepaliveMilliseconds   int64 `json:"webSocketKeepaliveMilliseconds"`
	SenderReconnectGraceMilliseconds int64 `json:"senderReconnectGraceMilliseconds"`
}

type SessionID

type SessionID [SessionIDBytes]byte

SessionID 是中转分配的接收会话标识的原始字节形式。JSON 消息里以 base64url 无填充字符串出现,转发帧头里以定长原始字节出现——定长使 帧头解析零分配、无需长度字段。

func DecodeForwardFrame

func DecodeForwardFrame(frame []byte) (SessionID, []byte, error)

DecodeForwardFrame 解出转发帧的路由头与内层帧(内层共享底层数组,零拷贝 ——中转对内层零知识,原样入队转发)。

func DecodeTerminalForwardFrame

func DecodeTerminalForwardFrame(frame []byte) (SessionID, []byte, error)

func ParseSessionID

func ParseSessionID(s string) (SessionID, error)

ParseSessionID 解析 JSON 消息里的 sessionId 线格式。

func (SessionID) String

func (id SessionID) String() string

String 返回 JSON 消息使用的线格式。

type Signal

type Signal struct {
	Type      string          `json:"type"`
	SessionID string          `json:"sessionId"`
	Kind      string          `json:"kind"`
	Payload   json.RawMessage `json:"payload"`
}

Signal:WebRTC 协商消息,双向经中转转发(§6.7)。Payload 对中转不透明, 原样转发零解析。

func NewSignal

func NewSignal(sessionID, kind string, payload json.RawMessage) *Signal

Jump to

Keyboard shortcuts

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