ng-gateway-sdk 0.1.0

SDK for building NG Gateway southward drivers and northward plugins.
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
use super::types::{AlarmSeverity, DropPolicy, TargetType};
use crate::{AccessMode, DataType, NGValue, PointValue, Transform};
use bytes::Bytes;
use chrono::{DateTime, Duration, Utc};
use sea_orm::FromJsonQueryResult;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, fmt::Debug, sync::Arc};
use uuid::Uuid;

/// Command message received from platform
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Command {
    /// Command identifier
    pub command_id: String,
    /// Command type/name
    pub key: String,
    /// Target type
    pub target_type: TargetType,
    /// Device identifier
    pub device_id: Option<i32>,
    /// Device name
    pub device_name: Option<String>,
    /// Command parameters
    pub params: Option<serde_json::Value>,
    /// Command expiration time
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,
    /// Timestamp when command was issued
    pub timestamp: DateTime<Utc>,
}

impl Command {
    /// Create new command
    pub fn new(
        command_id: String,
        key: String,
        target_type: TargetType,
        device_id: i32,
        device_name: String,
        params: serde_json::Value,
    ) -> Self {
        Self {
            command_id,
            key,
            target_type,
            device_id: Some(device_id),
            device_name: Some(device_name),
            params: Some(params),
            timeout_ms: None,
            timestamp: Utc::now(),
        }
    }

    /// Set command timeout
    pub fn with_timeout(mut self, timeout_ms: u64) -> Self {
        self.timeout_ms = Some(timeout_ms);
        self
    }

    #[inline]
    /// Check if command has expired
    pub fn is_expired(&self) -> bool {
        if let Some(expires_at) = self.timeout_ms {
            Utc::now() > self.timestamp + Duration::milliseconds(expires_at as i64)
        } else {
            false
        }
    }
}

/// Write-point request (control-plane): a northward plugin asks Gateway to write a single point.
///
/// # Notes
/// - `point_id` is the stable primary key in gateway runtime.
/// - `value` uses `NGValue` to avoid JSON allocations on the hot path.
/// - `timeout_ms` is an overall upper bound that gateway may split across queueing + driver I/O.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WritePoint {
    /// Request identifier for correlating async response.
    pub request_id: String,
    /// Target point identifier.
    pub point_id: i32,
    /// Value to write.
    pub value: NGValue,
    /// Timestamp when the request was created at the plugin boundary.
    pub timestamp: DateTime<Utc>,
    /// Optional overall timeout in milliseconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,
}

/// Write-point response (Gateway -> northward plugin).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WritePointResponse {
    /// Correlates to `WritePoint.request_id`.
    pub request_id: String,
    /// Target point identifier.
    pub point_id: i32,
    /// Target device identifier (for routing/logging convenience).
    pub device_id: i32,
    /// Target device name (stable snapshot at response time).
    ///
    /// # Notes
    /// - This is provided for northward plugins so they can publish platform-facing
    ///   payloads without performing extra runtime lookups.
    /// - For hot paths, `Arc<str>` is used to keep clones cheap.
    #[serde(with = "arc_str_serde")]
    pub device_name: Arc<str>,
    /// Point key used for platform payload mapping (stable snapshot at response time).
    ///
    /// # Notes
    /// - `point_key` is the semantic identifier used by most northward protocols (e.g. MQTT JSON keys).
    /// - This is included to support best-practice "reported state" publishing without additional lookups.
    #[serde(with = "arc_str_serde")]
    pub point_key: Arc<str>,
    /// Unified status.
    pub status: WritePointStatus,
    /// Optional error details when failed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<WritePointError>,
    /// Applied value (optional). Gateway may echo the requested value on success.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub applied_value: Option<NGValue>,
    /// Completion time generated by gateway.
    pub completed_at: DateTime<Utc>,
}

impl WritePointResponse {
    #[inline]
    pub fn success(
        request_id: String,
        point_id: i32,
        device_id: i32,
        device_name: Arc<str>,
        point_key: Arc<str>,
        applied_value: Option<NGValue>,
        completed_at: DateTime<Utc>,
    ) -> Self {
        Self {
            request_id,
            point_id,
            device_id,
            device_name,
            point_key,
            status: WritePointStatus::Success,
            error: None,
            applied_value,
            completed_at,
        }
    }

    #[inline]
    pub fn failed(
        request_id: String,
        point_id: i32,
        device_id: i32,
        device_name: Arc<str>,
        point_key: Arc<str>,
        error: WritePointError,
        completed_at: DateTime<Utc>,
    ) -> Self {
        Self {
            request_id,
            point_id,
            device_id,
            device_name,
            point_key,
            status: WritePointStatus::Failed,
            error: Some(error),
            applied_value: None,
            completed_at,
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum WritePointStatus {
    Success,
    Failed,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WritePointError {
    pub kind: WritePointErrorKind,
    pub message: String,
}

impl WritePointError {
    /// Create a [`WritePointError`] with a kind and a human-readable message.
    ///
    /// This helper is designed for hot-path code where we want to construct errors
    /// without introducing additional allocation patterns beyond the final `String`.
    #[inline]
    pub fn new(kind: WritePointErrorKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            message: message.into(),
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum WritePointErrorKind {
    // ===== Gateway validation =====
    NotFound,
    NotWriteable,
    TypeMismatch,
    OutOfRange,
    NotConnected,
    // ===== Queueing/serialization =====
    QueueTimeout,
    // ===== Driver execution =====
    DriverError,
}

/// Device connected data message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeviceConnectedData {
    /// Device identifier
    pub device_id: i32,
    /// Device name
    pub device_name: String,
    /// Device type
    pub device_type: String,
}

/// Device disconnected data message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeviceDisconnectedData {
    /// Device identifier
    pub device_id: i32,
    /// Device name
    pub device_name: String,
    /// Device type
    pub device_type: String,
}

/// Telemetry data message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TelemetryData {
    /// Device identifier
    pub device_id: i32,
    /// Device name
    pub device_name: String,
    /// Timestamp of the data
    pub timestamp: DateTime<Utc>,
    /// Telemetry values as point-id keyed updates.
    ///
    /// `point_id` is the primary key for all hot-path operations.
    pub values: Vec<PointValue>,
    /// Additional metadata
    #[serde(default)]
    pub metadata: HashMap<String, serde_json::Value>,
}

impl TelemetryData {
    /// Create new telemetry data
    pub fn new(device_id: i32, device_name: impl Into<String>, values: Vec<PointValue>) -> Self {
        Self {
            device_id,
            device_name: device_name.into(),
            timestamp: Utc::now(),
            values,
            metadata: HashMap::new(),
        }
    }

    /// Add metadata to the telemetry data
    pub fn with_metadata(mut self, metadata: HashMap<String, serde_json::Value>) -> Self {
        self.metadata = metadata;
        self
    }

    /// Serialize to JSON bytes with zero-copy optimization
    pub fn to_json_bytes(&self) -> Result<Bytes, serde_json::Error> {
        let json = serde_json::to_vec(self)?;
        Ok(Bytes::from(json))
    }
}

/// Attribute data message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AttributeData {
    /// Device identifier
    pub device_id: i32,
    /// Device name
    pub device_name: String,
    /// Timestamp of the attributes
    pub timestamp: DateTime<Utc>,
    /// Client-side attributes (point-id keyed updates).
    #[serde(default)]
    pub client_attributes: Vec<PointValue>,
    /// Shared attributes (point-id keyed updates).
    #[serde(default)]
    pub shared_attributes: Vec<PointValue>,
    /// Server-side attributes (point-id keyed updates).
    #[serde(default)]
    pub server_attributes: Vec<PointValue>,
}

impl AttributeData {
    /// Create new attribute data with client attributes
    pub fn new_client_attributes(
        device_id: i32,
        device_name: impl Into<String>,
        attributes: Vec<PointValue>,
    ) -> Self {
        Self {
            device_id,
            device_name: device_name.into(),
            timestamp: Utc::now(),
            client_attributes: attributes,
            shared_attributes: Vec::new(),
            server_attributes: Vec::new(),
        }
    }

    /// Create new attribute data with shared attributes
    pub fn new_shared_attributes(
        device_id: i32,
        device_name: impl Into<String>,
        attributes: Vec<PointValue>,
    ) -> Self {
        Self {
            device_id,
            device_name: device_name.into(),
            timestamp: Utc::now(),
            client_attributes: Vec::new(),
            shared_attributes: attributes,
            server_attributes: Vec::new(),
        }
    }

    /// Serialize to JSON bytes
    pub fn to_json_bytes(&self) -> Result<Bytes, serde_json::Error> {
        let json = serde_json::to_vec(self)?;
        Ok(Bytes::from(json))
    }
}

/// RPC request message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RpcRequest {
    /// Target type
    pub target_type: TargetType,
    /// Request identifier
    pub request_id: Uuid,
    /// Device identifier
    pub device_id: i32,
    /// Device name
    pub device_name: String,
    /// Request method
    pub method: String,
    /// Request parameters
    pub params: Option<serde_json::Value>,
}

/// Server RPC response message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerRpcResponse {
    /// Request identifier this response corresponds to
    /// NOTE: Use String to align with platform-specific request id formats (e.g. ThingsBoard numeric ids)
    pub request_id: String,
    /// Target type
    pub target_type: TargetType,
    /// Response result (success)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<serde_json::Value>,
    /// Error information (failure)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Timestamp of the response
    pub timestamp: DateTime<Utc>,
}

/// Client RPC response message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClientRpcResponse {
    /// Device identifier
    pub device_id: i32,
    /// Device name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub device_name: Option<String>,
    /// Request identifier this response corresponds to
    /// NOTE: Use String to align with platform-specific request id formats (e.g. ThingsBoard numeric ids)
    pub request_id: String,
    /// Target type
    pub target_type: TargetType,
    /// Response result (success)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<serde_json::Value>,
    /// Error information (failure)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Timestamp of the response
    pub timestamp: DateTime<Utc>,
}

impl ClientRpcResponse {
    /// Create successful RPC response
    pub fn success(
        request_id: String,
        target_type: TargetType,
        device_id: i32,
        device_name: Option<String>,
        result: serde_json::Value,
    ) -> Self {
        Self {
            request_id,
            target_type,
            device_id,
            device_name,
            result: Some(result),
            error: None,
            timestamp: Utc::now(),
        }
    }

    /// Create error RPC response
    pub fn error(
        request_id: String,
        target_type: TargetType,
        device_id: i32,
        device_name: Option<String>,
        error: String,
    ) -> Self {
        Self {
            request_id,
            target_type,
            device_id,
            device_name,
            result: None,
            error: Some(error),
            timestamp: Utc::now(),
        }
    }

    pub fn is_success(&self) -> bool {
        self.error.is_none()
    }

    /// Serialize to JSON bytes
    pub fn to_json_bytes(&self) -> Result<Bytes, serde_json::Error> {
        let json = serde_json::to_vec(self)?;
        Ok(Bytes::from(json))
    }
}

/// Alarm data message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlarmData {
    /// Device identifier
    pub device_id: i32,
    /// Device name
    pub device_name: String,
    /// Alarm type identifier
    pub alarm_type: String,
    /// Alarm severity level
    pub severity: AlarmSeverity,
    /// Human-readable alarm message
    pub message: String,
    /// Additional alarm details
    pub details: HashMap<String, serde_json::Value>,
    /// Timestamp when alarm was triggered
    pub timestamp: DateTime<Utc>,
    /// Whether the alarm has been cleared
    pub cleared: bool,
}

impl AlarmData {
    /// Create new alarm
    pub fn new(
        device_id: i32,
        device_name: String,
        alarm_type: String,
        severity: AlarmSeverity,
        message: String,
    ) -> Self {
        Self {
            device_id,
            device_name,
            alarm_type,
            severity,
            message,
            details: HashMap::new(),
            timestamp: Utc::now(),
            cleared: false,
        }
    }

    /// Mark alarm as cleared
    pub fn clear(mut self) -> Self {
        self.cleared = true;
        self
    }

    /// Add details to the alarm
    pub fn with_details(mut self, details: HashMap<String, serde_json::Value>) -> Self {
        self.details = details;
        self
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, FromJsonQueryResult)]
#[serde(rename_all = "camelCase")]
pub struct QueuePolicy {
    #[serde(default = "QueuePolicy::default_capacity")]
    pub capacity: u32,
    #[serde(default = "QueuePolicy::default_drop_policy")]
    pub drop_policy: DropPolicy,
    #[serde(default = "QueuePolicy::default_block_duration_ms")]
    pub block_duration: u64,
    /// Enable buffer queue for unconnected state
    #[serde(default = "QueuePolicy::default_buffer_enabled")]
    pub buffer_enabled: bool,
    /// Buffer queue capacity (max number of items to buffer)
    #[serde(default = "QueuePolicy::default_buffer_capacity")]
    pub buffer_capacity: u32,
    /// Buffer expiration time in milliseconds (0 means no expiration)
    #[serde(default = "QueuePolicy::default_buffer_expire_ms")]
    pub buffer_expire_ms: u64,
}

impl QueuePolicy {
    fn default_capacity() -> u32 {
        1000
    }

    fn default_drop_policy() -> DropPolicy {
        DropPolicy::Discard
    }

    fn default_block_duration_ms() -> u64 {
        1000
    }

    fn default_buffer_enabled() -> bool {
        true
    }

    fn default_buffer_capacity() -> u32 {
        1000
    }

    fn default_buffer_expire_ms() -> u64 {
        300_000 // 5 minutes
    }
}

impl sea_orm::IntoActiveValue<QueuePolicy> for QueuePolicy {
    fn into_active_value(self) -> sea_orm::ActiveValue<QueuePolicy> {
        sea_orm::ActiveValue::Set(self)
    }
}

/// Serde adapter for `Arc<str>` fields.
///
/// `Arc<str>` does not implement serde traits by default, but we want the type for
/// low-allocation clones on hot paths. This adapter serializes it as a normal string.
mod arc_str_serde {
    use serde::{Deserialize, Deserializer, Serializer};
    use std::sync::Arc;

    pub fn serialize<S>(v: &Arc<str>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(v.as_ref())
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Arc<str>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Ok(Arc::<str>::from(s))
    }

    pub mod option {
        use super::*;
        use serde::Deserialize;

        pub fn serialize<S>(v: &Option<Arc<str>>, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            match v {
                Some(s) => serializer.serialize_some(s.as_ref()),
                None => serializer.serialize_none(),
            }
        }

        pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Arc<str>>, D::Error>
        where
            D: Deserializer<'de>,
        {
            let opt = Option::<String>::deserialize(deserializer)?;
            Ok(opt.map(Arc::<str>::from))
        }
    }
}

/// Point metadata snapshot for northward consumption.
///
/// This struct is intended to be:
/// - **Read-only** for plugins
/// - **Cheap to clone** via `Arc<PointMeta>`
/// - **Stable** across core internal refactors
///
/// All strings are stored as `Arc<str>` to reduce cloning cost.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PointMeta {
    /// Point identifier (primary key).
    pub point_id: i32,
    /// Channel identifier.
    pub channel_id: i32,
    /// Channel name.
    #[serde(with = "arc_str_serde")]
    pub channel_name: Arc<str>,
    /// Device identifier.
    pub device_id: i32,
    /// Device name.
    #[serde(with = "arc_str_serde")]
    pub device_name: Arc<str>,
    /// Point display name.
    #[serde(with = "arc_str_serde")]
    pub point_name: Arc<str>,
    /// Point key used for protocol encoding and UI display.
    #[serde(with = "arc_str_serde")]
    pub point_key: Arc<str>,
    /// Strong data type definition for this point.
    pub data_type: DataType,
    /// Access mode for read/write validation.
    pub access_mode: AccessMode,
    /// Unit of measurement (optional).
    #[serde(default, with = "arc_str_serde::option")]
    pub unit: Option<Arc<str>>,
    /// Minimum allowed engineering value (optional).
    pub min_value: Option<f64>,
    /// Maximum allowed engineering value (optional).
    pub max_value: Option<f64>,
    /// Logical-layer transform rules for this point.
    ///
    /// This is always present; identity semantics are defined by `Transform`.
    #[serde(default)]
    pub transform: Transform,
    /// Human-readable description (optional).
    #[serde(default, with = "arc_str_serde::option")]
    pub description: Option<Arc<str>>,
}

impl PointMeta {
    /// Get the wire data type (protocol-level, memory-layout semantics).
    ///
    /// For `PointMeta`, this is the configured `data_type` persisted in the gateway.
    #[inline]
    pub fn wire_data_type(&self) -> DataType {
        self.data_type
    }

    /// Get the logical data type (northward-facing semantics).
    ///
    /// This is derived from `transform.transform_data_type` and falls back to the
    /// wire data type when not configured.
    #[inline]
    pub fn logical_data_type(&self) -> DataType {
        self.transform.resolve_logical_datatype(self.data_type)
    }

    #[inline]
    pub fn readable(&self) -> bool {
        matches!(self.access_mode, AccessMode::Read | AccessMode::ReadWrite)
    }

    #[inline]
    pub fn writable(&self) -> bool {
        matches!(self.access_mode, AccessMode::Write | AccessMode::ReadWrite)
    }
}