-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.d
430 lines (396 loc) · 13.5 KB
/
client.d
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
module oras.client;
import oras.protocol;
import oras.http.base : TransportError, Header;
import oras.http.requests;
import oras.data;
import mir.algebraic;
import mir.ion.value;
import mir.ion.exception;
public import oras.protocol;
enum manifestContentType = "application/vnd.oci.image.manifest.v1+json";
alias Client = BaseClient!(oras.http.requests.Transport);
alias Config = oras.http.requests.Transport.Config;
struct BaseClient(T) {
alias Transport = T;
private Transport transport;
this(Transport.Config config) {
this.transport = Transport(config);
}
Result!(ManifestResponse) getManifest(Name name, Reference reference) const nothrow @safe {
return transport
.get(Routes.manifest(name, reference), [Header("accept"): manifestContentType])
.then!((r) @trusted => r.decode!(ManifestResponse));
}
Variant!(bool, TransportError) hasManifest(Name name, Reference reference) const nothrow @safe {
return transport
.head(Routes.manifest(name, reference))
.then!((r) => r.code == 200);
}
Result!(BlobResponse!(Transport.ByteStream)) getBlob(Name name, Digest digest) const nothrow @trusted {
auto res = transport.get(Routes.blob(name, digest));
try {
return res.then!((r) => r.decode!(BlobResponse!(Transport.ByteStream)));
} catch (Exception e) {
return Result!(BlobResponse!(Transport.ByteStream))(DecodingError(e));
}
}
Variant!(bool, TransportError) hasBlob(Name name, Digest digest) const nothrow @safe {
return transport
.head(Routes.blob(name, digest))
.then!((r) => r.code == 200);
// TODO: if not 404 then httperror
}
Result!(PushResult) push(Name name, Tag tag, Result!(PushResult) delegate(ref PushSession!BaseClient) scope nothrow @safe work) nothrow @safe {
return upload(name, toBlob("{}"))
.then!((UploadResult configResult) {
auto config = Manifest.Config("application/vnd.oci.image.config.v1+json", configResult.digest, configResult.size);
auto session = PushSession!BaseClient(this, name, tag, config);
return work(session);
});
}
T pull(T)(Name name, Reference reference, T delegate(ref PullSession!BaseClient) scope nothrow @safe work) nothrow @safe {
return getManifest(name, reference)
.then!((ManifestResponse response) {
auto session = PullSession!BaseClient(this, name, reference, response.body);
return work(session);
});
}
Result!(UploadResult) upload(T)(Name name, Blob!T blob) const nothrow @safe {
alias R = Result!(UploadResult);
static if (isChunked!T) {
return chunkedUpload(name, (ref ChunkedUploadSession!Transport s) {
foreach(chunk; blob.byChunks) {
auto result = s.upload(chunk);
if (!result._is!ChunkResult) {
s.cancel();
return R(result.trustedGet!(ErrorTypes));
}
}
return s.finish();
});
} else {
return upload(name, (ref UploadSession!Transport s) {
return s.upload(blob);
});
}
}
Result!(UploadResult) upload(Name name, Result!UploadResult delegate(ref UploadSession!Transport) scope nothrow @safe work) const nothrow @safe {
alias R = Result!(UploadResult);
return transport
.post(Routes.upload(name), null)
.then!((r) @safe {
if (r.code != 202) {
return R(r.decodeError());
}
if (auto location = Header("location") in r.headers) {
auto session = UploadSession!Transport(transport, *location);
return work(session);
}
return R(DecodingError(new Exception("Missing location header")));
});
}
Result!(UploadResult) chunkedUpload(Name name, Result!UploadResult delegate(ref ChunkedUploadSession!Transport) scope nothrow @safe work) const nothrow @safe {
alias R = Result!(UploadResult);
return transport
.post(Routes.upload(name), [Header("content-length"): "0"])
.then!((r) {
if (r.code != 202) {
return R(r.decodeError());
}
if (auto location = Header("location") in r.headers) {
auto session = ChunkedUploadSession!Transport(transport, *location);
return work(session);
}
return R(DecodingError(new Exception("Missing location header")));
});
}
Result!(ManifestResult) storeManifest(Name name, Reference reference, Manifest manifest) const nothrow @trusted {
alias R = Result!(ManifestResult);
auto encoded = manifest.toJsonBytes;
if (encoded._is!Exception) {
return R(DecodingError(encoded.trustedGet!Exception));
}
auto bytes = encoded.trustedGet!(ubyte[]);
return transport
.put(Routes.manifest(name, reference), bytes, [Header("content-type"): manifest.mediaType])
.then!((r) @safe nothrow {
if (r.code != 201) {
return R(r.decodeError());
}
return r.decode!(ManifestResult).then!((ManifestResult m) {
auto reqDigest = Hasher!"sha256".toDigest(bytes);
if (m.digest != reqDigest) {
return R(DecodingError(new Exception("Digest invalid")));
}
return R(m);
});
});
}
}
struct UploadSession(Transport) {
private {
Transport transport;
string location;
}
Result!(UploadResult) upload(T)(Blob!T blob) const nothrow @safe {
alias R = Result!(UploadResult);
return transport
.put(Routes.upload(location, blob.digest), blob.bytes, [Header("content-type"): "application/octet-stream"])
.then!((r) {
if (r.code != 201)
return R(r.decode!HttpError);
auto result = r.decode!UploadResult.then!((UploadResult r){
r.size = blob.bytes.length;
return r;
});
return R(result);
});
}
}
struct ChunkedUploadSession(Transport) {
private {
Transport transport;
string location;
size_t offset;
Hasher!"sha256" hasher;
}
Result!(ChunkResult) upload(T)(Chunk!T chunk) nothrow @safe {
import mir.format : text;
auto range = text("bytes=", offset, "-", offset + chunk.bytes.length);
auto headers = [Header("content-type"): "application/octet-stream", Header("range"): range, Header("content-length"): text(chunk.bytes.length)];
alias R = Result!(ChunkResult);
hasher.put(chunk.bytes);
return transport
.patch(Routes.upload(location, chunk.digest), chunk.bytes, headers)
.then!((r) {
if (r.code != 202)
return R(r.decode!HttpError);
return r.decode!ChunkResult.then!((ChunkResult result) {
this.location = result.location;
this.offset += chunk.bytes.length;
return R(result);
});
});
}
Nullable!(ErrorTypes) cancel() nothrow @safe {
// TODO: implement cancel
return typeof(return).init;
}
Result!(UploadResult) finish() nothrow @safe {
alias R = Result!(UploadResult);
auto digest = hasher.toDigest();
ubyte[] bytes;
return transport
.put(Routes.upload(location, digest), bytes)
.then!((r) {
if (r.code != 201)
return R(r.decode!HttpError);
auto result = r.decode!UploadResult.then!((UploadResult r){
r.size = offset;
return r;
});
return R(result);
});
}
}
struct PushSession(Client) {
private {
Client client;
Name name;
Tag tag;
Manifest.Config config;
Manifest.Layer[] layers;
}
Result!(Manifest.Layer) pushLayer(T)(AnnotatedLayer!T layer) @safe nothrow {
return client.upload(name, layer.blob)
.then!((UploadResult blobResult) nothrow {
auto layer = Manifest.Layer(layer.mediaType, blobResult.digest, blobResult.size, layer.annotations);
layers ~= layer;
return layer;
});
}
Nullable!(ErrorTypes) cancel() @safe nothrow {
// TODO implement
return typeof(return).init;
}
Result!(PushResult) finish(string[string] annotations = null) @safe nothrow {
import std.datetime.systime : Clock;
import std.datetime.timezone : UTC;
import std.exception : assumeWontThrow;
annotations.require(Annotations.imageCreated, Clock.currTime(UTC()).toISOExtString).assumeWontThrow;
auto manifest = Manifest(2, manifestContentType, layers, annotations, config);
return client.storeManifest(name, Reference(tag), manifest)
.then!((ManifestResult r){
return PushResult(name, tag, r.location, r.digest, manifest);
});
}
}
struct PullSession(Client) {
private {
Client client;
Name name;
Reference reference;
Manifest manifest;
}
Result!(BlobResponse!(Client.Transport.ByteStream)) pullLayer(const Manifest.Layer layer) const @safe nothrow {
return client.getBlob(name, layer.digest);
}
const(Manifest.Layer)[] layers() const @safe nothrow {
return manifest.layers;
}
}
struct BlobResponse(ByteStream) {
string[Header] headers;
ByteStream body;
}
struct ManifestResult {
string[Header] headers;
@Header("location")
string location;
@Header("docker-content-digest")
Digest digest;
}
struct UploadResult {
string[Header] headers;
@Header("location")
string location;
@Header("docker-content-digest")
Digest digest;
size_t size;
}
struct ChunkResult {
string[Header] headers;
@Header("location")
string location;
}
struct PushResult {
Name name;
Tag tag;
string location;
Digest digest;
Manifest manifest;
}
@reflectErr
struct HttpError {
size_t code;
ApiError[] errors;
string[Header] headers;
}
@reflectErr
struct DecodingError {
Exception exception;
}
struct Hasher(string algorithm) {
import std.digest.sha : SHA256, toHexString, LetterCase;
static if (algorithm == "sha256")
private SHA256 hasher;
else static assert("Algorithm \""~algorithm~"\" not supported");
void put(T)(T bytes) {
hasher.put(bytes);
}
Digest toDigest() {
import mir.format : text;
auto hash = hasher.finish[].toHexString!(LetterCase.lower).text();
return Digest(algorithm, hash);
}
static Digest toDigest(T)(T input) {
typeof(this) hasher;
hasher.put(input);
return hasher.toDigest();
}
}
import std.meta : AliasSeq;
alias ErrorTypes = AliasSeq!(TransportError, HttpError, DecodingError);
alias Result(T) = Variant!(T, ErrorTypes);
alias then(alias fun) = match!(some!(fun), none!"a");
private template decode(T) {
alias R = Variant!(T, HttpError, DecodingError);
R decode(P)(ref P p) nothrow @trusted {
import std.traits : getSymbolsByUDA, getUDAs;
try {
if (p.code >= 200 && p.code < 400) {
T t;
static if (__traits(hasMember, T, "body")) {
static if (is(typeof(T.body) == typeof(p.byteStream))) {
t.body = p.byteStream;
} else {
t.body = p.deserializeJson!(typeof(t.body));
}
}
static foreach(symbol; getSymbolsByUDA!(T, Header)) {{
enum udas = getUDAs!(symbol, Header);
static assert(udas.length == 1);
alias TargetType = typeof(symbol);
static if (is(TargetType == Digest)) {
auto result = Digest.from(p.headers[udas[0]]);
auto err = result.match!((Digest digest) {
__traits(getMember, t, __traits(identifier, symbol)) = digest;
return null;
}, (StringError e) {
return DecodingError(new Exception(e.message));
});
if (!err.isNull) {
return R(err.get());
}
} else {
__traits(getMember, t, __traits(identifier, symbol)) = p.headers[udas[0]];
}
}}
static if (__traits(hasMember, T, "headers"))
t.headers = p.headers;
return R(t);
}
} catch (Exception e) {
return R(DecodingError(e));
}
return p.decodeError().match!(a => R(a));
}
}
private Variant!(HttpError, DecodingError) decodeError(P)(ref P p) nothrow @trusted {
alias R = Variant!(HttpError, DecodingError);
try {
HttpError err;
err.code = p.code;
if (p.length > 0) {
static struct Error {
ApiError[] errors;
}
import std.algorithm : startsWith;
if (p.headers[Header("content-type")].startsWith("application/json"))
err.errors = p.deserializeJson!Error.errors;
}
err.headers = p.headers;
return R(err);
} catch (Exception e) {
return R(DecodingError(e));
}
}
private Digest digest(T)(Blob!T blob) nothrow @safe pure if (!isChunked!T) {
return Hasher!"sha256".toDigest(blob.bytes);
}
private Digest digest(T)(Chunk!T chunk) nothrow @safe pure {
return Hasher!"sha256".toDigest(chunk.bytes);
}
private struct Routes {
import mir.format : text;
static string manifest(Name name, Reference reference) @trusted pure nothrow {
return text("/v2/", name.value, "/manifests/", reference.match!(r => r.toString));
}
static string blob(Name name, Digest digest) @trusted pure nothrow {
return text("/v2/", name.value, "/blobs/", digest);
}
static string upload(Name name) @trusted pure nothrow {
return text("/v2/", name.value, "/blobs/uploads/");
}
static string upload(string location, Digest digest) @trusted pure nothrow {
import std.algorithm : canFind, find;
import std.string;
if (location.representation.find('?').length == 0)
return text(location, "?digest=", digest);
return text(location, "&digest=", digest);
}
static string upload(Name name, Digest digest) @trusted pure nothrow {
auto location = Routes.upload(name);
return Routes.upload(location, digest);
}
}