Skip to content

Commit

Permalink
Swift: Client configuration example (awsdocs#5425)
Browse files Browse the repository at this point in the history
* New Swift example: how to configure a client
  • Loading branch information
shepazon authored Sep 29, 2023
1 parent d21c709 commit 7f12f8d
Show file tree
Hide file tree
Showing 5 changed files with 195 additions and 14 deletions.
26 changes: 26 additions & 0 deletions swift/example_code/swift-sdk/config/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// swift-tools-version: 5.8
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
name: "config",
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(
url: "https://github.com/awslabs/aws-sdk-swift",
from: "0.24.0"
),
],
targets: [
// Targets are the basic building blocks of a package, defining a module or a test suite.
// Targets can depend on other targets in this package and products from dependencies.
.executableTarget(
name: "config",
dependencies: [
.product(name: "AWSS3", package: "aws-sdk-swift"),
],
path: "Sources"
),
]
)
67 changes: 67 additions & 0 deletions swift/example_code/swift-sdk/config/Sources/ConfigExample.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// An example demonstrating how to configure an Amazon S3 client using the AWS
// SDK for Swift. The same principle applies to all services.

import Foundation
import ClientRuntime
import AWSS3

@main
struct ConfigExample {
static func main() async {
// snippet-start:[config.swift.use-custom-configuration]
let config: S3Client.S3ClientConfiguration

// Create an Amazon S3 client configuration object that specifies the
// region as "us-east-1", the adaptive retry mode, and the maximum
// number of retries as 5.

do {
// snippet-start:[config.swift.create-configuration]
config = try await S3Client.S3ClientConfiguration(
region: "us-east-1",
retryMode: .adaptive,
maxAttempts: 5
)
// snippet-end:[config.swift.create-configuration]
} catch {
print("Error: Unable to create configuration")
dump(error)
exit(1)
}

// Create an Amazon S3 client using the configuration created above.

// snippet-start:[config.swift.create-client]
let client = S3Client(config: config)
// snippet-end:[config.swift.create-client]
// snippet-end:[config.swift.use-custom-configuration]

// Ensure debug output is enabled so the HTTP header data is included
// in the output. The test can use this information to ensure the
// configuration is being used as expected.

SDKLoggingSystem.initialize(logLevel: .debug)

// Use the client to list the user's buckets. Return without any
// output if no buckets are found.

do {
let output = try await client.listBuckets(input: ListBucketsInput())

guard let buckets = output.buckets else {
return
}

for bucket in buckets {
print("\(bucket.name ?? "<unknown>")")
}
} catch {
print("Error: Unable to get list of buckets")
dump(error)
exit(2)
}
}
}
8 changes: 8 additions & 0 deletions swift/example_code/swift-sdk/config/test-cfn.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
AWSTemplateFormatVersion: "2010-09-09"
Description: Set up test environment for Swift config example.

Resources:
Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: "swift-sdk-test-config-example-v1"
80 changes: 80 additions & 0 deletions swift/example_code/swift-sdk/config/test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#!/bin/bash

stack_name="swift-sdk-test-config-example-v1"

# Set up the test environment. If an error occurs, abort the test and return
# an appropriate status code.

cmd_output=$(aws cloudformation create-stack --template-body file://test-cfn.yaml --stack-name "$stack_name")
cmd_exit_code=$?

if [[ "$cmd_exit_code" -ne 0 ]]; then
echo "Unable to create test environment. Is the AWS CLI installed and configured?"
exit "$cmd_exit_code"
fi

# Give the stack time to show up. This probably should be monitoring for it to
# appear instead.

sleep 5

# Run the program and capture the output so we can verify that the results
# match our expectations.

cmd_output=$(swift run)
cmd_exit_code=$?

# Make sure the HTTP Host header matches the configuration's setting for
# us-east-1. If any of these checks fail, the exit code is at least 100.
# Each error then gets a specific value added to the exit code, letting the
# result code be used to see which error(s) occurred.
#
# * Region mismatch: 1
# * Retry mode mismatch: 2
#
# If a Region mismatch occurs but the retry mode matches, the exit code is
# 101. If the retry mode mismatches but everything else is correct, the exit
# code is 102. If both the Region and retry mode mismatch, the exit code is
# 103.

config_exit_code="0"
if [[ "$cmd_output" != *"Host: s3.us-east-1.amazonaws.com"* ]]; then
echo "Error: The HTTP Host should be s3.us-east-1.amazonaws.com but is not."
config_exit_code=$(($config_exit_code + "1"))
fi
if [[ "$cmd_output" != *"cfg/retry-mode#adaptive"* ]]; then
echo "Error: The retry mode is not set to 'adaptive' as expected."
config_exit_code=$(($config_exit_code + "2"))
fi
if [[ "$config_exit_code" -ne "0" ]]; then
config_exit_code=$(($config_exit_code + "100"))
fi

# Remove the test bucket.

cmd_output=$(aws s3 rb s3://$stack_name)
cmd_exit_code=$?

if [[ "$cmd_exit_code" -ne 0 ]]; then
echo "Error deleting the test bucket '$stack_name'."
# exit $cmd_exit_code
fi

# Tear down the test environment.

cmd_output=$(aws cloudformation delete-stack --stack-name "$stack_name")
cmd_exit_code=$?

if [[ "$cmd_exit_code" -ne 0 ]]; then
echo "Error removing the test stack '$stack_name'."
# exit $cmd_exit_code
fi

# Return the configuration test status code if there is one. Otherwise return
# the most recent command exit code.

if [[ "$config_exit_code" -ne "0" ]]; then
exit "$config_exit_code"
fi

exit "$cmd_exit_code"
28 changes: 14 additions & 14 deletions swift/tools/swiftbuild.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
def swiftbuild(test, run, packages, swiftc_options):
# Process the package directories. Each directory in `packages` that has a
# `Package.swift` file is built using the `swiftc` command.

results = ()
num_packages_found = 0
for dir in packages:
Expand All @@ -29,7 +28,6 @@ def swiftbuild(test, run, packages, swiftc_options):
results = results + ((path, output),)

# Display a table of build results.

if num_packages_found != 0:
print("{0: <65} {1}".format("Example", "Status"))
print("-"*65, "-"*6)
Expand Down Expand Up @@ -100,10 +98,10 @@ def build_package(test, run, package, swiftc_options):
command_gerund = "building"

# If testing, look to see if there's a `test.sh` file. If so,
# the build command is "sh path/to/test.sh"
# the build command is "bash path/to/test.sh"
test_script = package / "test.sh"
if test and test_script.exists() and test_script.is_file():
command_parts = ["sh", test_script]
command_parts = ["bash", test_script]
else:
# Construct the command to build the project.
command_parts = ["swift", build_command]
Expand All @@ -129,22 +127,24 @@ def build_package(test, run, package, swiftc_options):

args = parser.parse_args()

# If no package list provided, use all directories in the
# current working directory.

if len(args.packages) == 0:
cwd_path = pathlib.Path().absolute()
package_list = [item for item in cwd_path.iterdir() if item.is_dir()]
else:
package_list = args.packages

# Build swiftc command line option list

swiftc_options = []

if args.hide_warnings:
swiftc_options.append("-suppress-warnings")
if args.parseable:
swiftc_options.append("-parseable-output")

# If no package list provided, use all directories in the
# current working directory.
if len(args.packages) == 0:
cwd_path = pathlib.Path().absolute()
if is_package_dir(cwd_path):
package_list = [cwd_path]
else:
package_list = [item for item in cwd_path.iterdir() if item.is_dir()]
else:
package_list = args.packages


swiftbuild(args.test, args.run, package_list, swiftc_options)

0 comments on commit 7f12f8d

Please sign in to comment.