azure_iot_operations_services/
schema_registry.rs

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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Types for Schema Registry operations.

use core::fmt::Debug;
use std::{collections::HashMap, fmt};

use azure_iot_operations_protocol::{common::aio_protocol_error::AIOProtocolError, rpc_command};
use derive_builder::Builder;
use thiserror::Error;

use schemaregistry_gen::schema_registry::client as sr_client_gen;

/// Schema Registry Client implementation wrapper
mod client;
/// Schema Registry generated code
mod schemaregistry_gen;

pub use client::Client;

/// The default schema version to use if not provided.
const DEFAULT_SCHEMA_VERSION: &str = "1";

// ~~~~~~~~~~~~~~~~~~~SDK Created Structs~~~~~~~~~~~~~~~~~~~~~~~~

/// Represents an error that occurred in the Azure IoT Operations Schema Registry Client implementation.
#[derive(Debug, Error)]
#[error(transparent)]
pub struct Error(#[from] ErrorKind);

impl Error {
    /// Returns the [`ErrorKind`] of the error.
    #[must_use]
    pub fn kind(&self) -> &ErrorKind {
        &self.0
    }
}

/// Represents the kinds of errors that occur in the Azure IoT Operations Schema Registry implementation.
#[derive(Error, Debug)]
#[allow(clippy::large_enum_variant)]
pub enum ErrorKind {
    /// An error occurred in the AIO Protocol. See [`AIOProtocolError`] for more information.
    #[error(transparent)]
    AIOProtocolError(#[from] AIOProtocolError),
    /// An argument provided for a request was invalid.
    #[error(transparent)]
    InvalidRequestArgument(#[from] rpc_command::invoker::RequestBuilderError),
    /// An error was returned by the Schema Registry Service.
    #[error("{0:?}")]
    ServiceError(#[from] ServiceError),
}

// ~~~~~~~~~~~~~~~~~~~DTDL Equivalent Error~~~~~~~

/// Error codes for schema operations.
#[derive(Debug, Clone)]
#[repr(i32)]
pub enum ErrorCode {
    /// Bad request error.
    BadRequest = 400,
    /// Internal server error.
    InternalError = 500,
    /// Not found error.
    NotFound = 404,
}

/// Additional details about the error.
#[derive(Debug, Clone)]
pub struct ErrorDetails {
    /// Multi-part error code for classification and root causing of errors (e.g., '400.200').
    pub code: Option<String>,
    /// Correlation ID for tracing the error across systems.
    pub correlation_id: Option<String>,
    /// Human-readable helpful error message to provide additional context for the error
    pub message: Option<String>,
}

/// Target of the error
#[derive(Debug, Clone)]
pub enum ErrorTarget {
    /// Schema description
    DescriptionProperty,
    /// Schema display name
    DisplayNameProperty,
    /// Schema format
    FormatProperty,
    /// Schema name
    NameProperty,
    /// Schema ARM resource
    SchemaArmResource,
    /// Content of the schema
    SchemaContentProperty,
    /// Schema registry ARM resource
    SchemaRegistryArmResource,
    /// Schema type
    SchemaTypeProperty,
    /// Schema version ARM resource
    SchemaVersionArmResource,
    /// Tags of the schema
    TagsProperty,
    /// Version of the schema
    VersionProperty,
}

/// Error object for schema operations
#[derive(Debug, Clone)]
pub struct ServiceError {
    /// Error code for classification of errors (ex: '400', '404', '500', etc.).
    pub code: ErrorCode,
    /// Additional details about the error, if available.
    pub details: Option<ErrorDetails>,
    /// Inner error object for nested errors, if applicable.
    pub inner_error: Option<ErrorDetails>,
    /// Human-readable error message.
    pub message: String,
    /// Target of the error, if applicable (e.g., 'schemaType').
    pub target: Option<ErrorTarget>,
}

impl From<sr_client_gen::SchemaRegistryErrorCode> for ErrorCode {
    fn from(code: sr_client_gen::SchemaRegistryErrorCode) -> Self {
        match code {
            sr_client_gen::SchemaRegistryErrorCode::BadRequest => ErrorCode::BadRequest,
            sr_client_gen::SchemaRegistryErrorCode::InternalError => ErrorCode::InternalError,
            sr_client_gen::SchemaRegistryErrorCode::NotFound => ErrorCode::NotFound,
        }
    }
}

impl From<sr_client_gen::SchemaRegistryErrorDetails> for ErrorDetails {
    fn from(details: sr_client_gen::SchemaRegistryErrorDetails) -> Self {
        ErrorDetails {
            code: details.code,
            correlation_id: details.correlation_id,
            message: details.message,
        }
    }
}

impl From<sr_client_gen::SchemaRegistryErrorTarget> for ErrorTarget {
    fn from(target: sr_client_gen::SchemaRegistryErrorTarget) -> Self {
        match target {
            sr_client_gen::SchemaRegistryErrorTarget::DescriptionProperty => {
                ErrorTarget::DescriptionProperty
            }
            sr_client_gen::SchemaRegistryErrorTarget::DisplayNameProperty => {
                ErrorTarget::DisplayNameProperty
            }
            sr_client_gen::SchemaRegistryErrorTarget::FormatProperty => ErrorTarget::FormatProperty,
            sr_client_gen::SchemaRegistryErrorTarget::NameProperty => ErrorTarget::NameProperty,
            sr_client_gen::SchemaRegistryErrorTarget::SchemaArmResource => {
                ErrorTarget::SchemaArmResource
            }
            sr_client_gen::SchemaRegistryErrorTarget::SchemaContentProperty => {
                ErrorTarget::SchemaContentProperty
            }
            sr_client_gen::SchemaRegistryErrorTarget::SchemaRegistryArmResource => {
                ErrorTarget::SchemaRegistryArmResource
            }
            sr_client_gen::SchemaRegistryErrorTarget::SchemaTypeProperty => {
                ErrorTarget::SchemaTypeProperty
            }
            sr_client_gen::SchemaRegistryErrorTarget::SchemaVersionArmResource => {
                ErrorTarget::SchemaVersionArmResource
            }
            sr_client_gen::SchemaRegistryErrorTarget::TagsProperty => ErrorTarget::TagsProperty,
            sr_client_gen::SchemaRegistryErrorTarget::VersionProperty => {
                ErrorTarget::VersionProperty
            }
        }
    }
}

impl From<sr_client_gen::SchemaRegistryError> for ServiceError {
    fn from(error: sr_client_gen::SchemaRegistryError) -> Self {
        ServiceError {
            code: error.code.into(),
            details: error.details.map(Into::into),
            inner_error: error.inner_error.map(Into::into),
            message: error.message,
            target: error.target.map(Into::into),
        }
    }
}

impl fmt::Display for ServiceError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl std::error::Error for ServiceError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        None
    }
}

// ~~~~~~~~~~~~~~~~~~~DTDL Equivalent Structs and Enums~~~~~~~

/// Supported schema formats
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Format {
    /// Delta/1.0
    Delta1,
    /// JsonSchema/draft-07
    JsonSchemaDraft07,
}

/// Supported schema types.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SchemaType {
    /// Message Schema
    MessageSchema,
}

// TODO: Implement proper Equality for schema_content. At this point, it is just a string comparison.
/// Schema object
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Schema {
    /// Human-readable description of the schema.
    pub description: Option<String>,
    /// Human-readable display name.
    pub display_name: Option<String>,
    /// Format of the schema.
    pub format: Format,
    /// Hash of the schema content.
    pub hash: Option<String>,
    /// Schema name.
    pub name: String,
    /// Schema registry namespace. Uniquely identifies a schema registry within a tenant.
    pub namespace: String,
    /// Content stored in the schema.
    pub schema_content: String,
    /// Type of the schema.
    pub schema_type: SchemaType,
    /// Schema tags.
    pub tags: HashMap<String, String>,
    /// Version of the schema. Allowed between 0-9.
    pub version: String,
}

// TODO: Implement proper Equality for schema_content. At this point, it is just a string comparison.
/// Request to put a schema in the schema registry.
#[derive(Builder, Clone, Debug, PartialEq, Eq)]
#[builder(setter(into), build_fn(validate = "Self::validate"))]
pub struct PutSchemaRequest {
    /// Human-readable description of the schema.
    #[builder(default)]
    pub description: Option<String>,
    /// Human-readable display name.
    #[builder(default)]
    pub display_name: Option<String>,
    /// The format of the schema.
    pub format: Format,
    /// Content stored in the schema.
    pub schema_content: String,
    /// Type of the schema.
    #[builder(default = "SchemaType::MessageSchema")]
    pub schema_type: SchemaType,
    /// Schema tags.
    #[builder(default)]
    pub tags: HashMap<String, String>,
    /// Version of the schema. Allowed between 0-9.
    #[builder(default = "DEFAULT_SCHEMA_VERSION.to_string()")]
    pub version: String,
}

impl PutSchemaRequestBuilder {
    /// Validate the [`PutSchemaRequest`].
    ///
    /// # Errors
    /// Returns a `String` describing the error if `display_name`, `schema_content`, or `version` is empty.
    fn validate(&self) -> Result<(), String> {
        if let Some(Some(display_name)) = &self.display_name {
            if display_name.is_empty() {
                return Err("display_name cannot be empty".to_string());
            }
        }

        if let Some(version) = &self.version {
            if version.is_empty() {
                return Err("version cannot be empty".to_string());
            }
        }

        if let Some(schema_content) = &self.schema_content {
            if schema_content.is_empty() {
                return Err("schema_content cannot be empty".to_string());
            }
        }

        Ok(())
    }
}

/// Request to get a schema from the schema registry.
#[derive(Builder, Clone, Debug, PartialEq, Eq)]
#[builder(setter(into), build_fn(validate = "Self::validate"))]
pub struct GetSchemaRequest {
    /// Schema name.
    name: String,
    /// Version of the schema. Allowed between 0-9.
    #[builder(default = "DEFAULT_SCHEMA_VERSION.to_string()")]
    version: String,
}

impl GetSchemaRequestBuilder {
    /// Validate the [`GetRequest`].
    ///
    /// # Errors
    /// Returns a `String` describing the error if `name` or `version` is empty.
    fn validate(&self) -> Result<(), String> {
        if let Some(name) = &self.name {
            if name.is_empty() {
                return Err("name cannot be empty".to_string());
            }
        }

        if let Some(version) = &self.version {
            if version.is_empty() {
                return Err("version cannot be empty".to_string());
            }
        }

        Ok(())
    }
}

impl From<Format> for sr_client_gen::Format {
    fn from(format: Format) -> Self {
        match format {
            Format::Delta1 => sr_client_gen::Format::Delta1,
            Format::JsonSchemaDraft07 => sr_client_gen::Format::JsonSchemaDraft07,
        }
    }
}

impl From<sr_client_gen::Format> for Format {
    fn from(format: sr_client_gen::Format) -> Self {
        match format {
            sr_client_gen::Format::Delta1 => Format::Delta1,
            sr_client_gen::Format::JsonSchemaDraft07 => Format::JsonSchemaDraft07,
        }
    }
}

impl From<SchemaType> for sr_client_gen::SchemaType {
    fn from(schema_type: SchemaType) -> Self {
        match schema_type {
            SchemaType::MessageSchema => sr_client_gen::SchemaType::MessageSchema,
        }
    }
}

impl From<sr_client_gen::SchemaType> for SchemaType {
    fn from(schema_type: sr_client_gen::SchemaType) -> Self {
        match schema_type {
            sr_client_gen::SchemaType::MessageSchema => SchemaType::MessageSchema,
        }
    }
}
impl From<sr_client_gen::Schema> for Schema {
    fn from(schema: sr_client_gen::Schema) -> Self {
        Schema {
            description: schema.description,
            display_name: schema.display_name,
            format: schema.format.into(),
            hash: schema.hash,
            name: schema.name,
            namespace: schema.namespace,
            schema_content: schema.schema_content,
            schema_type: schema.schema_type.into(),
            tags: schema.tags.unwrap_or_default(),
            version: schema.version,
        }
    }
}