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

Update s3-upload example for HB 2.0 #75

Merged
merged 4 commits into from
May 6, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ Examples converted to Hummingbird 2.0
- [todos-mongokitten-openapi](https://github.com/hummingbird-project/hummingbird-examples/tree/main/todos-mongokitten-openapi) - Todos application, using MongoDB driver [MongoKitten](https://github.com/orlandos-nl/MongoKitten) and the [OpenAPI runtime](https://github.com/apple/swift-openapi-runtime).
- [todos-postgres-tutorial](https://github.com/hummingbird-project/hummingbird-examples/tree/main/todos-postgres-tutorial) - Todos application, based off [TodoBackend](http://todobackend.com) spec, using PostgresNIO. Sample code that goes along with the [Todos tutorial](https://hummingbird-project.github.io/hummingbird-docs/2.0/tutorials/todos).
- [upload](https://github.com/hummingbird-project/hummingbird-examples/tree/main/upload) - File uploading and downloading.
- [upload-s3](https://github.com/hummingbird-project/hummingbird-examples/tree/main/upload-s3) - File uploading and downloading using AWS S3 as backing store.
- [webauthn](https://github.com/hummingbird-project/hummingbird-examples/tree/main/webauthn) - Web app demonstrating WebAuthn(PassKey) authentication.
- [websocket-chat](https://github.com/hummingbird-project/hummingbird-examples/tree/main/websocket-chat) - Simple chat application using WebSockets.
- [websocket-echo](https://github.com/hummingbird-project/hummingbird-examples/tree/main/websocket-echo) - Simple WebSocket based echo server.
Expand All @@ -30,6 +31,5 @@ Examples still working with Hummingbird 1.0
- [auth-srp](https://github.com/hummingbird-project/hummingbird-examples/tree/1.x.x/auth-srp) - Secure Remote Password authentication.
- [ios-image-server](https://github.com/hummingbird-project/hummingbird-examples/tree/1.x.x/ios-image-server) - iOS web server that provides access to iPhone photo library.
- [todos-fluent](https://github.com/hummingbird-project/hummingbird-examples/tree/1.x.x/todos-fluent) - Todos application, based off [TodoBackend](http://todobackend.com) spec, using Fluent
- [upload-s3](https://github.com/hummingbird-project/hummingbird-examples/tree/1.x.x/upload-s3) - File uploading and downloading using AWS S3 as backing store.

The full set of Hummingbird 1.0 examples can be found at https://github.com/hummingbird-project/hummingbird-examples/tree/1.x.x
13 changes: 6 additions & 7 deletions upload-s3/Package.swift
Original file line number Diff line number Diff line change
@@ -1,26 +1,25 @@
// swift-tools-version:5.5
// swift-tools-version:5.9
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
name: "upload-s3",
platforms: [.macOS("12.0")],
platforms: [.macOS("14.0")],
adam-fowler marked this conversation as resolved.
Show resolved Hide resolved
products: [
.executable(name: "App", targets: ["App"]),
],
dependencies: [
.package(url: "https://github.com/hummingbird-project/hummingbird.git", from: "1.0.0"),
.package(url: "https://github.com/soto-project/soto.git", from: "6.0.0"),
.package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.0.0"),
.package(url: "https://github.com/hummingbird-project/hummingbird.git", from: "2.0.0-beta"),
.package(url: "https://github.com/soto-project/soto.git", from: "7.0.0-beta"),
.package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.3.0"),
],
targets: [
.executableTarget(
name: "App",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
.product(name: "Hummingbird", package: "hummingbird"),
.product(name: "HummingbirdFoundation", package: "hummingbird"),
.product(name: "SotoS3", package: "soto"),
],
swiftSettings: [
Expand All @@ -34,7 +33,7 @@ let package = Package(
name: "AppTests",
dependencies: [
.byName(name: "App"),
.product(name: "HummingbirdXCT", package: "hummingbird"),
.product(name: "HummingbirdTesting", package: "hummingbird"),
]
),
]
Expand Down
26 changes: 15 additions & 11 deletions upload-s3/Sources/App/App.swift
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
import ArgumentParser
import Hummingbird
import Logging

@main
struct App: ParsableCommand, AppArguments {
struct App: AsyncParsableCommand, AppArguments {
@Option(name: .shortAndLong)
var hostname: String = "127.0.0.1"

@Option(name: .shortAndLong)
var port: Int = 8080

func run() throws {
let app = HBApplication(
configuration: .init(
address: .hostname(self.hostname, port: self.port),
serverName: "Hummingbird"
)
)
try app.configure(self)
try app.start()
app.wait()
@Option(name: .shortAndLong)
var logLevel: Logger.Level?

func run() async throws {
let app = buildApplication(self)
try await app.runService()
}
}

/// Extend `Logger.Level` so it can be used as an argument
#if compiler(>=6.0)
extension Logger.Level: @retroactive ExpressibleByArgument {}
#else
extension Logger.Level: ExpressibleByArgument {}
#endif
93 changes: 93 additions & 0 deletions upload-s3/Sources/App/Application+build.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import Foundation
import Hummingbird
import Logging
import ServiceLifecycle
import SotoS3

/// Application arguments protocol. We use a protocol so we can call
/// `HBApplication.configure` inside Tests as well as in the App executable.
/// Any variables added here also have to be added to `App` in App.swift and
/// `TestArguments` in AppTest.swift
public protocol AppArguments {
var hostname: String { get }
var port: Int { get }
var logLevel: Logger.Level? { get }
}

struct AWSClientService: Service {
let client: AWSClient

func run() async throws {
// Ignore cancellation error
try? await gracefulShutdown()
try await self.client.shutdown()
}
}

func buildApplication(_ args: AppArguments) -> some ApplicationProtocol {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
func buildApplication(_ args: AppArguments) -> some ApplicationProtocol {
func buildApplication(_ args: some AppArguments) -> some ApplicationProtocol {

let logger = {
var logger = Logger(label: "html-form")
logger.logLevel = args.logLevel ?? .info
return logger
}()
let env = Environment()
guard let bucket = env.get("s3_upload_bucket") else {
preconditionFailure("Requires \"s3_upload_bucket\" environment variable")
}

let awsClient = AWSClient()
let s3 = S3(client: awsClient, region: .euwest1)

let router = Router()
router.middlewares.add(LogRequestsMiddleware(.info))

router.addRoutes(
S3FileController(
s3: s3,
bucket: bucket,
folder: env.get("s3_upload_folder") ?? "hb-upload-s3"
).getRoutes(),
atPath: "files"
)
router.get("/health") { request, context in
return HTTPResponse.Status.ok
}
var app = Application(
router: router,
configuration: .init(address: .hostname(args.hostname, port: args.port)),
logger: logger
)
app.addServices(AWSClientService(client: awsClient))
return app
}

/*
extension HBApplication {
/// configure your application
/// add middleware
/// setup the encoder/decoder
/// add your routes
func configure(_: AppArguments) throws {
let env = HBEnvironment()
guard let bucket = env.get("s3_upload_bucket") else {
preconditionFailure("Requires \"s3_upload_bucket\" environment variable")
}

self.encoder = JSONEncoder()
self.middleware.add(HBLogRequestsMiddleware(.info))
self.aws.client = AWSClient(httpClientProvider: .createNewWithEventLoopGroup(self.eventLoopGroup))
let s3 = S3(client: self.aws.client, region: .euwest1)

let fileController = S3FileController(
s3: s3,
bucket: bucket,
folder: env.get("s3_upload_folder") ?? "hb-upload-s3"
)
fileController.addRoutes(to: self.router.group("files"))

self.router.get("/health") { _ -> HTTPResponseStatus in
return .ok
}
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Commented code

*/
39 changes: 0 additions & 39 deletions upload-s3/Sources/App/Application+configure.swift

This file was deleted.

20 changes: 0 additions & 20 deletions upload-s3/Sources/App/Application+soto.swift

This file was deleted.

Loading