Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow WebSocket maxFrameSize to be configured #2195

Merged
merged 2 commits into from Mar 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion Sources/Vapor/Response/Response.swift
Expand Up @@ -33,7 +33,7 @@ public final class Response: CustomStringConvertible {
}

internal enum Upgrader {
case webSocket(onUpgrade: (WebSocket) -> ())
case webSocket(maxFrameSize: WebSocketMaxFrameSize, onUpgrade: (WebSocket) -> ())
}

internal var upgrader: Upgrader?
Expand Down
8 changes: 7 additions & 1 deletion Sources/Vapor/Routing/RoutesBuilder+WebSocket.swift
@@ -1,12 +1,18 @@
public enum WebSocketMaxFrameSize {
case `default`
case override(Int)
}

extension RoutesBuilder {
@discardableResult
public func webSocket(
_ path: PathComponent...,
maxFrameSize: WebSocketMaxFrameSize = .`default`,
onUpgrade: @escaping (Request, WebSocket) -> ()
) -> Route {
return self.on(.GET, path) { request -> Response in
let res = Response(status: .switchingProtocols)
res.upgrader = .webSocket(onUpgrade: { ws in
res.upgrader = .webSocket(maxFrameSize: maxFrameSize, onUpgrade: { ws in
onUpgrade(request, ws)
})
return res
Expand Down
11 changes: 9 additions & 2 deletions Sources/Vapor/Server/HTTPServerUpgradeHandler.swift
Expand Up @@ -51,8 +51,15 @@ final class HTTPServerUpgradeHandler: ChannelDuplexHandler, RemovableChannelHand
self.upgradeState = .upgraded
if res.status == .switchingProtocols, let upgrader = res.upgrader {
switch upgrader {
case .webSocket(let onUpgrade):
let webSocketUpgrader = NIOWebSocketServerUpgrader(automaticErrorHandling: false, shouldUpgrade: { channel, _ in
case .webSocket(let maxFrameSize, let onUpgrade):
let maxFrameSizeBytes: Int
switch maxFrameSize {
case .`default`:
maxFrameSizeBytes = 1 << 14
case .override(let bytes):
maxFrameSizeBytes = bytes
}
let webSocketUpgrader = NIOWebSocketServerUpgrader(maxFrameSize: maxFrameSizeBytes, automaticErrorHandling: false, shouldUpgrade: { channel, _ in
return channel.eventLoop.makeSucceededFuture([:])
}, upgradePipelineHandler: { channel, req in
return WebSocket.server(on: channel, onUpgrade: onUpgrade)
Expand Down