Repository navigation
Expand file tree
/
Copy pathStorageBucket.swift
More file actions
924 lines (879 loc) · 39.4 KB
/
Copy pathStorageBucket.swift
File metadata and controls
924 lines (879 loc) · 39.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
import ConcurrencyExtras
public import Foundation
public import HTTPTypes
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
/// A handle on one Storage bucket, for file operations within it.
///
/// Obtain a ``StorageBucket`` by calling ``StorageClient/from(_:)`` with the bucket
/// identifier you want to operate on:
///
/// ```swift
/// let avatars = storage.from("avatars")
///
/// // Upload a PNG
/// try await avatars.upload(path: "user123.png", data: imageData)
///
/// // Generate a signed URL valid for 60 seconds
/// let url = try await avatars.createSignedURL(path: "user123.png", expiresIn: .seconds(60))
/// ```
///
/// ## Topics
///
/// ### Uploading files
///
/// - ``upload(path:data:options:progress:)``
/// - ``upload(path:fileURL:options:progress:)``
/// - ``upload(path:body:options:progress:)``
/// - ``upload(path:item:contentType:options:progress:)``
/// - ``update(path:data:options:progress:)``
/// - ``update(path:fileURL:options:progress:)``
/// - ``update(path:body:options:progress:)``
///
/// ### Uploading via signed URLs
///
/// - ``createSignedUploadURL(path:upsert:)``
/// - ``uploadToSignedURL(path:token:data:options:progress:)``
/// - ``uploadToSignedURL(path:token:fileURL:options:progress:)``
/// - ``uploadToSignedURL(path:token:body:options:progress:)``
///
/// ### Downloading files
///
/// - ``download(path:options:progress:)``
/// - ``DownloadResponse``
/// - ``publicURL(path:options:)``
///
/// ### Managing files
///
/// - ``move(from:to:toBucket:sourceVersionID:)``
/// - ``copy(from:to:toBucket:sourceVersionID:options:)``
/// - ``remove(paths:)``
/// - ``remove(versions:)``
/// - ``objects(prefix:options:)``
/// - ``list(path:options:)``
/// - ``info(path:versionID:)``
/// - ``exists(path:)``
/// - ``purgeCache(path:transformationsOnly:)``
///
/// ### Creating signed URLs
///
/// - ``createSignedURL(path:expiresIn:options:)``
/// - ``createSignedURLs(paths:expiresIn:options:)``
///
/// ### Customizing headers
///
/// - ``settingHeader(name:value:)``
///
/// ### Configuration
///
/// - ``configuration``
public struct StorageBucket: Sendable {
/// The identifier of the bucket this instance operates on.
public let id: String
let api: StorageAPI
/// The configuration used to initialize this client instance.
public var configuration: StorageClient.Configuration { api.configuration }
init(id: String, api: StorageAPI) {
self.id = id
self.api = api
}
/// Returns a new ``StorageBucket`` with an additional HTTP header merged into the underlying
/// configuration, included in all requests made by the returned instance.
///
/// Because ``StorageBucket`` is an immutable value type, this method does not mutate `self` —
/// it returns a new instance. Discarding the return value is a no-op, so always use the result:
///
/// ```swift
/// storage.from("avatars")
/// .settingHeader(name: .init("X-Custom-Header")!, value: "x-custom-header")
/// .list()
/// ```
///
/// - Parameters:
/// - name: The header field. Names match case-insensitively.
/// - value: The value of the header field.
/// - Returns: A new ``StorageBucket`` with the header merged into the configuration's headers.
public func settingHeader(name: HTTPField.Name, value: String) -> Self {
StorageBucket(id: id, api: api.settingHeader(name: name, value: value))
}
private struct SignedURLAPIResponse: Decodable {
let signedURL: String
}
private struct SignedURLsAPIResponse: Decodable {
let signedURL: String?
let path: String
let error: String?
}
/// Sends an upload request, reporting the request body's progress to `progress`.
private func sendUpload(
_ request: StorageRequest,
progress: (@Sendable (TransferProgress) -> Void)?
) async throws -> UploadResponse {
var request = request
guard let progress, let body = request.body else {
return try await api.execute(request).decoded()
}
request.body = body.reportingProgress { [length = body.length] in
progress(TransferProgress(completedBytes: $0, of: length))
}
return try await api.execute(request).decoded()
}
private func _uploadOrUpdate(
method: HTTPRequest.Method,
path: String,
body: HTTPBody,
options: UploadOptions,
progress: (@Sendable (TransferProgress) -> Void)?
) async throws -> UploadedObject {
let key = try ObjectKey(path)
let response = try await sendUpload(
api.requests.upload(method: method, bucket: id, key: key, body: body, options: options),
progress: progress)
return UploadedObject(
id: response.id.flatMap(UUID.init(uuidString:)), path: key.path, fullPath: response.key)
}
/// Uploads a file to an existing bucket.
///
/// ```swift
/// let response = try await storage.from("avatars").upload(path: "user123.png", data: imageData)
/// print(response.fullPath) // "avatars/user123.png"
/// ```
///
/// - Parameters:
/// - path: The relative file path within the bucket, e.g. `"folder/subfolder/filename.png"`.
/// The bucket must already exist before attempting to upload.
/// - data: The raw bytes to store in the bucket.
/// - options: Upload options such as cache control, content type, and upsert behavior.
/// - progress: Called as the bytes are sent; see ``TransferProgress``.
/// - Returns: An ``UploadedObject`` containing the stored object's identifier and path.
/// - Throws: ``StorageError`` if the upload fails or the caller is not authorized.
@discardableResult
public func upload(
path: String,
data: Data,
options: UploadOptions = UploadOptions(),
progress: (@Sendable (TransferProgress) -> Void)? = nil
) async throws -> UploadedObject {
try await _uploadOrUpdate(
method: .post, path: path, body: HTTPBody(data), options: options, progress: progress)
}
/// Uploads a file from a local file URL to an existing bucket.
///
/// Use this overload when you have a `URL` pointing to a file on disk rather than raw `Data`
/// already loaded in memory. This is preferable for large files because the data is streamed
/// rather than read entirely into memory first.
///
/// - Parameters:
/// - path: The relative file path within the bucket, e.g. `"folder/subfolder/filename.png"`.
/// The bucket must already exist before attempting to upload.
/// - fileURL: A `file://` URL pointing to the local file to upload.
/// - options: Upload options such as cache control, content type, and upsert behavior.
/// - progress: Called as the bytes are sent; see ``TransferProgress``.
/// - Returns: An ``UploadedObject`` containing the stored object's identifier and path.
/// - Throws: ``StorageError`` if the upload fails or the caller is not authorized.
@discardableResult
public func upload(
path: String,
fileURL: URL,
options: UploadOptions = UploadOptions(),
progress: (@Sendable (TransferProgress) -> Void)? = nil
) async throws -> UploadedObject {
try await _uploadOrUpdate(
method: .post, path: path, body: HTTPBody(fileURL: fileURL),
options: options.inferringContentType(from: fileURL), progress: progress)
}
/// Uploads a stream of bytes to an existing bucket.
///
/// The body streams as it is sent, so its bytes never have to sit in memory at once. A
/// ``HTTPBody/Length/known(_:)`` length is sent as `Content-Length`, which lets Storage refuse
/// an object over the bucket's size limit before any byte is sent; with
/// ``HTTPBody/Length/unknown`` the upload is sent chunked and only fails once the limit is
/// passed. A ``HTTPBody/IterationBehavior/single`` body cannot be sent twice, so the request is
/// never retried and a redirect is not followed.
///
/// ```swift
/// let body = HTTPBody(chunks, length: .known(size), iterationBehavior: .single)
/// try await storage.from("videos").upload(path: "clip.mov", body: body)
/// ```
///
/// - Parameters:
/// - path: The relative file path within the bucket, e.g. `"folder/subfolder/filename.png"`.
/// The bucket must already exist before attempting to upload.
/// - body: The bytes to store in the bucket.
/// - options: Upload options such as cache control, content type, and upsert behavior.
/// - progress: Called as the bytes are sent; see ``TransferProgress``.
/// - Returns: An ``UploadedObject`` containing the stored object's identifier and path.
/// - Throws: ``StorageError`` if the upload fails or the caller is not authorized.
@discardableResult
public func upload(
path: String,
body: HTTPBody,
options: UploadOptions = UploadOptions(),
progress: (@Sendable (TransferProgress) -> Void)? = nil
) async throws -> UploadedObject {
try await _uploadOrUpdate(
method: .post, path: path, body: body, options: options, progress: progress)
}
/// A resumable upload of a local file, to start with ``ResumableUpload/start()``.
///
/// The file is sent in ``ResumableUploadConfiguration/chunkSize`` pieces over tus, so the
/// upload can be paused, resumed, and continued after the process restarts. A file outside
/// the app container, or in its temporary directory, is copied first so it is still there
/// next launch.
///
/// ```swift
/// let upload = try bucket.resumableUpload(path: "video.mp4", fileURL: url)
/// try await upload.start()
/// let object = try await upload.result
/// ```
///
/// - Parameters:
/// - path: The relative file path within the bucket, e.g. `"folder/subfolder/filename.mp4"`.
/// - fileURL: A `file://` URL pointing to the local file to upload.
/// - options: Upload options such as cache control, content type, and upsert behavior.
/// - Returns: The upload, not yet started.
/// - Throws: ``StorageError`` if `path` is not a valid object path, and the file system's error
/// if `fileURL` cannot be read.
@_spi(Experimental)
public func resumableUpload(
path: String,
fileURL: URL,
options: UploadOptions = UploadOptions()
) throws -> ResumableUpload {
let key = try ObjectKey(path)
let (size, _) = try ResumableStore.attributes(of: fileURL)
let fingerprint = try ResumableStore.fingerprint(
url: api.configuration.url, bucketID: id, path: key.path, fileURL: fileURL)
return ResumableUpload.handle(fingerprint: fingerprint, api: api) {
ResumableUpload(
fingerprint: fingerprint,
bucketID: id, path: key.path, totalBytes: size, input: .file(fileURL),
options: options.inferringContentType(from: fileURL), api: api)
}
}
/// A resumable upload of bytes in memory, to start with ``ResumableUpload/start()``.
///
/// The bytes are written to the upload's record directory first, so the upload can continue
/// after the process restarts.
///
/// - Parameters:
/// - path: The relative file path within the bucket, e.g. `"folder/subfolder/filename.png"`.
/// - data: The raw bytes to store in the bucket.
/// - options: Upload options such as cache control, content type, and upsert behavior.
/// - Returns: The upload, not yet started.
/// - Throws: ``StorageError`` if `path` is not a valid object path.
@_spi(Experimental)
public func resumableUpload(
path: String,
data: Data,
options: UploadOptions = UploadOptions()
) throws -> ResumableUpload {
let key = try ObjectKey(path)
let fingerprint = ResumableStore.fingerprint(
url: api.configuration.url, bucketID: id, path: key.path, data: data)
return ResumableUpload.handle(fingerprint: fingerprint, api: api) {
ResumableUpload(
fingerprint: fingerprint,
bucketID: id, path: key.path, totalBytes: Int64(data.count), input: .data(data),
options: options, api: api)
}
}
/// Replaces an existing file at the specified path with new data.
///
/// Unlike ``upload(path:data:options:progress:)`` with `upsert: true`, this method always targets an
/// existing object and will throw if the path does not exist.
///
/// - Parameters:
/// - path: The relative file path within the bucket, e.g. `"folder/subfolder/filename.png"`.
/// The bucket must already exist before attempting to update.
/// - data: The raw bytes to overwrite the existing file with.
/// - options: Upload options such as cache control and content type. `upsert` is ignored:
/// `update` always replaces the object.
/// - progress: Called as the bytes are sent; see ``TransferProgress``.
/// - Returns: An ``UploadedObject`` containing the updated object's identifier and path.
/// - Throws: ``StorageError`` if the path does not exist or the caller is not authorized.
@discardableResult
public func update(
path: String,
data: Data,
options: UploadOptions = UploadOptions(),
progress: (@Sendable (TransferProgress) -> Void)? = nil
) async throws -> UploadedObject {
try await _uploadOrUpdate(
method: .put, path: path, body: HTTPBody(data), options: options, progress: progress)
}
/// Replaces an existing file at the specified path with a new local file.
///
/// Use this overload when the replacement content is available as a `URL` pointing to a file on
/// disk rather than raw `Data`. Large files are streamed rather than fully loaded into memory.
///
/// - Parameters:
/// - path: The relative file path within the bucket, e.g. `"folder/subfolder/filename.png"`.
/// The bucket must already exist before attempting to update.
/// - fileURL: A `file://` URL pointing to the local file to use as the replacement.
/// - options: Upload options such as cache control and content type. `upsert` is ignored:
/// `update` always replaces the object.
/// - progress: Called as the bytes are sent; see ``TransferProgress``.
/// - Returns: An ``UploadedObject`` containing the updated object's identifier and path.
/// - Throws: ``StorageError`` if the path does not exist or the caller is not authorized.
@discardableResult
public func update(
path: String,
fileURL: URL,
options: UploadOptions = UploadOptions(),
progress: (@Sendable (TransferProgress) -> Void)? = nil
) async throws -> UploadedObject {
try await _uploadOrUpdate(
method: .put, path: path, body: HTTPBody(fileURL: fileURL),
options: options.inferringContentType(from: fileURL), progress: progress)
}
/// Replaces an existing file at the specified path with a stream of bytes.
///
/// The body streams as it is sent, so its bytes never have to sit in memory at once. A
/// ``HTTPBody/Length/known(_:)`` length is sent as `Content-Length`, which lets Storage refuse
/// an object over the bucket's size limit before any byte is sent; with
/// ``HTTPBody/Length/unknown`` the upload is sent chunked and only fails once the limit is
/// passed. A ``HTTPBody/IterationBehavior/single`` body cannot be sent twice, so the request is
/// never retried and a redirect is not followed.
///
/// - Parameters:
/// - path: The relative file path within the bucket, e.g. `"folder/subfolder/filename.png"`.
/// The bucket must already exist before attempting to update.
/// - body: The bytes to overwrite the existing file with.
/// - options: Upload options such as cache control and content type. `upsert` is ignored:
/// `update` always replaces the object.
/// - progress: Called as the bytes are sent; see ``TransferProgress``.
/// - Returns: An ``UploadedObject`` containing the updated object's identifier and path.
/// - Throws: ``StorageError`` if the path does not exist or the caller is not authorized.
@discardableResult
public func update(
path: String,
body: HTTPBody,
options: UploadOptions = UploadOptions(),
progress: (@Sendable (TransferProgress) -> Void)? = nil
) async throws -> UploadedObject {
try await _uploadOrUpdate(
method: .put, path: path, body: body, options: options, progress: progress)
}
/// Moves an existing file to a new path, optionally within a different bucket.
///
/// ```swift
/// try await storage.from("docs").move(from: "draft.pdf", to: "published/report.pdf")
/// ```
///
/// - Parameters:
/// - source: The original file path including the file name, e.g. `"folder/image.png"`.
/// - destination: The new file path including the new file name, e.g. `"archive/image.png"`.
/// - toBucket: The bucket to move the file into. `nil` moves it within this bucket.
/// - sourceVersionID: The version of the source to move. `nil` moves the current version.
/// - Throws: ``StorageError`` if the source does not exist or the caller is not authorized.
public func move(
from source: String,
to destination: String,
toBucket: String? = nil,
sourceVersionID: String? = nil
) async throws {
try await api.execute(
api.requests.move(
bucket: id, source: ObjectKey(source), destination: ObjectKey(destination),
destinationBucket: toBucket, sourceVersionID: sourceVersionID)
)
}
/// Copies an existing file to a new path, optionally within a different bucket.
///
/// ```swift
/// let copy = try await storage.from("docs").copy(from: "original.pdf", to: "backup/original.pdf")
/// print(copy.fullPath) // "docs/backup/original.pdf"
/// ```
///
/// - Parameters:
/// - source: The original file path including the file name, e.g. `"folder/image.png"`.
/// - destination: The destination path including the new file name, e.g. `"folder/image-copy.png"`.
/// - toBucket: The bucket to copy the file into. `nil` copies it within this bucket.
/// - sourceVersionID: The version of the source to copy. `nil` copies the current version.
/// - options: Whether to replace an existing destination, and the metadata of the copy.
/// - Returns: The copy's identifier and path.
/// - Throws: ``StorageError`` if the source does not exist, the destination exists and
/// ``CopyOptions/upsert`` is `false`, or the caller is not authorized.
@discardableResult
public func copy(
from source: String,
to destination: String,
toBucket: String? = nil,
sourceVersionID: String? = nil,
options: CopyOptions = CopyOptions()
) async throws -> UploadedObject {
let destinationKey = try ObjectKey(destination)
let response = try await api.execute(
api.requests.copy(
bucket: id, source: ObjectKey(source), destination: destinationKey,
destinationBucket: toBucket, sourceVersionID: sourceVersionID, options: options)
)
.decoded(as: UploadResponse.self)
return UploadedObject(
id: response.id.flatMap(UUID.init(uuidString:)), path: destinationKey.path,
fullPath: response.key)
}
/// Creates a signed URL for sharing a private file for a fixed period of time.
///
/// ```swift
/// // Inline preview URL, valid for 5 minutes
/// let url = try await storage.from("docs").createSignedURL(path: "report.pdf", expiresIn: .seconds(300))
///
/// // Force download with original file name
/// let downloadURL = try await storage.from("docs").createSignedURL(
/// path: "report.pdf",
/// expiresIn: .seconds(60),
/// options: SignedURLOptions(download: .withOriginalName)
/// )
/// ```
///
/// - Parameters:
/// - path: The file path including the file name, e.g. `"folder/image.png"`.
/// - expiresIn: How long the URL stays valid, e.g. `.seconds(60)`. Whole seconds are sent;
/// less than one second throws ``StorageError`` with kind `invalidRequest`.
/// - options: The download behavior, image transformation, version and cache nonce.
/// - Returns: A signed `URL` ready to share.
/// - Throws: ``StorageError`` if the path does not exist or the caller is not authorized.
public func createSignedURL(
path: String,
expiresIn: Duration,
options: SignedURLOptions = SignedURLOptions()
) async throws -> URL {
let response = try await api.execute(
api.requests.sign(
bucket: id, key: ObjectKey(path), expiresIn: Self.seconds(expiresIn),
transform: options.transform, versionID: options.versionID)
)
.decoded(as: SignedURLAPIResponse.self)
return try api.requests.resolve(
response.signedURL,
query: Self.urlQuery(download: options.download, cacheNonce: options.cacheNonce))
}
/// Creates signed URLs for multiple files in a single request.
///
/// Each element in the returned array is a ``SignedURLResult``: either
/// `.success(path:signedURL:)` or `.failure(path:error:)`. Exactly one case applies per item.
/// Paths that do not exist produce a `.failure` result rather than throwing.
///
/// ```swift
/// let results = try await storage.from("docs").createSignedURLs(
/// paths: ["a.pdf", "b.pdf", "missing.pdf"],
/// expiresIn: .seconds(3600)
/// )
/// for result in results {
/// switch result {
/// case .success(let path, let url): print(path, url)
/// case .failure(let path, let error): print(path, "failed:", error)
/// }
/// }
/// ```
///
/// - Parameters:
/// - paths: File paths to sign, e.g. `["folder/image.png", "folder2/image2.png"]`.
/// - expiresIn: How long the URLs stay valid, e.g. `.seconds(60)`. Whole seconds are sent;
/// less than one second throws ``StorageError`` with kind `invalidRequest`.
/// - options: The download behavior and cache nonce.
/// - Returns: An array of ``SignedURLResult`` values, one per requested path, preserving order.
/// - Throws: ``StorageError`` if the request itself fails (e.g. unauthorized). Individual missing
/// paths are reported as ``SignedURLResult/failure(path:error:)`` rather than thrown.
public func createSignedURLs(
paths: [String],
expiresIn: Duration,
options: SignedURLsOptions = SignedURLsOptions()
) async throws -> [SignedURLResult] {
let response = try await api.execute(
api.requests.sign(
bucket: id, keys: paths.map { try ObjectKey($0) }, expiresIn: Self.seconds(expiresIn))
)
.decoded(as: [SignedURLsAPIResponse].self)
let query = Self.urlQuery(download: options.download, cacheNonce: options.cacheNonce)
return try response.map { item in
if let signedURLString = item.signedURL {
let url = try api.requests.resolve(signedURLString, query: query)
return .success(path: item.path, signedURL: url)
} else {
return .failure(path: item.path, error: item.error ?? "Unknown error")
}
}
}
/// The whole seconds the sign routes take. A per-call value, so a bad one throws rather than
/// traps.
private static func seconds(_ expiresIn: Duration) throws -> Int {
guard expiresIn >= .seconds(1) else {
throw StorageError(
kind: .invalidRequest, message: "A signed URL must expire at least one second from now.")
}
return Int(expiresIn.components.seconds)
}
/// The `download` and `cacheNonce` query items every URL-returning method appends.
private static func urlQuery(download: DownloadBehavior?, cacheNonce: String?) -> [URLQueryItem] {
var query: [URLQueryItem] = []
if let download {
query.append(URLQueryItem(name: "download", value: download.queryValue))
}
if let cacheNonce {
query.append(URLQueryItem(name: "cacheNonce", value: cacheNonce))
}
return query
}
/// Deletes one or more files from the bucket.
///
/// ```swift
/// let removed = try await storage.from("avatars").remove(paths: ["user123.png", "temp/draft.png"])
/// ```
///
/// - Parameter paths: File paths to delete, including the file name,
/// e.g. `["folder/image.png", "other/doc.pdf"]`. Storage takes at most 1000 by default; a
/// project can set another limit.
/// - Returns: An array of ``StorageObject`` values representing the files that were removed.
/// - Throws: ``StorageError`` if the request fails, names more objects than the project allows,
/// or the caller is not authorized.
@discardableResult
public func remove(paths: [String]) async throws -> [StorageObject] {
try await api.execute(
api.requests.remove(bucket: id, keys: paths.map { try ObjectKey($0) })
)
.decoded()
}
/// Deletes specific versions of objects in a versioned bucket.
///
/// ```swift
/// let versions = try await bucket.list(path: "docs", options: ListOptions(versions: .only))
/// try await bucket.remove(
/// versions: versions.compactMap { object in
/// object.version.map { ObjectVersion(path: "docs/\(object.name)", versionID: $0) }
/// })
/// ```
///
/// - Parameter versions: The object versions to delete. Storage takes at most 1000 by default;
/// a project can set another limit.
/// - Returns: The deleted versions.
/// - Throws: ``StorageError`` if the request fails, names more versions than the project
/// allows, or the caller is not authorized.
@discardableResult
public func remove(versions: [ObjectVersion]) async throws -> [StorageObject] {
try await api.execute(
api.requests.remove(
bucket: id, versions: versions.map { (try ObjectKey($0.path), $0.versionID) })
)
.decoded()
}
/// Lists all files within a bucket folder.
///
/// ```swift
/// let files = try await storage.from("avatars").list(path: "users/")
/// ```
///
/// - Parameters:
/// - path: The folder prefix to list, e.g. `"users/"`. Pass `nil` to list the bucket root.
/// - options: Paging, sort and filters. Defaults to the first 100 entries sorted by name
/// ascending.
/// - Returns: The files and folders one level under `path`, with names relative to it. A
/// folder is an entry whose ``StorageObject/isFolder`` is `true`.
/// - Throws: ``StorageError`` if the request fails or the caller is not authorized.
public func list(
path: String? = nil,
options: ListOptions = ListOptions()
) async throws -> [StorageObject] {
try await api.execute(
api.requests.list(bucket: id, prefix: ObjectKey(prefix: path ?? ""), options: options)
)
.decoded()
}
/// Downloads a file, returning as soon as Storage sends the response headers.
///
/// The response's ``DownloadResponse/body`` streams the object and can be read once. Read it
/// into memory, write it to a file, or process it chunk by chunk:
///
/// ```swift
/// let avatars = storage.from("avatars")
///
/// // Into memory
/// let data = try await avatars.download(path: "user123.png").data()
///
/// // To a file, without holding the object in memory
/// try await avatars.download(path: "user123.png").write(to: fileURL)
///
/// // Chunk by chunk
/// for try await chunk in try await avatars.download(path: "user123.png").body {
/// parser.feed(chunk)
/// }
/// ```
///
/// For public buckets, prefer requesting the URL returned by
/// ``publicURL(path:options:)`` directly.
///
/// - Parameters:
/// - path: The file path including the file name, e.g. `"folder/image.png"`.
/// - options: The byte range, version, cache nonce, image transformation and extra headers.
/// - progress: Called as the body is read; see ``TransferProgress``.
/// ``TransferProgress/totalBytes`` is `nil` when Storage sends no `Content-Length`, as for a
/// transformed image.
/// - Returns: The response headers and the body.
/// - Throws: ``StorageError`` if the file does not exist or the caller is not authorized,
/// before any byte of the body is read. A network failure while the body streams throws
/// ``StorageError`` with kind `transport` from the body.
public func download(
path: String,
options: DownloadOptions = DownloadOptions(),
progress: (@Sendable (TransferProgress) -> Void)? = nil
) async throws -> DownloadResponse {
let (head, body) = try await api.stream(
api.requests.download(bucket: id, key: ObjectKey(path), options: options)
)
var response = body ?? HTTPBody(Data())
if let progress {
let read = LockIsolated<Int64>(0)
let length = response.length
response = HTTPBody(
response.map { chunk in
let completed = read.withValue {
$0 += Int64(chunk.count)
return $0
}
progress(TransferProgress(completedBytes: completed, of: length))
return chunk
},
length: length, iterationBehavior: .single)
}
return DownloadResponse(status: head.status, headers: head.headerFields, body: response)
}
/// Retrieves metadata about an existing file without downloading its content.
///
/// - Parameters:
/// - path: The file path including the file name, e.g. `"folder/image.png"`.
/// - versionID: The version to describe. `nil` describes the current version.
/// - Returns: A ``ObjectInfo`` containing size, content type, ETag, and other metadata.
/// - Throws: ``StorageError`` if the file does not exist or the caller is not authorized.
public func info(path: String, versionID: String? = nil) async throws -> ObjectInfo {
try await api.execute(api.requests.info(bucket: id, key: ObjectKey(path), versionID: versionID))
.decoded()
}
/// Checks whether a file exists in the bucket without downloading it.
///
/// Reads the object's metadata, so the answer is `false` only when Storage reports that the
/// key does not exist (``StorageError/Code/noSuchKey``, or a 404 in the body with no code).
/// Every other failure throws, including a missing bucket (``StorageError/Code/noSuchBucket``)
/// and an expired session (``StorageError/Code/invalidJWT``), which a `HEAD` request could not
/// tell apart from a missing file.
///
/// - Parameter path: The file path including the file name, e.g. `"folder/image.png"`.
/// - Returns: `true` if the file exists and is accessible, `false` if it does not exist.
/// - Throws: ``StorageError`` for errors other than a missing key (e.g. network failure,
/// authorization errors, or a missing bucket).
public func exists(path: String) async throws -> Bool {
do {
_ = try await info(path: path)
return true
} catch let error as StorageError
where error.code == .noSuchKey || (error.code == nil && error.serverError?.statusCode == 404)
{
return false
}
}
/// Purges the CDN cache for a file, so the next request for it is served from Storage again.
/// The CDN can take up to 60 seconds to apply the purge.
///
/// > Important: This requires the `secret` key and the `purgeCache` tenant feature. On
/// > self-hosted Storage, a CDN purge endpoint must also be configured, otherwise the request
/// > fails.
///
/// - Parameters:
/// - path: The file path including the file name, e.g. `"folder/image.png"`. Only that exact
/// file is purged; there is no wildcard or folder purge.
/// - transformationsOnly: Pass `true` to purge only the resized and reformatted variants and
/// keep the original cached. By default, the original and all its variants are purged.
/// - Throws: ``StorageError`` if the caller is not authorized or cache purging is not enabled.
public func purgeCache(path: String, transformationsOnly: Bool = false) async throws {
try await api.execute(
api.requests.purgeCache(
bucket: id, key: ObjectKey(path), transformationsOnly: transformationsOnly)
)
}
/// Returns the public URL for a file in a public bucket.
///
/// ```swift
/// // Inline display URL
/// let url = storage.from("avatars").publicURL(path: "user123.png")
///
/// // Force download with original file name
/// let dlURL = storage.from("docs").publicURL(
/// path: "report.pdf", options: PublicURLOptions(download: .withOriginalName))
/// ```
///
/// > Note: The bucket must be set to public for this URL to be accessible without authentication.
///
/// Never throws: the base URL was validated when the client was created and every path is
/// percent-encoded into a valid URL. Whether Storage accepts the key is Storage's call, as it
/// is for every other method; a `.` or `..` segment is sent encoded rather than refused.
///
/// - Parameters:
/// - path: The file path including the file name, e.g. `"folder/image.png"`.
/// - options: The download behavior, image transformation, version and cache nonce.
/// - Returns: The publicly accessible `URL` for the file.
public func publicURL(
path: String,
options: PublicURLOptions = PublicURLOptions()
) -> URL {
var query = Self.urlQuery(download: options.download, cacheNonce: options.cacheNonce)
if let versionID = options.versionID {
query.append(URLQueryItem(name: "versionId", value: versionID))
}
return api.requests.publicURL(
bucket: id, key: ObjectKey(lenient: path), transform: options.transform?.queryItems ?? [],
query: query)
}
/// Creates a signed upload URL that allows uploading a file without further authentication.
///
/// Signed upload URLs are valid for 2 hours. Pass the returned ``SignedUploadURL/token`` to
/// ``uploadToSignedURL(path:token:data:options:progress:)`` (or the file-URL variant) to perform the upload.
///
/// ```swift
/// let signedUpload = try await storage.from("avatars").createSignedUploadURL(path: "user123.png")
/// // Share signedUpload.token with the uploader
/// try await storage.from("avatars").uploadToSignedURL(
/// path: "user123.png",
/// token: signedUpload.token,
/// data: imageData
/// )
/// ```
///
/// - Parameters:
/// - path: The destination file path including the file name, e.g. `"folder/image.png"`.
/// - upsert: Whether the upload made with the token may replace an existing object at
/// `path`. Defaults to `false`.
/// - Returns: A ``SignedUploadURL`` containing the signed URL and an upload token.
/// - Throws: ``StorageError`` if the request fails or the caller is not authorized.
public func createSignedUploadURL(
path: String,
upsert: Bool = false
) async throws -> SignedUploadURL {
struct Response: Decodable {
let url: String
}
let key = try ObjectKey(path)
let response = try await api.execute(
api.requests.createSignedUploadURL(bucket: id, key: key, upsert: upsert)
)
.decoded(as: Response.self)
let signedURL = try api.requests.resolve(response.url)
guard
let token = URLComponents(url: signedURL, resolvingAgainstBaseURL: false)?.queryItems?
.first(where: { $0.name == "token" })?.value
else {
throw StorageError(kind: .decoding, message: "No token returned by API")
}
return SignedUploadURL(signedURL: signedURL, path: key.path, token: token)
}
/// Uploads raw data to a pre-signed upload URL.
///
/// Obtain the `token` from ``createSignedUploadURL(path:upsert:)`` before calling this method.
///
/// - Parameters:
/// - path: The destination file path, e.g. `"folder/subfolder/filename.png"`.
/// The bucket must already exist.
/// - token: The upload token from ``createSignedUploadURL(path:upsert:)``.
/// - data: The raw bytes to store in the bucket.
/// - options: Upload options such as cache control and content type. `upsert` is ignored:
/// the token decides whether an existing object is replaced.
/// - progress: Called as the bytes are sent; see ``TransferProgress``.
/// - Returns: An ``UploadedObject`` with the stored path; Storage returns no object id for a
/// signed-URL upload, so ``UploadedObject/id`` is `nil`.
/// - Throws: ``StorageError`` if the token is invalid, expired, or the upload fails.
@discardableResult
public func uploadToSignedURL(
path: String,
token: String,
data: Data,
options: UploadOptions = UploadOptions(),
progress: (@Sendable (TransferProgress) -> Void)? = nil
) async throws -> UploadedObject {
try await _uploadToSignedURL(
path: path, token: token, body: HTTPBody(data), options: options, progress: progress)
}
/// Uploads a local file to a pre-signed upload URL.
///
/// Obtain the `token` from ``createSignedUploadURL(path:upsert:)`` before calling this method.
/// Use this overload for large files where streaming from disk is preferable to loading all
/// content into memory.
///
/// - Parameters:
/// - path: The destination file path, e.g. `"folder/subfolder/filename.png"`.
/// The bucket must already exist.
/// - token: The upload token from ``createSignedUploadURL(path:upsert:)``.
/// - fileURL: A `file://` URL pointing to the local file to upload.
/// - options: Upload options such as cache control and content type. `upsert` is ignored:
/// the token decides whether an existing object is replaced.
/// - progress: Called as the bytes are sent; see ``TransferProgress``.
/// - Returns: An ``UploadedObject`` with the stored path; Storage returns no object id for a
/// signed-URL upload, so ``UploadedObject/id`` is `nil`.
/// - Throws: ``StorageError`` if the token is invalid, expired, or the upload fails.
@discardableResult
public func uploadToSignedURL(
path: String,
token: String,
fileURL: URL,
options: UploadOptions = UploadOptions(),
progress: (@Sendable (TransferProgress) -> Void)? = nil
) async throws -> UploadedObject {
try await _uploadToSignedURL(
path: path, token: token, body: HTTPBody(fileURL: fileURL),
options: options.inferringContentType(from: fileURL), progress: progress)
}
/// Uploads a stream of bytes to a pre-signed upload URL.
///
/// Obtain the `token` from ``createSignedUploadURL(path:upsert:)`` before calling this method.
/// The body streams as it is sent, so its bytes never have to sit in memory at once. A
/// ``HTTPBody/Length/known(_:)`` length is sent as `Content-Length`, which lets Storage refuse
/// an object over the bucket's size limit before any byte is sent; with
/// ``HTTPBody/Length/unknown`` the upload is sent chunked and only fails once the limit is
/// passed. A ``HTTPBody/IterationBehavior/single`` body cannot be sent twice, so the request is
/// never retried and a redirect is not followed.
///
/// - Parameters:
/// - path: The destination file path, e.g. `"folder/subfolder/filename.png"`.
/// The bucket must already exist.
/// - token: The upload token from ``createSignedUploadURL(path:upsert:)``.
/// - body: The bytes to store in the bucket.
/// - options: Upload options such as cache control and content type. `upsert` is ignored:
/// the token decides whether an existing object is replaced.
/// - progress: Called as the bytes are sent; see ``TransferProgress``.
/// - Returns: An ``UploadedObject`` with the stored path; Storage returns no object id for a
/// signed-URL upload, so ``UploadedObject/id`` is `nil`.
/// - Throws: ``StorageError`` if the token is invalid, expired, or the upload fails.
@discardableResult
public func uploadToSignedURL(
path: String,
token: String,
body: HTTPBody,
options: UploadOptions = UploadOptions(),
progress: (@Sendable (TransferProgress) -> Void)? = nil
) async throws -> UploadedObject {
try await _uploadToSignedURL(
path: path, token: token, body: body, options: options, progress: progress)
}
private func _uploadToSignedURL(
path: String,
token: String,
body: HTTPBody,
options: UploadOptions,
progress: (@Sendable (TransferProgress) -> Void)?
) async throws -> UploadedObject {
let key = try ObjectKey(path)
let response = try await sendUpload(
api.requests.uploadToSignedURL(
bucket: id, key: key, token: token, body: body, options: options),
progress: progress)
return UploadedObject(id: nil, path: key.path, fullPath: response.key)
}
}
extension UploadOptions {
/// A file keeps its own type when the storage path has a different extension, or none.
fileprivate func inferringContentType(from fileURL: URL) -> UploadOptions {
var options = self
options.contentType = contentType ?? mimeType(forPathExtension: fileURL.pathExtension)
return options
}
}