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 upload-async sample for HB v2 #50

Merged
merged 2 commits into from
Jan 17, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
# Hummingbird Example Code

Examples converted to Hummingbird 2.0
- [hello](https://github.com/hummingbird-project/hummingbird-examples/tree/2.x.x/hello) - Basic application setup
- [html-form](https://github.com/hummingbird-project/hummingbird-examples/tree/2.x.x/html-form) - Link HTML form to Hummingbird application
- [http2](https://github.com/hummingbird-project/hummingbird-examples/tree/2.x.x/http2) - Basic application with HTTP2 upgrade added
- [hello](https://github.com/hummingbird-project/hummingbird-examples/tree/2.x.x/hello) - Basic application setup.
- [html-form](https://github.com/hummingbird-project/hummingbird-examples/tree/2.x.x/html-form) - Link HTML form to Hummingbird application.
- [http2](https://github.com/hummingbird-project/hummingbird-examples/tree/2.x.x/http2) - Basic application with HTTP2 upgrade added.
- [sessions](https://github.com/hummingbird-project/hummingbird-examples/tree/2.x.x/sessions) - Username/password and session authentication.
- [todos-dynamodb](https://github.com/hummingbird-project/hummingbird-examples/tree/2.x.x/todos-dynamodb) - Todos application, based off [TodoBackend](http://todobackend.com) spec, using DynamoDB
- [todos-dynamodb](https://github.com/hummingbird-project/hummingbird-examples/tree/2.x.x/todos-dynamodb) - Todos application, based off [TodoBackend](http://todobackend.com) spec, using DynamoDB.
- [todos-postgres-tutorial](https://github.com/hummingbird-project/hummingbird-examples/tree/2.x.x/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/2.x.x/upload) - File uploading and downloading.

Examples still working with Hummingbird 1.0
- [auth-cognito](https://github.com/hummingbird-project/hummingbird-examples/tree/main/auth-cognito) - Authentication via AWS Cognito.
Expand All @@ -20,7 +21,6 @@ Examples still working with Hummingbird 1.0
- [proxy-server-core](https://github.com/hummingbird-project/hummingbird-examples/tree/main/proxy-server-core) - Version of proxy server only using HummingbirdCore
- [todos-fluent](https://github.com/hummingbird-project/hummingbird-examples/tree/main/todos-fluent) - Todos application, based off [TodoBackend](http://todobackend.com) spec, using Fluent
- [todos-lambda](https://github.com/hummingbird-project/hummingbird-examples/tree/main/todos-lambda) - Todos application, based off [TodoBackend](http://todobackend.com) spec, using DynamoDB and running on AWS Lambda.
- [upload-async](https://github.com/hummingbird-project/hummingbird-examples/tree/main/upload-async) - File uploading and downloading using the async/await APIs
- [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.
Expand Down
24 changes: 0 additions & 24 deletions upload-async/Sources/App/Application+configure.swift

This file was deleted.

29 changes: 0 additions & 29 deletions upload-async/Sources/Server/main.swift

This file was deleted.

52 changes: 0 additions & 52 deletions upload-async/Tests/AppTests/AppTests.swift

This file was deleted.

File renamed without changes.
File renamed without changes.
22 changes: 7 additions & 15 deletions upload-async/Package.swift → upload/Package.swift
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
// swift-tools-version:5.5
// swift-tools-version:5.9

import PackageDescription

let package = Package(
name: "upload-async",
platforms: [.macOS("12.0")],
products: [
.executable(name: "Server", targets: ["Server"]),
],
platforms: [.macOS(.v14)],
dependencies: [
.package(url: "https://github.com/hummingbird-project/hummingbird.git", from: "1.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", branch: "2.x.x"),
.package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.3.0"),
],
targets: [
.target(
.executableTarget(
name: "App",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
.product(name: "Hummingbird", package: "hummingbird"),
.product(name: "HummingbirdFoundation", package: "hummingbird"),
],
Expand All @@ -26,17 +24,11 @@ let package = Package(
.unsafeFlags(["-cross-module-optimization"], .when(configuration: .release)),
]
),
.executableTarget(
name: "Server",
dependencies: [
.byName(name: "App"),
.product(name: "ArgumentParser", package: "swift-argument-parser"),
]
),
.testTarget(
name: "AppTests",
dependencies: [
.byName(name: "App"),
.product(name: "Hummingbird", package: "hummingbird"),
.product(name: "HummingbirdXCT", package: "hummingbird"),
]
),
Expand Down
File renamed without changes.
36 changes: 36 additions & 0 deletions upload/Sources/App/Application+build.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Hummingbird server framework project
//
// Copyright (c) 2021-2021 the Hummingbird authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

import Hummingbird
import HummingbirdFoundation
import Logging
import NIOCore

struct UploadRequestContext: HBRequestContext {
var coreContext: HBCoreRequestContext
init(allocator: ByteBufferAllocator, logger: Logger) {
self.coreContext = .init(
requestDecoder: JSONDecoder(),
responseEncoder: JSONEncoder(),
allocator: allocator,
logger: logger
)
}
}

func buildApplication(args: AppArguments) -> some HBApplicationProtocol {
let router = HBRouter(context: UploadRequestContext.self)
FileController().addRoutes(to: router.group("files"))
return HBApplication(router: router)
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,17 @@
//===----------------------------------------------------------------------===//

import Foundation
import HTTPTypes
import Hummingbird
import HummingbirdFoundation

/// Handles file transfers
struct FileController {
func addRoutes(to group: HBRouterGroup) {
let fileIO = HBFileIO()

func addRoutes(to group: HBRouterGroup<some HBRequestContext>) {
group.get(":filename", use: self.download)
group.post("/", options: .streamBody, use: self.upload)
group.post("/", use: self.upload)
}

// MARK: - Upload
Expand All @@ -34,20 +37,17 @@ struct FileController {
/// then that name will be used as the file name on disk, otherwise
/// a UUID will be used.
/// - Returns: A JSONEncoded ``UploadModel``
private func upload(_ request: HBRequest) async throws -> UploadModel {
guard request.body.stream != nil else { throw HBHTTPError(.unauthorized) }
@Sendable private func upload(_ request: HBRequest, context: some HBRequestContext) async throws -> UploadModel {
let fileName = fileName(for: request)

let uploadModel = UploadModel(filename: fileName)
let fileURL = try uploadModel.destinationURL()

request.logger.info(.init(stringLiteral: "Uploading: \(uploadModel)"))
let fileIO = HBFileIO(application: request.application)
try await fileIO.writeFile(
context.logger.info(.init(stringLiteral: "Uploading: \(uploadModel)"))
try await self.fileIO.writeFile(
contents: request.body,
path: fileURL.path,
context: request.context,
logger: request.logger
context: context
)
return uploadModel
}
Expand All @@ -59,17 +59,13 @@ struct FileController {
/// - Returns: HBResponse of chunked bytes if success
/// Note that this download has no login checks and allows anyone to download
/// by its filename alone.
private func download(_ request: HBRequest) async throws -> HBResponse {
guard let filename = request.parameters.get("filename", as: String.self) else {
throw HBHTTPError(.badRequest)
}
@Sendable private func download(_ request: HBRequest, context: some HBRequestContext) async throws -> HBResponse {
let filename = try context.parameters.require("filename", as: String.self)
let uploadModel = UploadModel(filename: filename)
let uploadURL = try uploadModel.destinationURL(allowsOverwrite: true)
let fileIO = HBFileIO(application: request.application)
let body = try await fileIO.loadFile(
let body = try await self.fileIO.loadFile(
path: uploadURL.path,
context: request.context,
logger: request.logger
context: context
)
return HBResponse(
status: .ok,
Expand All @@ -80,10 +76,10 @@ struct FileController {

/// Adds headers for a given filename
/// IDEA: this is a good place to set the "Content-Type" property
private func headers(for filename: String) -> HTTPHeaders {
return HTTPHeaders([
("Content-Disposition", "attachment;filename=\"\(filename)\""),
])
private func headers(for filename: String) -> HTTPFields {
return [
.contentDisposition: "attachment;filename=\"\(filename)\"",
]
}
}

Expand All @@ -95,9 +91,13 @@ extension FileController {
}

private func fileName(for request: HBRequest) -> String {
guard let fileName = request.headers["File-Name"].first else {
guard let fileName = request.headers[.fileName] else {
return self.uuidFileName()
}
return fileName
}
}

extension HTTPField.Name {
static var fileName: Self { .init("File-Name")! }
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ struct UploadModel: HBResponseCodable {
}

extension UploadModel: CustomStringConvertible {
var description: String { filename }
var description: String { self.filename }
}

extension UploadModel {
Expand All @@ -20,11 +20,12 @@ extension UploadModel {
/// - allowsOverwrite: set `true` to overwrite any file with the same filename
/// - Returns: the target directory for uploads
func destinationURL(searchPath: FileManager.SearchPathDirectory = .documentDirectory, allowsOverwrite: Bool = false) throws -> URL {
let fileURL = try FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true)
.appendingPathComponent(filename)
let fileURL = try FileManager.default.url(
for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
).appendingPathComponent(self.filename)

guard allowsOverwrite == false else { return fileURL }
guard FileManager.default.fileExists(atPath: fileURL.path) == false else {
Expand Down
21 changes: 21 additions & 0 deletions upload/Sources/App/app.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import ArgumentParser
import Hummingbird

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

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

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

protocol AppArguments {
var hostname: String { get }
var port: Int { get }
}
Loading