origincloud-pvs 0.80.0

The Origin Cloud persistent volume service (PVS) API: volumes, snapshots and storage classes.
Documentation
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
//! The generated clients send each method as its HTTP binding says.

use std::sync::{Arc, Mutex};

use fake_server::{FakeServer, Received, Response};
use origincloud_core::protobuf::FieldMask;
use origincloud_core::{AccessToken, Client};
use origincloud_pvs::v1beta1::{
    CreateVolumeRequest, DeleteVolumeRequest, GetVolumeRequest, ImportVolumeRequest,
    ListStorageClassesRequest, ListVolumesRequest, StorageClassClient, UpdateVolumeRequest, Volume,
    VolumeClient,
};
use serde_json::{Value, json};

const ZONE: &str = "projects/p/zones/z";

fn client(server: &FakeServer) -> Client {
    Client::builder()
        .endpoint(server.url())
        .credentials(AccessToken::new("t"))
        .build()
        .unwrap()
}

/// A client whose calls are recorded and answered with `answer`.
async fn recording(answer: &'static str) -> (FakeServer, Client, Arc<Mutex<Vec<Received>>>) {
    let calls = Arc::new(Mutex::new(Vec::new()));
    let log = Arc::clone(&calls);
    let server = FakeServer::start(move |r| {
        log.lock().unwrap().push(r);
        async move { Response::json(answer) }
    })
    .await;
    let client = client(&server);
    (server, client, calls)
}

fn is_uuid(s: &str) -> bool {
    s.len() == 36 && s.chars().all(|c| c.is_ascii_hexdigit() || c == '-')
}

fn json_of(r: &Received) -> Value {
    serde_json::from_slice(&r.body).unwrap()
}

#[tokio::test]
async fn each_binding_is_sent_as_its_http_rule_says() {
    let (_server, client, calls) =
        recording(r#"{"name":"projects/p/zones/z/operations/op-1"}"#).await;
    let volumes = VolumeClient::new(&client);
    let name = format!("{ZONE}/volumes/vol-1");

    volumes
        .list_volumes(ListVolumesRequest {
            parent: ZONE.to_owned(),
            page_size: 5,
            page_token: "next".to_owned(),
        })
        .await
        .unwrap();
    volumes
        .update_volume(UpdateVolumeRequest {
            volume: Some(Volume {
                name: name.clone(),
                size_gib: 2,
                ..Default::default()
            }),
            update_mask: Some(FieldMask {
                paths: vec!["size_gib".to_owned(), "tags".to_owned()],
            }),
            ..Default::default()
        })
        .await
        .unwrap();
    volumes
        .import_volume(ImportVolumeRequest {
            parent: ZONE.to_owned(),
            volume: Some(Volume {
                size_gib: 3,
                ..Default::default()
            }),
            source_url: "https://example.com/disk.img".to_owned(),
            request_id: "given".to_owned(),
            ..Default::default()
        })
        .await
        .unwrap();
    volumes
        .delete_volume(DeleteVolumeRequest {
            name: name.clone(),
            ..Default::default()
        })
        .await
        .unwrap();

    let calls = calls.lock().unwrap();
    let [list, update, imported, deleted] = calls.as_slice() else {
        panic!("{calls:?}");
    };
    assert_eq!(list.method, "GET");
    assert_eq!(list.path, format!("/v1beta1/{ZONE}/volumes"));
    assert!(list.body.is_empty());
    assert_eq!(
        list.query_pairs(),
        [
            ("pageSize".to_owned(), "5".to_owned()),
            ("pageToken".to_owned(), "next".to_owned())
        ]
    );

    // body: "volume": the volume is the body, the rest goes in the query.
    assert_eq!(update.method, "PATCH");
    assert_eq!(update.path, format!("/v1beta1/{name}"));
    assert_eq!(json_of(update), json!({"name": name, "sizeGib": 2}));
    assert_eq!(update.query_values("updateMask"), ["sizeGib,tags"]);
    assert!(is_uuid(&update.query_values("requestId")[0]), "{update:?}");

    // body: "*": everything is the body, nothing the query.
    assert_eq!(imported.method, "POST");
    assert_eq!(imported.path, format!("/v1beta1/{ZONE}/volumes:import"));
    assert!(imported.query.is_empty());
    assert_eq!(
        json_of(imported),
        json!({"parent": ZONE, "volume": {"sizeGib": 3}, "sourceUrl": "https://example.com/disk.img", "requestId": "given"})
    );

    assert_eq!(deleted.method, "DELETE");
    assert_eq!(deleted.path, format!("/v1beta1/{name}"));
    assert!(deleted.body.is_empty());
    assert!(
        is_uuid(&deleted.query_values("requestId")[0]),
        "{deleted:?}"
    );
}

#[tokio::test]
async fn an_empty_request_id_is_filled_in_and_a_given_one_kept() {
    let (_server, client, calls) =
        recording(r#"{"name":"projects/p/zones/z/operations/op-1"}"#).await;
    let volumes = VolumeClient::new(&client);
    let request = CreateVolumeRequest {
        parent: ZONE.to_owned(),
        volume: Some(Volume {
            size_gib: 1,
            ..Default::default()
        }),
        ..Default::default()
    };

    volumes.create_volume(request.clone()).await.unwrap();
    volumes.create_volume(request).await.unwrap();
    let calls = calls.lock().unwrap();
    let first = &calls[0].query_values("requestId")[0];
    let second = &calls[1].query_values("requestId")[0];
    assert!(is_uuid(first) && is_uuid(second), "{first} {second}");
    assert_ne!(first, second, "each call gets its own request id");
    assert_eq!(json_of(&calls[0]), json!({"sizeGib": 1}));
}

/// A create sent again because the API refused its consistency token
/// carries the same request id, so it can't create twice.
#[tokio::test]
async fn a_create_sent_again_for_a_refused_token_keeps_its_request_id() {
    let calls = Arc::new(Mutex::new(Vec::<Received>::new()));
    let log = Arc::clone(&calls);
    let server = FakeServer::start(move |r| {
        let refused = r.header("origin-consistency-token").is_some();
        log.lock().unwrap().push(r);
        async move {
            if refused {
                Response::json(r#"{"error":{"code":400,"status":"INVALID_ARGUMENT","message":"the Origin-Consistency-Token header must be a token a response of this API carried"}}"#)
                    .with_status(400)
            } else {
                Response::json(r#"{"name":"projects/p/zones/z/operations/op-1"}"#)
            }
        }
    })
    .await;
    let client = client(&server);
    client.set_consistency_token("v1.from-another-api");

    VolumeClient::new(&client)
        .create_volume(CreateVolumeRequest {
            parent: ZONE.to_owned(),
            ..Default::default()
        })
        .await
        .unwrap();
    let calls = calls.lock().unwrap();
    assert_eq!(calls.len(), 2);
    let first = &calls[0].query_values("requestId")[0];
    assert!(is_uuid(first), "{first}");
    assert_eq!(&calls[1].query_values("requestId")[0], first);
    assert_eq!(calls[1].header("origin-consistency-token"), None);
}

#[tokio::test]
async fn a_create_without_a_volume_sends_an_empty_one() {
    let (_server, client, calls) =
        recording(r#"{"name":"projects/p/zones/z/operations/op-1"}"#).await;
    VolumeClient::new(&client)
        .create_volume(CreateVolumeRequest {
            parent: ZONE.to_owned(),
            ..Default::default()
        })
        .await
        .unwrap();
    assert_eq!(calls.lock().unwrap()[0].text(), "{}");
}

#[tokio::test]
async fn a_name_is_escaped_once() {
    let (_server, client, calls) = recording("{}").await;
    VolumeClient::new(&client)
        .get_volume(GetVolumeRequest {
            name: "projects/a b%/zones/z/volumes/v".to_owned(),
        })
        .await
        .unwrap();
    assert_eq!(
        calls.lock().unwrap()[0].path,
        "/v1beta1/projects/a%20b%25/zones/z/volumes/v"
    );
}

#[tokio::test]
async fn a_name_of_the_wrong_form_is_refused_before_sending() {
    let (_server, client, calls) = recording("{}").await;
    let err = VolumeClient::new(&client)
        .get_volume(GetVolumeRequest {
            name: "vol-1".to_owned(),
        })
        .await
        .unwrap_err();
    assert!(
        err.to_string()
            .contains("name must have the form projects/*/zones/*/volumes/*"),
        "{err}"
    );
    assert!(calls.lock().unwrap().is_empty());
}

/// A full resource name of the client's own service is sent as its
/// relative name: the same request as the relative name makes.
#[tokio::test]
async fn a_full_name_of_the_service_is_sent_as_its_relative_name() {
    let (_server, client, calls) =
        recording(r#"{"name":"projects/p/zones/z/operations/op-1"}"#).await;
    let volumes = VolumeClient::new(&client);
    let relative = format!("{ZONE}/volumes/vol-1");
    for name in [
        relative.clone(),
        format!("//pvs.origincloudapis.eu/{relative}"),
    ] {
        let parent = name.strip_suffix("/volumes/vol-1").unwrap().to_owned();
        volumes
            .get_volume(GetVolumeRequest { name: name.clone() })
            .await
            .unwrap();
        volumes
            .list_volumes(ListVolumesRequest {
                parent,
                ..Default::default()
            })
            .await
            .unwrap();
        volumes
            .delete_volume(DeleteVolumeRequest {
                name,
                request_id: "given".to_owned(),
            })
            .await
            .unwrap();
    }
    let calls = calls.lock().unwrap();
    let sent: Vec<(String, String, String)> = calls
        .iter()
        .map(|r| (r.method.clone(), r.path.clone(), r.query.clone()))
        .collect();
    let [get, list, delete] = [
        ("GET", format!("/v1beta1/{relative}"), ""),
        ("GET", format!("/v1beta1/{ZONE}/volumes"), ""),
        ("DELETE", format!("/v1beta1/{relative}"), "requestId=given"),
    ]
    .map(|(m, p, q)| (m.to_owned(), p, q.to_owned()));
    assert_eq!(
        sent,
        [get.clone(), list.clone(), delete.clone(), get, list, delete]
    );
}

/// A full name in a path field that the body also carries, as an update's
/// resource does, is sent as the relative name in both: the same request.
#[tokio::test]
async fn a_full_name_in_the_body_s_resource_is_sent_as_its_relative_name() {
    let (_server, client, calls) =
        recording(r#"{"name":"projects/p/zones/z/operations/op-1"}"#).await;
    let volumes = VolumeClient::new(&client);
    let relative = format!("{ZONE}/volumes/vol-1");
    for name in [
        relative.clone(),
        format!("//pvs.origincloudapis.eu/{relative}"),
    ] {
        volumes
            .update_volume(UpdateVolumeRequest {
                volume: Some(Volume {
                    name,
                    size_gib: 2,
                    ..Default::default()
                }),
                request_id: "given".to_owned(),
                ..Default::default()
            })
            .await
            .unwrap();
        volumes
            .import_volume(ImportVolumeRequest {
                parent: format!("//pvs.origincloudapis.eu/{ZONE}"),
                request_id: "given".to_owned(),
                ..Default::default()
            })
            .await
            .unwrap();
    }
    let calls = calls.lock().unwrap();
    let [update, import, full_update, full_import] = calls.as_slice() else {
        panic!("{calls:?}");
    };
    assert_eq!(
        json_of(full_update),
        json!({"name": relative, "sizeGib": 2})
    );
    for (a, b) in [(update, full_update), (import, full_import)] {
        assert_eq!(
            (&a.method, &a.path, &a.query, &a.body),
            (&b.method, &b.path, &b.query, &b.body)
        );
    }
    assert_eq!(json_of(full_import)["parent"], json!(ZONE));
}

/// A full name of another service, or one that isn't a valid full name,
/// is refused before anything is sent, naming the field and the host the
/// client calls.
#[tokio::test]
async fn a_name_of_another_service_is_refused_before_sending() {
    let (_server, client, calls) = recording("{}").await;
    let volumes = VolumeClient::new(&client);
    for (name, says) in [
        (
            "//compute.origincloudapis.eu/projects/p/zones/z/volumes/vol-1",
            "name must be a name on pvs.origincloudapis.eu, got",
        ),
        (
            "//pvs.eu-central1-az1.origincloudapis.eu/projects/p/zones/z/volumes/vol-1",
            "the service's global host, pvs.origincloudapis.eu",
        ),
        (
            "//pvs.origincloudapis.eu/v1beta1/projects/p/zones/z/volumes/vol-1",
            "carries the API version \"v1beta1\"",
        ),
        ("urn:origincloud:storage:o:p:volume:vol-1", "is a URN"),
        (
            "//pvs.origincloudapis.eu/projects/p/zones/z/volumes/vol-1/",
            "ends with a '/'",
        ),
        // A full name of the service, but not of a volume.
        (
            "//pvs.origincloudapis.eu/projects/p/zones/z/snapshots/s-1",
            "name must have the form projects/*/zones/*/volumes/*",
        ),
    ] {
        let err = volumes
            .get_volume(GetVolumeRequest {
                name: name.to_owned(),
            })
            .await
            .unwrap_err();
        assert!(
            matches!(err, origincloud_core::Error::InvalidRequest(_)),
            "{name}: {err:?}"
        );
        assert!(err.to_string().contains(says), "{name}: {err}");
    }
    let err = volumes
        .list_volumes(ListVolumesRequest {
            parent: "//resourcemanager.origincloudapis.eu/projects/p".to_owned(),
            ..Default::default()
        })
        .await
        .unwrap_err();
    assert!(
        err.to_string()
            .contains("parent must be a name on pvs.origincloudapis.eu"),
        "{err}"
    );
    assert!(calls.lock().unwrap().is_empty());
}

#[tokio::test]
async fn a_response_is_read_with_proto3_json() {
    let (_server, client, _) = recording(
        r#"{"name":"projects/p/zones/z/volumes/vol-1","sizeGib":10,"state":"AVAILABLE","resizeState":"RESIZE_COMPLETED","tags":{"origin:name":"data"},"aFieldFromANewerApi":1,"creator":"user:u1"}"#,
    )
    .await;
    let volume = VolumeClient::new(&client)
        .get_volume(GetVolumeRequest {
            name: format!("{ZONE}/volumes/vol-1"),
        })
        .await
        .unwrap();
    assert_eq!(volume.size_gib, 10);
    assert_eq!(
        volume.state(),
        origincloud_pvs::v1beta1::volume::State::Available
    );
    assert_eq!(
        volume.resize_state(),
        origincloud_pvs::v1beta1::volume::ResizeState::ResizeCompleted
    );
    assert_eq!(volume.tags["origin:name"], "data");
    assert_eq!(volume.creator, "user:u1");
}

#[tokio::test]
async fn all_volumes_follows_the_pages() {
    let server = FakeServer::start(|r| async move {
        let token = r.query_values("pageToken").pop().unwrap_or_default();
        Response::json(match token.as_str() {
            "" => format!(
                r#"{{"volumes":[{{"name":"{ZONE}/volumes/vol-1"}},{{"name":"{ZONE}/volumes/vol-2"}}],"nextPageToken":"p2"}}"#
            ),
            "p2" => format!(r#"{{"volumes":[{{"name":"{ZONE}/volumes/vol-3"}}]}}"#),
            other => panic!("page token {other}"),
        })
    })
    .await;
    let client = client(&server);
    let mut pages = VolumeClient::new(&client).all_volumes(ListVolumesRequest {
        parent: ZONE.to_owned(),
        ..Default::default()
    });
    let mut names = Vec::new();
    while let Some(volume) = pages.next().await {
        names.push(volume.unwrap().name.rsplit('/').next().unwrap().to_owned());
    }
    assert_eq!(names, ["vol-1", "vol-2", "vol-3"]);
}

#[tokio::test]
async fn a_service_without_a_parent_is_sent_without_one() {
    let (_server, client, calls) =
        recording(r#"{"storageClasses":[{"name":"storageClasses/gp1"}]}"#).await;
    let classes = StorageClassClient::new(&client)
        .list_storage_classes(ListStorageClassesRequest::default())
        .await
        .unwrap();
    assert_eq!(classes.storage_classes[0].name, "storageClasses/gp1");
    let calls = calls.lock().unwrap();
    assert_eq!(calls[0].method, "GET");
    assert_eq!(calls[0].path, "/v1beta1/storageClasses");
}

#[test]
fn the_clients_use_the_service_s_regional_host() {
    let client = Client::builder()
        .credentials(AccessToken::new("t"))
        .region("eu-central1")
        .build()
        .unwrap();
    let volumes = VolumeClient::new(&client);
    assert_eq!(
        volumes.service().base_url().unwrap().as_str(),
        "https://pvs.eu-central1.origincloudapis.eu/"
    );
}

/// `with_options` bounds the attempts of the calls made through the client
/// it returns; the client it came from retries as before.
#[tokio::test]
async fn with_options_turns_retries_off_for_its_calls() {
    let calls = Arc::new(Mutex::new(0));
    let counted = Arc::clone(&calls);
    let server = FakeServer::start(move |_| {
        *counted.lock().unwrap() += 1;
        async {
            Response::json(r#"{"error":{"code":503,"status":"UNAVAILABLE","details":[{"@type":"type.googleapis.com/google.rpc.RetryInfo","retryDelay":"0.010s"}]}}"#)
                .with_status(503)
        }
    })
    .await;
    let client = Client::builder()
        .endpoint(server.url())
        .credentials(AccessToken::new("t"))
        .max_attempts(3)
        .build()
        .unwrap();
    let volumes = VolumeClient::new(&client);
    let create = || CreateVolumeRequest {
        parent: ZONE.to_owned(),
        ..Default::default()
    };

    let once = volumes.with_options(origincloud_core::CallOptions::new().max_attempts(1));
    once.create_volume(create()).await.unwrap_err();
    assert_eq!(std::mem::take(&mut *calls.lock().unwrap()), 1);

    volumes.create_volume(create()).await.unwrap_err();
    assert_eq!(*calls.lock().unwrap(), 3);
}