forked from googleapis/java-storage-nio
/
FakeStorageRpc.java
506 lines (459 loc) · 15.6 KB
/
FakeStorageRpc.java
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
/*
* Copyright 2016 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.storage.contrib.nio.testing;
import com.google.api.services.storage.model.Bucket;
import com.google.api.services.storage.model.ServiceAccount;
import com.google.api.services.storage.model.StorageObject;
import com.google.cloud.Tuple;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.spi.v1.StorageRpc;
import com.google.cloud.storage.testing.StorageRpcTestBase;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.nio.file.FileAlreadyExistsException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.concurrent.NotThreadSafe;
/**
* A bare-bones in-memory implementation of StorageRpc, meant for testing.
*
* <p>This class is <i>not</i> thread-safe. It's also (currently) limited in the following ways:
*
* <ul>
* <li>Supported
* <ul>
* <li>object create
* <li>object get
* <li>object delete
* <li>list the contents of a bucket
* <li>generations
* </ul>
* <li>Unsupported
* <ul>
* <li>bucket create
* <li>bucket get
* <li>bucket delete
* <li>list all buckets
* <li>file attributes
* <li>patch
* <li>continueRewrite
* <li>createBatch
* <li>checksums, etags
* <li>IAM operations
* <li>BucketLock operations
* <li>HMAC key operations
* </ul>
* </ul>
*/
@NotThreadSafe
class FakeStorageRpc extends StorageRpcTestBase {
// fullname -> metadata
Map<String, StorageObject> metadata = new HashMap<>();
// fullname -> contents
Map<String, byte[]> contents = new HashMap<>();
// fullname -> future contents that will be visible on close.
Map<String, byte[]> futureContents = new HashMap<>();
private final boolean throwIfOption;
/** @param throwIfOption if true, we throw when given any option */
public FakeStorageRpc(boolean throwIfOption) {
this.throwIfOption = throwIfOption;
}
// remove all files
void reset() {
metadata = new HashMap<>();
contents = new HashMap<>();
}
@Override
public StorageObject create(StorageObject object, InputStream content, Map<Option, ?> options)
throws StorageException {
potentiallyThrow(options);
String key = fullname(object);
metadata.put(key, object);
try {
contents.put(key, com.google.common.io.ByteStreams.toByteArray(content));
} catch (IOException e) {
throw new StorageException(e);
}
// TODO: crc, etc
return object;
}
@Override
public Tuple<String, Iterable<StorageObject>> list(String bucket, Map<Option, ?> options)
throws StorageException {
String delimiter = null;
String preprefix = "";
String pageToken = null;
long maxResults = Long.MAX_VALUE;
for (Map.Entry<Option, ?> e : options.entrySet()) {
switch (e.getKey()) {
case PAGE_TOKEN:
pageToken = (String) e.getValue();
break;
case PREFIX:
preprefix = (String) e.getValue();
if (preprefix.startsWith("/")) {
preprefix = preprefix.substring(1);
}
break;
case DELIMITER:
delimiter = (String) e.getValue();
break;
case FIELDS:
// ignore and return all the fields
break;
case MAX_RESULTS:
maxResults = (Long) e.getValue();
break;
case USER_PROJECT:
// prevent unsupported operation
break;
default:
throw new UnsupportedOperationException("Unknown option: " + e.getKey());
}
}
final String prefix = preprefix;
List<StorageObject> values = new ArrayList<>();
Map<String, StorageObject> folders = new HashMap<>();
for (StorageObject so : metadata.values()) {
if (!so.getName().startsWith(prefix)) {
continue;
}
if (processedAsFolder(so, delimiter, prefix, folders)) {
continue;
}
so.setSize(size(so));
if (so.getBucket().equals(bucket)) {
values.add(so);
}
}
values.addAll(folders.values());
// truncate to max allowed length
if (values.size() > maxResults) {
List<StorageObject> newValues = new ArrayList<>();
for (int i = 0; i < maxResults; i++) {
newValues.add(values.get(i));
}
values = newValues;
}
// null cursor to indicate there is no more data (empty string would cause us to be called
// again).
// The type cast seems to be necessary to help Java's typesystem remember that collections are
// iterable.
return Tuple.of(pageToken, (Iterable<StorageObject>) values);
}
/** Returns the requested bucket or {@code null} if not found. */
@Override
public Bucket get(Bucket bucket, Map<Option, ?> options) throws StorageException {
potentiallyThrow(options);
return null;
}
/** Returns the requested storage object or {@code null} if not found. */
@Override
public StorageObject get(StorageObject object, Map<Option, ?> options) throws StorageException {
// we allow the "ID" option because we need to, but then we give a whole answer anyways
// because the caller won't mind the extra fields.
if (throwIfOption
&& !options.isEmpty()
&& options.size() > 1
&& options.keySet().toArray()[0] != Storage.BlobGetOption.fields(Storage.BlobField.ID)) {
throw new UnsupportedOperationException();
}
String key = fullname(object);
if (metadata.containsKey(key)) {
StorageObject ret = metadata.get(key);
ret.setSize(size(ret));
ret.setId(key);
return ret;
}
return null;
}
@Override
public Bucket patch(Bucket bucket, Map<Option, ?> options) throws StorageException {
potentiallyThrow(options);
return null;
}
@Override
public StorageObject patch(StorageObject storageObject, Map<Option, ?> options)
throws StorageException {
potentiallyThrow(options);
return null;
}
@Override
public boolean delete(Bucket bucket, Map<Option, ?> options) throws StorageException {
return false;
}
@Override
public boolean delete(StorageObject object, Map<Option, ?> options) throws StorageException {
String key = fullname(object);
contents.remove(key);
return null != metadata.remove(key);
}
@Override
public StorageObject compose(
Iterable<StorageObject> sources, StorageObject target, Map<Option, ?> targetOptions)
throws StorageException {
return null;
}
@Override
public byte[] load(StorageObject storageObject, Map<Option, ?> options) throws StorageException {
String key = fullname(storageObject);
if (!contents.containsKey(key)) {
throw new StorageException(404, "File not found: " + key);
}
return contents.get(key);
}
@Override
public Tuple<String, byte[]> read(
StorageObject from, Map<Option, ?> options, long zposition, int zbytes)
throws StorageException {
// if non-null, then we check the file's at that generation.
Long generationMatch = null;
for (Option op : options.keySet()) {
if (op.equals(StorageRpc.Option.IF_GENERATION_MATCH)) {
generationMatch = (Long) options.get(op);
} else {
throw new UnsupportedOperationException("Unknown option: " + op);
}
}
String key = fullname(from);
if (!contents.containsKey(key)) {
throw new StorageException(404, "File not found: " + key);
}
checkGeneration(key, generationMatch);
long position = zposition;
int bytes = zbytes;
if (position < 0) {
position = 0;
}
byte[] full = contents.get(key);
if ((int) position + bytes > full.length) {
bytes = full.length - (int) position;
}
if (bytes <= 0) {
// special case: you're trying to read past the end
return Tuple.of("etag-goes-here", new byte[0]);
}
byte[] ret = new byte[bytes];
System.arraycopy(full, (int) position, ret, 0, bytes);
return Tuple.of("etag-goes-here", ret);
}
@Override
public long read(
StorageObject from, Map<Option, ?> options, long position, OutputStream outputStream) {
// if non-null, then we check the file's at that generation.
Long generationMatch = null;
for (Option op : options.keySet()) {
if (op.equals(StorageRpc.Option.IF_GENERATION_MATCH)) {
generationMatch = (Long) options.get(op);
} else {
throw new UnsupportedOperationException("Unknown option: " + op);
}
}
String key = fullname(from);
if (!contents.containsKey(key)) {
throw new StorageException(404, "File not found: " + key);
}
checkGeneration(key, generationMatch);
if (position < 0) {
position = 0;
}
byte[] full = contents.get(key);
int bytes = (int) (full.length - position);
if (bytes <= 0) {
// special case: you're trying to read past the end
return 0;
}
try {
outputStream.write(full, (int) position, bytes);
} catch (IOException e) {
throw new StorageException(500, "Failed to write to file", e);
}
return bytes;
}
@Override
public String open(StorageObject object, Map<Option, ?> options) throws StorageException {
String key = fullname(object);
// if non-null, then we check the file's at that generation.
Long generationMatch = null;
for (Option option : options.keySet()) {
// this is a bit of a hack, since we don't implement generations.
if (option == Option.IF_GENERATION_MATCH) {
generationMatch = (Long) options.get(option);
}
}
checkGeneration(key, generationMatch);
metadata.put(key, object);
return fullname(object);
}
@Override
public String open(String signedURL) {
return null;
}
@Override
public void write(
String uploadId, byte[] toWrite, int toWriteOffset, long destOffset, int length, boolean last)
throws StorageException {
writeWithResponse(uploadId, toWrite, toWriteOffset, destOffset, length, last);
}
@Override
public StorageObject writeWithResponse(
String uploadId,
byte[] toWrite,
int toWriteOffset,
long destOffset,
int length,
boolean last) {
// this may have a lot more allocations than ideal, but it'll work.
byte[] bytes;
if (futureContents.containsKey(uploadId)) {
bytes = futureContents.get(uploadId);
if (bytes.length < length + destOffset) {
byte[] newBytes = new byte[(int) (length + destOffset)];
System.arraycopy(bytes, 0, newBytes, (int) 0, bytes.length);
bytes = newBytes;
}
} else {
bytes = new byte[(int) (length + destOffset)];
}
System.arraycopy(toWrite, toWriteOffset, bytes, (int) destOffset, length);
// we want to mimic the GCS behavior that file contents are only visible on close.
StorageObject storageObject = null;
if (last) {
contents.put(uploadId, bytes);
futureContents.remove(uploadId);
if (metadata.containsKey(uploadId)) {
storageObject = metadata.get(uploadId);
Long generation = storageObject.getGeneration();
if (null == generation) {
generation = Long.valueOf(0);
}
storageObject.setGeneration(++generation);
metadata.put(uploadId, storageObject);
}
} else {
futureContents.put(uploadId, bytes);
}
return storageObject;
}
@Override
public RewriteResponse openRewrite(RewriteRequest rewriteRequest) throws StorageException {
String sourceKey = fullname(rewriteRequest.source);
// a little hackish, just good enough for the tests to work.
if (!contents.containsKey(sourceKey)) {
throw new StorageException(404, "File not found: " + sourceKey);
}
// if non-null, then we check the file's at that generation.
Long generationMatch = null;
for (Option option : rewriteRequest.targetOptions.keySet()) {
// this is a bit of a hack, since we don't implement generations.
if (option == Option.IF_GENERATION_MATCH) {
generationMatch = (Long) rewriteRequest.targetOptions.get(option);
}
}
String destKey = fullname(rewriteRequest.target);
// if this is a new file, set generation to 1, else increment the existing generation
long generation = 1;
if (metadata.containsKey(destKey)) {
generation = metadata.get(destKey).getGeneration() + 1;
}
checkGeneration(destKey, generationMatch);
byte[] data = contents.get(sourceKey);
rewriteRequest.target.setGeneration(generation);
rewriteRequest.target.setSize(BigInteger.valueOf(data.length));
metadata.put(destKey, rewriteRequest.target);
contents.put(destKey, Arrays.copyOf(data, data.length));
return new RewriteResponse(
rewriteRequest,
rewriteRequest.target,
data.length,
true,
"rewriteToken goes here",
data.length);
}
private String fullname(StorageObject so) {
return (so.getBucket() + "/" + so.getName());
}
private BigInteger size(StorageObject so) {
String key = fullname(so);
if (contents.containsKey(key)) {
return BigInteger.valueOf(contents.get(key).length);
}
return null;
}
private void potentiallyThrow(Map<Option, ?> options) throws UnsupportedOperationException {
if (throwIfOption && !options.isEmpty()) {
throw new UnsupportedOperationException();
}
}
/**
* Throw if we're asking for generation 0 and the file exists, or if the requested generation
* number doesn't match what is asked.
*
* @param key
* @param generationMatch
*/
private void checkGeneration(String key, Long generationMatch) {
if (null == generationMatch) {
return;
}
if (generationMatch == 0 && metadata.containsKey(key)) {
throw new StorageException(new FileAlreadyExistsException(key));
}
if (generationMatch != 0) {
Long generation = metadata.get(key).getGeneration();
if (!generationMatch.equals(generation)) {
throw new StorageException(
404, "Generation mismatch. Requested " + generationMatch + " but got " + generation);
}
}
}
// Returns true if this is a folder. Adds it to folders if it isn't already there.
private static boolean processedAsFolder(
StorageObject so,
String delimiter,
String prefix, /* inout */
Map<String, StorageObject> folders) {
if (delimiter == null) {
return false;
}
int nextSlash = so.getName().indexOf(delimiter, prefix.length());
if (nextSlash < 0) {
return false;
}
String folderName = so.getName().substring(0, nextSlash + 1);
if (folders.containsKey(folderName)) {
return true;
}
StorageObject fakeFolder = new StorageObject();
fakeFolder.setName(folderName);
fakeFolder.setBucket(so.getBucket());
fakeFolder.setGeneration(so.getGeneration());
fakeFolder.set("isDirectory", true);
fakeFolder.setSize(BigInteger.ZERO);
folders.put(folderName, fakeFolder);
return true;
}
@Override
public ServiceAccount getServiceAccount(String projectId) {
return null;
}
}