-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
GoogleCloudStorageBlobStorage.cs
189 lines (151 loc) · 6.41 KB
/
GoogleCloudStorageBlobStorage.cs
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Google.Api.Gax;
using Google.Apis.Auth.OAuth2;
using Google.Cloud.Storage.V1;
using FluentStorage.Blobs;
using Objects = Google.Apis.Storage.v1.Data.Objects;
using Object = Google.Apis.Storage.v1.Data.Object;
using Google;
using System.Net;
using System.Linq;
using Google.Apis.Storage.v1;
namespace FluentStorage.Gcp.CloudStorage.Blobs {
class GoogleCloudStorageBlobStorage : GenericBlobStorage {
//for intro see https://cloud.google.com/storage/docs/reference/libraries#client-libraries-install-csharp
private readonly StorageClient _client;
private readonly string _bucketName;
protected override bool CanListHierarchy => false;
public GoogleCloudStorageBlobStorage(string bucketName, GoogleCredential credential = null, EncryptionKey encryptionKey = null) : base() {
_client = StorageClient.Create(credential, encryptionKey);
_bucketName = bucketName;
}
protected override async Task<IReadOnlyCollection<Blob>> ListAtAsync(string path, ListOptions options, CancellationToken cancellationToken) {
ObjectsResource.ListRequest request = _client.Service.Objects.List(_bucketName);
request.Prefix = StoragePath.IsRootPath(path) ? null : (NormalisePath(path) + "/");
request.Delimiter = "/";
request.MaxResults = options.PageSize ?? ListOptions.PAGE_SIZE;
var page = new List<Blob>();
do {
Objects serviceObjects = await request.ExecuteAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
if (serviceObjects.Items != null) {
page.AddRange(GConvert.ToBlobs(serviceObjects.Items, options));
}
if (serviceObjects.Prefixes != null) {
//the only info we have about prefixes is it's name
page.AddRange(serviceObjects.Prefixes.Select(p => new Blob(p, BlobItemKind.Folder)));
}
request.PageToken = serviceObjects.NextPageToken;
}
while (request.PageToken != null);
return page;
}
private async Task<IReadOnlyCollection<Blob>> LegacyListAtAsync(string path, ListOptions options, CancellationToken cancellationToken) {
PagedAsyncEnumerable<Objects, Object> objects = _client.ListObjectsAsync(
_bucketName,
StoragePath.IsRootPath(options.FolderPath) ? null : options.FolderPath,
new ListObjectsOptions {
Delimiter = options.Recurse ? null : "/"
});
return await GConvert.ToBlobsAsync(objects, options).ConfigureAwait(false);
}
public override async Task SetBlobsAsync(IEnumerable<Blob> blobs, CancellationToken cancellationToken = default) {
GenericValidation.CheckBlobFullPaths(blobs);
await Task.WhenAll(blobs.Select(b => SetBlobAsync(b, cancellationToken))).ConfigureAwait(false);
}
private async Task SetBlobAsync(Blob blob, CancellationToken cancellationToken = default) {
Object item = await _client.GetObjectAsync(_bucketName, NormalisePath(blob.FullPath), cancellationToken: cancellationToken).ConfigureAwait(false);
if (item.Metadata == null) {
item.Metadata = new Dictionary<string, string>();
}
foreach (KeyValuePair<string, string> metadata in blob.Metadata) {
if (item.Metadata.ContainsKey(metadata.Key)) {
item.Metadata[metadata.Key] = metadata.Value;
}
else {
item.Metadata.Add(metadata.Key, metadata.Value);
}
}
await _client.UpdateObjectAsync(item, cancellationToken: cancellationToken).ConfigureAwait(false);
}
protected override async Task<Blob> GetBlobAsync(string fullPath, CancellationToken cancellationToken) {
fullPath = NormalisePath(fullPath);
try {
Object obj = await _client.GetObjectAsync(_bucketName, fullPath,
new GetObjectOptions {
//todo
},
cancellationToken).ConfigureAwait(false);
return GConvert.ToBlob(obj);
}
catch (GoogleApiException ex) when (ex.HttpStatusCode == HttpStatusCode.NotFound) {
return null;
}
}
protected override async Task DeleteSingleAsync(string fullPath, CancellationToken cancellationToken) {
try {
await _client.DeleteObjectAsync(_bucketName, NormalisePath(fullPath), cancellationToken: cancellationToken).ConfigureAwait(false);
}
catch (GoogleApiException ex) when (ex.HttpStatusCode == HttpStatusCode.NotFound) {
//when not found, just ignore
//try delete everything recursively
IReadOnlyCollection<Blob?> childObjects = await ListAtAsync(fullPath, new ListOptions { Recurse = true }, cancellationToken).ConfigureAwait(false);
foreach (Blob? blob in childObjects) {
if (blob == null) {
continue;
}
try {
await _client.DeleteObjectAsync(_bucketName, NormalisePath(blob.FullPath), cancellationToken: cancellationToken).ConfigureAwait(false);
}
catch (GoogleApiException exc) when (exc.HttpStatusCode == HttpStatusCode.NotFound) {
}
}
}
}
protected override async Task<bool> ExistsAsync(string fullPath, CancellationToken cancellationToken) {
GenericValidation.CheckBlobFullPath(fullPath);
try {
await _client.GetObjectAsync(
_bucketName, NormalisePath(fullPath),
null,
cancellationToken).ConfigureAwait(false);
return true;
}
catch (GoogleApiException ex) when (ex.HttpStatusCode == HttpStatusCode.NotFound) {
return false;
}
}
public override async Task WriteAsync(string fullPath, Stream dataStream,
bool append = false, CancellationToken cancellationToken = default) {
if (append)
throw new NotSupportedException();
GenericValidation.CheckBlobFullPath(fullPath);
fullPath = NormalisePath(fullPath);
await _client.UploadObjectAsync(_bucketName, fullPath, null, dataStream, cancellationToken: cancellationToken).ConfigureAwait(false);
}
public override async Task<Stream> OpenReadAsync(string fullPath, CancellationToken cancellationToken = default) {
GenericValidation.CheckBlobFullPath(fullPath);
fullPath = NormalisePath(fullPath);
// no read streaming support in this crappy SDK
var ms = new MemoryStream();
try {
await _client.DownloadObjectAsync(_bucketName, fullPath, ms, cancellationToken: cancellationToken).ConfigureAwait(false);
}
catch (GoogleApiException ex) when (ex.HttpStatusCode == HttpStatusCode.NotFound) {
return null;
}
ms.Position = 0;
return ms;
}
/// <summary>
/// GCP requires no trailing root
/// </summary>
private static string NormalisePath(string path) {
path = StoragePath.Normalize(path);
return path.Substring(1);
}
}
}