Skip to content

feat: serde dynamo #40

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ tracing = "0.1"
tracing-subscriber = { version = "0.2", features = ["fmt", "json"] }
tokio = { version = "1", features = ["full"] }

[dependencies.serde_dynamo]
git = "https://github.com/sciguy16/serde_dynamo.git"
branch = "aws-0_5"
features = ["aws-sdk-dynamodb+0_6"]
version = "3.0.0-alpha"
optional = true

[dev-dependencies]
# Only allow hardcoded credentials for unit tests
aws-types = { version = "0.4", features = ["hardcoded-credentials"] }
Expand All @@ -32,7 +39,7 @@ reqwest = { version = "0.11", features = ["json"] }

[features]
default = ["lambda"]
lambda = ["lambda_runtime", "lambda_http", "rayon"]
lambda = ["lambda_runtime", "lambda_http", "rayon", "serde_dynamo"]

[[bin]]
name = "delete-product"
Expand Down
85 changes: 0 additions & 85 deletions src/store/dynamodb/ext.rs

This file was deleted.

64 changes: 15 additions & 49 deletions src/store/dynamodb/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,9 @@ use super::{Store, StoreDelete, StoreGet, StoreGetAll, StorePut};
use crate::{Error, Product, ProductRange};
use async_trait::async_trait;
use aws_sdk_dynamodb::{model::AttributeValue, Client};
use std::collections::HashMap;
use serde_dynamo::aws_sdk_dynamodb_0_6::{from_attribute_value, from_item, from_items, to_item};
use tracing::{info, instrument};

mod ext;
use ext::AttributeValuesExt;

/// DynamoDB store implementation.
pub struct DynamoDBStore {
client: Client,
Expand Down Expand Up @@ -42,14 +39,15 @@ impl StoreGetAll for DynamoDBStore {
let res = req.send().await?;

// Build response
let products = match res.items {
Some(items) => items
.into_iter()
.map(|v| v.try_into())
.collect::<Result<Vec<Product>, Error>>()?,
let products: Vec<Product> = match res.items {
Some(items) => from_items(items).map_err(|_|
// TODO: Find out correct error from underlying error?
Error::InternalError("Missing name"))?,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This already shows a problem: How to map the underlying error to our very specific error Missing name. I don't think that the underlying serde errors give us that info: https://github.com/zenlist/serde_dynamo/blob/3.0.0-alpha/src/error.rs

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking into the source code, it looks like it just uses serde_dynamo::ErrorImpl::Message, which might contain the right message - but that's not a guarantee. The best thing would be to write a small sample using the Product struct and serde_dynamo.

None => Vec::default(),
};
let next = res.last_evaluated_key.map(|m| m.get_s("id").unwrap());
let next = res
.last_evaluated_key
.map(|m| from_attribute_value(m["id"].clone()).unwrap());
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if there is a more elegant way to write this?

Ok(ProductRange { products, next })
}
}
Expand All @@ -69,7 +67,8 @@ impl StoreGet for DynamoDBStore {
.await?;

Ok(match res.item {
Some(item) => Some(item.try_into()?),
// TODO: Find out correct error from underlying error?
Some(item) => from_item(item).map_err(|_| Error::InternalError("Missing name"))?,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same problem as above.

None => None,
})
}
Expand All @@ -84,7 +83,8 @@ impl StorePut for DynamoDBStore {
self.client
.put_item()
.table_name(&self.table_name)
.set_item(Some(product.into()))
// TODO: Can this fail?
.set_item(Some(to_item(product).unwrap()))
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We still have a unit test for that, so we tested that to_item can serialize a product.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That shouldn't fail since all the fields in a product map to valid DynamoDB attributes.

.send()
.await?;

Expand All @@ -109,48 +109,14 @@ impl StoreDelete for DynamoDBStore {
}
}

impl From<&Product> for HashMap<String, AttributeValue> {
/// Convert a &Product into a DynamoDB item
fn from(value: &Product) -> HashMap<String, AttributeValue> {
let mut retval = HashMap::new();
retval.insert("id".to_owned(), AttributeValue::S(value.id.clone()));
retval.insert("name".to_owned(), AttributeValue::S(value.name.clone()));
retval.insert(
"price".to_owned(),
AttributeValue::N(format!("{:}", value.price)),
);

retval
}
}
impl TryFrom<HashMap<String, AttributeValue>> for Product {
type Error = Error;

/// Try to convert a DynamoDB item into a Product
///
/// This could fail as the DynamoDB item might be missing some fields.
fn try_from(value: HashMap<String, AttributeValue>) -> Result<Self, Self::Error> {
Ok(Product {
id: value
.get_s("id")
.ok_or(Error::InternalError("Missing id"))?,
name: value
.get_s("name")
.ok_or(Error::InternalError("Missing name"))?,
price: value
.get_n("price")
.ok_or(Error::InternalError("Missing price"))?,
})
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::Error;
use aws_sdk_dynamodb::{Client, Config, Credentials, Region};
use aws_smithy_client::{erase::DynConnector, test_connection::TestConnection};
use aws_smithy_http::body::SdkBody;
use std::collections::HashMap;

/// Config for mocking DynamoDB
async fn get_mock_config() -> Config {
Expand Down Expand Up @@ -368,7 +334,7 @@ mod tests {
value.insert("name".to_owned(), AttributeValue::S("name".to_owned()));
value.insert("price".to_owned(), AttributeValue::N("1.0".to_owned()));

let product = Product::try_from(value).unwrap();
let product: Product = from_item(value).unwrap();
assert_eq!(product.id, "id");
assert_eq!(product.name, "name");
assert_eq!(product.price, 1.0);
Expand All @@ -382,7 +348,7 @@ mod tests {
price: 1.5,
};

let value: HashMap<String, AttributeValue> = (&product).into();
let value: HashMap<String, AttributeValue> = to_item(product).unwrap();
assert_eq!(value.get("id").unwrap().as_s().unwrap(), "id");
assert_eq!(value.get("name").unwrap().as_s().unwrap(), "name");
assert_eq!(value.get("price").unwrap().as_n().unwrap(), "1.5");
Expand Down