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
//! Simple Resource
use crate::common::ArrErr;
use crate::grpc::server::{Id, ValidationResult};
use crate::grpc::GrpcDataObjectType;
use core::fmt::Debug;
use log::error;
use std::collections::HashMap;
use std::marker::PhantomData;
use uuid::Uuid;
pub use super::{ObjectType, Resource, ResourceObject};
pub use crate::postgres::init::PsqlInitResource;
pub use crate::postgres::init::PsqlInitSimpleResource;
pub use crate::postgres::simple_resource::*;
pub use crate::postgres::PsqlSearch;
/// Generic trait providing specific functions for our `simple` resources
pub trait SimpleResource<T>: Resource + PsqlType + ObjectType<T>
where
T: GrpcDataObjectType,
{
/// Returns [`Some<String>`] with the value of [`SimpleResource<T>`]'s `id` field
///
/// Returns [`None`] if no `id` field was found in `T`'s [`ResourceDefinition`](super::ResourceDefinition)
/// Returns [`None`] if the `id` field value is not set
fn get_id(&self) -> Option<String> {
match Self::try_get_id_field() {
Ok(field) => match self.get_ids() {
Some(map) => map.get(&field).cloned(),
None => None,
},
Err(_) => None,
}
}
/// Set [`SimpleResource<T>`]'s `id` [`String`]
///
/// Logs an error if no `id` field was found in `T`'s [`ResourceDefinition`](super::ResourceDefinition)
fn set_id(&mut self, id: String) {
match Self::try_get_id_field() {
Ok(field) => match self.get_ids() {
Some(mut map) => {
map.insert(field, id);
}
None => {
self.set_ids(HashMap::from([(field, id)]));
}
},
Err(_) => {
error!(
"(set_id) Could not set id for Resource Object [{}].",
Self::get_psql_table()
);
}
}
}
/// Returns [`SimpleResource<T>`]'s `id` [`String`]
///
/// # Errors
///
/// Returns [`ArrErr`] "No id provided for GenericResource when calling \[try_get_id\]" if the `id` field is [`None`]
fn try_get_id(&self) -> Result<String, ArrErr> {
match self.get_id() {
Some(id) => Ok(id),
None => {
let error = "No id provided for GenericResource.".to_string();
error!("(try_get_id) {}", error);
Err(ArrErr::Error(error))
}
}
}
/// Returns [`SimpleResource<T>`]'s `id` [`String`] as [`Uuid`]
///
/// # Errors
///
/// Returns [`ArrErr`] if the `id` [`String`] could not be converted to a valid [`Uuid`]
fn try_get_uuid(&self) -> Result<Uuid, ArrErr> {
Uuid::try_parse(&self.try_get_id()?).map_err(ArrErr::from)
}
}
impl<T: GrpcDataObjectType + prost::Message> SimpleResource<T> for ResourceObject<T> where
Self: PsqlType
{
}
impl<T: GrpcDataObjectType> PsqlObjectType<T> for ResourceObject<T> where Self: ObjectType<T> {}
impl<T: GrpcDataObjectType> PsqlType for ResourceObject<T> where Self: ObjectType<T> + Resource {}
/// Generic resource result wrapper struct used to implement our generic traits
#[derive(Debug)]
pub struct GenericResourceResult<T, U>
where
T: SimpleResource<U>,
U: GrpcDataObjectType,
{
/// [`PhantomData`] needed to provide the [`GrpcDataObjectType`] during implementation
pub phantom: PhantomData<U>,
/// [`ResourceObject`] with resource id and data
pub resource: Option<T>,
/// [`ValidationResult`] returned from the update action
pub validation_result: ValidationResult,
}
impl<T> From<Id> for ResourceObject<T>
where
Self: ObjectType<T>,
T: GrpcDataObjectType + prost::Message,
{
fn from(id: Id) -> Self {
let id_field = match Self::try_get_id_field() {
Ok(field) => field,
Err(e) => {
// Panic here, we should -always- have an id_field configured for our simple resources.
// If we hit this scenario, we should fix our code, so we need to let this know with a hard crash.
panic!("(from) Can't convert Id into ResourceObject<T>: {e}")
}
};
Self {
ids: Some(HashMap::from([(id_field, id.id)])),
data: None,
mask: None,
}
}
}
impl<T> From<T> for ResourceObject<T>
where
Self: ObjectType<T>,
T: GrpcDataObjectType + prost::Message,
{
fn from(obj: T) -> Self {
Self {
ids: None,
data: Some(obj),
mask: None,
}
}
}
/// Generates gRPC server implementations
#[macro_export]
macro_rules! build_grpc_simple_resource_impl {
($resource:tt) => {
impl PsqlSearch for ResourceObject<Data> {}
impl PsqlInitSimpleResource for ResourceObject<Data> {}
impl PsqlInitResource for ResourceObject<Data> {
fn _get_create_table_query() -> String {
<ResourceObject<Data> as PsqlInitSimpleResource>::_get_create_table_query()
}
}
impl TryFrom<Vec<Row>> for List {
type Error = ArrErr;
fn try_from(rows: Vec<Row>) -> Result<Self, ArrErr> {
debug!("(try_from) Converting Vec<Row> to List: {:?}", rows);
let mut res: Vec<Object> = Vec::with_capacity(rows.len());
for row in rows.into_iter() {
let id: Uuid = row.get(format!("{}_id", stringify!($resource)).as_str());
let converted = Object {
id: id.to_string(),
data: Some(row.try_into()?),
};
res.push(converted);
}
Ok(List { list: res })
}
}
};
}
/// Generates `From` trait implementations for [`ResourceObject<Data>`] into and from Grpc defined Resource.
#[macro_export]
macro_rules! build_generic_resource_impl_from {
() => {
impl From<Object> for ResourceObject<Data> {
fn from(obj: Object) -> Self {
let id_field = match Self::try_get_id_field() {
Ok(field) => field,
Err(e) => {
// Panic here, we should -always- have an id_field configured for our simple resources.
// If we hit this scenario, we should fix our code, so we need to let this know with a hard crash.
panic!("(from) Can't convert Object into ResourceObject<Data>: {e}")
}
};
Self {
ids: Some(HashMap::from([(id_field, obj.id)])),
data: obj.data,
mask: None,
}
}
}
impl From<ResourceObject<Data>> for Object {
fn from(obj: ResourceObject<Data>) -> Self {
let id = obj.try_get_id();
match id {
Ok(id) => Self {
id,
data: obj.get_data(),
},
Err(e) => {
panic!(
"(from) Can't convert ResourceObject<Data> into {} without an 'id': {e}",
stringify!(Object)
)
}
}
}
}
impl From<UpdateObject> for ResourceObject<Data> {
fn from(obj: UpdateObject) -> Self {
let id_field = match Self::try_get_id_field() {
Ok(field) => field,
Err(e) => {
// Panic here, we should -always- have an id_field configured for our simple resources.
// If we hit this scenario, we should fix our code, so we need to let this know with a hard crash.
panic!("(from) Can't convert UpdateObject into ResourceObject<Data>: {e}")
}
};
Self {
ids: Some(HashMap::from([(id_field, obj.id)])),
data: obj.data,
mask: obj.mask,
}
}
}
impl From<GenericResourceResult<ResourceObject<Data>, Data>> for Response {
fn from(obj: GenericResourceResult<ResourceObject<Data>, Data>) -> Self {
let res = match obj.resource {
Some(obj) => {
let res: Object = obj.into();
Some(res)
}
None => None,
};
Self {
validation_result: Some(obj.validation_result),
object: res,
}
}
}
};
}