spiral-sdk 0.1.10

Rust SDK for Spiral resource and table APIs
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
// Generated by tools/service-contracts/rust.py. Do not edit.
#![doc = "Generated transport-independent contract objects."]

use std::collections::BTreeMap;
use std::error::Error as StdError;
use std::fmt::{self, Display, Formatter};

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;
use spiral_contract::error::{ErrorEnvelope, ServiceError};
use spiral_contract::safelong::{SafeLong, SafeUnsignedLong};
use spiral_contract::strict::{DeserializeStrict, Strict};
use uuid::Uuid;

/// Counters of one execution of an Arbor Table scan, as the executor reported them. Fragments and
/// files are Arbor concepts, so a scan of another table format takes its own arm. `resourceId` and
/// `versionId` of the record name the Table version that was read. An execution that ended before
/// its last row (`finished` false) counts only the splits that it read to their end.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArborScanUsage {
    /// Contract field filesConsidered.
    #[serde(rename = "filesConsidered")]
    pub files_considered: SafeUnsignedLong,
    /// Contract field filesPruned.
    #[serde(rename = "filesPruned")]
    pub files_pruned: SafeUnsignedLong,
    /// Contract field finished.
    #[serde(rename = "finished")]
    pub finished: bool,
    /// Contract field fragmentsConsidered.
    #[serde(rename = "fragmentsConsidered")]
    pub fragments_considered: SafeUnsignedLong,
    /// Contract field fragmentsPruned.
    #[serde(rename = "fragmentsPruned")]
    pub fragments_pruned: SafeUnsignedLong,
    /// Contract field outputRows.
    #[serde(rename = "outputRows")]
    pub output_rows: SafeUnsignedLong,
    /// Contract field storage.
    #[serde(rename = "storage")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub storage: Option<StorageReads>,
}
impl<'de> DeserializeStrict<'de> for ArborScanUsage {
    fn deserialize_strict<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct __Wire {
            #[serde(rename = "filesConsidered")]
            files_considered: Strict<SafeUnsignedLong>,
            #[serde(rename = "filesPruned")]
            files_pruned: Strict<SafeUnsignedLong>,
            #[serde(rename = "finished")]
            finished: Strict<bool>,
            #[serde(rename = "fragmentsConsidered")]
            fragments_considered: Strict<SafeUnsignedLong>,
            #[serde(rename = "fragmentsPruned")]
            fragments_pruned: Strict<SafeUnsignedLong>,
            #[serde(rename = "outputRows")]
            output_rows: Strict<SafeUnsignedLong>,
            #[serde(rename = "storage")]
            #[serde(default)]
            storage: Strict<Option<StorageReads>>,
        }
        let wire = __Wire::deserialize(deserializer)?;
        Ok(Self {
            files_considered: wire.files_considered.0,
            files_pruned: wire.files_pruned.0,
            finished: wire.finished.0,
            fragments_considered: wire.fragments_considered.0,
            fragments_pruned: wire.fragments_pruned.0,
            output_rows: wire.output_rows.0,
            storage: wire.storage.0,
        })
    }
}

/// Identifier of the project whose usage a request reports.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ProjectId(pub String);
impl std::fmt::Display for ProjectId {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(formatter)
    }
}
impl<'de> DeserializeStrict<'de> for ProjectId {
    fn deserialize_strict<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        Ok(Self(Strict::<String>::deserialize(deserializer)?.0))
    }
}

/// At most 1,000 records of one project. The service drops and counts a record that occurred more
/// than 30 days before it receives the request, or more than five minutes after.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReportUsageRecordsRequest {
    /// Contract field records.
    #[serde(rename = "records")]
    pub records: Vec<UsageRecord>,
}
impl<'de> DeserializeStrict<'de> for ReportUsageRecordsRequest {
    fn deserialize_strict<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct __Wire {
            #[serde(rename = "records")]
            records: Strict<Vec<UsageRecord>>,
        }
        let wire = __Wire::deserialize(deserializer)?;
        Ok(Self {
            records: wire.records.0,
        })
    }
}

/// Events scoped to exactly one legacy table or project. The service rejects requests that provide
/// both scope identifiers or neither identifier.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReportUsageRequest {
    /// Contract field events.
    #[serde(rename = "events")]
    pub events: Vec<UsageEvent>,
    /// Contract field projectId.
    #[serde(rename = "projectId")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project_id: Option<String>,
    /// Contract field tableId.
    #[serde(rename = "tableId")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub table_id: Option<String>,
}
impl<'de> DeserializeStrict<'de> for ReportUsageRequest {
    fn deserialize_strict<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct __Wire {
            #[serde(rename = "events")]
            events: Strict<Vec<UsageEvent>>,
            #[serde(rename = "projectId")]
            #[serde(default)]
            project_id: Strict<Option<String>>,
            #[serde(rename = "tableId")]
            #[serde(default)]
            table_id: Strict<Option<String>>,
        }
        let wire = __Wire::deserialize(deserializer)?;
        Ok(Self {
            events: wire.events.0,
            project_id: wire.project_id.0,
            table_id: wire.table_id.0,
        })
    }
}

/// Whether the storage counters include every read of the scan or only some. A scan reads storage
/// in two ways. It reads some objects itself. It reads payload files through a file reader that all
/// scans in the process share, and that reader does not know which scan asked for which bytes.
/// `complete` means the counters include both, so `bytes` is everything the scan read. `direct`
/// means the counters include only the reads that the scan made itself. Reads through the shared
/// reader are missing, so the counters are a lower bound. Do not add `direct` counters to
/// `complete` counters.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum StorageReadScope {
    /// A known contract value.
    Complete,
    /// A known contract value.
    Direct,
    /// A value introduced by a newer server.
    Unknown(String),
}
impl Serialize for StorageReadScope {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(match self {
            Self::Complete => "complete",
            Self::Direct => "direct",
            Self::Unknown(value) => value,
        })
    }
}
impl<'de> Deserialize<'de> for StorageReadScope {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        Ok(match String::deserialize(deserializer)?.as_str() {
            "complete" => Self::Complete,
            "direct" => Self::Direct,
            value => Self::Unknown(value.to_owned()),
        })
    }
}
impl<'de> DeserializeStrict<'de> for StorageReadScope {
    fn deserialize_strict<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        enum __Known {
            #[serde(rename = "complete")]
            Complete,
            #[serde(rename = "direct")]
            Direct,
        }
        Ok(match __Known::deserialize(deserializer)? {
            __Known::Complete => Self::Complete,
            __Known::Direct => Self::Direct,
        })
    }
}

/// Successful object reads of one scan execution. `scope` says which of the scan's reads the
/// counters include.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StorageReads {
    /// Contract field bytes.
    #[serde(rename = "bytes")]
    pub bytes: SafeUnsignedLong,
    /// Contract field readTimeNs.
    #[serde(rename = "readTimeNs")]
    pub read_time_ns: SafeUnsignedLong,
    /// Contract field requests.
    #[serde(rename = "requests")]
    pub requests: SafeUnsignedLong,
    /// Contract field scope.
    #[serde(rename = "scope")]
    pub scope: StorageReadScope,
}
impl<'de> DeserializeStrict<'de> for StorageReads {
    fn deserialize_strict<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct __Wire {
            #[serde(rename = "bytes")]
            bytes: Strict<SafeUnsignedLong>,
            #[serde(rename = "readTimeNs")]
            read_time_ns: Strict<SafeUnsignedLong>,
            #[serde(rename = "requests")]
            requests: Strict<SafeUnsignedLong>,
            #[serde(rename = "scope")]
            scope: Strict<StorageReadScope>,
        }
        let wire = __Wire::deserialize(deserializer)?;
        Ok(Self {
            bytes: wire.bytes.0,
            read_time_ns: wire.read_time_ns.0,
            requests: wire.requests.0,
            scope: wire.scope.0,
        })
    }
}

/// One schema-agnostic metering event. The server overwrites project_id and org_id with
/// authoritative values before delivery.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct UsageEvent {
    /// Contract field eventType.
    #[serde(rename = "eventType")]
    pub event_type: String,
    /// Contract field properties.
    #[serde(rename = "properties")]
    pub properties: BTreeMap<String, Value>,
}
impl<'de> DeserializeStrict<'de> for UsageEvent {
    fn deserialize_strict<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct __Wire {
            #[serde(rename = "eventType")]
            event_type: Strict<String>,
            #[serde(rename = "properties")]
            properties: Strict<BTreeMap<String, Value>>,
        }
        let wire = __Wire::deserialize(deserializer)?;
        Ok(Self {
            event_type: wire.event_type.0,
            properties: wire.properties.0,
        })
    }
}

/// What a record measured. The arm name is the versioned schema of the measurement. A change in
/// meaning takes a new arm, such as `arborScanV2`, and never changes an existing one. A server
/// rejects an arm that it does not know, so a server that accepts a new arm deploys before a host
/// that sends it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum UsageMeasurement {
    /// A known union arm.
    ArborScanV1(ArborScanUsage),
    /// An unknown discriminator and its complete wire object.
    Unknown { tag: String, value: Value },
}
impl Serialize for UsageMeasurement {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::ArborScanV1(value) => {
                let mut object = serde_json::Map::new();
                object.insert("type".into(), Value::String("arborScanV1".into()));
                object.insert(
                    "arborScanV1".into(),
                    serde_json::to_value(value).map_err(serde::ser::Error::custom)?,
                );
                Value::Object(object).serialize(serializer)
            }
            Self::Unknown { tag, value } => {
                if value.get("type").and_then(Value::as_str) != Some(tag.as_str()) {
                    return Err(serde::ser::Error::custom(
                        "unknown union discriminator mismatch",
                    ));
                }
                value.serialize(serializer)
            }
        }
    }
}
impl<'de> Deserialize<'de> for UsageMeasurement {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = Value::deserialize(deserializer)?;
        let tag = value
            .get("type")
            .and_then(Value::as_str)
            .ok_or_else(|| serde::de::Error::custom("union requires type"))?;
        match tag {
            "arborScanV1" => Ok(Self::ArborScanV1(
                serde_json::from_value(
                    value
                        .get("arborScanV1")
                        .cloned()
                        .ok_or_else(|| serde::de::Error::custom("union requires matching arm"))?,
                )
                .map_err(serde::de::Error::custom)?,
            )),
            tag => Ok(Self::Unknown {
                tag: tag.to_owned(),
                value,
            }),
        }
    }
}
impl<'de> DeserializeStrict<'de> for UsageMeasurement {
    fn deserialize_strict<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        enum __Tag0 {
            #[serde(rename = "arborScanV1")]
            Value,
        }
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct __Arm0 {
            #[serde(rename = "type")]
            _tag: __Tag0,
            #[serde(rename = "arborScanV1")]
            value: Strict<ArborScanUsage>,
        }
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum __Known {
            ArborScanV1(Box<__Arm0>),
        }
        Ok(match __Known::deserialize(deserializer)? {
            __Known::ArborScanV1(arm) => Self::ArborScanV1(arm.value.0),
        })
    }
}

/// One raw measurement of work that a host ran for a project, such as one Table scan. A record
/// states what happened and never carries a price. The host sets `id` once and keeps it when it
/// sends the record again. `occurredAtMicros` is when the work ended, in microseconds since the
/// Unix epoch. `source` names the host software, for example `rust-sdk`, and `emitterVersion` its
/// version. The service adds the organization, the caller and the time it received the record.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct UsageRecord {
    /// Contract field emitterVersion.
    #[serde(rename = "emitterVersion")]
    pub emitter_version: String,
    /// Contract field id.
    #[serde(rename = "id")]
    pub id: Uuid,
    /// Contract field measurement.
    #[serde(rename = "measurement")]
    pub measurement: UsageMeasurement,
    /// Contract field occurredAtMicros.
    #[serde(rename = "occurredAtMicros")]
    pub occurred_at_micros: SafeLong,
    /// Contract field resourceId.
    #[serde(rename = "resourceId")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resource_id: Option<Uuid>,
    /// Contract field source.
    #[serde(rename = "source")]
    pub source: String,
    /// Contract field versionId.
    #[serde(rename = "versionId")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version_id: Option<Uuid>,
}
impl<'de> DeserializeStrict<'de> for UsageRecord {
    fn deserialize_strict<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct __Wire {
            #[serde(rename = "emitterVersion")]
            emitter_version: Strict<String>,
            #[serde(rename = "id")]
            id: Strict<Uuid>,
            #[serde(rename = "measurement")]
            measurement: Strict<UsageMeasurement>,
            #[serde(rename = "occurredAtMicros")]
            occurred_at_micros: Strict<SafeLong>,
            #[serde(rename = "resourceId")]
            #[serde(default)]
            resource_id: Strict<Option<Uuid>>,
            #[serde(rename = "source")]
            source: Strict<String>,
            #[serde(rename = "versionId")]
            #[serde(default)]
            version_id: Strict<Option<Uuid>>,
        }
        let wire = __Wire::deserialize(deserializer)?;
        Ok(Self {
            emitter_version: wire.emitter_version.0,
            id: wire.id.0,
            measurement: wire.measurement.0,
            occurred_at_micros: wire.occurred_at_micros.0,
            resource_id: wire.resource_id.0,
            source: wire.source.0,
            version_id: wire.version_id.0,
        })
    }
}

/// Typed errors declared by this service contract.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum UsageError {
    /// Usage:Conflict.
    Conflict { reason: String },
    /// Usage:InvalidArgument.
    InvalidArgument { reason: String },
    /// Usage:NotFound.
    NotFound { resource: String },
}
impl UsageError {
    /// HTTP status for this declared error.
    pub fn status(&self) -> u16 {
        match self {
            Self::Conflict { .. } => 409,
            Self::InvalidArgument { .. } => 400,
            Self::NotFound { .. } => 404,
        }
    }
    /// Serialize only contract-declared error parameters.
    pub fn envelope(&self, instance: String) -> ErrorEnvelope {
        match self {
            Self::Conflict { reason } => {
                let mut envelope = ErrorEnvelope::new("CONFLICT", "Usage:Conflict", instance);
                envelope
                    .parameters
                    .insert("reason".into(), reason.to_string());
                envelope
            }
            Self::InvalidArgument { reason } => {
                let mut envelope =
                    ErrorEnvelope::new("INVALID_ARGUMENT", "Usage:InvalidArgument", instance);
                envelope
                    .parameters
                    .insert("reason".into(), reason.to_string());
                envelope
            }
            Self::NotFound { resource } => {
                let mut envelope = ErrorEnvelope::new("NOT_FOUND", "Usage:NotFound", instance);
                envelope
                    .parameters
                    .insert("resource".into(), resource.to_string());
                envelope
            }
        }
    }
    /// Decode a declared error and its typed error parameters.
    pub fn decode_envelope(envelope: &ErrorEnvelope) -> Option<Self> {
        if envelope.error_instance_id.len() != 36
            || Uuid::parse_str(&envelope.error_instance_id).is_err()
        {
            return None;
        }
        match envelope.error_name.as_str() {
            "Usage:Conflict" => {
                if envelope.error_code != "CONFLICT" {
                    return None;
                }
                let reason = envelope.parameters.get("reason")?.clone();
                Some(Self::Conflict { reason })
            }
            "Usage:InvalidArgument" => {
                if envelope.error_code != "INVALID_ARGUMENT" {
                    return None;
                }
                let reason = envelope.parameters.get("reason")?.clone();
                Some(Self::InvalidArgument { reason })
            }
            "Usage:NotFound" => {
                if envelope.error_code != "NOT_FOUND" {
                    return None;
                }
                let resource = envelope.parameters.get("resource")?.clone();
                Some(Self::NotFound { resource })
            }
            _ => None,
        }
    }
}
impl Display for UsageError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Conflict { reason } => write!(formatter, "Usage:Conflict (reason: {})", reason),
            Self::InvalidArgument { reason } => {
                write!(formatter, "Usage:InvalidArgument (reason: {})", reason)
            }
            Self::NotFound { resource } => {
                write!(formatter, "Usage:NotFound (resource: {})", resource)
            }
        }
    }
}
impl StdError for UsageError {}
impl ServiceError for UsageError {
    fn to_envelope(&self, instance: String) -> ErrorEnvelope {
        Self::envelope(self, instance)
    }
    fn from_envelope(envelope: &ErrorEnvelope) -> Option<Self> {
        Self::decode_envelope(envelope)
    }
}