'usleep in Swifter degrades overtime
I have the following server:
import SwiftUI
import Swifter
@main
struct MacInputServer: App {
let server: HttpServer;
var body: some Scene {
WindowGroup {
ContentView()
}
}
func sleep(req: HttpRequest) -> HttpResponse {
usleep(100_000);
return .ok(.text(""))
}
init() {
server = HttpServer()
server["/sleep"] = sleep
try! server.start(999, forceIPv4: true, priority: DispatchQoS.QoSClass.userInteractive);
}
}
I'm running while true; do time curl localhost:999/sleep; done
to test it. The first ~100 requests finish in about 120ms as expected. But after that it starts hanging for up to 10 seconds:
curl localhost:999/sleep 0.01s user 0.01s system 11% cpu 0.118 total
curl localhost:999/sleep 0.01s user 0.01s system 0% cpu 10.121 total
curl localhost:999/sleep 0.01s user 0.01s system 0% cpu 5.134 total
curl localhost:999/sleep 0.00s user 0.01s system 0% cpu 5.902 total
Why?
Solution 1:[1]
Well looks like it's swifter's fault - in HttpServerIO.swift it dispatches the requests to global queue like this:
DispatchQueue.global(qos: priority).async
Replacing it with
DispatchQueue.init(label: "httpserver", qos: DispatchQoS.userInteractive)
Fixed the problem. Obviously editing source code of a 3rd party package stinks, and the header suggests that this file was last updated in 2016. I've moved to vapor and it's miles better than swifter.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Henlo |