use std::collections::BTreeMap;
use std::sync::Arc;
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use fakecloud_core::multi_account::{AccountState, MultiAccountState};
pub const IOT_SNAPSHOT_SCHEMA_VERSION: u32 = 1;
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct IotData {
#[serde(default)]
pub resources: BTreeMap<String, BTreeMap<String, Value>>,
#[serde(default)]
pub tags: BTreeMap<String, BTreeMap<String, String>>,
#[serde(default)]
pub singletons: BTreeMap<String, Value>,
#[serde(default)]
pub relations: BTreeMap<String, Vec<String>>,
#[serde(default)]
pub seq: u64,
}
impl IotData {
pub fn get_resource(&self, rtype: &str, id: &str) -> Option<&Value> {
self.resources.get(rtype).and_then(|m| m.get(id))
}
pub fn put_resource(&mut self, rtype: &str, id: &str, record: Value) {
self.resources
.entry(rtype.to_string())
.or_default()
.insert(id.to_string(), record);
}
pub fn remove_resource(&mut self, rtype: &str, id: &str) -> Option<Value> {
let removed = self.resources.get_mut(rtype).and_then(|m| m.remove(id));
if let Some(m) = self.resources.get(rtype) {
if m.is_empty() {
self.resources.remove(rtype);
}
}
removed
}
pub fn list_resources(&self, rtype: &str) -> Vec<Value> {
self.resources
.get(rtype)
.map(|m| m.values().cloned().collect())
.unwrap_or_default()
}
pub fn list_resource_entries(&self, rtype: &str) -> Vec<(String, Value)> {
self.resources
.get(rtype)
.map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
.unwrap_or_default()
}
pub fn next_seq(&mut self) -> u64 {
self.seq += 1;
self.seq
}
}
impl AccountState for IotData {
fn new_for_account(_account_id: &str, _region: &str, _endpoint: &str) -> Self {
Self::default()
}
}
pub type SharedIotState = Arc<RwLock<MultiAccountState<IotData>>>;
#[derive(Debug, Serialize, Deserialize)]
pub struct IotSnapshot {
pub schema_version: u32,
pub accounts: MultiAccountState<IotData>,
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn new_account_is_empty() {
let data = IotData::new_for_account("000000000000", "us-east-1", "");
assert!(data.resources.is_empty());
assert!(data.tags.is_empty());
assert!(data.singletons.is_empty());
}
#[test]
fn resource_round_trips() {
let mut d = IotData::default();
d.put_resource("things", "sensor-1", json!({"thingName": "sensor-1"}));
assert_eq!(
d.get_resource("things", "sensor-1").unwrap()["thingName"],
"sensor-1"
);
assert_eq!(d.list_resources("things").len(), 1);
assert!(d.remove_resource("things", "sensor-1").is_some());
assert!(d.get_resource("things", "sensor-1").is_none());
assert!(!d.resources.contains_key("things"));
}
}