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 examples for Swift 5.5 #223

Merged
merged 3 commits into from
Aug 19, 2021
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
16 changes: 8 additions & 8 deletions Examples/LambdaFunctions/Package.swift
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
// swift-tools-version:5.2
// swift-tools-version:5.5

import PackageDescription

let package = Package(
name: "swift-aws-lambda-runtime-samples",
platforms: [
.macOS(.v10_13),
.macOS(.v12),
],
products: [
// introductory example
Expand All @@ -24,16 +24,16 @@ let package = Package(
.package(name: "swift-aws-lambda-runtime", path: "../.."),
],
targets: [
.target(name: "HelloWorld", dependencies: [
.product(name: "AWSLambdaRuntime", package: "swift-aws-lambda-runtime"),
]),
.target(name: "Benchmark", dependencies: [
.executableTarget(name: "Benchmark", dependencies: [
.product(name: "AWSLambdaRuntimeCore", package: "swift-aws-lambda-runtime"),
]),
.target(name: "ErrorHandling", dependencies: [
.executableTarget(name: "HelloWorld", dependencies: [
.product(name: "AWSLambdaRuntime", package: "swift-aws-lambda-runtime"),
]),
.executableTarget(name: "ErrorHandling", dependencies: [
.product(name: "AWSLambdaRuntime", package: "swift-aws-lambda-runtime"),
]),
.target(name: "CurrencyExchange", dependencies: [
.executableTarget(name: "CurrencyExchange", dependencies: [
.product(name: "AWSLambdaRuntime", package: "swift-aws-lambda-runtime"),
]),
]
Expand Down
2 changes: 1 addition & 1 deletion Examples/LambdaFunctions/Sources/Benchmark/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import NIO
// use this example which is more performant.
// `EventLoopLambdaHandler` does not offload the Lambda processing to a separate thread
// while the closure-based handlers do.
Lambda.run(BenchmarkHandler())
Lambda.run { $0.eventLoop.makeSucceededFuture(BenchmarkHandler()) }

struct BenchmarkHandler: EventLoopLambdaHandler {
typealias In = String
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,30 @@ import Logging

// MARK: - Run Lambda

Lambda.run { (context: Lambda.Context, _: Request, callback: @escaping (Result<[Exchange], Error>) -> Void) in
let calculator = ExchangeRatesCalculator()
calculator.run(logger: context.logger, callback: callback)
@main
struct CurrencyExchangeHandler: AsyncLambdaHandler {
typealias In = Request
typealias Out = [Exchange]

let calculator: ExchangeRatesCalculator

init(context: Lambda.InitializationContext) async throws {
// the ExchangeRatesCalculator() can be reused over and over
self.calculator = ExchangeRatesCalculator()
}

func handle(event: Request, context: Lambda.Context) async throws -> [Exchange] {
try await withCheckedThrowingContinuation { continuation in
self.calculator.run(logger: context.logger) { result in
switch result {
case .success(let exchanges):
continuation.resume(returning: exchanges)
case .failure(let error):
continuation.resume(throwing: error)
}
}
}
}
}

// MARK: - Business Logic
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,29 @@ import AWSLambdaRuntime

// MARK: - Run Lambda

// switch over the error type "requested" by the request, and trigger such error accordingly
Lambda.run { (context: Lambda.Context, request: Request, callback: (Result<Response, Error>) -> Void) in
switch request.error {
// no error here!
case .none:
callback(.success(Response(awsRequestID: context.requestID, requestID: request.requestID, status: .ok)))
// trigger a "managed" error - domain specific business logic failure
case .managed:
callback(.success(Response(awsRequestID: context.requestID, requestID: request.requestID, status: .error)))
// trigger an "unmanaged" error - an unexpected Swift Error triggered while processing the request
case .unmanaged(let error):
callback(.failure(UnmanagedError(description: error)))
// trigger a "fatal" error - a panic type error which will crash the process
case .fatal:
fatalError("crash!")
@main
struct ErrorsHappenHandler: AsyncLambdaHandler {
typealias In = Request
typealias Out = Response

init(context: Lambda.InitializationContext) async throws {}

func handle(event request: Request, context: Lambda.Context) async throws -> Response {
// switch over the error type "requested" by the request, and trigger such error accordingly
switch request.error {
// no error here!
case .none:
return Response(awsRequestID: context.requestID, requestID: request.requestID, status: .ok)
// trigger a "managed" error - domain specific business logic failure
case .managed:
return Response(awsRequestID: context.requestID, requestID: request.requestID, status: .error)
// trigger an "unmanaged" error - an unexpected Swift Error triggered while processing the request
case .unmanaged(let error):
throw UnmanagedError(description: error)
// trigger a "fatal" error - a panic type error which will crash the process
case .fatal:
fatalError("crash!")
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@
import AWSLambdaRuntime

// introductory example, the obligatory "hello, world!"
Lambda.run { (_: Lambda.Context, _: String, callback: (Result<String, Error>) -> Void) in
callback(.success("hello, world!"))
@main
struct HelloWorldHandler: AsyncLambdaHandler {
typealias In = String
typealias Out = String

init(context: Lambda.InitializationContext) async throws {
// setup your resources that you want to reuse here.
}

func handle(event: String, context: Lambda.Context) async throws -> String {
"hello, world"
}
}
8 changes: 5 additions & 3 deletions Examples/LocalDebugging/MyApp/MyApp.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 1140;
LastUpgradeCheck = 1140;
LastUpgradeCheck = 1300;
ORGANIZATIONNAME = "Tom Doron";
TargetAttributes = {
F7B6C1F9246121E800607A89 = {
Expand Down Expand Up @@ -205,6 +205,7 @@
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
Expand All @@ -229,7 +230,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.4;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
Expand Down Expand Up @@ -265,6 +266,7 @@
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
Expand All @@ -283,7 +285,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.4;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1140"
LastUpgradeVersion = "1300"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
Expand Down
42 changes: 20 additions & 22 deletions Examples/LocalDebugging/MyApp/MyApp/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ struct ContentView: View {
TextField("Username", text: $name)
SecureField("Password", text: $password)
Button(
action: self.register,
action: {
Task {
await self.register()
}
},
label: {
Text("Register")
.padding()
Expand All @@ -38,8 +42,8 @@ struct ContentView: View {
}.padding(100)
}

func register() {
guard let url = URL(string: "http://localhost:7000/invoke") else {
func register() async {
guard let url = URL(string: "http://127.0.0.1:7000/invoke") else {
fatalError("invalid url")
}
var request = URLRequest(url: url)
Expand All @@ -50,27 +54,21 @@ struct ContentView: View {
}
request.httpBody = jsonRequest

let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
do {
if let error = error {
throw CommunicationError(reason: error.localizedDescription)
}
guard let httpResponse = response as? HTTPURLResponse else {
throw CommunicationError(reason: "invalid response, expected HTTPURLResponse")
}
guard httpResponse.statusCode == 200 else {
throw CommunicationError(reason: "invalid response code: \(httpResponse.statusCode)")
}
guard let data = data else {
throw CommunicationError(reason: "invald response, empty body")
}
let response = try JSONDecoder().decode(Response.self, from: data)
self.setResponse(response.message)
} catch {
self.setResponse("\(error)")
do {
let (data, response) = try await URLSession.shared.data(for: request)

guard let httpResponse = response as? HTTPURLResponse else {
throw CommunicationError(reason: "invalid response, expected HTTPURLResponse")
}
guard httpResponse.statusCode == 200 else {
throw CommunicationError(reason: "invalid response code: \(httpResponse.statusCode)")
}
let jsonResponse = try JSONDecoder().decode(Response.self, from: data)

self.response = jsonResponse.message
} catch {
self.response = error.localizedDescription
}
task.resume()
}

func setResponse(_ text: String) {
Expand Down
6 changes: 3 additions & 3 deletions Examples/LocalDebugging/MyLambda/Package.swift
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
// swift-tools-version:5.2
// swift-tools-version:5.5

import PackageDescription

let package = Package(
name: "MyLambda",
platforms: [
.macOS(.v10_13),
.macOS(.v12),
],
products: [
.executable(name: "MyLambda", targets: ["MyLambda"]),
Expand All @@ -18,7 +18,7 @@ let package = Package(
.package(name: "Shared", path: "../Shared"),
],
targets: [
.target(
.executableTarget(
name: "MyLambda", dependencies: [
.product(name: "AWSLambdaRuntime", package: "swift-aws-lambda-runtime"),
.product(name: "Shared", package: "Shared"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,17 @@ import Shared

// set LOCAL_LAMBDA_SERVER_ENABLED env variable to "true" to start
// a local server simulator which will allow local debugging
Lambda.run { (_, request: Request, callback: @escaping (Result<Response, Error>) -> Void) in
// TODO: something useful
callback(.success(Response(message: "Hello, \(request.name)!")))
@main
struct MyLambdaHandler: AsyncLambdaHandler {
typealias In = Request
typealias Out = Response

init(context: Lambda.InitializationContext) async throws {
// setup your resources that you want to reuse for every invocation here.
}

func handle(event request: Request, context: Lambda.Context) async throws -> Response {
// TODO: something useful
Response(message: "Hello, \(request.name)!")
}
}