Skip to content

Commit

Permalink
Introduces persist_event_if (#142)
Browse files Browse the repository at this point in the history
I introduced a new `persist_event_if` function to be used where a potentially async side effect needs to be performed so that we may construct a persistent event.

In my particular situation, I have a behaviour that maintains a synchronised counter and a private key for all edge-based gateways. This counter is required to be incremented and then encrypted along with a single entity's stable MAC address, which is a field of the entity state. The result is a value that can be used in a "public address" which does not reveal an underlying stable address.

For more info on this type of address: https://en.wikipedia.org/wiki/IPv6_address#Stable_privacy_addresses.
  • Loading branch information
huntc authored Feb 1, 2024
1 parent e0c43db commit ad0a353
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions akka-persistence-rs/src/effect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,28 @@ where
{
}

/// A side effect to run a function asynchronously and then, if ok,
/// persist an event. The associated
/// behavior is available so that communication channels, for
/// example, can be accessed by the side-effect. Additionally, the
/// latest state given any previous effect having persisted an event,
/// or else the state at the outset of the effects being applied,
/// is also available.
pub fn persist_event_if<B, F, R>(f: F) -> ThenPersistEvent<B, F, R>
where
B: EventSourcedBehavior + Send + Sync + 'static,
B::State: Send + Sync,
F: FnOnce(&B, Option<&B::State>, Result) -> R + Send,
R: Future<Output = StdResult<Option<B::Event>, Error>> + Send,
<B as EventSourcedBehavior>::Event: Send,
{
ThenPersistEvent {
deletion_event: false,
f: Some(f),
phantom: PhantomData,
}
}

/// The return type of [EffectExt::then_reply].
pub struct ThenReply<B, F, R, T> {
f: Option<F>,
Expand Down Expand Up @@ -784,4 +806,36 @@ mod tests {

assert_eq!(reply_to_receiver.await, Ok(reply_value));
}

#[test(tokio::test)]
async fn test_persist_event_if() {
let entity_id = EntityId::from("entity-id");
let expected = EventEnvelope {
deletion_event: false,
entity_id: entity_id.clone(),
seq_nr: 1,
event: TestEvent,
timestamp: Utc::now(),
};
let mut handler = TestHandler {
expected: expected.clone(),
};
let mut entity_ops = TestEntityOps {
expected_get_entity_id: entity_id.clone(),
get_result: TestState,
expected_update: expected,
};

assert!(persist_event_if(|_b, _, _| async { Ok(Some(TestEvent)) })
.process(
&TestBehavior,
&mut handler,
&mut entity_ops,
&entity_id,
&mut 0,
Ok(()),
)
.await
.is_ok());
}
}

0 comments on commit ad0a353

Please sign in to comment.