sserelay

package
v0.0.1-beta.5 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: AGPL-3.0 Imports: 8 Imported by: 0

Documentation

Overview

Package sserelay 提供原始字节级 SSE relay:从 io.Reader 增量读取 SSE 帧, 原样转发给 http.ResponseWriter,自适应批量 Flush,并以 Observer 旁路暴露 事件信息(仅用于 usage 提取,不参与转发决策)。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func InferEventName

func InferEventName(data []byte) []byte

InferEventName 从 data-only 帧的 data 载荷推断事件名(顶层 "type" 字符串 值):帧首 `{"type":"` 锚定命中 → 值区间直接切片返回(零分配——Observer 每帧调用;解码器/反序列化对字符串结果必物化分配,字节直取;照 internal/billing/image_usage.go eventTypeIs 先例;值内 \ 转义跳过并以裸 字节返回——类型值恒无转义 ASCII,等价比较语义)。锚定不匹配(非首键/ 冒号后空白/前导空白/type 非字符串/null/畸形帧)→ 回退 json.Unmarshal 全量 解码(兼容——行为与旧 EventName 推断一致)。无 type / type 为空串 / 非 JSON → nil。返回切片:锚定路径指向输入字节(仅调用期间有效——调用方不得 跨帧保留);回退路径为本次分配。

func Relay

func Relay(ctx context.Context, dst http.ResponseWriter, src io.Reader, cfg Config) error

Relay 把 src 的 SSE 流原样转发到 dst。流结束 = EOF / 读错误 / ctx 取消。

Types

type Config

type Config struct {
	FlushBytes    int           // 缓冲达到该值立即 flush;0 时默认 4096
	FlushInterval time.Duration // 从 relay 启动起以固定间隔触发 timer flush(仅 pending > 0 时实际 flush);0 时默认 1ms
	Observer      Observer
	// Mapper 可选的逐帧转换器(协议转换 W5):nil = 原样转发(热路径零开销,
	// 单帧一次 nil 判定)。非 nil 时每帧先经 Mapper 变换再写出;Observer 仍见
	// 原始帧(用量提取不因转换失真)。drop=true → 帧丢弃不写出。映射帧字节
	// 生命周期仅限本帧:Mapper 返回后 relay 立即写出,调用方可复用缓冲。
	Mapper func(Event) (frame []byte, drop bool)
}

type Event

type Event struct {
	Raw   []byte // 完整原始帧(含结尾空行)
	Event []byte // event: 字段值;data-only 帧为空
	Data  []byte // 合并后的 data: payload(多行以 \n 连接)
}

Event 是一次 SSE 事件的旁路视图。 Raw/Event/Data 均指向 relay 内部复用的缓冲,仅在本次 Observer 回调期间有效; 消费方不得跨帧保留这些切片(下一帧会复用同一批缓冲)。

func (Event) EventName

func (e Event) EventName() []byte

EventName 返回帧的有效事件名:event: 字段值优先;缺名(data-only)帧从 data 的 JSON "type" 字段推断(InferEventName——resp/messages 流帧的 type 与事件名同值,非规范上游缺 event: 行时可用,P3)。仍无 → 空。仅缺名帧 触发推断,具名帧零开销(Observer 每帧调用)。返回切片生命周期同 Event (具名帧与锚定命中推断值均指向复用缓冲,仅回调内有效;锚定未命中回退 全量解码的推断值为本次分配)。

type Observer

type Observer func(Event)

Observer 在帧(原样或经 Mapper 变换后)写出后调用;不得阻塞 relay,不得 修改已写出的字节。回调参数 Event 的各切片仅在回调内有效(见 Event 注释), 不得跨帧保留。Mapper 存在时 Observer 始终见原始帧(转换不使用量提取失真)。

Jump to

Keyboard shortcuts

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