Skip to content
Draft
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// swift-tools-version: 5.9
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// (swift-tools-version has two lines here because it needs to be the first
// line in the file, but it should also appear in the snippet below)
//
// snippet-start:[swift.rds.scenario.package]
// 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: "getbucket",
// Let Xcode know the minimum Apple platforms supported.
platforms: [
.macOS(.v13),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(
url: "https://github.com/awslabs/aws-sdk-swift",
from: "1.4.0"),
.package(
url: "https://github.com/aws/aws-sdk-swift-s3-transfer-manager.git",
branch: "main"
),
.package(
url: "https://github.com/apple/swift-argument-parser.git",
branch: "main"
)
],
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: "getbucket",
dependencies: [
.product(name: "AWSS3", package: "aws-sdk-swift"),
.product(name: "S3TransferManager", package: "aws-sdk-swift-s3-transfer-manager"),
.product(name: "ArgumentParser", package: "swift-argument-parser")
],
path: "Sources")

]
)
// snippet-end:[swift.rds.scenario.package]
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// The main code for the streaming bucket download example for the
// S3 Transfer Manager in the AWS SDK for Swift.

// snippet-start:[swift.s3tm.streaming.imports]
import AWSS3
import S3TransferManager
import Foundation
// snippet-end:[swift.s3tm.streaming.imports]

class Example {
let region: String
let bucketName: String

init(region: String, bucket: String) {
self.region = region
self.bucketName = bucket
}

/// The body of the example.
func run() async throws {
// snippet-start:[swift.s3tm.streaming.config-create]
let s3Config = try await S3Client.S3ClientConfiguration(
region: region
)

// Create an S3TransferManager object.

let s3tmConfig = try await S3TransferManagerConfig(
s3ClientConfig: s3Config, // Configuration for the S3Client
targetPartSizeBytes: 16 * 1024 * 1024, // 16 MB part size
multipartUploadThresholdBytes: 128 * 1024 * 1024, // 128 MB threshold
multipartDownloadType: .part
)

let s3tm = S3TransferManager(config: s3tmConfig)
// snippet-end:[swift.s3tm.streaming.config-create]

// Create a listener for events from the download of the bucket, to
// monitor the overall state of the download.

// snippet-start:[swift.s3tm.streaming.bucket-listener]
let downloadBucketStreamingTransferListener = DownloadBucketStreamingTransferListener()

Task {
for try await downloadBucketTransferEvent in downloadBucketStreamingTransferListener.eventStream {
switch downloadBucketTransferEvent {
case .initiated(let input, _):
print("Download of bucket \(input.bucket) started...")

case .complete(let input, _, let snapshot):
print("Download of bucket \(input.bucket) complete. Downloaded \(snapshot.transferredFiles) files.")
downloadBucketStreamingTransferListener.closeStream()

case .failed(let input, let snapshot):
print("*** Download of bucket \(input.bucket) failed after downloading \(snapshot.transferredFiles) files.")
downloadBucketStreamingTransferListener.closeStream()
}
}
}
// snippet-end:[swift.s3tm.streaming.bucket-listener]

// Create the directory to download the bucket into. The new directory
// is placed into the user's Downloads folder and has the same name as
// the bucket being downloaded.

guard let downloadsDirectory = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first else {
print("*** Unable to locate the Downloads directory.")
return
}

let targetDirectory = downloadsDirectory.appending(component: bucketName, directoryHint: .isDirectory)
try FileManager.default.createDirectory(at: targetDirectory, withIntermediateDirectories: true)

// Start downloading the bucket by calling S3TransferManager.downloadBucket(input:).

// snippet-start:[swift.s3tm.streaming.downloadBucket]
let downloadBucketTask = try s3tm.downloadBucket(
input: DownloadBucketInput(
bucket: bucketName,
destination: targetDirectory,
// The listener for the overall bucket download process.
directoryTransferListeners: [downloadBucketStreamingTransferListener],
// A factory that creates a listener for each file being downloaded.
objectTransferListenerFactory: {
let objectListener = DownloadObjectStreamingTransferListener()

Task {
for try await downloadObjectTransferEvent in objectListener.eventStream {
switch downloadObjectTransferEvent {
// The download of a file has begun.
case .initiated(let input, _):
print(" Downloading file \(input.key)...")

// The number of bytes received so far has been updated.
case .bytesTransferred(let input, let snapshot):
print(" Transferred \(snapshot.transferredBytes) total bytes of file \(input.key)...")

// A file download has completed.
case .complete(let input, _, let snapshot):
print(" Finished downloading file \(input.key) (\(snapshot.transferredBytes) bytes).")
objectListener.closeStream()

// The download of the file has failed.
case .failed(let input, let snapshot):
print("*** Download of file \(input.key) failed after \(snapshot.transferredBytes) bytes.")
objectListener.closeStream()
}
}
}

return [
objectListener
]
}
)
)
// snippet-end:[swift.s3tm.streaming.downloadBucket]

// Wait for the bucket to finish downloading, then display the results.

// snippet-start:[swift.s3tm.streaming.wait-for-download]
do {
let downloadBucketOutput = try await downloadBucketTask.value
print("Total files downloaded: \(downloadBucketOutput.objectsDownloaded)")
print("Number of failed downloads: \(downloadBucketOutput.objectsFailed)")
} catch {
print("*** Error downloading the bucket: \(error.localizedDescription)")
}
// snippet-end:[swift.s3tm.streaming.wait-for-download]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import ArgumentParser
import Foundation

struct ExampleCommand: ParsableCommand {
@Option(help: "AWS Region name")
var region = "us-east-1"
@Argument(help: "Name of the Amazon S3 bucket to download")
var bucketName: String

static var configuration = CommandConfiguration(
commandName: "getbucket",
abstract: """
Downloads a bucket from Amazon S3 using the S3 Transfer Manager.
""",
discussion: """
"""
)

/// Called by ``main()`` to do the actual running of the AWS
/// example.
func runAsync() async throws {
let example = Example(region: region, bucket: bucketName)

try await example.run()
}
}

/// The program's asynchronous entry point.
@main
struct Main {
/// The function that serves as the main asynchronous entry point for the
/// example. It parses the command line using the Swift Argument Parser,
/// then calls the `runAsync()` function to run the example itself.
static func main() async {
let args = Array(CommandLine.arguments.dropFirst())

do {
let command = try ExampleCommand.parse(args)
try await command.runAsync()
} catch {
ExampleCommand.exit(withError: error)
}
}
}
51 changes: 51 additions & 0 deletions swift/example_code/s3-transfer-manager/upload-file/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// swift-tools-version: 5.9
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// (swift-tools-version has two lines here because it needs to be the first
// line in the file, but it should also appear in the snippet below)
//
// snippet-start:[swift.rds.scenario.package]
// 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: "putfile",
// Let Xcode know the minimum Apple platforms supported.
platforms: [
.macOS(.v13),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(
url: "https://github.com/awslabs/aws-sdk-swift",
from: "1.4.0"),
.package(
url: "https://github.com/aws/aws-sdk-swift-s3-transfer-manager.git",
branch: "main"
),
.package(
url: "https://github.com/apple/swift-argument-parser.git",
branch: "main"
)
],
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: "putfile",
dependencies: [
.product(name: "AWSS3", package: "aws-sdk-swift"),
.product(name: "S3TransferManager", package: "aws-sdk-swift-s3-transfer-manager"),
.product(name: "ArgumentParser", package: "swift-argument-parser")
],
path: "Sources")

]
)
// snippet-end:[swift.rds.scenario.package]
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// The main code for file upload download example for the S3 Transfer Manager
// in the AWS SDK for Swift. This example doesn't include progress monitoring.
//
// The bucket downloading example
// (swift/example_code/s3-transfer-manager/download-streaming) includes an
// example of how to use progress monitoring.


// snippet-start:[swift.s3tm.upload.imports]
import AWSS3
import AWSClientRuntime
import S3TransferManager
import Foundation
import Smithy
import SmithyStreams
// snippet-end:[swift.s3tm.upload.imports]

class Example {
let filePath: String
let bucketName: String

init(path: String, bucket: String) {
self.filePath = path
self.bucketName = bucket
}

/// The body of the example.
func run() async throws {
// snippet-start:[swift.s3tm.upload.uploadObject]
let s3tm = try await S3TransferManager()

let fileURL = URL(string: filePath)
guard let fileURL else {
print("*** The file at \(filePath) doesn't exist.")
return
}

// Prepare the upload request.

let fileName = fileURL.lastPathComponent
let fileHandle = try FileHandle(forReadingFrom: fileURL)
let byteStream = ByteStream.stream(FileStream(fileHandle: fileHandle))

let uploadObjectInput = UploadObjectInput(
body: byteStream,
bucket: bucketName,
key: fileName,
transferListeners: [UploadObjectLoggingTransferListener()]
)

// Start the upload, then wait for it to complete.

do {
let uploadObjectTask = try s3tm.uploadObject(
input: uploadObjectInput
)

_ = try await uploadObjectTask.value
} catch let error as AWSServiceError {
if error.errorCode == "NoSuchBucket" {
print("*** The specified bucket, \(bucketName), doesn't exist.")
return
} else {
print("An unrecognized error occurred: \(error.message ?? "<unknown>")")
return
}
} catch {
print("*** An error occurred uploading the file: \(error.localizedDescription)")
}
// snippet-end:[swift.s3tm.upload.uploadObject]
}
}
Loading
Loading