-
Notifications
You must be signed in to change notification settings - Fork 86
/
object.rs
1510 lines (1366 loc) · 56.1 KB
/
object.rs
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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
pub use crate::resources::bucket::Owner;
use crate::resources::object_access_control::ObjectAccessControl;
use futures::Stream;
#[cfg(feature = "global-client")]
use futures::TryStream;
use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC};
use std::collections::HashMap;
/// A resource representing a file in Google Cloud Storage.
#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Object {
/// The kind of item this is. For objects, this is always `storage#object`.
pub kind: String,
/// The ID of the object, including the bucket name, object name, and generation number.
pub id: String,
/// The link to this object.
pub self_link: String,
/// The name of the object. Required if not specified by URL parameter.
pub name: String,
/// The name of the bucket containing this object.
pub bucket: String,
/// The content generation of this object. Used for object versioning.
#[serde(deserialize_with = "crate::from_str")]
pub generation: i64,
/// The version of the metadata for this object at this generation. Used for preconditions and
/// for detecting changes in metadata. A metageneration number is only meaningful in the context
/// of a particular generation of a particular object.
#[serde(deserialize_with = "crate::from_str")]
pub metageneration: i64,
/// Content-Type of the object data. If an object is stored without a Content-Type, it is served
/// as application/octet-stream.
pub content_type: Option<String>,
/// The creation time of the object in RFC 3339 format.
pub time_created: chrono::DateTime<chrono::Utc>,
/// The modification time of the object metadata in RFC 3339 format.
pub updated: chrono::DateTime<chrono::Utc>,
/// The deletion time of the object in RFC 3339 format. Returned if and only if this version of
/// the object is no longer a live version, but remains in the bucket as a noncurrent version.
pub time_deleted: Option<chrono::DateTime<chrono::Utc>>,
/// Whether or not the object is subject to a temporary hold.
pub temporary_hold: Option<bool>,
/// Whether or not the object is subject to an event-based hold.
pub event_based_hold: Option<bool>,
/// The earliest time that the object can be deleted, based on a bucket's retention policy, in
/// RFC 3339 format.
pub retention_expiration_time: Option<chrono::DateTime<chrono::Utc>>,
/// Storage class of the object.
pub storage_class: String,
/// The time at which the object's storage class was last changed. When the object is initially
/// created, it will be set to timeCreated.
pub time_storage_class_updated: chrono::DateTime<chrono::Utc>,
/// Content-Length of the data in bytes.
#[serde(deserialize_with = "crate::from_str")]
pub size: u64,
/// MD5 hash of the data; encoded using base64. For more information about using the MD5 hash,
/// see Hashes and ETags: Best Practices.
pub md5_hash: Option<String>,
/// Media download link.
pub media_link: String,
/// Content-Encoding of the object data.
pub content_encoding: Option<String>,
/// Content-Disposition of the object data.
pub content_disposition: Option<String>,
/// Content-Language of the object data.
pub content_language: Option<String>,
/// Cache-Control directive for the object data. If omitted, and the object is accessible to all
/// anonymous users, the default will be public, max-age=3600.
pub cache_control: Option<String>,
/// User-provided metadata, in key/value pairs.
pub metadata: Option<std::collections::HashMap<String, String>>,
/// Access controls on the object, containing one or more objectAccessControls Resources. If
/// iamConfiguration.uniformBucketLevelAccess.enabled is set to true, this field is omitted in
/// responses, and requests that specify this field fail.
pub acl: Option<Vec<ObjectAccessControl>>,
/// The owner of the object. This will always be the uploader of the object. If
/// `iamConfiguration.uniformBucketLevelAccess.enabled` is set to true, this field does not
/// apply, and is omitted in responses.
pub owner: Option<Owner>,
/// CRC32c checksum, as described in RFC 4960, Appendix B; encoded using base64 in big-endian
/// byte order. For more information about using the CRC32c checksum, see Hashes and ETags: Best
/// Practices.
pub crc32c: String,
/// Number of underlying components that make up a composite object. Components are accumulated
/// by compose operations, counting 1 for each non-composite source object and componentCount
/// for each composite source object. Note: componentCount is included in the metadata for
/// composite objects only.
#[serde(default, deserialize_with = "crate::from_str_opt")]
pub component_count: Option<i32>,
/// HTTP 1.1 Entity tag for the object.
pub etag: String,
/// Metadata of customer-supplied encryption key, if the object is encrypted by such a key.
pub customer_encryption: Option<CustomerEncrypton>,
/// Cloud KMS Key used to encrypt this object, if the object is encrypted by such a key.
pub kms_key_name: Option<String>,
}
/// Contains data about how a user might encrypt their files in Google Cloud Storage.
#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomerEncrypton {
/// The encryption algorithm.
pub encryption_algorithm: String,
/// SHA256 hash value of the encryption key.
pub key_sha256: String,
}
/// The request that is supplied to perform `Object::compose`.
#[derive(Debug, PartialEq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ComposeRequest {
/// The kind of item this is. Will always be `storage#composeRequest`.
pub kind: String,
/// The list of source objects that will be concatenated into a single object.
pub source_objects: Vec<SourceObject>,
/// Properties of the resulting object.
pub destination: Option<Object>,
}
/// A SourceObject represents one of the objects that is to be composed.
#[derive(Debug, PartialEq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SourceObject {
/// The source object's name. All source objects must have the same storage class and reside in
/// the same bucket.
pub name: String,
/// The generation of this object to use as the source.
pub generation: Option<i64>,
/// Conditions that must be met for this operation to execute.
pub object_preconditions: Option<ObjectPrecondition>,
}
/// Allows conditional copying of this file.
#[derive(Debug, PartialEq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ObjectPrecondition {
/// Only perform the composition if the generation of the source object that would be used
/// matches this value. If this value and a generation are both specified, they must be the same
/// value or the call will fail.
pub if_generation_match: i64,
}
/// The request that is supplied to perform `Object::list`.
/// See [the Google Cloud Storage API
/// reference](https://cloud.google.com/storage/docs/json_api/v1/objects/list)
/// for more details.
#[derive(Debug, PartialEq, serde::Serialize, Default, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ListRequest {
/// When specified, allows the `list` to operate like a directory listing by splitting the
/// object location on this delimiter.
pub delimiter: Option<String>,
/// Filter results to objects whose names are lexicographically before `end_offset`.
/// If `start_offset` is also set, the objects listed have names between `start_offset`
/// (inclusive) and `end_offset` (exclusive).
pub end_offset: Option<String>,
/// If true, objects that end in exactly one instance of `delimiter` have their metadata
/// included in `items` in addition to the relevant part of the object name appearing in
/// `prefixes`.
pub include_trailing_delimiter: Option<bool>,
/// Maximum combined number of entries in `items` and `prefixes` to return in a single
/// page of responses. Because duplicate entries in `prefixes` are omitted, fewer total
/// results may be returned than requested. The service uses this parameter or 1,000
/// items, whichever is smaller.
pub max_results: Option<usize>,
/// A previously-returned page token representing part of the larger set of results to view.
/// The `page_token` is an encoded field that marks the name and generation of the last object
/// in the returned list. In a subsequent request using the `page_token`, items that come after
/// the `page_token` are shown (up to `max_results`).
///
/// If the page token is provided, all objects starting at that page token are queried
pub page_token: Option<String>,
/// Filter results to include only objects whose names begin with this prefix.
pub prefix: Option<String>,
/// Set of properties to return. Defaults to `NoAcl`.
pub projection: Option<Projection>,
/// Filter results to objects whose names are lexicographically equal to or after
/// `start_offset`. If `end_offset` is also set, the objects listed have names between
/// `start_offset` (inclusive) and `end_offset` (exclusive).
pub start_offset: Option<String>,
/// If true, lists all versions of an object as distinct results in order of increasing
/// generation number. The default value for versions is false. For more information, see
/// Object Versioning.
pub versions: Option<bool>,
}
/// Acceptable values of `projection` properties to return from `Object::list` requests.
#[derive(Debug, PartialEq, serde::Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub enum Projection {
/// Include all properties.
Full,
/// Omit the owner, acl property.
NoAcl,
}
/// Response from `Object::list`.
#[derive(Debug, serde::Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ObjectList {
/// The kind of item this is. For lists of objects, this is always `storage#objects`.
pub kind: String,
/// The list of objects, ordered lexicographically by name.
#[serde(default = "Vec::new")]
pub items: Vec<Object>,
/// Object name prefixes for objects that matched the listing request but were excluded
/// from `items` because of a delimiter. Values in this list are object names up to and
/// including the requested delimiter. Duplicate entries are omitted from this list.
#[serde(default = "Vec::new")]
pub prefixes: Vec<String>,
/// The continuation token, included only if there are more items to return. Provide
/// this value as the `page_token` of a subsequent request in order to return the next
/// page of results.
pub next_page_token: Option<String>,
}
#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct RewriteResponse {
pub(crate) kind: String,
pub(crate) total_bytes_rewritten: String,
pub(crate) object_size: String,
pub(crate) done: bool,
pub(crate) resource: Object,
}
impl Object {
/// Create a new object.
/// Upload a file as that is loaded in memory to google cloud storage, where it will be
/// interpreted according to the mime type you specified.
/// ## Example
/// ```rust,no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fn read_cute_cat(_in: &str) -> Vec<u8> { vec![0, 1] }
/// use cloud_storage::Object;
///
/// let file: Vec<u8> = read_cute_cat("cat.png");
/// Object::create("cat-photos", file, "recently read cat.png", "image/png").await?;
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "global-client")]
pub async fn create(
bucket: &str,
file: Vec<u8>,
filename: &str,
mime_type: &str,
) -> crate::Result<Self> {
crate::CLOUD_CLIENT
.object()
.create(bucket, file, filename, mime_type)
.await
}
/// The synchronous equivalent of `Object::create`.
///
/// ### Features
/// This function requires that the feature flag `sync` is enabled in `Cargo.toml`.
#[cfg(all(feature = "global-client", feature = "sync"))]
pub fn create_sync(
bucket: &str,
file: Vec<u8>,
filename: &str,
mime_type: &str,
) -> crate::Result<Self> {
crate::runtime()?.block_on(Self::create(bucket, file, filename, mime_type))
}
/// Create a new object. This works in the same way as `Object::create`, except it does not need
/// to load the entire file in ram.
/// ## Example
/// ```rust,no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use cloud_storage::Object;
///
/// let file = reqwest::Client::new()
/// .get("https://my_domain.rs/nice_cat_photo.png")
/// .send()
/// .await?
/// .bytes_stream();
/// Object::create_streamed("cat-photos", file, 10, "recently read cat.png", "image/png").await?;
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "global-client")]
pub async fn create_streamed<S>(
bucket: &str,
stream: S,
length: impl Into<Option<u64>>,
filename: &str,
mime_type: &str,
) -> crate::Result<Self>
where
S: TryStream + Send + Sync + 'static,
S::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
bytes::Bytes: From<S::Ok>,
{
crate::CLOUD_CLIENT
.object()
.create_streamed(bucket, stream, length, filename, mime_type)
.await
}
/// The synchronous equivalent of `Object::create_streamed`.
///
/// ### Features
/// This function requires that the feature flag `sync` is enabled in `Cargo.toml`.
#[cfg(all(feature = "global-client", feature = "sync"))]
pub fn create_streamed_sync<R: std::io::Read + Send + 'static>(
bucket: &str,
mut file: R,
length: impl Into<Option<u64>>,
filename: &str,
mime_type: &str,
) -> crate::Result<Self> {
let mut buffer = Vec::new();
file.read_to_end(&mut buffer)
.map_err(|e| crate::Error::Other(e.to_string()))?;
let stream = futures::stream::once(async { Ok::<_, crate::Error>(buffer) });
crate::runtime()?.block_on(Self::create_streamed(
bucket, stream, length, filename, mime_type,
))
}
/// Obtain a list of objects within this Bucket. This function will repeatedly query Google and
/// merge the responses into one. Google responds with 1000 Objects at a time, so if you want to
/// make sure only one http call is performed, make sure to set `list_request.max_results` to
/// 1000.
/// ### Example
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use cloud_storage::{Object, ListRequest};
///
/// let all_objects = Object::list("my_bucket", ListRequest::default()).await?;
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "global-client")]
pub async fn list(
bucket: &str,
list_request: ListRequest,
) -> crate::Result<impl Stream<Item = crate::Result<ObjectList>> + '_> {
crate::CLOUD_CLIENT
.object()
.list(bucket, list_request)
.await
}
/// The synchronous equivalent of `Object::list`.
///
/// ### Features
/// This function requires that the feature flag `sync` is enabled in `Cargo.toml`.
#[cfg(all(feature = "global-client", feature = "sync"))]
pub fn list_sync(bucket: &str, list_request: ListRequest) -> crate::Result<Vec<ObjectList>> {
use futures::TryStreamExt;
let rt = crate::runtime()?;
let listed = rt.block_on(Self::list(bucket, list_request))?;
rt.block_on(listed.try_collect())
}
/// Obtains a single object with the specified name in the specified bucket.
/// ### Example
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use cloud_storage::Object;
///
/// let object = Object::read("my_bucket", "path/to/my/file.png").await?;
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "global-client")]
pub async fn read(bucket: &str, file_name: &str) -> crate::Result<Self> {
crate::CLOUD_CLIENT.object().read(bucket, file_name).await
}
/// The synchronous equivalent of `Object::read`.
///
/// ### Features
/// This function requires that the feature flag `sync` is enabled in `Cargo.toml`.
#[cfg(all(feature = "global-client", feature = "sync"))]
pub fn read_sync(bucket: &str, file_name: &str) -> crate::Result<Self> {
crate::runtime()?.block_on(Self::read(bucket, file_name))
}
/// Download the content of the object with the specified name in the specified bucket.
/// ### Example
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use cloud_storage::Object;
///
/// let bytes = Object::download("my_bucket", "path/to/my/file.png").await?;
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "global-client")]
pub async fn download(bucket: &str, file_name: &str) -> crate::Result<Vec<u8>> {
crate::CLOUD_CLIENT
.object()
.download(bucket, file_name)
.await
}
/// The synchronous equivalent of `Object::download`.
///
/// ### Features
/// This function requires that the feature flag `sync` is enabled in `Cargo.toml`.
#[cfg(all(feature = "global-client", feature = "sync"))]
pub fn download_sync(bucket: &str, file_name: &str) -> crate::Result<Vec<u8>> {
crate::runtime()?.block_on(Self::download(bucket, file_name))
}
/// Download the content of the object with the specified name in the specified bucket, without
/// allocating the whole file into a vector.
/// ### Example
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use cloud_storage::Object;
/// use futures::StreamExt;
/// use std::fs::File;
/// use std::io::{BufWriter, Write};
///
/// let mut stream = Object::download_streamed("my_bucket", "path/to/my/file.png").await?;
/// let mut file = BufWriter::new(File::create("file.png").unwrap());
/// while let Some(byte) = stream.next().await {
/// file.write_all(&[byte.unwrap()]).unwrap();
/// }
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "global-client")]
pub async fn download_streamed(
bucket: &str,
file_name: &str,
) -> crate::Result<impl Stream<Item = crate::Result<u8>> + Unpin> {
crate::CLOUD_CLIENT
.object()
.download_streamed(bucket, file_name)
.await
}
/// Obtains a single object with the specified name in the specified bucket.
/// ### Example
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use cloud_storage::Object;
///
/// let mut object = Object::read("my_bucket", "path/to/my/file.png").await?;
/// object.content_type = Some("application/xml".to_string());
/// object.update().await?;
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "global-client")]
pub async fn update(&self) -> crate::Result<Self> {
crate::CLOUD_CLIENT.object().update(self).await
}
/// The synchronous equivalent of `Object::download`.
///
/// ### Features
/// This function requires that the feature flag `sync` is enabled in `Cargo.toml`.
#[cfg(all(feature = "global-client", feature = "sync"))]
pub fn update_sync(&self) -> crate::Result<Self> {
crate::runtime()?.block_on(self.update())
}
/// Deletes a single object with the specified name in the specified bucket.
/// ### Example
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use cloud_storage::Object;
///
/// Object::delete("my_bucket", "path/to/my/file.png").await?;
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "global-client")]
pub async fn delete(bucket: &str, file_name: &str) -> crate::Result<()> {
crate::CLOUD_CLIENT.object().delete(bucket, file_name).await
}
/// The synchronous equivalent of `Object::delete`.
///
/// ### Features
/// This function requires that the feature flag `sync` is enabled in `Cargo.toml`.
#[cfg(all(feature = "global-client", feature = "sync"))]
pub fn delete_sync(bucket: &str, file_name: &str) -> crate::Result<()> {
crate::runtime()?.block_on(Self::delete(bucket, file_name))
}
/// Obtains a single object with the specified name in the specified bucket.
/// ### Example
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use cloud_storage::object::{Object, ComposeRequest, SourceObject};
///
/// let obj1 = Object::read("my_bucket", "file1").await?;
/// let obj2 = Object::read("my_bucket", "file2").await?;
/// let compose_request = ComposeRequest {
/// kind: "storage#composeRequest".to_string(),
/// source_objects: vec![
/// SourceObject {
/// name: obj1.name.clone(),
/// generation: None,
/// object_preconditions: None,
/// },
/// SourceObject {
/// name: obj2.name.clone(),
/// generation: None,
/// object_preconditions: None,
/// },
/// ],
/// destination: None,
/// };
/// let obj3 = Object::compose("my_bucket", &compose_request, "test-concatted-file").await?;
/// // obj3 is now a file with the content of obj1 and obj2 concatted together.
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "global-client")]
pub async fn compose(
bucket: &str,
req: &ComposeRequest,
destination_object: &str,
) -> crate::Result<Self> {
crate::CLOUD_CLIENT
.object()
.compose(bucket, req, destination_object)
.await
}
/// The synchronous equivalent of `Object::compose`.
///
/// ### Features
/// This function requires that the feature flag `sync` is enabled in `Cargo.toml`.
#[cfg(all(feature = "global-client", feature = "sync"))]
pub fn compose_sync(
bucket: &str,
req: &ComposeRequest,
destination_object: &str,
) -> crate::Result<Self> {
crate::runtime()?.block_on(Self::compose(bucket, req, destination_object))
}
/// Copy this object to the target bucket and path
/// ### Example
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use cloud_storage::object::{Object, ComposeRequest};
///
/// let obj1 = Object::read("my_bucket", "file1").await?;
/// let obj2 = obj1.copy("my_other_bucket", "file2").await?;
/// // obj2 is now a copy of obj1.
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "global-client")]
pub async fn copy(&self, destination_bucket: &str, path: &str) -> crate::Result<Self> {
crate::CLOUD_CLIENT
.object()
.copy(self, destination_bucket, path)
.await
}
/// The synchronous equivalent of `Object::copy`.
///
/// ### Features
/// This function requires that the feature flag `sync` is enabled in `Cargo.toml`.
#[cfg(all(feature = "global-client", feature = "sync"))]
pub fn copy_sync(&self, destination_bucket: &str, path: &str) -> crate::Result<Self> {
crate::runtime()?.block_on(self.copy(destination_bucket, path))
}
/// Moves a file from the current location to the target bucket and path.
///
/// ## Limitations
/// This function does not yet support rewriting objects to another
/// * Geographical Location,
/// * Encryption,
/// * Storage class.
/// These limitations mean that for now, the rewrite and the copy methods do the same thing.
/// ### Example
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use cloud_storage::object::Object;
///
/// let obj1 = Object::read("my_bucket", "file1").await?;
/// let obj2 = obj1.rewrite("my_other_bucket", "file2").await?;
/// // obj2 is now a copy of obj1.
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "global-client")]
pub async fn rewrite(&self, destination_bucket: &str, path: &str) -> crate::Result<Self> {
crate::CLOUD_CLIENT
.object()
.rewrite(self, destination_bucket, path)
.await
}
/// The synchronous equivalent of `Object::rewrite`.
///
/// ### Features
/// This function requires that the feature flag `sync` is enabled in `Cargo.toml`.
#[cfg(all(feature = "global-client", feature = "sync"))]
pub fn rewrite_sync(&self, destination_bucket: &str, path: &str) -> crate::Result<Self> {
crate::runtime()?.block_on(self.rewrite(destination_bucket, path))
}
/// Creates a [Signed Url](https://cloud.google.com/storage/docs/access-control/signed-urls)
/// which is valid for `duration` seconds, and lets the posessor download the file contents
/// without any authentication.
/// ### Example
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use cloud_storage::{Client, object::{Object, ComposeRequest}};
///
/// let client = Client::default();
/// let obj1 = client.object().read("my_bucket", "file1").await?;
/// let url = obj1.download_url(50)?;
/// // url is now a url to which an unauthenticated user can make a request to download a file
/// // for 50 seconds.
/// # Ok(())
/// # }
/// ```
pub fn download_url(&self, duration: u32) -> crate::Result<String> {
self.sign(&self.name, duration, "GET", None, &HashMap::new())
}
/// Creates a [Signed Url](https://cloud.google.com/storage/docs/access-control/signed-urls)
/// which is valid for `duration` seconds, and lets the posessor download the file contents
/// without any authentication.
/// ### Example
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use cloud_storage::{Client, object::{Object, ComposeRequest}};
///
/// let client = Client::default();
/// let obj1 = client.object().read("my_bucket", "file1").await?;
/// let url = obj1.download_url(50)?;
/// // url is now a url to which an unauthenticated user can make a request to download a file
/// // for 50 seconds.
/// # Ok(())
/// # }
/// ```
pub fn download_url_with(
&self,
duration: u32,
opts: crate::DownloadOptions,
) -> crate::Result<String> {
self.sign(
&self.name,
duration,
"GET",
opts.content_disposition,
&HashMap::new(),
)
}
/// Creates a [Signed Url](https://cloud.google.com/storage/docs/access-control/signed-urls)
/// which is valid for `duration` seconds, and lets the posessor upload data to a blob
/// without any authentication.
/// ### Example
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use cloud_storage::{Client, object::{Object, ComposeRequest}};
///
/// let client = Client::default();
/// let obj1 = client.object().read("my_bucket", "file1").await?;
/// let url = obj1.upload_url(50)?;
/// // url is now a url to which an unauthenticated user can make a PUT request to upload a file
/// // for 50 seconds.
/// # Ok(())
/// # }
/// ```
pub fn upload_url(&self, duration: u32) -> crate::Result<String> {
self.sign(&self.name, duration, "PUT", None, &HashMap::new())
}
/// Creates a [Signed Url](https://cloud.google.com/storage/docs/access-control/signed-urls)
/// which is valid for `duration` seconds, and lets the posessor upload data and custom metadata
/// to a blob without any authentication.
/// ### Example
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use cloud_storage::{Client, object::{Object, ComposeRequest}};
/// use std::collections::HashMap;
///
/// let client = Client::default();
/// let obj1 = client.object().read("my_bucket", "file1").await?;
/// let mut custom_metadata = HashMap::new();
/// custom_metadata.insert(String::from("field"), String::from("value"));
/// let (url, headers) = obj1.upload_url_with(50, custom_metadata)?;
/// // url is now a url to which an unauthenticated user can make a PUT request to upload a file
/// // for 50 seconds. Note that the user must also include the returned headers in the PUT request
/// # Ok(())
/// # }
/// ```
pub fn upload_url_with(
&self,
duration: u32,
custom_metadata: HashMap<String, String>,
) -> crate::Result<(String, HashMap<String, String>)> {
let url = self.sign(&self.name, duration, "PUT", None, &custom_metadata)?;
let mut headers = HashMap::new();
for (k, v) in custom_metadata.iter() {
headers.insert(format!("x-goog-meta-{}", k.to_string()), v.to_string());
}
Ok((url, headers))
}
// /// Creates a [Signed Url](https://cloud.google.com/storage/docs/access-control/signed-urls)
// /// which is valid for `duration` seconds, and lets the posessor upload new file contents.
// /// without any authentication.
// pub fn upload_url(&self, duration: u32) -> crate::Result<String> {
// self.sign(&self.name, duration, "POST")
// }
#[inline(always)]
fn sign(
&self,
file_path: &str,
duration: u32,
http_verb: &str,
content_disposition: Option<String>,
custom_metadata: &HashMap<String, String>,
) -> crate::Result<String> {
use openssl::sha;
if duration > 604800 {
let msg = format!(
"duration may not be greater than 604800, but was {}",
duration
);
return Err(crate::Error::Other(msg));
}
// 0 Sort and construct the canonical headers
let mut headers = vec![("host".to_string(), "storage.googleapis.com".to_string())];
// Add custom metadata headers, guaranteed unique by HashMap input
for (k, v) in custom_metadata.iter() {
headers.push((format!("x-goog-meta-{}", k.to_string()), v.to_string()));
}
headers.sort_unstable_by(|(k1, _), (k2, _)| k1.cmp(&k2));
let canonical_headers: String = headers
.iter()
.map(|(k, v)| format!("{}:{}", k.to_lowercase(), v.to_lowercase()))
.collect::<Vec<String>>()
.join("\n");
let signed_headers = headers
.iter()
.map(|(k, _)| k.to_lowercase())
.collect::<Vec<String>>()
.join(";");
// 1 construct the canonical request
let issue_date = chrono::Utc::now();
let file_path = self.path_to_resource(file_path);
let query_string = Self::get_canonical_query_string(
&issue_date,
duration,
&signed_headers,
content_disposition,
);
let canonical_request = self.get_canonical_request(
&file_path,
&query_string,
http_verb,
&canonical_headers,
&signed_headers,
);
// 2 get hex encoded SHA256 hash the canonical request
let hash = sha::sha256(canonical_request.as_bytes());
let hex_hash = hex::encode(hash);
// 3 construct the string to sign
let string_to_sign = format!(
"{signing_algorithm}\n\
{current_datetime}\n\
{credential_scope}\n\
{hashed_canonical_request}",
signing_algorithm = "GOOG4-RSA-SHA256",
current_datetime = issue_date.format("%Y%m%dT%H%M%SZ"),
credential_scope = Self::get_credential_scope(&issue_date),
hashed_canonical_request = hex_hash,
);
// 4 sign the string to sign with RSA - SHA256
let buffer = Self::sign_str(&string_to_sign)?;
let signature = hex::encode(&buffer);
// 5 construct the signed url
Ok(format!(
"https://storage.googleapis.com{path_to_resource}?\
{query_string}&\
X-Goog-Signature={request_signature}",
path_to_resource = file_path,
query_string = query_string,
request_signature = signature,
))
}
#[inline(always)]
fn get_canonical_request(
&self,
path: &str,
query_string: &str,
http_verb: &str,
headers: &str,
signed_headers: &str,
) -> String {
format!(
"{http_verb}\n\
{path_to_resource}\n\
{canonical_query_string}\n\
{canonical_headers}\n\
\n\
{signed_headers}\n\
{payload}",
http_verb = http_verb,
path_to_resource = path,
canonical_query_string = query_string,
canonical_headers = headers,
signed_headers = signed_headers,
payload = "UNSIGNED-PAYLOAD",
)
}
#[inline(always)]
fn get_canonical_query_string(
date: &chrono::DateTime<chrono::Utc>,
exp: u32,
headers: &str,
content_disposition: Option<String>,
) -> String {
let credential = format!(
"{authorizer}/{scope}",
authorizer = crate::SERVICE_ACCOUNT.client_email,
scope = Self::get_credential_scope(date),
);
let mut s = format!(
"X-Goog-Algorithm={algo}&\
X-Goog-Credential={cred}&\
X-Goog-Date={date}&\
X-Goog-Expires={exp}&\
X-Goog-SignedHeaders={signed}",
algo = "GOOG4-RSA-SHA256",
cred = percent_encode(&credential),
date = date.format("%Y%m%dT%H%M%SZ"),
exp = exp,
signed = percent_encode(headers),
);
if let Some(cd) = content_disposition {
s.push_str(&format!("&response-content-disposition={}", cd));
}
s
}
#[inline(always)]
fn path_to_resource(&self, path: &str) -> String {
format!(
"/{bucket}/{file_path}",
bucket = self.bucket,
file_path = percent_encode_noslash(path),
)
}
#[inline(always)]
fn get_credential_scope(date: &chrono::DateTime<chrono::Utc>) -> String {
format!("{}/henk/storage/goog4_request", date.format("%Y%m%d"))
}
#[inline(always)]
fn sign_str(message: &str) -> crate::Result<Vec<u8>> {
use openssl::{hash::MessageDigest, pkey::PKey, sign::Signer};
let key = PKey::private_key_from_pem(crate::SERVICE_ACCOUNT.private_key.as_bytes())?;
let mut signer = Signer::new(MessageDigest::sha256(), &key)?;
signer.update(message.as_bytes())?;
Ok(signer.sign_to_vec()?)
}
}
const ENCODE_SET: &AsciiSet = &NON_ALPHANUMERIC
.remove(b'*')
.remove(b'-')
.remove(b'.')
.remove(b'_');
const NOSLASH_ENCODE_SET: &AsciiSet = &ENCODE_SET.remove(b'/').remove(b'~');
// We need to be able to percent encode stuff, but without touching the slashes in filenames. To
// this end we create an implementation that does this, without touching the slashes.
fn percent_encode_noslash(input: &str) -> String {
utf8_percent_encode(input, NOSLASH_ENCODE_SET).to_string()
}
pub(crate) fn percent_encode(input: &str) -> String {
utf8_percent_encode(input, ENCODE_SET).to_string()
}
#[cfg(all(test, feature = "global-client"))]
mod tests {
use super::*;
use crate::Error;
use futures::{stream, StreamExt, TryStreamExt};
#[tokio::test]
async fn create() -> Result<(), Box<dyn std::error::Error>> {
let bucket = crate::read_test_bucket().await;
Object::create(&bucket.name, vec![0, 1], "test-create", "text/plain").await?;
Ok(())
}
#[tokio::test]
async fn create_streamed() -> Result<(), Box<dyn std::error::Error>> {
let bucket = crate::read_test_bucket().await;
let stream = stream::iter([0u8, 1].iter())
.map(Ok::<_, Box<dyn std::error::Error + Send + Sync>>)
.map_ok(|&b| bytes::BytesMut::from(&[b][..]));
Object::create_streamed(
&bucket.name,
stream,
2,
"test-create-streamed",
"text/plain",
)
.await?;
Ok(())
}
#[tokio::test]
async fn list() -> Result<(), Box<dyn std::error::Error>> {
let test_bucket = crate::read_test_bucket().await;
let _v: Vec<ObjectList> = Object::list(&test_bucket.name, ListRequest::default())
.await?
.try_collect()
.await?;
Ok(())
}
async fn flattened_list_prefix_stream(
bucket: &str,
prefix: &str,
) -> Result<Vec<Object>, Box<dyn std::error::Error>> {
let request = ListRequest {
prefix: Some(prefix.into()),
..Default::default()
};
Ok(Object::list(bucket, request)
.await?
.map_ok(|object_list| object_list.items)
.try_concat()
.await?)
}
#[tokio::test]
async fn list_prefix() -> Result<(), Box<dyn std::error::Error>> {
let test_bucket = crate::read_test_bucket().await;
let prefix_names = [
"test-list-prefix/1",
"test-list-prefix/2",
"test-list-prefix/sub/1",
"test-list-prefix/sub/2",
];
for name in &prefix_names {
Object::create(&test_bucket.name, vec![0, 1], name, "text/plain").await?;