Skip to content

Added a small swift http server with FlyingFox #442

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 107 additions & 0 deletions bench/algorithm/http-server/1.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import FlyingFox
import Foundation

struct PayloadContent: Codable {
let value: Int
init(value: Int){
self.value = value;
}
}

class DummyServer {
let server : HTTPServer

private func handleRequest(request: HTTPRequest) async -> HTTPResponse{
do {
let bodyStr = try await request.bodyData
let body = try JSONDecoder().decode(PayloadContent.self, from: bodyStr)
let response = "\(body.value)"
if let responseData = response.data(using: .utf8) {
return HTTPResponse(statusCode: .ok, body: responseData)
}
} catch {
print("An unexpected error occurred: \(error)")
}
return HTTPResponse(statusCode: .internalServerError, body: Data("Internal Server Error".utf8))
}

init(_ port: UInt16) async {
server = HTTPServer(port: port)
await server.appendRoute("POST /api") {request in
return await self.handleRequest(request: request)
}
}

func start() async throws {
try await server.start()
}

func stop() async throws{
await server.stop(timeout: 3)
}
}

func send(url: URL, value: Int) async -> Int {
let payload = PayloadContent(value: value)
guard let jsonData = try? JSONEncoder().encode(payload) else { return 0 }

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
do {
let (data, _) = try await URLSession.shared.data(for: request)
if let responseStr = String(data: data, encoding: .utf8), let intValue = Int(responseStr) {
return intValue
}
} catch {
print(error)
}
return 0
}

func main()async throws{
print("Hello world!")
// Command line arguments
let args = CommandLine.arguments
var n = 10

if args.count == 2, let inputNumber = Int(args[1]) {
n = inputNumber
}
print(n)

// Generate a random port number in the range 20000 to 50000
let port = UInt16.random(in: 20000...50000)

let task = Task {
let server = await DummyServer(port)
try await server.start()
}
let urlString = "http://localhost:\(port)/api"

guard let url = URL(string: urlString) else {
print("Invalid URL")
exit(1)
}

var sum = 0

await withTaskGroup(of: Int.self) { group in
for i in 1...n {
group.addTask {
await send(url: url, value: i)
}
}

for await result in group {
sum += result
}
}

print(sum)
task.cancel()

}

try await main()
3 changes: 3 additions & 0 deletions bench/bench_swift.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ problems:
- name: knucleotide
source:
- 2.swift
- name: http-server
source:
- 1.swift
compiler_version_command: swift --version
compiler_version_regex:
runtime_version_parameter:
Expand Down
11 changes: 7 additions & 4 deletions bench/include/swift/Package.swift
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
// swift-tools-version:5.5
// swift-tools-version:5.7
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
name: "app",
platforms: [
.macOS(.v13)
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
.package(url: "https://github.com/attaswift/BigInt.git", from: "5.3.0")
// .package(url: "https://github.com/httpswift/swifter.git", .upToNextMajor(from: "1.5.0"))
.package(url: "https://github.com/attaswift/BigInt.git", from: "5.3.0"),
.package(url: "https://github.com/swhitty/FlyingFox.git", .upToNextMajor(from: "0.15.0"))
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
Expand All @@ -18,7 +21,7 @@ let package = Package(
name: "app",
dependencies: [
"BigInt",
// .product(name: "Swifter", package: "swifter")
"FlyingFox",
]),
// .testTarget(
// name: "appTests",
Expand Down
Loading