Skip to content

Commit aa35ddf

Browse files
committed
Fix Vapor WebSocket integration for binary protocol
- Add X-Server-Node-ID header in upgrade response - Auto-detect binary vs JSON format - Send replies as binary frames
1 parent 3a0c664 commit aa35ddf

1 file changed

Lines changed: 24 additions & 9 deletions

File tree

Sources/TransmissionVapor/VaporIntegration.swift

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,21 @@ extension Application {
3333
throw Abort(.internalServerError, reason: "TransmissionSystem not registered")
3434
}
3535

36+
let serverNodeID = system.nodeID.id
3637
let routes = application.grouped(middleware)
37-
routes.webSocket(PathComponent(stringLiteral: path)) { req, ws in
38-
await VaporWebSocketBridge.handleWebSocket(req: req, ws: ws, system: system)
39-
}
38+
routes.webSocket(
39+
PathComponent(stringLiteral: path),
40+
shouldUpgrade: { req in
41+
var headers = HTTPHeaders()
42+
headers.add(name: "X-Server-Node-ID", value: serverNodeID)
43+
return req.eventLoop.makeSucceededFuture(headers)
44+
},
45+
onUpgrade: { req, ws in
46+
Task {
47+
await VaporWebSocketBridge.handleWebSocket(req: req, ws: ws, system: system)
48+
}
49+
}
50+
)
4051
}
4152
}
4253
}
@@ -94,10 +105,15 @@ public actor VaporWebSocketBridge {
94105

95106
private func processMessage(_ data: Data) async {
96107
do {
97-
let decoder = JSONDecoder()
98-
decoder.userInfo[.transmissionSystem] = system
99-
100-
let envelope = try decoder.decode(WireEnvelope.self, from: data)
108+
let envelope: WireEnvelope
109+
110+
if let firstByte = data.first, firstByte <= 2 {
111+
envelope = try WireEnvelope.decodeCompact(from: data)
112+
} else {
113+
let decoder = JSONDecoder()
114+
decoder.userInfo[.transmissionSystem] = system
115+
envelope = try decoder.decode(WireEnvelope.self, from: data)
116+
}
101117

102118
switch envelope {
103119
case .call(let call):
@@ -113,11 +129,10 @@ public actor VaporWebSocketBridge {
113129
}
114130

115131
private func handleCall(_ call: CallEnvelope) async {
116-
// Capture ws for the sendReply closure
117132
let wsRef = ws
118133

119134
await system.handleCall(call) { replyData in
120-
try await wsRef.send(raw: replyData, opcode: .text)
135+
try await wsRef.send(raw: replyData, opcode: .binary)
121136
}
122137
}
123138

0 commit comments

Comments
 (0)