-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBucket.java
More file actions
465 lines (433 loc) · 17.2 KB
/
Bucket.java
File metadata and controls
465 lines (433 loc) · 17.2 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
package store.reduct.model.bucket;
import static store.reduct.utils.http.HttpHeaders.*;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigInteger;
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.ByteBuffer;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.PriorityBlockingQueue;
import lombok.*;
import org.apache.commons.lang3.ArrayUtils;
import store.reduct.client.ReductClient;
import store.reduct.common.BucketURL;
import store.reduct.common.RecordURL;
import store.reduct.common.exception.ReductException;
import store.reduct.model.QueryOptions;
import store.reduct.model.mapper.BucketMapper;
import store.reduct.model.record.QueryId;
import store.reduct.model.record.Record;
import store.reduct.utils.JsonUtils;
import store.reduct.utils.Strings;
import store.reduct.utils.http.Queries;
@NoArgsConstructor
@EqualsAndHashCode
@ToString
@AllArgsConstructor
@Getter
@Setter
public class Bucket {
private static final String TS = "ts";
public static final String X_REDUCT_TIME_IS_NOT_SUCH_LONG_FORMAT = "Received from server x-reduct-time is not such Long format, or empty.";
public static final String CONTENT_TYPE_IS_NOT_SET_IN_THE_RECORD = "The Content-Type is not set in the record.";
public static final String CONTENT_LENGTH_IS_NOT_SET_IN_THE_RECORD = "The Content-Length is not set in the record.";
public Bucket(String name, ReductClient reductClient) {
this.name = name;
this.reductClient = reductClient;
}
@JsonIgnore
private ReductClient reductClient;
/**
* Name of the bucket
*/
@JsonProperty("name")
private String name;
/**
* Number of entries in the bucket
*/
@JsonProperty("entry_count")
private Integer entryCount;
/**
* Size of stored data in the bucket in bytes
*/
@JsonProperty("size")
private Integer size;
/**
* Unix timestamp of oldest record in microseconds
*/
@JsonProperty("oldest_record")
private BigInteger oldestRecord;
/**
* Unix timestamp of latest record in microseconds
*/
@JsonProperty("latest_record")
private BigInteger latestRecord;
/**
*
*/
@JsonProperty("is_provisioned")
private Boolean isProvisioned;
@JsonProperty("settings")
private BucketSettings bucketSettings;
@SuppressWarnings("unchecked")
@JsonProperty("info")
private void unpackInfo(Map<String, Object> info) {
this.name = info.get("name").toString();
this.entryCount = Integer.valueOf(info.get("entry_count").toString());
this.size = Integer.valueOf(info.get("size").toString());
this.oldestRecord = new BigInteger(info.get("oldest_record").toString());
this.latestRecord = new BigInteger(info.get("latest_record").toString());
this.isProvisioned = Boolean.getBoolean(info.get("is_provisioned").toString());
}
@JsonProperty("entries")
private List<EntryInfo> entryInfos;
/**
* Get information about a bucket The method returns the current settings,
* stats, and entry list of the bucket in JSON format. If authentication is
* enabled, the method needs a valid API token.
*
* @return Returns this Bucket object with updated fields
*/
public Bucket read() throws ReductException, IllegalArgumentException {
BucketMapper.INSTANCE.copy(this, reductClient.getBucket(name));
return this;
}
/**
* To update settings of a bucket, the request should have a JSON document with
* all the settings.
*
* @param bucketSettings
* @throws ReductException
* If, unable to create the bucket. The instance of the exception
* holds the error message returned in the x-reduct-error header and
* the status code to indicate the failure. Some status codes: 401
* -> Access token is invalid or was not provided. 403 -> Access
* token does not have required permissions. 409 -> Bucket with this
* name already exists. 422 -> Invalid request. 500 -> Internal
* server error.
* @throws ReductException
* If, any client side error occur.
* @throws IllegalArgumentException
* If, the bucket name is null or empty.
*/
@JsonIgnore
public void setSettings(BucketSettings bucketSettings) throws ReductException, IllegalArgumentException {
String createBucketPath = BucketURL.CREATE_BUCKET.getUrl().formatted(name);
URI uri = URI.create("%s/%s".formatted(reductClient.getServerProperties().url(), createBucketPath));
HttpRequest.Builder httpRequest = HttpRequest.newBuilder().uri(uri)
.PUT(HttpRequest.BodyPublishers.ofString(JsonUtils.serialize(bucketSettings)));
reductClient.sendAndGetOnlySuccess(httpRequest, HttpResponse.BodyHandlers.discarding()); // TODO ask about
// default settings.
// The
// answer from DB always is empty for
// success, but settings sets as
// default. This bucket will always have
// settings as null until invoke read.
}
/**
* The method updates the Bucket and returns updated BucketSettings. If
* authentication is enabled, the method needs a valid API token.
*
* @return BucketSettings
*/
@JsonIgnore
public BucketSettings getSettings() {
return this.read().getBucketSettings();
}
/**
* Write a record to an entry.
*
* @param entryName
* @param record
* @throws ReductException
* @throws IllegalArgumentException
*/
public void writeRecord(String entryName, @NonNull Record record) throws ReductException, IllegalArgumentException {
// TODO validation block
if (isNotValidRecord(record)) {
throw new ReductException("Validation error");
}
Long timestamp = Objects.nonNull(record.getTimestamp()) && record.getTimestamp() > 0
? record.getTimestamp()
: Instant.now().getNano() / 1000;
URI uri = URI.create(reductClient.getServerProperties().url()
+ String.format(RecordURL.WRITE_ENTRY.getUrl(), name, entryName) + new Queries(TS, timestamp));
HttpRequest.Builder builder = HttpRequest.newBuilder().uri(uri).header(getContentTypeHeader(), record.getType())
.POST(HttpRequest.BodyPublishers.ofByteArray(record.getBody()));
reductClient.sendAndGetOnlySuccess(builder, HttpResponse.BodyHandlers.ofString());
}
/**
* Write batch of records
*
* @param entryName
* @param records
* @throws ReductException
* @throws IllegalArgumentException
*/
public void writeRecords(String entryName, Iterator<Record> records)
throws ReductException, IllegalArgumentException {
URI uri = URI.create(reductClient.getServerProperties().url()
+ String.format(RecordURL.WRITE_ENTRY_BATCH.getUrl(), name, entryName));
HttpRequest.Builder builder = HttpRequest.newBuilder().uri(uri);
byte[] body = null;
while (records.hasNext()) {
Record record = records.next();
// TODO validation block
if (isNotValidRecord(record)) {
throw new ReductException("Validation error");
}
byte[] byteBodyArray = record.getBody();
body = ArrayUtils.addAll(body, byteBodyArray);
builder.header(getXReductTimeWithNumberHeader(record.getTimestamp()),
byteBodyArray.length + "," + record.getType());
}
if (Objects.nonNull(body)) {
builder.POST(HttpRequest.BodyPublishers.ofByteArray(body));
reductClient.sendAndGetOnlySuccess(builder, HttpResponse.BodyHandlers.ofString()).body();
}
}
/**
* Get a record from an entry.
*
* @param entryName
* @param timestamp
* @return
* @throws ReductException
* @throws IllegalArgumentException
*/
public Record readRecord(String entryName, Long timestamp) throws ReductException, IllegalArgumentException {
if (Strings.isBlank(name) || Strings.isBlank(entryName)) {
throw new ReductException("Validation error");
}
String timeStampQuery = Objects.isNull(timestamp) ? "" : new Queries(TS, timestamp).toString();
URI uri = URI.create(reductClient.getServerProperties().url()
+ String.format(RecordURL.GET_ENTRY.getUrl(), name, entryName) + timeStampQuery);
HttpRequest.Builder builder = HttpRequest.newBuilder().uri(uri).GET();
HttpResponse<byte[]> httpResponse = reductClient.sendAndGetOnlySuccess(builder,
HttpResponse.BodyHandlers.ofByteArray());
return Record.builder().body(httpResponse.body())
.timestamp(httpResponse.headers().firstValue(getXReductTimeHeader()).map(Long::parseLong)
.orElseThrow(() -> new ReductException(X_REDUCT_TIME_IS_NOT_SUCH_LONG_FORMAT)))
.type(httpResponse.headers().firstValue(getContentTypeHeader())
.orElseThrow(() -> new ReductException(CONTENT_TYPE_IS_NOT_SET_IN_THE_RECORD)))
.length(httpResponse.headers().firstValue(getContentLengthHeader()).map(Integer::parseInt)
.orElseThrow(() -> new ReductException(CONTENT_LENGTH_IS_NOT_SET_IN_THE_RECORD)))
.build();
}
/**
* Get only meta information about record.
*
* @param entryName
* @param timestamp
* @return
* @throws ReductException
* @throws IllegalArgumentException
*/
public Record getMetaInfo(String entryName, Long timestamp) throws ReductException, IllegalArgumentException {
if (Strings.isBlank(name) || Strings.isBlank(entryName)) {
throw new ReductException("Validation error");
}
String timeStampQuery = Objects.isNull(timestamp) ? "" : new Queries(TS, timestamp).toString();
URI uri = URI.create(reductClient.getServerProperties().url()
+ String.format(RecordURL.GET_ENTRY.getUrl(), name, entryName) + timeStampQuery);
HttpRequest.Builder builder = HttpRequest.newBuilder().uri(uri).method("HEAD",
HttpRequest.BodyPublishers.noBody());
HttpResponse<byte[]> httpResponse = reductClient.sendAndGetOnlySuccess(builder,
HttpResponse.BodyHandlers.ofByteArray());
return Record.builder()
.timestamp(httpResponse.headers().firstValue(getXReductTimeHeader()).map(Long::parseLong)
.orElseThrow(() -> new ReductException(X_REDUCT_TIME_IS_NOT_SUCH_LONG_FORMAT)))
.type(httpResponse.headers().firstValue(getContentTypeHeader())
.orElseThrow(() -> new ReductException(CONTENT_TYPE_IS_NOT_SET_IN_THE_RECORD)))
.length(httpResponse.headers().firstValue(getContentLengthHeader()).map(Integer::parseInt)
.orElseThrow(() -> new ReductException(CONTENT_LENGTH_IS_NOT_SET_IN_THE_RECORD)))
.build();
}
/**
* Query records for a time interval
*
* @param entryName
* @param start
* @param stop
* @param ttl
* @return
*/
public Iterator<Record> query(String entryName, Long start, Long stop, Long ttl)
throws ReductException, IllegalArgumentException {
if (Strings.isBlank(name) || Strings.isBlank(entryName) || Objects.isNull(start) || Objects.isNull(stop)
|| Objects.isNull(ttl)) {
throw new ReductException("Validation error");
}
URI uri = URI.create(
reductClient.getServerProperties().url() + String.format(RecordURL.QUERY.getUrl(), name, entryName)
+ new Queries("start", start).add("stop", stop).add("ttl", ttl));
HttpRequest.Builder builder = HttpRequest.newBuilder().uri(uri).GET();
HttpResponse<String> response = reductClient.sendAndGetOnlySuccess(builder,
HttpResponse.BodyHandlers.ofString());
QueryId queryId = JsonUtils.parseObject(response.body(), QueryId.class);
return new RecordIterator(name, entryName, queryId.getId(), reductClient.getServerProperties().url());
}
/**
* Query records for a time interval
*
* @param entryName
* @param options
* @return
*/
public Iterator<Record> query(String entryName, QueryOptions options)
throws ReductException, IllegalArgumentException {
return query(entryName, options.getStart(), options.getStop(), options.getTtl());
}
public Iterator<Record> getMetaInfos(String entryName, Long start, Long stop, Long ttl)
throws ReductException, IllegalArgumentException {
if (Strings.isBlank(name) || Strings.isBlank(entryName) || Objects.isNull(start) || Objects.isNull(stop)
|| Objects.isNull(ttl)) {
throw new ReductException("Validation error");
}
URI uri = URI.create(
reductClient.getServerProperties().url() + String.format(RecordURL.QUERY.getUrl(), name, entryName)
+ new Queries("start", start).add("stop", stop).add("ttl", ttl));
HttpRequest.Builder builder = HttpRequest.newBuilder().uri(uri).GET();
HttpResponse<String> response = reductClient.sendAndGetOnlySuccess(builder,
HttpResponse.BodyHandlers.ofString());
QueryId queryId = JsonUtils.parseObject(response.body(), QueryId.class);
return new MetaInfoIterator(name, entryName, queryId.getId(), reductClient.getServerProperties().url());
}
private boolean isNotValidRecord(Record val) {
return val.getTimestamp() <= 0 || Objects.isNull(val.getBody());
}
private class RecordIterator implements Iterator<Record> {
@Getter(AccessLevel.PACKAGE)
private final HttpRequest.Builder builder;
private final String recordEntryName;
@Getter(AccessLevel.PACKAGE)
private final PriorityBlockingQueue<HeaderInstance> headerInstances = new PriorityBlockingQueue<>(8,
Comparator.comparingLong(instance -> instance.ts));
private byte[] body;
@Setter(AccessLevel.PACKAGE)
@Getter(AccessLevel.PACKAGE)
private boolean last = false;
boolean hasNextRecord() {
return !headerInstances.isEmpty();
}
private RecordIterator(String bucketName, String recordEntryName, Long queryId, String baseUrl) {
this(recordEntryName, queryId, HttpRequest.newBuilder()
.uri(URI.create(baseUrl + String.format(RecordURL.GET_ENTRIES.getUrl(), bucketName, recordEntryName)
+ new Queries("q", queryId)))
.GET());
}
private RecordIterator(String recordEntryName, Long queryId, HttpRequest.Builder builder) {
if (Objects.isNull(queryId)) {
throw new ReductException("Validation error: queryId is null");
}
this.recordEntryName = recordEntryName;
this.builder = builder;
}
@Override
public boolean hasNext() {
if (hasNextRecord()) {
return true;
}
if (!isLast()) {
HttpResponse<byte[]> httpResponse = reductClient.send(builder, HttpResponse.BodyHandlers.ofByteArray());
if (httpResponse.statusCode() != 204) {
body = httpResponse.body();
int offset = 0;
for (Map.Entry<String, List<String>> ent : httpResponse.headers().map().entrySet()) {
if (ent.getKey().contains(getXReductTimeWithUnderscoreHeader())) {
String ts = ent.getKey().substring(getXReductTimeWithUnderscoreHeader().length());
String[] split = ent.getValue().get(0).split(",");
if (split.length < 2) {
throw new ReductException(
String.format("Headers has a wrong format for timestamp: %s", ts));
}
try {
int length = Integer.parseInt(split[0]);
String type = split[1];
headerInstances.put(HeaderInstance.builder()
.ts(Optional.of(ts).map(Long::parseLong).orElseThrow(
() -> new ReductException(X_REDUCT_TIME_IS_NOT_SUCH_LONG_FORMAT)))
.type(type).length(length).offset(offset).build());
offset += length;
} catch (NumberFormatException ex) {
throw new ReductException(CONTENT_LENGTH_IS_NOT_SET_IN_THE_RECORD);
}
}
}
} else {
setLast(true);
}
}
return hasNextRecord();
}
@Override
public Record next() {
if (last) {
throw new NoSuchElementException();
} else if (Objects.isNull(body) || !hasNextRecord()) {
throw new ReductException("Invoke hasNext() method first");
}
HeaderInstance instance = headerInstances.poll();
ByteBuffer byteBuffer = ByteBuffer.wrap(body);
byte[] nextBody = new byte[instance.length];
byteBuffer.position(instance.getOffset());
byteBuffer.get(nextBody, 0, instance.getLength());
return Record.builder().body(nextBody).timestamp(instance.getTs()).type(instance.getType())
.length(instance.getLength()).build();
}
}
private class MetaInfoIterator extends RecordIterator {
private MetaInfoIterator(String bucketName, String recordEntryName, Long queryId, String baseUrl) {
super(bucketName, recordEntryName, queryId, baseUrl);
}
private MetaInfoIterator(String recordEntryName, Long queryId, HttpRequest.Builder builder) {
super(recordEntryName, queryId, builder.method("HEAD", HttpRequest.BodyPublishers.noBody()));
}
@Override
public boolean hasNext() {
if (hasNextRecord()) {
return true;
}
if (!isLast()) {
HttpResponse<byte[]> httpResponse = reductClient.send(getBuilder(),
HttpResponse.BodyHandlers.ofByteArray());
if (httpResponse.statusCode() != 204) {
for (Map.Entry<String, List<String>> ent : httpResponse.headers().map().entrySet()) {
if (ent.getKey().contains(getXReductTimeWithUnderscoreHeader())) {
String ts = ent.getKey().substring(getXReductTimeWithUnderscoreHeader().length());
String[] split = ent.getValue().get(0).split(",");
if (split.length < 2) {
throw new ReductException(
String.format("Headers has a wrong format for timestamp: %s", ts));
}
try {
int length = Integer.parseInt(split[0]);
String type = split[1];
getHeaderInstances().put(HeaderInstance.builder()
.ts(Optional.of(ts).map(Long::parseLong).orElseThrow(
() -> new ReductException(X_REDUCT_TIME_IS_NOT_SUCH_LONG_FORMAT)))
.type(type).length(length).build());
} catch (NumberFormatException ex) {
throw new ReductException(CONTENT_LENGTH_IS_NOT_SET_IN_THE_RECORD);
}
}
}
} else {
setLast(true);
}
}
return hasNextRecord();
}
}
@Data
@Builder
private static class HeaderInstance {
Long ts;
String type;
int length;
int offset;
}
}