Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:recycle: Migrate broadcast stream contracts https://github.com/siyuan-note/siyuan/issues/19378

Daniel086aef196b44
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index ac91222175..34bc11ad69 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -2221,8 +2221,7 @@ export type WorkspaceInfoData = { "siyuanVer": string; "workspaceDir": string; }
export type ZipRequestInput = { "path": string; "zipPath": string; };
export type APILegacyGETPath =
- "/es/broadcast/subscribe" |
- "/ws/broadcast";
+ never;
export interface APIGETRoutes {
"/api/ai/mcp/oauth/callback/:flowID": {
@@ -2310,6 +2309,13 @@ export interface APIGETRoutes {
response: { "code": 0; "data": string; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "none";
};
+ "/es/broadcast/subscribe": {
+ request: EmptyRequestInput;
+ response: string | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "none";
+ output: "sse";
+ sse: { raw: {"eventNames":"dynamic","dataEncoding":"raw","id":true,"retry":true}; };
+ };
"/es/network/proxy": {
request: EmptyRequestInput;
response: Blob | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -2324,6 +2330,13 @@ export interface APIGETRoutes {
output: "pluginService";
pluginService: {"variants":[{"mode":"JSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"JSONP","statusPolicy":"plugin","mediaTypes":["application/javascript","application/json"],"payload":"jsonp-or-json","headersOverrideMedia":true},{"mode":"AsciiJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"IndentedJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"PureJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"json","headersOverrideMedia":true},{"mode":"SecureJSON","statusPolicy":"plugin","mediaTypes":["application/json"],"payload":"secure-json","headersOverrideMedia":true},{"mode":"XML","statusPolicy":"plugin","mediaTypes":["application/xml"],"payload":"xml","headersOverrideMedia":true},{"mode":"YAML","statusPolicy":"plugin","mediaTypes":["application/yaml"],"payload":"yaml","headersOverrideMedia":true},{"mode":"TOML","statusPolicy":"plugin","mediaTypes":["application/toml"],"payload":"toml","headersOverrideMedia":true},{"mode":"ProtoBuf","statusPolicy":"plugin","mediaTypes":["application/x-protobuf"],"payload":"protobuf","headersOverrideMedia":true},{"mode":"file","statusPolicy":"file","mediaTypes":["dynamic"],"payload":"bytes","headersOverrideMedia":true},{"mode":"string","statusPolicy":"plugin","mediaTypes":["text/plain"],"payload":"text","headersOverrideMedia":true},{"mode":"raw","statusPolicy":"plugin","mediaTypes":["dynamic"],"payload":"bytes","headersOverrideMedia":true},{"mode":"redirect","statusPolicy":"redirect","mediaTypes":["text/html"],"payload":"redirect","headersOverrideMedia":true},{"mode":"proxy","statusPolicy":"proxy","mediaTypes":["upstream"],"payload":"bytes","headersOverrideMedia":true},{"mode":"empty","statusPolicy":"plugin","mediaTypes":["optional"],"payload":"none","headersOverrideMedia":true},{"mode":"websocket","statusPolicy":"websocket","mediaTypes":["upgrade-or-text"],"payload":"frames","headersOverrideMedia":false},{"mode":"sse","statusPolicy":"sse","mediaTypes":["text/event-stream"],"payload":"events","headersOverrideMedia":false},{"mode":"admission","statusPolicy":"admission","mediaTypes":["text/plain"],"payload":"text","headersOverrideMedia":true}],"admissionStatuses":[400,404,500,503],"webSocketFrames":["text","binary","close","ping","pong"],"sseEventNames":"dynamic","sseData":"json-or-text","sseEvent":{"type":"object","properties":{"data":{"$ref":"#/$defs/JSONValue"},"event":{"type":"string"},"id":{"type":"string"},"retry":{"type":"integer"}},"required":["data"],"additionalProperties":false}};
};
+ "/ws/broadcast": {
+ request: EmptyRequestInput;
+ response: null | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "none";
+ output: "websocket";
+ websocket: { incoming: Blob; outgoing: Blob; failureStatus: 0; raw: {"frames":[1,2,8,9,10],"upgradeErrorStatuses":[400,403,405,500],"emptyClosedResponse":true}; };
+ };
"/ws/network/proxy": {
request: EmptyRequestInput;
response: Blob | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
diff --git a/kernel/api/broadcast.go b/kernel/api/broadcast.go
index e7e4e13221..f4f3053f33 100644
--- a/kernel/api/broadcast.go
+++ b/kernel/api/broadcast.go
@@ -357,7 +357,13 @@ type ChannelInfo struct {
// @example
//
// "ws://localhost:6806/ws/broadcast?channel=test"
-func broadcast(c *gin.Context) {
+var broadcast = contractHandler(apicontract.BroadcastWebSocket, func(c *gin.Context, _ apicontract.EmptyRequest) apicontract.Response[apicontract.Null] {
+ return apicontract.UpgradeWebSocket[apicontract.Null](func(http.ResponseWriter, *http.Request) {
+ serveBroadcastWebSocket(c)
+ })
+})
+
+func serveBroadcastWebSocket(c *gin.Context) {
var (
channel = c.Query("channel")
broadcastChannel *BroadcastChannel
@@ -512,7 +518,13 @@ func PruneBroadcastChannels() []string {
// @example
//
// "http://localhost:6806/es/broadcast/subscribe?retry=1000&channel=test1&channel=test2"
-func broadcastSubscribe(c *gin.Context) {
+var broadcastSubscribe = contractHandler(apicontract.BroadcastSubscribe, func(c *gin.Context, _ apicontract.EmptyRequest) apicontract.Response[apicontract.Null] {
+ return apicontract.StreamSSE[apicontract.Null](func(http.ResponseWriter, *http.Request) {
+ serveBroadcastSubscribe(c)
+ })
+})
+
+func serveBroadcastSubscribe(c *gin.Context) {
// REF: https://github.com/gin-gonic/examples/blob/master/server-sent-event/main.go
c.Header("Content-Type", "text/event-stream")
c.Header("Cache-Control", "no-cache")
diff --git a/kernel/api/contract_broadcast_stream_test.go b/kernel/api/contract_broadcast_stream_test.go
new file mode 100644
index 0000000000..fd1664639d
--- /dev/null
+++ b/kernel/api/contract_broadcast_stream_test.go
@@ -0,0 +1,183 @@
+package api
+
+import (
+ "bytes"
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/asaskevich/EventBus"
+ "github.com/gin-gonic/gin"
+ "github.com/gorilla/websocket"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+)
+
+type broadcastTestBus struct {
+ EventBus.Bus
+ subscribed atomic.Int32
+}
+
+func (bus *broadcastTestBus) Subscribe(topic string, handler any) error {
+ err := bus.Bus.Subscribe(topic, handler)
+ if err == nil {
+ bus.subscribed.Add(1)
+ }
+ return err
+}
+
+func broadcastTestWait(t *testing.T, ready func() bool) {
+ t.Helper()
+ deadline := time.Now().Add(5 * time.Second)
+ for !ready() {
+ if time.Now().After(deadline) {
+ t.Fatal("broadcast lifecycle did not settle")
+ }
+ time.Sleep(time.Millisecond)
+ }
+}
+
+func TestAPIContractBroadcastRawSSE(t *testing.T) {
+ saved := UnifiedSSE
+ bus := &broadcastTestBus{Bus: EventBus.New()}
+ UnifiedSSE = &EventSourceServer{EventBus: bus, WaitGroup: &sync.WaitGroup{}, Subscriber: &EventSourceSubscriber{lock: &sync.Mutex{}}}
+ channel := "contract-broadcast\nraw"
+ engine := gin.New()
+ engine.GET("/es/broadcast/subscribe", broadcastSubscribe)
+ server := httptest.NewServer(engine)
+ ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
+ t.Cleanup(func() {
+ cancel()
+ server.Close()
+ UnifiedSSE.WaitGroup.Wait()
+ DestroyBroadcastChannel(channel, true)
+ UnifiedSSE = saved
+ })
+ open := func(query string) *http.Response {
+ t.Helper()
+ request, _ := http.NewRequestWithContext(ctx, "GET", server.URL+"/es/broadcast/subscribe"+query, nil)
+ response, err := http.DefaultClient.Do(request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { response.Body.Close() })
+ return response
+ }
+ selected := open("?retry=25&channel=" + url.QueryEscape(channel))
+ all := open("?retry=invalid")
+ broadcastTestWait(t, func() bool {
+ return bus.subscribed.Load() == 2
+ })
+ bundle, err := apicontract.BuildBundle()
+ if err != nil {
+ t.Fatal(err)
+ }
+ read := func(response *http.Response, want string) {
+ t.Helper()
+ body := make([]byte, len(want))
+ if _, err := io.ReadFull(response.Body, body); err != nil || string(body) != want {
+ t.Fatalf("raw SSE changed: %q want %q (%v)", body, want, err)
+ }
+ if err := bundle.ValidateHTTPResponse("GET", "/es/broadcast/subscribe", response.StatusCode, response.Header.Get("Content-Type"), body); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, kind := range []MessageType{MessageTypeString, MessageTypeBinary} {
+ UnifiedSSE.SendEvent(&MessageEvent{ID: "id\nraw", Type: kind, Name: channel, Data: []byte{'a', '\n', 0, 255, '\r'}})
+ read(selected, "id:id\\nraw\nevent:contract-broadcast\\nraw\nretry:25\ndata:a\ndata:\x00\xff\\r\n\n")
+ read(all, "id:id\\nraw\nevent:contract-broadcast\\nraw\ndata:a\ndata:\x00\xff\\r\n\n")
+ }
+ UnifiedSSE.SendEvent(&MessageEvent{Type: MessageTypeClose, Name: channel})
+ if remaining, err := io.ReadAll(selected.Body); err != nil || len(remaining) != 0 {
+ t.Fatalf("selected close changed: %q %v", remaining, err)
+ }
+ UnifiedSSE.SendEvent(&MessageEvent{ID: "after", Type: MessageTypeString, Name: channel, Data: []byte("still subscribed")})
+ read(all, "id:after\nevent:contract-broadcast\\nraw\ndata:still subscribed\n\n")
+ if selected.Header.Get("Cache-Control") != "no-cache" || selected.Header.Get("Connection") != "keep-alive" {
+ t.Fatal("SSE headers changed")
+ }
+ cancel()
+ all.Body.Close()
+ broadcastTestWait(t, func() bool { return UnifiedSSE.Subscriber.Count() == 0 })
+}
+
+func TestAPIContractBroadcastWebSocket(t *testing.T) {
+ channel := "contract-broadcast-ws"
+ engine := gin.New()
+ engine.GET("/ws/broadcast", broadcast)
+ server := httptest.NewServer(engine)
+ defer server.Close()
+ defer DestroyBroadcastChannel(channel, true)
+ endpoint := "ws" + strings.TrimPrefix(server.URL, "http") + "/ws/broadcast?channel=" + channel
+ first, response, err := websocket.DefaultDialer.Dial(endpoint, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer first.Close()
+ second, _, err := websocket.DefaultDialer.Dial(endpoint, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer second.Close()
+ broadcastTestWait(t, func() bool {
+ current := GetBroadcastChannel(channel)
+ return current != nil && current.WebSocket.Len() == 2
+ })
+ bundle, err := apicontract.BuildBundle()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = bundle.ValidateHTTPResponse("GET", "/ws/broadcast", response.StatusCode, response.Header.Get("Content-Type"), nil); err != nil {
+ t.Fatal(err)
+ }
+ for _, kind := range []int{websocket.TextMessage, websocket.BinaryMessage} {
+ data := []byte("not JSON")
+ if kind == websocket.BinaryMessage {
+ data = []byte{0, 255, 1}
+ }
+ if err = first.WriteMessage(kind, data); err != nil {
+ t.Fatal(err)
+ }
+ _ = second.SetReadDeadline(time.Now().Add(5 * time.Second))
+ actualKind, actual, err := second.ReadMessage()
+ if err != nil || actualKind != kind || !bytes.Equal(actual, data) {
+ t.Fatalf("broadcast frame changed: %d %x %v", actualKind, actual, err)
+ }
+ if err = bundle.ValidateRawWebSocketFrame("GET", "/ws/broadcast", false, actualKind, actual); err != nil {
+ t.Fatal(err)
+ }
+ }
+ denied, denial, err := websocket.DefaultDialer.Dial(endpoint, http.Header{"Origin": []string{"https://foreign.invalid"}, "Sec-Fetch-Site": []string{"cross-site"}})
+ if denied != nil {
+ denied.Close()
+ }
+ if err == nil || denial == nil {
+ t.Fatal("cross-origin broadcast accepted")
+ }
+ body, _ := io.ReadAll(denial.Body)
+ denial.Body.Close()
+ if denial.StatusCode != 403 {
+ t.Fatalf("upgrade error changed: %d", denial.StatusCode)
+ }
+ if err = bundle.ValidateHTTPResponse("GET", "/ws/broadcast", denial.StatusCode, denial.Header.Get("Content-Type"), body); err != nil {
+ t.Fatal(err)
+ }
+ first.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(1000, "done"))
+ first.Close()
+ current := GetBroadcastChannel(channel)
+ if current == nil {
+ t.Fatal("remaining subscriber lost its channel")
+ }
+ _, _ = current.BroadcastString("remaining")
+ _ = second.SetReadDeadline(time.Now().Add(5 * time.Second))
+ _, data, err := second.ReadMessage()
+ if err != nil || string(data) != "remaining" {
+ t.Fatalf("channel was closed for remaining subscriber: %s %v", data, err)
+ }
+}
diff --git a/kernel/apicontract/broadcast_protocol.go b/kernel/apicontract/broadcast_protocol.go
new file mode 100644
index 0000000000..c834d16003
--- /dev/null
+++ b/kernel/apicontract/broadcast_protocol.go
@@ -0,0 +1,97 @@
+package apicontract
+
+import (
+ "fmt"
+ "mime"
+ "reflect"
+)
+
+type RawSSEDefinition struct {
+ EventNames string `json:"eventNames"`
+ DataEncoding string `json:"dataEncoding"`
+ ID bool `json:"id"`
+ Retry bool `json:"retry"`
+}
+
+type RawWebSocketDefinition struct {
+ Frames []int `json:"frames"`
+ UpgradeErrorStatuses []int `json:"upgradeErrorStatuses"`
+ EmptyClosedResponse bool `json:"emptyClosedResponse"`
+}
+
+func RawSSEOptions() ResponseOptions {
+ return ResponseOptions{Output: SSEOutput, SSE: &SSEDefinition{Raw: &RawSSEDefinition{EventNames: "dynamic", DataEncoding: "raw", ID: true, Retry: true}}}
+}
+
+func RawWebSocketOptions() ResponseOptions {
+ return ResponseOptions{Output: WebSocketOutput, WebSocket: &WebSocketDefinition{Raw: &RawWebSocketDefinition{Frames: []int{1, 2, 8, 9, 10}, UpgradeErrorStatuses: []int{400, 403, 405, 500}, EmptyClosedResponse: true}}}
+}
+
+func rawSSESchema(definition *SSEDefinition) (*SSESchema, error) {
+ if len(definition.Events) != 0 || !reflect.DeepEqual(definition.Raw, RawSSEOptions().SSE.Raw) {
+ return nil, fmt.Errorf("invalid raw SSE event declaration")
+ }
+ return &SSESchema{Raw: definition.Raw}, nil
+}
+
+func rawWebSocketSchema(definition *WebSocketDefinition) (*WebSocketSchema, error) {
+ if definition.Incoming != nil || definition.Outgoing != nil || definition.FailureStatus != 0 || !reflect.DeepEqual(definition.Raw, RawWebSocketOptions().WebSocket.Raw) {
+ return nil, fmt.Errorf("invalid raw WebSocket declaration")
+ }
+ return &WebSocketSchema{Incoming: &Schema{Type: "string", Format: "binary"}, Outgoing: &Schema{Type: "string", Format: "binary"}, Raw: definition.Raw}, nil
+}
+
+func validateRawWebSocketHTTP(schema *WebSocketSchema, status int, contentType string, payload []byte) (bool, error) {
+ if schema.Raw == nil {
+ return false, nil
+ }
+ if status == 101 {
+ if len(payload) != 0 {
+ return true, fmt.Errorf("WebSocket upgrade cannot contain a body")
+ }
+ return true, nil
+ }
+ if status == 200 && len(payload) == 0 && schema.Raw.EmptyClosedResponse {
+ return true, nil
+ }
+ media, _, _ := mime.ParseMediaType(contentType)
+ for _, allowed := range schema.Raw.UpgradeErrorStatuses {
+ if status == allowed && media == "text/plain" {
+ return true, nil
+ }
+ }
+ return false, nil
+}
+
+// ValidateRawSSEEvent 校验事件协议;事件数据是原始字节,不进行 JSON 解码或 Base64 转码。
+func (b *Bundle) ValidateRawSSEEvent(method, path, name, id string, retry uint, payload []byte) error {
+ for _, endpoint := range b.Endpoints {
+ if endpoint.Method == method && endpoint.Path == path {
+ if endpoint.SSE == nil || endpoint.SSE.Raw == nil {
+ return fmt.Errorf("endpoint does not declare raw SSE events")
+ }
+ return nil
+ }
+ }
+ return fmt.Errorf("unregistered API contract: %s %s", method, path)
+}
+
+func (b *Bundle) ValidateRawWebSocketFrame(method, path string, incoming bool, frameType int, payload []byte) error {
+ for _, endpoint := range b.Endpoints {
+ if endpoint.Method == method && endpoint.Path == path {
+ if endpoint.WebSocket == nil || endpoint.WebSocket.Raw == nil {
+ return fmt.Errorf("endpoint does not declare raw WebSocket frames")
+ }
+ for _, allowed := range endpoint.WebSocket.Raw.Frames {
+ if frameType == allowed {
+ if frameType >= 8 && len(payload) > 125 {
+ return fmt.Errorf("WebSocket control frame exceeds 125 bytes")
+ }
+ return nil
+ }
+ }
+ return fmt.Errorf("undeclared raw WebSocket frame: %d", frameType)
+ }
+ }
+ return fmt.Errorf("unregistered API contract: %s %s", method, path)
+}
diff --git a/kernel/apicontract/broadcast_protocol_test.go b/kernel/apicontract/broadcast_protocol_test.go
new file mode 100644
index 0000000000..a70ec39a28
--- /dev/null
+++ b/kernel/apicontract/broadcast_protocol_test.go
@@ -0,0 +1,68 @@
+package apicontract
+
+import (
+ "net/http"
+ "testing"
+)
+
+func TestRawBroadcastProtocols(t *testing.T) {
+ previous := definitions
+ t.Cleanup(func() { definitions = previous })
+ ws := define[EmptyRequest, Null]("rawBroadcastWS", "/test/broadcast/ws", NoBody, RawWebSocketOptions(), "GET")
+ stream := define[EmptyRequest, Null]("rawBroadcastSSE", "/test/broadcast/es", NoBody, RawSSEOptions(), "GET")
+ bundle, err := BuildBundle()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, tt := range []struct {
+ path string
+ status int
+ media, body string
+ valid bool
+ }{
+ {"/test/broadcast/ws", 101, "", "", true},
+ {"/test/broadcast/ws", 200, "", "", true},
+ {"/test/broadcast/ws", 403, "text/plain; charset=utf-8", "Forbidden\n", true},
+ {"/test/broadcast/ws", 200, "application/json", `{"code":-1,"msg":"denied","data":null}`, true},
+ {"/test/broadcast/ws", 404, "text/plain", "not found", false},
+ {"/test/broadcast/ws", 101, "", "body", false},
+ {"/test/broadcast/es", 200, "text/event-stream", "event: channel\ndata: not JSON\n\n", true},
+ {"/test/broadcast/es", 200, "application/json", `{"code":-1,"msg":"denied","data":null}`, true},
+ {"/test/broadcast/es", 201, "text/event-stream", "", false},
+ } {
+ if err := bundle.ValidateHTTPResponse("GET", tt.path, tt.status, tt.media, []byte(tt.body)); (err == nil) != tt.valid {
+ t.Errorf("%+v: %v", tt, err)
+ }
+ }
+ for _, name := range []string{"", "dynamic", "channel\nname"} {
+ if err := bundle.ValidateRawSSEEvent("GET", "/test/broadcast/es", name, "id\nvalue", 123, []byte{0, 255}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, incoming := range []bool{false, true} {
+ for _, frame := range []int{1, 2, 8, 9, 10} {
+ if err := bundle.ValidateRawWebSocketFrame("GET", "/test/broadcast/ws", incoming, frame, []byte{0, 255}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ if err := bundle.ValidateRawWebSocketFrame("GET", "/test/broadcast/ws", false, 3, nil); err == nil {
+ t.Fatal("undeclared frame accepted")
+ }
+ if err := bundle.ValidateRawWebSocketFrame("GET", "/test/broadcast/ws", false, 9, make([]byte, 126)); err == nil {
+ t.Fatal("oversized control frame accepted")
+ }
+ if ws.Status(UpgradeWebSocket[Null](func(http.ResponseWriter, *http.Request) {})) != 101 || stream.Status(StreamSSE[Null](func(http.ResponseWriter, *http.Request) {})) != 200 {
+ t.Fatal("stream lifecycle status changed")
+ }
+ invalid := RawSSEOptions().SSE
+ invalid.Events = []SSEEventDefinition{SSEEvent[string]("json")}
+ if _, err := rawSSESchema(invalid); err == nil {
+ t.Fatal("mixed raw/JSON events accepted")
+ }
+ invalidWS := RawWebSocketOptions().WebSocket
+ invalidWS.Raw.Frames = []int{3}
+ if _, err := rawWebSocketSchema(invalidWS); err == nil {
+ t.Fatal("invalid frame set accepted")
+ }
+}
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 87f3e669ba..665fc79757 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -1001,3 +1001,6 @@ var UndoState = define[TransactionUndoStateRequest, TransactionUndoState]("undoS
var PerformUndo = define[TransactionHistoryRequest, TransactionHistoryResult]("performUndo", "/api/transactions/undo", JSONBody, ResponseOptions{}, "POST")
var PerformRedo = define[TransactionHistoryRequest, TransactionHistoryResult]("performRedo", "/api/transactions/redo", JSONBody, ResponseOptions{}, "POST")
var ClearHistory = define[TransactionClearHistoryRequest, Null]("clearHistory", "/api/transactions/clearHistory", JSONBody, ResponseOptions{}, "POST")
+
+var BroadcastWebSocket = define[EmptyRequest, Null]("broadcast", "/ws/broadcast", NoBody, RawWebSocketOptions(), "GET")
+var BroadcastSubscribe = define[EmptyRequest, Null]("broadcastSubscribe", "/es/broadcast/subscribe", NoBody, RawSSEOptions(), "GET")
diff --git a/kernel/apicontract/legacy_routes.json b/kernel/apicontract/legacy_routes.json
index da05786033..fe51488c70 100644
--- a/kernel/apicontract/legacy_routes.json
+++ b/kernel/apicontract/legacy_routes.json
@@ -1,4 +1 @@
-[
- {"method":"GET","path":"/es/broadcast/subscribe","handler":"broadcastSubscribe"},
- {"method":"GET","path":"/ws/broadcast","handler":"broadcast"}
-]
+[]
diff --git a/kernel/apicontract/response.go b/kernel/apicontract/response.go
index 8ce3e1f253..0bdc331055 100644
--- a/kernel/apicontract/response.go
+++ b/kernel/apicontract/response.go
@@ -62,6 +62,9 @@ func (e Endpoint[Request, Data]) Status(r Response[Data]) int {
if e.definition.Output != WebSocketOutput || e.definition.WebSocket == nil {
panic("endpoint does not declare WebSocket output")
}
+ if r.websocketFailure && e.definition.WebSocket.Raw != nil {
+ panic("raw WebSocket errors must be written by the upgrader")
+ }
if r.upgrade != nil {
return 101
}
diff --git a/kernel/apicontract/schema.go b/kernel/apicontract/schema.go
index bf3716226a..e0bb95b820 100644
--- a/kernel/apicontract/schema.go
+++ b/kernel/apicontract/schema.go
@@ -46,9 +46,10 @@ type EndpointSchema struct {
}
type WebSocketSchema struct {
- Incoming *Schema `json:"incoming"`
- Outgoing *Schema `json:"outgoing"`
- FailureStatus int `json:"failureStatus"`
+ Incoming *Schema `json:"incoming"`
+ Outgoing *Schema `json:"outgoing"`
+ FailureStatus int `json:"failureStatus"`
+ Raw *RawWebSocketDefinition `json:"raw,omitempty"`
}
type Bundle struct {
@@ -597,7 +598,7 @@ func BuildBundle() (*Bundle, error) {
return nil, fmt.Errorf("WebSocket output requires message declarations: %s", definition.Name)
}
if ws := definition.WebSocket; ws != nil {
- if definition.Body != NoBody || definition.DataOnError || definition.ErrorStatus != 0 || ws.FailureStatus < 400 || ws.FailureStatus > 599 {
+ if definition.Body != NoBody || definition.DataOnError || definition.ErrorStatus != 0 || ws.Raw == nil && (ws.FailureStatus < 400 || ws.FailureStatus > 599) {
return nil, fmt.Errorf("invalid WebSocket response options: %s", definition.Name)
}
for _, method := range definition.Methods {
@@ -605,15 +606,26 @@ func BuildBundle() (*Bundle, error) {
return nil, fmt.Errorf("WebSocket upgrade requires GET: %s", definition.Name)
}
}
- incoming, err := b.schema(ws.Incoming, true)
- if err != nil {
- return nil, err
- }
- outgoing, err := b.schema(ws.Outgoing, false)
- if err != nil {
- return nil, err
+ if ws.Raw != nil {
+ if definition.Data != reflect.TypeFor[Null]() {
+ return nil, fmt.Errorf("raw WebSocket output requires Null data: %s", definition.Name)
+ }
+ var err error
+ websocket, err = rawWebSocketSchema(ws)
+ if err != nil {
+ return nil, err
+ }
+ } else {
+ incoming, err := b.schema(ws.Incoming, true)
+ if err != nil {
+ return nil, err
+ }
+ outgoing, err := b.schema(ws.Outgoing, false)
+ if err != nil {
+ return nil, err
+ }
+ websocket = &WebSocketSchema{Incoming: incoming, Outgoing: outgoing, FailureStatus: ws.FailureStatus}
}
- websocket = &WebSocketSchema{Incoming: incoming, Outgoing: outgoing, FailureStatus: ws.FailureStatus}
}
if definition.Output == DirectJSONOutput && (definition.DataOnError || definition.ErrorStatus != 0) {
return nil, fmt.Errorf("direct JSON output cannot use envelope data or error status options: %s", definition.Name)
@@ -755,6 +767,11 @@ func (b *Bundle) ValidateHTTPResponse(method, path string, status int, contentTy
}
return nil
}
+ if endpoint.WebSocket != nil {
+ if handled, err := validateRawWebSocketHTTP(endpoint.WebSocket, status, contentType, payload); handled {
+ return err
+ }
+ }
if endpoint.WebSocket != nil && status == 101 {
if len(payload) != 0 {
return fmt.Errorf("WebSocket upgrade must not contain an HTTP body")
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 4b2ce196b8..304deec5eb 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -105207,6 +105207,70 @@
]
}
},
+ {
+ "method": "GET",
+ "path": "/es/broadcast/subscribe",
+ "handler": "broadcastSubscribe",
+ "body": "none",
+ "request": {
+ "$ref": "#/$defs/EmptyRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ },
+ "output": "sse",
+ "sse": {
+ "raw": {
+ "eventNames": "dynamic",
+ "dataEncoding": "raw",
+ "id": true,
+ "retry": true
+ }
+ }
+ },
{
"method": "GET",
"path": "/es/network/proxy",
@@ -105546,6 +105610,89 @@
}
}
},
+ {
+ "method": "GET",
+ "path": "/ws/broadcast",
+ "handler": "broadcast",
+ "body": "none",
+ "request": {
+ "$ref": "#/$defs/EmptyRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "null"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ },
+ "output": "websocket",
+ "websocket": {
+ "incoming": {
+ "type": "string",
+ "format": "binary"
+ },
+ "outgoing": {
+ "type": "string",
+ "format": "binary"
+ },
+ "failureStatus": 0,
+ "raw": {
+ "frames": [
+ 1,
+ 2,
+ 8,
+ 9,
+ 10
+ ],
+ "upgradeErrorStatuses": [
+ 400,
+ 403,
+ 405,
+ 500
+ ],
+ "emptyClosedResponse": true
+ }
+ }
+ },
{
"method": "GET",
"path": "/ws/network/proxy",
diff --git a/kernel/apicontract/sse.go b/kernel/apicontract/sse.go
index 23ffe98d2f..61e0ae975c 100644
--- a/kernel/apicontract/sse.go
+++ b/kernel/apicontract/sse.go
@@ -23,9 +23,13 @@ func SSEEvent[Payload any](name string) SSEEventDefinition {
return SSEEventDefinition{name: name, payload: reflect.TypeFor[Payload]()}
}
-type SSEDefinition struct{ Events []SSEEventDefinition }
+type SSEDefinition struct {
+ Events []SSEEventDefinition
+ Raw *RawSSEDefinition
+}
type SSESchema struct {
- Events map[string]*Schema `json:"events"`
+ Events map[string]*Schema `json:"events,omitempty"`
+ Raw *RawSSEDefinition `json:"raw,omitempty"`
}
func SSEOptions(events ...SSEEventDefinition) ResponseOptions {
@@ -43,6 +47,9 @@ func StreamSSE[Data any](serve func(http.ResponseWriter, *http.Request)) Respons
func (r Response[Data]) Stream() func(http.ResponseWriter, *http.Request) { return r.stream }
func (b *schemaBuilder) sseSchema(definition *SSEDefinition) (*SSESchema, error) {
+ if definition != nil && definition.Raw != nil {
+ return rawSSESchema(definition)
+ }
if definition == nil || len(definition.Events) == 0 {
return nil, fmt.Errorf("SSE output requires event declarations")
}
@@ -69,6 +76,9 @@ func (b *Bundle) ValidateSSEEvent(method, path, name string, payload []byte) err
if endpoint.SSE == nil {
return fmt.Errorf("endpoint does not declare SSE events")
}
+ if endpoint.SSE.Raw != nil {
+ return b.ValidateRawSSEEvent(method, path, name, "", 0, payload)
+ }
schema, exists := endpoint.SSE.Events[name]
if !exists {
return fmt.Errorf("undeclared SSE event: %s", name)
diff --git a/kernel/apicontract/typescript.go b/kernel/apicontract/typescript.go
index aa5afbf7bf..dfc1731550 100644
--- a/kernel/apicontract/typescript.go
+++ b/kernel/apicontract/typescript.go
@@ -178,14 +178,24 @@ func (b *Bundle) TypeScript(legacy []Route) []byte {
fmt.Fprintf(&output, " contentVariants: %s;\n", variants)
}
if ws := endpoint.WebSocket; ws != nil {
- fmt.Fprintf(&output, " websocket: { incoming: %s; outgoing: %s; failureStatus: %d; };\n", b.typeScript(ws.Incoming), b.typeScript(ws.Outgoing), ws.FailureStatus)
+ fmt.Fprintf(&output, " websocket: { incoming: %s; outgoing: %s; failureStatus: %d;", b.typeScript(ws.Incoming), b.typeScript(ws.Outgoing), ws.FailureStatus)
+ if ws.Raw != nil {
+ raw, _ := json.Marshal(ws.Raw)
+ fmt.Fprintf(&output, " raw: %s;", raw)
+ }
+ output.WriteString(" };\n")
}
if sse := endpoint.SSE; sse != nil {
- output.WriteString(" sse: { events: { ")
- for _, name := range sortedKeys(sse.Events) {
- fmt.Fprintf(&output, "%s: %s; ", quote(name), b.typeScript(sse.Events[name]))
+ if sse.Raw != nil {
+ raw, _ := json.Marshal(sse.Raw)
+ fmt.Fprintf(&output, " sse: { raw: %s; };\n", raw)
+ } else {
+ output.WriteString(" sse: { events: { ")
+ for _, name := range sortedKeys(sse.Events) {
+ fmt.Fprintf(&output, "%s: %s; ", quote(name), b.typeScript(sse.Events[name]))
+ }
+ output.WriteString("}; };\n")
}
- output.WriteString("}; };\n")
}
if proxy := endpoint.Proxy; proxy != nil {
protocol, _ := json.Marshal(proxy)
diff --git a/kernel/apicontract/websocket.go b/kernel/apicontract/websocket.go
index 78e9bc6738..a0be3b5790 100644
--- a/kernel/apicontract/websocket.go
+++ b/kernel/apicontract/websocket.go
@@ -12,6 +12,7 @@ type WebSocketDefinition struct {
Incoming reflect.Type
Outgoing reflect.Type
FailureStatus int
+ Raw *RawWebSocketDefinition
}
func WebSocketOptions[Incoming, Outgoing any](failureStatus int) ResponseOptions {
@@ -43,6 +44,9 @@ func (b *Bundle) ValidateWebSocketMessage(method, path string, incoming bool, pa
if endpoint.WebSocket == nil {
return fmt.Errorf("endpoint does not declare WebSocket messages")
}
+ if endpoint.WebSocket.Raw != nil {
+ return nil
+ }
schema := endpoint.WebSocket.Outgoing
if incoming {
schema = endpoint.WebSocket.Incoming