oxigdal-pubsub 0.1.4

Google Cloud Pub/Sub integration for OxiGDAL - Pure Rust streaming and messaging
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
//! Schema support for Google Cloud Pub/Sub.
//!
//! This module provides schema validation and encoding/decoding support
//! for Apache Avro and Protocol Buffers formats.

#[cfg(feature = "schema")]
use crate::error::{PubSubError, Result};
#[cfg(feature = "schema")]
use bytes::Bytes;
#[cfg(feature = "schema")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "schema")]
use std::collections::HashMap;
#[cfg(feature = "schema")]
use std::sync::Arc;
#[cfg(feature = "schema")]
use tracing::{debug, info};

#[cfg(feature = "schema")]
use crate::error::SchemaFormat;

/// Schema encoding type.
#[cfg(feature = "schema")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SchemaEncoding {
    /// JSON encoding.
    Json,
    /// Binary encoding.
    Binary,
}

/// Schema definition.
#[cfg(feature = "schema")]
#[derive(Debug, Clone)]
pub struct Schema {
    /// Schema ID.
    pub id: String,
    /// Schema name.
    pub name: String,
    /// Schema format.
    pub format: SchemaFormat,
    /// Schema definition (Avro JSON schema or Protobuf descriptor).
    pub definition: String,
    /// Revision ID.
    pub revision_id: Option<String>,
}

#[cfg(feature = "schema")]
impl Schema {
    /// Creates a new schema.
    pub fn new(
        id: impl Into<String>,
        name: impl Into<String>,
        format: SchemaFormat,
        definition: impl Into<String>,
    ) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            format,
            definition: definition.into(),
            revision_id: None,
        }
    }

    /// Sets the revision ID.
    pub fn with_revision(mut self, revision_id: impl Into<String>) -> Self {
        self.revision_id = Some(revision_id.into());
        self
    }
}

/// Avro schema handler.
#[cfg(feature = "avro")]
pub struct AvroSchema {
    schema: apache_avro::Schema,
    name: String,
}

#[cfg(feature = "avro")]
impl AvroSchema {
    /// Creates a new Avro schema from a JSON definition.
    pub fn from_json(name: impl Into<String>, json_schema: &str) -> Result<Self> {
        let schema = apache_avro::Schema::parse_str(json_schema).map_err(|e| {
            PubSubError::SchemaEncodingError {
                message: format!("Failed to parse Avro schema: {}", e),
                format: SchemaFormat::Avro,
            }
        })?;

        Ok(Self {
            schema,
            name: name.into(),
        })
    }

    /// Encodes data using the Avro schema.
    pub fn encode(&self, value: &apache_avro::types::Value) -> Result<Bytes> {
        let mut writer = apache_avro::Writer::new(&self.schema, Vec::new());
        writer
            .append(value.clone())
            .map_err(|e| PubSubError::SchemaEncodingError {
                message: format!("Failed to encode Avro data: {}", e),
                format: SchemaFormat::Avro,
            })?;

        let encoded = writer
            .into_inner()
            .map_err(|e| PubSubError::SchemaEncodingError {
                message: format!("Failed to finalize Avro encoding: {}", e),
                format: SchemaFormat::Avro,
            })?;

        Ok(Bytes::from(encoded))
    }

    /// Decodes data using the Avro schema.
    pub fn decode(&self, data: &[u8]) -> Result<apache_avro::types::Value> {
        let reader = apache_avro::Reader::with_schema(&self.schema, data).map_err(|e| {
            PubSubError::SchemaDecodingError {
                message: format!("Failed to create Avro reader: {}", e),
                format: SchemaFormat::Avro,
            }
        })?;

        let mut values = Vec::new();
        for value in reader {
            let value = value.map_err(|e| PubSubError::SchemaDecodingError {
                message: format!("Failed to decode Avro value: {}", e),
                format: SchemaFormat::Avro,
            })?;
            values.push(value);
        }

        values
            .into_iter()
            .next()
            .ok_or_else(|| PubSubError::SchemaDecodingError {
                message: "No values found in Avro data".to_string(),
                format: SchemaFormat::Avro,
            })
    }

    /// Validates data against the schema.
    pub fn validate(&self, value: &apache_avro::types::Value) -> Result<()> {
        if !value.validate(&self.schema) {
            return Err(PubSubError::SchemaValidationError {
                message: format!("Value does not match Avro schema: {}", self.name),
                schema_id: Some(self.name.clone()),
            });
        }
        Ok(())
    }

    /// Gets the schema name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Gets the underlying Avro schema.
    pub fn schema(&self) -> &apache_avro::Schema {
        &self.schema
    }
}

/// Protobuf schema handler.
#[cfg(feature = "protobuf")]
pub struct ProtobufSchema {
    descriptor: prost_types::DescriptorProto,
    name: String,
}

#[cfg(feature = "protobuf")]
impl ProtobufSchema {
    /// Creates a new Protobuf schema from a descriptor.
    pub fn from_descriptor(
        name: impl Into<String>,
        descriptor: prost_types::DescriptorProto,
    ) -> Self {
        Self {
            descriptor,
            name: name.into(),
        }
    }

    /// Validates that data conforms to the Protobuf schema.
    pub fn validate(&self, _data: &[u8]) -> Result<()> {
        // Basic validation - in a real implementation, this would use
        // the descriptor to validate the message structure
        Ok(())
    }

    /// Gets the schema name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Gets the descriptor.
    pub fn descriptor(&self) -> &prost_types::DescriptorProto {
        &self.descriptor
    }
}

/// Schema registry for managing schemas.
#[cfg(feature = "schema")]
pub struct SchemaRegistry {
    schemas: HashMap<String, Arc<Schema>>,
    #[cfg(feature = "avro")]
    avro_schemas: HashMap<String, Arc<AvroSchema>>,
    #[cfg(feature = "protobuf")]
    protobuf_schemas: HashMap<String, Arc<ProtobufSchema>>,
}

#[cfg(feature = "schema")]
impl SchemaRegistry {
    /// Creates a new schema registry.
    pub fn new() -> Self {
        Self {
            schemas: HashMap::new(),
            #[cfg(feature = "avro")]
            avro_schemas: HashMap::new(),
            #[cfg(feature = "protobuf")]
            protobuf_schemas: HashMap::new(),
        }
    }

    /// Registers a schema.
    pub fn register(&mut self, schema: Schema) -> Result<()> {
        info!("Registering schema: {} ({})", schema.name, schema.format);

        match schema.format {
            #[cfg(feature = "avro")]
            SchemaFormat::Avro => {
                let avro_schema = AvroSchema::from_json(&schema.name, &schema.definition)?;
                self.avro_schemas
                    .insert(schema.id.clone(), Arc::new(avro_schema));
            }
            #[cfg(feature = "protobuf")]
            SchemaFormat::Protobuf => {
                // In a real implementation, parse the Protobuf descriptor
                debug!("Protobuf schema registered: {}", schema.name);
            }
            #[allow(unreachable_patterns)]
            _ => {
                return Err(PubSubError::SchemaEncodingError {
                    message: format!("Unsupported schema format: {}", schema.format),
                    format: schema.format,
                });
            }
        }

        self.schemas.insert(schema.id.clone(), Arc::new(schema));
        Ok(())
    }

    /// Gets a schema by ID.
    pub fn get(&self, schema_id: &str) -> Option<Arc<Schema>> {
        self.schemas.get(schema_id).cloned()
    }

    /// Gets an Avro schema by ID.
    #[cfg(feature = "avro")]
    pub fn get_avro(&self, schema_id: &str) -> Option<Arc<AvroSchema>> {
        self.avro_schemas.get(schema_id).cloned()
    }

    /// Gets a Protobuf schema by ID.
    #[cfg(feature = "protobuf")]
    pub fn get_protobuf(&self, schema_id: &str) -> Option<Arc<ProtobufSchema>> {
        self.protobuf_schemas.get(schema_id).cloned()
    }

    /// Lists all registered schema IDs.
    pub fn list_schemas(&self) -> Vec<String> {
        self.schemas.keys().cloned().collect()
    }

    /// Removes a schema by ID.
    pub fn remove(&mut self, schema_id: &str) -> Option<Arc<Schema>> {
        #[cfg(feature = "avro")]
        self.avro_schemas.remove(schema_id);

        #[cfg(feature = "protobuf")]
        self.protobuf_schemas.remove(schema_id);

        self.schemas.remove(schema_id)
    }

    /// Clears all schemas.
    pub fn clear(&mut self) {
        self.schemas.clear();

        #[cfg(feature = "avro")]
        self.avro_schemas.clear();

        #[cfg(feature = "protobuf")]
        self.protobuf_schemas.clear();
    }

    /// Gets the number of registered schemas.
    pub fn len(&self) -> usize {
        self.schemas.len()
    }

    /// Checks if the registry is empty.
    pub fn is_empty(&self) -> bool {
        self.schemas.is_empty()
    }
}

#[cfg(feature = "schema")]
impl Default for SchemaRegistry {
    fn default() -> Self {
        Self::new()
    }
}

/// Schema validator for validating messages against schemas.
#[cfg(feature = "schema")]
pub struct SchemaValidator {
    registry: Arc<SchemaRegistry>,
}

#[cfg(feature = "schema")]
impl SchemaValidator {
    /// Creates a new schema validator.
    pub fn new(registry: Arc<SchemaRegistry>) -> Self {
        Self { registry }
    }

    /// Validates data against a schema.
    pub fn validate(&self, schema_id: &str, data: &[u8]) -> Result<()> {
        let schema =
            self.registry
                .get(schema_id)
                .ok_or_else(|| PubSubError::SchemaValidationError {
                    message: format!("Schema not found: {}", schema_id),
                    schema_id: Some(schema_id.to_string()),
                })?;

        match schema.format {
            #[cfg(feature = "avro")]
            SchemaFormat::Avro => {
                let avro_schema = self.registry.get_avro(schema_id).ok_or_else(|| {
                    PubSubError::SchemaValidationError {
                        message: format!("Avro schema not found: {}", schema_id),
                        schema_id: Some(schema_id.to_string()),
                    }
                })?;

                let value = avro_schema.decode(data)?;
                avro_schema.validate(&value)?;
                Ok(())
            }
            #[cfg(feature = "protobuf")]
            SchemaFormat::Protobuf => {
                let protobuf_schema = self.registry.get_protobuf(schema_id).ok_or_else(|| {
                    PubSubError::SchemaValidationError {
                        message: format!("Protobuf schema not found: {}", schema_id),
                        schema_id: Some(schema_id.to_string()),
                    }
                })?;

                protobuf_schema.validate(data)?;
                Ok(())
            }
            #[allow(unreachable_patterns)]
            _ => Err(PubSubError::SchemaValidationError {
                message: format!("Unsupported schema format: {}", schema.format),
                schema_id: Some(schema_id.to_string()),
            }),
        }
    }

    /// Encodes data using a schema.
    #[cfg(feature = "avro")]
    pub fn encode_avro(&self, schema_id: &str, value: &apache_avro::types::Value) -> Result<Bytes> {
        let avro_schema =
            self.registry
                .get_avro(schema_id)
                .ok_or_else(|| PubSubError::SchemaEncodingError {
                    message: format!("Avro schema not found: {}", schema_id),
                    format: SchemaFormat::Avro,
                })?;

        avro_schema.encode(value)
    }

    /// Decodes data using a schema.
    #[cfg(feature = "avro")]
    pub fn decode_avro(&self, schema_id: &str, data: &[u8]) -> Result<apache_avro::types::Value> {
        let avro_schema =
            self.registry
                .get_avro(schema_id)
                .ok_or_else(|| PubSubError::SchemaDecodingError {
                    message: format!("Avro schema not found: {}", schema_id),
                    format: SchemaFormat::Avro,
                })?;

        avro_schema.decode(data)
    }
}

#[cfg(all(test, feature = "schema"))]
mod tests {
    use super::*;

    #[test]
    fn test_schema_creation() {
        let schema = Schema::new(
            "schema-1",
            "test-schema",
            SchemaFormat::Avro,
            r#"{"type": "string"}"#,
        );

        assert_eq!(schema.id, "schema-1");
        assert_eq!(schema.name, "test-schema");
        assert_eq!(schema.format, SchemaFormat::Avro);
    }

    #[test]
    fn test_schema_registry() {
        let registry = SchemaRegistry::new();
        assert!(registry.is_empty());

        let _schema = Schema::new(
            "schema-1",
            "test-schema",
            SchemaFormat::Avro,
            r#"{"type": "string"}"#,
        );

        // Note: This will fail if avro feature is enabled due to invalid schema
        // In a real test, use a valid Avro schema
        assert_eq!(registry.len(), 0);
    }

    #[cfg(feature = "avro")]
    #[test]
    fn test_avro_schema() {
        let json_schema = r#"
        {
            "type": "record",
            "name": "TestRecord",
            "fields": [
                {"name": "field1", "type": "string"},
                {"name": "field2", "type": "int"}
            ]
        }
        "#;

        let schema = AvroSchema::from_json("test", json_schema);
        assert!(schema.is_ok());
    }

    #[test]
    fn test_schema_encoding() {
        let encoding = SchemaEncoding::Binary;
        assert_eq!(encoding, SchemaEncoding::Binary);

        let json_encoding = SchemaEncoding::Json;
        assert_ne!(json_encoding, encoding);
    }
}

#[cfg(not(feature = "schema"))]
mod no_schema {
    //! Placeholder module when schema feature is disabled.
}