Skip to content
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

chore: port post-transaction from sqlx-ledger #57

Merged
merged 16 commits into from
May 16, 2024
Merged
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
47 changes: 47 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ async-trait = "0.1.80"
axum = { version = "0.7.5", features = ["macros"] }
axum-extra = { version = "0.9.3", default-features = false, features = ["tracing", "typed-header"] }
base64 = { version = "0.22.1" }
cached = { version = "0.51", features = ["async"] }
chrono = { version = "0.4.31", features = ["clock", "serde"], default-features = false }
clap = { version = "4.4", features = ["derive", "env"] }
derive_builder = "0.20.0"
Expand Down
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ re-run-nodejs-example: clean-deps start-deps
check-code: sdl
git diff --exit-code cala-server/schema.graphql
SQLX_OFFLINE=true cargo fmt --check --all
SQLX_OFFLINE=true cargo check
SQLX_OFFLINE=true cargo clippy --all-features
SQLX_OFFLINE=true cargo audit

Expand Down
13 changes: 13 additions & 0 deletions cala-cel-interpreter/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,16 @@ use thiserror::Error;

use crate::cel_type::*;

#[derive(Error, Debug)]
pub enum ResultCoercionError {
#[error("Error evaluating expression '{0}' - Could not coerce {1:?} into {2:?}")]
BadCoreTypeCoercion(String, CelType, CelType),
#[error("Error evaluating expression '{0}' - Could not coerce {1:?} into {2:?}")]
BadExternalTypeCoercion(String, CelType, &'static str),
#[error("Error evaluating expression '{0}' - Could not coerce {1:?} into {2:?} - Reason: {3}")]
ExternalTypeCoercionError(String, String, &'static str, String),
}

#[derive(Error, Debug)]
pub enum CelError {
#[error("CelError - CelParseError: {0}")]
Expand All @@ -28,6 +38,9 @@ pub enum CelError {
#[error("CelError - Unexpected: {0}")]
Unexpected(String),

#[error("CelError - {0}")]
ResultCoercionError(#[from] ResultCoercionError),

#[error("Error evaluating cell expression '{0}' - {1}")]
EvaluationError(String, Box<Self>),
}
8 changes: 4 additions & 4 deletions cala-cel-interpreter/src/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@ pub struct CelExpression {
}

impl CelExpression {
pub fn try_evaluate<'a, T: TryFrom<CelResult<'a>, Error = E>, E: From<CelError>>(
pub fn try_evaluate<'a, T: TryFrom<CelResult<'a>, Error = ResultCoercionError>>(
&'a self,
ctx: &CelContext,
) -> Result<T, E> {
) -> Result<T, CelError> {
let res = self.evaluate(ctx)?;
T::try_from(CelResult {
Ok(T::try_from(CelResult {
expr: &self.expr,
val: res,
})
})?)
}

pub fn evaluate(&self, ctx: &CelContext) -> Result<CelValue, CelError> {
Expand Down
38 changes: 23 additions & 15 deletions cala-cel-interpreter/src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -258,59 +258,63 @@ impl TryFrom<&CelValue> for Arc<String> {
}

impl<'a> TryFrom<CelResult<'a>> for NaiveDate {
type Error = CelError;
type Error = ResultCoercionError;

fn try_from(CelResult { expr, val }: CelResult) -> Result<Self, Self::Error> {
if let CelValue::Date(d) = val {
Ok(d)
} else {
Err(CelError::EvaluationError(
Err(ResultCoercionError::BadCoreTypeCoercion(
format!("{expr:?}"),
Box::new(CelError::BadType(CelType::Date, CelType::from(&val))),
CelType::from(&val),
CelType::Date,
))
}
}
}

impl<'a> TryFrom<CelResult<'a>> for Uuid {
type Error = CelError;
type Error = ResultCoercionError;

fn try_from(CelResult { expr, val }: CelResult) -> Result<Self, Self::Error> {
if let CelValue::Uuid(id) = val {
Ok(id)
} else {
Err(CelError::EvaluationError(
Err(ResultCoercionError::BadCoreTypeCoercion(
format!("{expr:?}"),
Box::new(CelError::BadType(CelType::Uuid, CelType::from(&val))),
CelType::from(&val),
CelType::Uuid,
))
}
}
}

impl<'a> TryFrom<CelResult<'a>> for String {
type Error = CelError;
type Error = ResultCoercionError;

fn try_from(CelResult { expr, val }: CelResult) -> Result<Self, Self::Error> {
if let CelValue::String(s) = val {
Ok(s.to_string())
} else {
Err(CelError::EvaluationError(
Err(ResultCoercionError::BadCoreTypeCoercion(
format!("{expr:?}"),
Box::new(CelError::BadType(CelType::String, CelType::from(&val))),
CelType::from(&val),
CelType::String,
))
}
}
}

impl<'a> TryFrom<CelResult<'a>> for Decimal {
type Error = CelError;
type Error = ResultCoercionError;

fn try_from(CelResult { expr, val }: CelResult) -> Result<Self, Self::Error> {
match val {
CelValue::Decimal(n) => Ok(n),
_ => Err(CelError::EvaluationError(
_ => Err(ResultCoercionError::BadCoreTypeCoercion(
format!("{expr:?}"),
Box::new(CelError::BadType(CelType::Decimal, CelType::from(&val))),
CelType::from(&val),
CelType::Decimal,
)),
}
}
Expand All @@ -328,19 +332,23 @@ impl From<&CelKey> for CelType {
}

impl TryFrom<&CelKey> for String {
type Error = CelError;
type Error = ResultCoercionError;

fn try_from(v: &CelKey) -> Result<Self, Self::Error> {
if let CelKey::String(s) = v {
Ok(s.to_string())
} else {
Err(CelError::BadType(CelType::String, CelType::from(v)))
Err(ResultCoercionError::BadCoreTypeCoercion(
format!("{v:?}"),
CelType::from(v),
CelType::String,
))
}
}
}

impl<'a> TryFrom<CelResult<'a>> for serde_json::Value {
type Error = CelError;
type Error = ResultCoercionError;

fn try_from(CelResult { expr, val }: CelResult) -> Result<Self, Self::Error> {
use serde_json::*;
Expand Down
7 changes: 5 additions & 2 deletions cala-ledger-core-types/src/balance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@ use serde::{Deserialize, Serialize};
use super::primitives::*;

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BalanceValues {
pub struct BalanceSnapshot {
pub journal_id: JournalId,
pub account_id: AccountId,
pub entry_id: EntryId,
pub currency: Currency,
pub version: u32,
pub created_at: DateTime<Utc>,
pub modified_at: DateTime<Utc>,
pub entry_id: EntryId,
pub settled_dr_balance: Decimal,
pub settled_cr_balance: Decimal,
pub settled_entry_id: EntryId,
Expand Down
1 change: 1 addition & 0 deletions cala-ledger-core-types/src/entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub struct EntryValues {
pub journal_id: JournalId,
pub account_id: AccountId,
pub entry_type: String,
pub sequence: u32,
pub layer: Layer,
pub units: Decimal,
pub currency: Currency,
Expand Down
12 changes: 11 additions & 1 deletion cala-ledger-core-types/src/outbox.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use serde::{Deserialize, Serialize};

use crate::{account::*, entry::*, journal::*, primitives::*, transaction::*, tx_template::*};
use crate::{
account::*, balance::*, entry::*, journal::*, primitives::*, transaction::*, tx_template::*,
};

#[derive(Debug, Serialize, Deserialize)]
pub struct OutboxEvent {
Expand Down Expand Up @@ -45,6 +47,14 @@ pub enum OutboxEventPayload {
source: DataSource,
entry: EntryValues,
},
BalanceCreated {
source: DataSource,
balance: BalanceSnapshot,
},
BalanceUpdated {
source: DataSource,
balance: BalanceSnapshot,
},
}

#[derive(
Expand Down
49 changes: 40 additions & 9 deletions cala-ledger-core-types/src/primitives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use rusty_money::{crypto, iso};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use cel_interpreter::{CelResult, CelValue};
use cel_interpreter::{CelResult, CelType, CelValue, ResultCoercionError};

crate::entity_id! { OutboxEventId }
crate::entity_id! { AccountId }
Expand All @@ -26,6 +26,22 @@ impl Default for DebitOrCredit {
}
}

impl<'a> TryFrom<CelResult<'a>> for DebitOrCredit {
type Error = ResultCoercionError;

fn try_from(CelResult { expr, val }: CelResult) -> Result<Self, Self::Error> {
match val {
CelValue::String(v) if v.as_ref() == "DEBIT" => Ok(DebitOrCredit::Debit),
CelValue::String(v) if v.as_ref() == "CREDIT" => Ok(DebitOrCredit::Credit),
v => Err(ResultCoercionError::BadExternalTypeCoercion(
format!("{expr:?}"),
CelType::from(&v),
"DebitOrCredit",
)),
}
}
}

#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, sqlx::Type)]
#[sqlx(type_name = "Status", rename_all = "snake_case")]
#[serde(rename_all = "snake_case")]
Expand All @@ -40,7 +56,7 @@ impl Default for Status {
}
}

#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, sqlx::Type)]
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Hash, sqlx::Type)]
#[sqlx(type_name = "Layer", rename_all = "snake_case")]
pub enum Layer {
Settled,
Expand All @@ -55,14 +71,18 @@ pub enum ParseLayerError {
}

impl<'a> TryFrom<CelResult<'a>> for Layer {
type Error = ParseLayerError;
type Error = ResultCoercionError;

fn try_from(CelResult { val, .. }: CelResult) -> Result<Self, Self::Error> {
fn try_from(CelResult { expr, val }: CelResult) -> Result<Self, Self::Error> {
match val {
CelValue::String(v) if v.as_ref() == "SETTLED" => Ok(Layer::Settled),
CelValue::String(v) if v.as_ref() == "PENDING" => Ok(Layer::Pending),
CelValue::String(v) if v.as_ref() == "ENCUMBERED" => Ok(Layer::Encumbered),
v => Err(ParseLayerError::UnknownLayer(format!("{v:?}"))),
v => Err(ResultCoercionError::BadExternalTypeCoercion(
format!("{expr:?}"),
CelType::from(&v),
"Layer",
)),
}
}
}
Expand Down Expand Up @@ -175,12 +195,23 @@ impl From<Currency> for &'static str {
}

impl<'a> TryFrom<CelResult<'a>> for Currency {
type Error = ParseCurrencyError;
type Error = ResultCoercionError;

fn try_from(CelResult { val, .. }: CelResult) -> Result<Self, Self::Error> {
fn try_from(CelResult { expr, val }: CelResult) -> Result<Self, Self::Error> {
match val {
CelValue::String(v) => v.as_ref().parse(),
v => Err(ParseCurrencyError::UnknownCurrency(format!("{v:?}"))),
CelValue::String(v) => v.as_ref().parse::<Currency>().map_err(|e| {
ResultCoercionError::ExternalTypeCoercionError(
format!("{expr:?}"),
format!("{v:?}"),
"Currency",
format!("{e:?}"),
)
}),
v => Err(ResultCoercionError::BadExternalTypeCoercion(
format!("{expr:?}"),
CelType::from(&v),
"Currency",
)),
}
}
}
Expand Down
Loading
Loading