dropshot-api-manager-types 0.6.0

Core types for Dropshot's API manager
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
// Copyright 2026 Oxide Computer Company

use crate::{ManagedApiMetadata, Versions};
use camino::Utf8PathBuf;
use std::{fmt, ops::Deref};

/// Context for validation of OpenAPI documents.
pub struct ValidationContext<'a> {
    backend: &'a mut dyn ValidationBackend,
}

impl<'a> ValidationContext<'a> {
    /// Not part of the public API -- only called by the OpenAPI manager.
    #[doc(hidden)]
    pub fn new(backend: &'a mut dyn ValidationBackend) -> Self {
        Self { backend }
    }

    /// Retrieves the identifier of the API being validated.
    ///
    /// This identifier is set via the OpenAPI manager's `ManagedApiConfig`
    /// type.
    pub fn ident(&self) -> &ApiIdent {
        self.backend.ident()
    }

    /// Returns a descriptor for the API's file name.
    ///
    /// The file name can be used to identify the version of the API being
    /// validated.
    pub fn file_name(&self) -> &ApiSpecFileName {
        self.backend.file_name()
    }

    /// Returns true if this is the latest version of a versioned API, or if the
    /// API is lockstep.
    ///
    /// This is particularly useful for extra files which might not themselves
    /// be versioned. In that case, you may wish to only generate the extra file
    /// for the latest version.
    pub fn is_latest(&self) -> bool {
        self.backend.is_latest()
    }

    /// Returns whether this version is blessed, or None if this is not a
    /// versioned API.
    pub fn is_blessed(&self) -> Option<bool> {
        self.backend.is_blessed()
    }

    /// Retrieves the versioning strategy for this API.
    pub fn versions(&self) -> &Versions {
        self.backend.versions()
    }

    /// Retrieves the title of the API being validated.
    pub fn title(&self) -> &str {
        self.backend.title()
    }

    /// Retrieves optional metadata for the API being validated.
    pub fn metadata(&self) -> &ManagedApiMetadata {
        self.backend.metadata()
    }

    /// Reports a validation error.
    pub fn report_error(&mut self, error: anyhow::Error) {
        self.backend.report_error(error);
    }

    /// Records that the file has the given contents.
    ///
    /// In check mode, if the files differ, an error is logged.
    ///
    /// In generate mode, the file is overwritten with the given contents.
    ///
    /// The path is treated as relative to the root of the repository.
    pub fn record_file_contents(
        &mut self,
        path: impl Into<Utf8PathBuf>,
        contents: Vec<u8>,
    ) {
        self.backend.record_file_contents(path.into(), contents);
    }
}

/// The backend for validation.
///
/// Not part of the public API -- only implemented by the OpenAPI manager.
#[doc(hidden)]
pub trait ValidationBackend {
    fn ident(&self) -> &ApiIdent;
    fn file_name(&self) -> &ApiSpecFileName;
    fn versions(&self) -> &Versions;
    fn is_latest(&self) -> bool;
    fn is_blessed(&self) -> Option<bool>;
    fn title(&self) -> &str;
    fn metadata(&self) -> &ManagedApiMetadata;
    fn report_error(&mut self, error: anyhow::Error);
    fn record_file_contents(&mut self, path: Utf8PathBuf, contents: Vec<u8>);
}

/// A lockstep API spec filename.
///
/// Lockstep APIs have a single OpenAPI document with no versioning. The
/// filename is simply `{ident}.json`.
#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
pub struct LockstepApiSpecFileName {
    ident: ApiIdent,
}

impl LockstepApiSpecFileName {
    /// Creates a new lockstep API spec filename.
    pub fn new(ident: ApiIdent) -> Self {
        Self { ident }
    }

    /// Returns the API identifier.
    pub fn ident(&self) -> &ApiIdent {
        &self.ident
    }

    /// Returns the path of this file relative to the root of the OpenAPI
    /// documents.
    pub fn path(&self) -> Utf8PathBuf {
        Utf8PathBuf::from(self.basename())
    }

    /// Returns the base name of this file path.
    pub fn basename(&self) -> String {
        format!("{}.json", self.ident)
    }
}

impl fmt::Display for LockstepApiSpecFileName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.path().as_str())
    }
}

/// A versioned API spec filename.
///
/// Versioned APIs can have multiple versions coexisting. The filename includes
/// the version and a content hash: `{ident}/{ident}-{version}-{hash}.json` (or
/// `.json.gitstub` for Git stub storage).
#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
pub struct VersionedApiSpecFileName {
    ident: ApiIdent,
    version: semver::Version,
    hash: String,
    kind: VersionedApiSpecKind,
}

impl VersionedApiSpecFileName {
    /// Creates a new versioned API spec filename (JSON format).
    pub fn new(
        ident: ApiIdent,
        version: semver::Version,
        hash: String,
    ) -> Self {
        Self { ident, version, hash, kind: VersionedApiSpecKind::Json }
    }

    /// Creates a new versioned API spec filename (Git stub format).
    pub fn new_git_stub(
        ident: ApiIdent,
        version: semver::Version,
        hash: String,
    ) -> Self {
        Self { ident, version, hash, kind: VersionedApiSpecKind::GitStub }
    }

    /// Returns the API identifier.
    pub fn ident(&self) -> &ApiIdent {
        &self.ident
    }

    /// Returns the version.
    pub fn version(&self) -> &semver::Version {
        &self.version
    }

    /// Returns the hash.
    pub fn hash(&self) -> &str {
        &self.hash
    }

    /// Returns the storage kind (JSON or Git stub).
    pub fn kind(&self) -> VersionedApiSpecKind {
        self.kind
    }

    /// Returns true if this is a Git stub.
    pub fn is_git_stub(&self) -> bool {
        self.kind == VersionedApiSpecKind::GitStub
    }

    /// Returns the path of this file relative to the root of the OpenAPI
    /// documents.
    pub fn path(&self) -> Utf8PathBuf {
        Utf8PathBuf::from_iter([self.ident.deref().clone(), self.basename()])
    }

    /// Returns the base name of this file path.
    pub fn basename(&self) -> String {
        match self.kind {
            VersionedApiSpecKind::Json => {
                format!("{}-{}-{}.json", self.ident, self.version, self.hash)
            }
            VersionedApiSpecKind::GitStub => {
                format!(
                    "{}-{}-{}.json.gitstub",
                    self.ident, self.version, self.hash
                )
            }
        }
    }

    /// Converts this filename to its JSON equivalent.
    ///
    /// If already JSON, returns a clone of self.
    pub fn to_json(&self) -> Self {
        Self {
            ident: self.ident.clone(),
            version: self.version.clone(),
            hash: self.hash.clone(),
            kind: VersionedApiSpecKind::Json,
        }
    }

    /// Converts this filename to its Git stub equivalent.
    ///
    /// If already a Git stub, returns a clone of self.
    pub fn to_git_stub(&self) -> Self {
        Self {
            ident: self.ident.clone(),
            version: self.version.clone(),
            hash: self.hash.clone(),
            kind: VersionedApiSpecKind::GitStub,
        }
    }

    /// Returns the basename as a Git stubname.
    ///
    /// - If already a Git stub, returns `basename()` directly.
    /// - If JSON, returns `basename() + ".gitstub"`.
    pub fn git_stub_basename(&self) -> String {
        match self.kind {
            VersionedApiSpecKind::GitStub => self.basename(),
            VersionedApiSpecKind::Json => {
                format!("{}.gitstub", self.basename())
            }
        }
    }

    /// Returns the basename as a JSON filename.
    ///
    /// - If already JSON, returns `basename()` directly.
    /// - If Git stub, returns the basename without `.gitstub`.
    pub fn json_basename(&self) -> String {
        match self.kind {
            VersionedApiSpecKind::Json => self.basename(),
            VersionedApiSpecKind::GitStub => {
                format!("{}-{}-{}.json", self.ident, self.version, self.hash)
            }
        }
    }
}

impl fmt::Display for VersionedApiSpecFileName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.path().as_str())
    }
}

/// Describes how a versioned API spec file is stored.
#[derive(Clone, Copy, Debug, Ord, PartialOrd, Eq, PartialEq)]
pub enum VersionedApiSpecKind {
    /// The spec is stored as a JSON file containing the full OpenAPI document.
    Json,
    /// The spec is stored as a Git stub.
    ///
    /// Instead of storing the full JSON content, a `.gitstub` file contains a
    /// reference in the format `commit:path` that can be used to retrieve the
    /// content via `git show`.
    GitStub,
}

/// Describes the path to an OpenAPI document file, relative to some root where
/// similar documents are found.
#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
pub enum ApiSpecFileName {
    /// A lockstep API: single OpenAPI document, no versioning.
    Lockstep(LockstepApiSpecFileName),
    /// A versioned API: multiple versions can coexist.
    Versioned(VersionedApiSpecFileName),
}

impl fmt::Display for ApiSpecFileName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.path().as_str())
    }
}

impl ApiSpecFileName {
    /// Returns the API identifier.
    pub fn ident(&self) -> &ApiIdent {
        match self {
            ApiSpecFileName::Lockstep(l) => l.ident(),
            ApiSpecFileName::Versioned(v) => v.ident(),
        }
    }

    /// Returns the path of this file relative to the root of the OpenAPI
    /// documents.
    pub fn path(&self) -> Utf8PathBuf {
        match self {
            ApiSpecFileName::Lockstep(l) => l.path(),
            ApiSpecFileName::Versioned(v) => v.path(),
        }
    }

    /// Returns the base name of this file path.
    pub fn basename(&self) -> String {
        match self {
            ApiSpecFileName::Lockstep(l) => l.basename(),
            ApiSpecFileName::Versioned(v) => v.basename(),
        }
    }

    /// For versioned APIs, returns the version part of the filename.
    pub fn version(&self) -> Option<&semver::Version> {
        match self {
            ApiSpecFileName::Lockstep(_) => None,
            ApiSpecFileName::Versioned(v) => Some(v.version()),
        }
    }

    /// For versioned APIs, returns the hash part of the filename.
    pub fn hash(&self) -> Option<&str> {
        match self {
            ApiSpecFileName::Lockstep(_) => None,
            ApiSpecFileName::Versioned(v) => Some(v.hash()),
        }
    }

    /// Returns true if this is a Git stub.
    pub fn is_git_stub(&self) -> bool {
        match self {
            ApiSpecFileName::Lockstep(_) => false,
            ApiSpecFileName::Versioned(v) => v.is_git_stub(),
        }
    }

    /// For versioned APIs, returns the kind of storage.
    pub fn versioned_kind(&self) -> Option<VersionedApiSpecKind> {
        match self {
            ApiSpecFileName::Lockstep(_) => None,
            ApiSpecFileName::Versioned(v) => Some(v.kind()),
        }
    }

    /// Converts a Git stubname to its JSON equivalent.
    ///
    /// For non-Git stubs, returns a clone of self.
    pub fn to_json_filename(&self) -> ApiSpecFileName {
        match self {
            ApiSpecFileName::Lockstep(_) => self.clone(),
            ApiSpecFileName::Versioned(v) => {
                ApiSpecFileName::Versioned(v.to_json())
            }
        }
    }

    /// Converts a JSON filename to its Git stub equivalent.
    ///
    /// For Git stubs, returns a clone of self.
    /// For lockstep files, returns a clone of self (lockstep files are not
    /// converted to Git stubs).
    pub fn to_git_stub_filename(&self) -> ApiSpecFileName {
        match self {
            ApiSpecFileName::Lockstep(_) => self.clone(),
            ApiSpecFileName::Versioned(v) => {
                ApiSpecFileName::Versioned(v.to_git_stub())
            }
        }
    }

    /// Returns the basename for this file as a Git stub.
    ///
    /// - If this is already a Git stub, returns `basename()` directly.
    /// - If this is a versioned JSON file, returns `basename() + ".gitstub"`.
    /// - For lockstep, returns `basename()` (lockstep files are not converted
    ///   to Git stubs).
    pub fn git_stub_basename(&self) -> String {
        match self {
            ApiSpecFileName::Lockstep(l) => l.basename(),
            ApiSpecFileName::Versioned(v) => v.git_stub_basename(),
        }
    }

    /// Returns the basename for this file as a JSON file.
    ///
    /// - If this is a Git stub, returns the basename without the `.gitstub`
    ///   suffix.
    /// - Otherwise, returns `basename()` directly.
    pub fn json_basename(&self) -> String {
        match self {
            ApiSpecFileName::Lockstep(l) => l.basename(),
            ApiSpecFileName::Versioned(v) => v.json_basename(),
        }
    }

    /// Returns a reference to the inner `VersionedApiSpecFileName` if this is
    /// a versioned API, or `None` if this is a lockstep API.
    pub fn as_versioned(&self) -> Option<&VersionedApiSpecFileName> {
        match self {
            ApiSpecFileName::Lockstep(_) => None,
            ApiSpecFileName::Versioned(v) => Some(v),
        }
    }

    /// Consumes `self` and returns the inner `VersionedApiSpecFileName` if
    /// this is a versioned API, or `None` if this is a lockstep API.
    pub fn into_versioned(self) -> Option<VersionedApiSpecFileName> {
        match self {
            ApiSpecFileName::Lockstep(_) => None,
            ApiSpecFileName::Versioned(v) => Some(v),
        }
    }

    /// Returns a reference to the inner `LockstepApiSpecFileName` if this is
    /// a lockstep API, or `None` if this is a versioned API.
    pub fn as_lockstep(&self) -> Option<&LockstepApiSpecFileName> {
        match self {
            ApiSpecFileName::Lockstep(l) => Some(l),
            ApiSpecFileName::Versioned(_) => None,
        }
    }

    /// Consumes `self` and returns the inner `LockstepApiSpecFileName` if
    /// this is a lockstep API, or `None` if this is a versioned API.
    pub fn into_lockstep(self) -> Option<LockstepApiSpecFileName> {
        match self {
            ApiSpecFileName::Lockstep(l) => Some(l),
            ApiSpecFileName::Versioned(_) => None,
        }
    }
}

impl From<LockstepApiSpecFileName> for ApiSpecFileName {
    fn from(l: LockstepApiSpecFileName) -> Self {
        ApiSpecFileName::Lockstep(l)
    }
}

impl From<VersionedApiSpecFileName> for ApiSpecFileName {
    fn from(v: VersionedApiSpecFileName) -> Self {
        ApiSpecFileName::Versioned(v)
    }
}

/// Newtype for API identifiers
#[derive(Clone, Ord, PartialOrd, Eq, PartialEq)]
pub struct ApiIdent(String);

impl fmt::Debug for ApiIdent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl Deref for ApiIdent {
    type Target = String;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl fmt::Display for ApiIdent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl<S: Into<String>> From<S> for ApiIdent {
    fn from(value: S) -> Self {
        Self(value.into())
    }
}

impl ApiIdent {
    /// Given an API identifier, return the basename of its "latest" symlink
    pub fn versioned_api_latest_symlink(&self) -> String {
        format!("{self}-latest.json")
    }

    /// Given an API identifier and a file name, determine if we're looking at
    /// this API's "latest" symlink
    pub fn versioned_api_is_latest_symlink(&self, base_name: &str) -> bool {
        base_name == self.versioned_api_latest_symlink()
    }
}