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

Make examples work #47

Open
wants to merge 1 commit 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
14 changes: 7 additions & 7 deletions aper-stateroom/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use aper::connection::{MessageToClient, MessageToServer, ServerConnection, ServerHandle};
use aper::{Aper, IntentMetadata};
use chrono::Utc;
use chrono::{DateTime, Utc};
pub use stateroom::ClientId;
use stateroom::{MessagePayload, StateroomContext, StateroomService};
use std::collections::HashMap;
Expand All @@ -11,7 +11,7 @@ where
P::Intent: Unpin + 'static,
{
connection: ServerConnection<P>,
suspended_event: Option<(P::Intent, IntentMetadata)>,
suspended_event: Option<(DateTime<Utc>, P::Intent)>,
client_connections: HashMap<ClientId, ServerHandle<P>>,

/// Pseudo-connection for sending timer events.
Expand Down Expand Up @@ -48,7 +48,7 @@ where
}

if let Some(ev) = &susp {
let dur = ev.1.timestamp.signed_duration_since(Utc::now());
let dur = ev.0.signed_duration_since(Utc::now());
ctx.set_timer(dur.num_milliseconds().max(0) as u32);
}

Expand Down Expand Up @@ -114,13 +114,13 @@ where
}

fn timer(&mut self, ctx: &impl StateroomContext) {
if let Some(mut event) = self.suspended_event.take() {
event.1.timestamp = Utc::now();
let event = bincode::serialize(&event).unwrap();
if let Some((_timestamp, intent)) = self.suspended_event.take() {
let intent = bincode::serialize(&intent).unwrap();
self.process_message(
MessageToServer::Intent {
intent: event,
intent,
client_version: 0,
metadata: IntentMetadata::new(None, Utc::now()),
Comment on lines +117 to +123
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use the original timestamp when constructing IntentMetadata

Currently, IntentMetadata is initialized with the current time using Utc::now(). To accurately reflect the intended execution time of the suspended intent, consider using the original timestamp _timestamp extracted from self.suspended_event.

Apply this diff to use the scheduled timestamp:

 metadata: IntentMetadata::new(None, Utc::now()),
+metadata: IntentMetadata::new(None, _timestamp),

Committable suggestion was skipped due to low confidence.

},
None,
ctx,
Expand Down
3 changes: 2 additions & 1 deletion aper/src/aper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use crate::{
store::{Store, StoreHandle},
IntentMetadata, Mutation,
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::{collections::VecDeque, fmt::Debug};

Expand All @@ -24,7 +25,7 @@ pub trait Aper: AperSync + 'static {
metadata: &IntentMetadata,
) -> Result<(), Self::Error>;

fn suspended_event(&self) -> Option<(Self::Intent, IntentMetadata)> {
fn suspended_event(&self) -> Option<(DateTime<Utc>, Self::Intent)> {
None
}
}
Expand Down
4 changes: 3 additions & 1 deletion aper/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub enum MessageToServer {
Intent {
intent: Vec<u8>,
client_version: u64,
metadata: IntentMetadata,
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure backward compatibility when adding metadata to MessageToServer::Intent

Adding the metadata field to the MessageToServer::Intent enum variant may lead to deserialization issues with clients or servers that are not updated to handle this new field. This change can break compatibility with existing systems.

Consider implementing versioning for your messages or providing default values to maintain backward compatibility with older clients and servers.

},
RequestState {
latest_version: u64,
Expand Down Expand Up @@ -82,6 +83,7 @@ impl<A: Aper> ClientConnection<A> {
(self.message_callback)(MessageToServer::Intent {
intent,
client_version: version,
metadata,
});

Ok(())
Expand Down Expand Up @@ -163,10 +165,10 @@ impl<A: Aper> ServerHandle<A> {
MessageToServer::Intent {
intent,
client_version,
metadata,
} => {
let intent = bincode::deserialize(intent).unwrap();
let mut server_borrow = self.server.lock().unwrap();
let metadata = IntentMetadata::new(Some(self.client_id), Utc::now());
let Ok(mutations) = server_borrow.apply(&intent, &metadata) else {
// still need to ack the client.

Expand Down
6 changes: 3 additions & 3 deletions examples/counter/common/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use aper::{data_structures::atom::Atom, Aper, AperSync, IntentEvent};
use aper::{data_structures::atom::Atom, Aper, AperSync, IntentMetadata};
use serde::{Deserialize, Serialize};

#[derive(AperSync, Clone)]
Expand All @@ -23,10 +23,10 @@ impl Aper for Counter {
type Intent = CounterIntent;
type Error = ();

fn apply(&mut self, event: &IntentEvent<CounterIntent>) -> Result<(), ()> {
fn apply(&mut self, intent: &CounterIntent, _metadata: &IntentMetadata) -> Result<(), ()> {
let value = self.value.get();

match &event.intent {
match &intent {
CounterIntent::Add(i) => {
self.value.set(value + i);
}
Expand Down
82 changes: 40 additions & 42 deletions examples/drop-four/common/src/state.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use aper::{
data_structures::{atom::Atom, fixed_array::FixedArray},
Aper, AperSync, IntentEvent,
Aper, AperSync, IntentMetadata,
};
use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -154,14 +154,14 @@ impl Aper for DropFourGame {
type Intent = GameTransition;
type Error = ();

fn apply(&mut self, event: &IntentEvent<Self::Intent>) -> Result<(), ()> {
match event.intent {
fn apply(&mut self, intent: &Self::Intent, metadata: &IntentMetadata) -> Result<(), ()> {
match intent {
GameTransition::Join => {
if PlayState::Waiting == self.play_state.get() {
if self.player_map.teal_player.get().is_none() {
self.player_map.teal_player.set(event.client);
self.player_map.teal_player.set(metadata.client);
} else if self.player_map.brown_player.get().is_none() {
self.player_map.brown_player.set(event.client);
self.player_map.brown_player.set(metadata.client);
Comment on lines +162 to +164
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle potential None values for metadata.client

When assigning metadata.client to teal_player and brown_player, ensure that metadata.client is Some(client_id) to avoid assigning None as a player ID, which may lead to unexpected behavior.

You can modify the code to check for Some(client_id) before assignment:

 if self.player_map.teal_player.get().is_none() {
+    if let Some(client_id) = metadata.client {
         self.player_map.teal_player.set(Some(client_id));
+    } else {
+        return Err(()); // Handle None client ID appropriately
+    }
 } else if self.player_map.brown_player.get().is_none() {
+    if let Some(client_id) = metadata.client {
         self.player_map.brown_player.set(Some(client_id));
         self.play_state.set(PlayState::Playing);
+    } else {
+        return Err(()); // Handle None client ID appropriately
+    }
 }

Committable suggestion was skipped due to low confidence.

self.play_state.set(PlayState::Playing);
}
}
Expand All @@ -171,15 +171,15 @@ impl Aper for DropFourGame {
if self.winner.get().is_some() {
return Ok(());
} // Someone has already won.
if self.player_map.id_of_color(self.next_player.get()) != event.client {
if self.player_map.id_of_color(self.next_player.get()) != metadata.client {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure correct comparison of client IDs

The comparison between self.player_map.id_of_color(self.next_player.get()) and metadata.client compares two Option<u32> values. To avoid potential mismatches due to None values, consider unwrapping both options safely before comparison.

You might adjust the code as follows:

-    if self.player_map.id_of_color(self.next_player.get()) != metadata.client {
+    if let (Some(expected_id), Some(actual_id)) = (
+        self.player_map.id_of_color(self.next_player.get()),
+        metadata.client,
+    ) {
+        if expected_id != actual_id {
+            return Ok(()); // Play out of turn.
+        }
+    } else {
+        return Ok(()); // Missing player ID.
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if self.player_map.id_of_color(self.next_player.get()) != metadata.client {
if let (Some(expected_id), Some(actual_id)) = (
self.player_map.id_of_color(self.next_player.get()),
metadata.client,
) {
if expected_id != actual_id {
return Ok(()); // Play out of turn.
}
} else {
return Ok(()); // Missing player ID.
}

return Ok(());
} // Play out of turn.

if let Some(insert_row) = self.board.lowest_open_row(c as u32) {
if let Some(insert_row) = self.board.lowest_open_row(*c as u32) {
self.board
.set(insert_row, c as u32, Some(self.next_player.get()));
.set(insert_row, *c as u32, Some(self.next_player.get()));
Comment on lines +178 to +180
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add bounds check for column index to prevent potential panics

When casting *c from usize to u32, ensure that the column index is within valid bounds to prevent integer overflow or out-of-bounds access.

Apply this diff to add a bounds check:

+    if (*c as u32) >= BOARD_COLS {
+        return Err(()); // Column index is out of bounds.
+    }
     if let Some(insert_row) = self.board.lowest_open_row(*c as u32) {
         self.board
             .set(insert_row, *c as u32, Some(self.next_player.get()));

Committable suggestion was skipped due to low confidence.


let winner = self.board.check_winner_at(insert_row as i32, c as i32);
let winner = self.board.check_winner_at(insert_row as i32, *c as i32);

self.winner.set(winner);
self.next_player.set(self.next_player.get().other());
Expand Down Expand Up @@ -221,31 +221,36 @@ mod tests {
#[test]
fn test_game() {
let mut game = DropFourGame::new();
let dummy_timestamp = Utc.timestamp_millis_opt(0).unwrap();
let player1 = 1;
let player2 = 2;

let player1_meta = IntentMetadata {
client: Some(player1),
timestamp: Utc.timestamp_millis_opt(0).unwrap(),
};
let player2_meta = IntentMetadata {
client: Some(player2),
timestamp: Utc.timestamp_millis_opt(0).unwrap(),
};

assert_eq!(Waiting, game.play_state.get());

game.apply(&IntentEvent::new(Some(player1), dummy_timestamp, Join))
.unwrap();
game.apply(&Join, &player1_meta).unwrap();

assert_eq!(Waiting, game.play_state.get());

assert_eq!(Some(player1), game.player_map.teal_player.get(),);
assert_eq!(Some(player1), game.player_map.teal_player.get());

game.apply(&IntentEvent::new(Some(player2), dummy_timestamp, Join))
.unwrap();
game.apply(&Join, &player2_meta).unwrap();

assert_eq!(game.play_state.get(), Playing,);
assert_eq!(Some(player2), game.player_map.brown_player.get(),);
assert_eq!(Teal, game.next_player.get(),);
assert_eq!(Some(player2), game.player_map.brown_player.get());
assert_eq!(Teal, game.next_player.get());

game.apply(&IntentEvent::new(Some(player1), dummy_timestamp, Drop(4)))
.unwrap();
game.apply(&Drop(4), &player1_meta).unwrap();

expect_disc(&game, 5, 4, Teal);
assert_eq!(Brown, game.next_player.get(),);
assert_eq!(Brown, game.next_player.get());

// v
// .......
Expand All @@ -255,10 +260,9 @@ mod tests {
// .......
// ....T..

game.apply(&IntentEvent::new(Some(player2), dummy_timestamp, Drop(4)))
.unwrap();
game.apply(&Drop(4), &player2_meta).unwrap();

assert_eq!(Teal, game.next_player.get(),);
assert_eq!(Teal, game.next_player.get());
expect_disc(&game, 4, 4, Brown);

// v
Expand All @@ -269,10 +273,9 @@ mod tests {
// ....B..
// ....T..

game.apply(&IntentEvent::new(Some(player1), dummy_timestamp, Drop(3)))
.unwrap();
game.apply(&Drop(3), &player1_meta).unwrap();

assert_eq!(Brown, game.next_player.get(),);
assert_eq!(Brown, game.next_player.get());
expect_disc(&game, 5, 3, Teal);

// v
Expand All @@ -283,10 +286,9 @@ mod tests {
// ....B..
// ...TT..

game.apply(&IntentEvent::new(Some(player2), dummy_timestamp, Drop(5)))
.unwrap();
game.apply(&Drop(5), &player2_meta).unwrap();

assert_eq!(Teal, game.next_player.get(),);
assert_eq!(Teal, game.next_player.get());
expect_disc(&game, 5, 5, Brown);

// v
Expand All @@ -297,10 +299,9 @@ mod tests {
// ....B..
// ...TTB.

game.apply(&IntentEvent::new(Some(player1), dummy_timestamp, Drop(2)))
.unwrap();
game.apply(&Drop(2), &player1_meta).unwrap();

assert_eq!(Brown, game.next_player.get(),);
assert_eq!(Brown, game.next_player.get());
expect_disc(&game, 5, 2, Teal);

// v
Expand All @@ -311,10 +312,9 @@ mod tests {
// ....B..
// ..TTTB.

game.apply(&IntentEvent::new(Some(player2), dummy_timestamp, Drop(2)))
.unwrap();
game.apply(&Drop(2), &player2_meta).unwrap();

assert_eq!(Teal, game.next_player.get(),);
assert_eq!(Teal, game.next_player.get());
expect_disc(&game, 4, 2, Brown);

// v
Expand All @@ -325,12 +325,11 @@ mod tests {
// ..B.B..
// ..TTTB.

game.apply(&IntentEvent::new(Some(player1), dummy_timestamp, Drop(1)))
.unwrap();
game.apply(&Drop(1), &player1_meta).unwrap();

assert_eq!(Brown, game.next_player.get(),);
assert_eq!(Brown, game.next_player.get());
expect_disc(&game, 5, 1, Teal);
assert_eq!(Some(Teal), game.winner.get(),);
assert_eq!(Some(Teal), game.winner.get());

// v
// .......
Expand All @@ -340,9 +339,8 @@ mod tests {
// ..B.B..
// .TTTTB.

game.apply(&IntentEvent::new(Some(player1), dummy_timestamp, Reset))
.unwrap();
game.apply(&Reset, &player1_meta).unwrap();

assert_eq!(None, game.winner.get(),);
assert_eq!(None, game.winner.get());
}
}
2 changes: 1 addition & 1 deletion examples/drop-four/service/.cargo/config
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[build]
target = "wasm32-wasi"
target = "wasm32-wasip1"
12 changes: 6 additions & 6 deletions examples/timer/common/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use aper::{data_structures::atom::Atom, Aper, AperSync, IntentEvent};
use aper::{data_structures::atom::Atom, Aper, AperSync, IntentMetadata};
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};

Expand All @@ -18,25 +18,25 @@ impl Aper for Timer {
type Intent = TimerIntent;
type Error = ();

fn apply(&mut self, event: &IntentEvent<Self::Intent>) -> Result<(), ()> {
match event.intent {
fn apply(&mut self, intent: &Self::Intent, metadata: &IntentMetadata) -> Result<(), ()> {
match intent {
TimerIntent::Reset => self.value.set(0),
TimerIntent::Increment => {
self.value.set(self.value.get() + 1);
self.last_increment.set(event.timestamp);
self.last_increment.set(metadata.timestamp);
}
}

Ok(())
}

fn suspended_event(&self) -> Option<IntentEvent<TimerIntent>> {
fn suspended_event(&self) -> Option<(DateTime<Utc>, TimerIntent)> {
let next_event = self
.last_increment
.get()
.checked_add_signed(Duration::seconds(1))
.unwrap();

Some(IntentEvent::new(None, next_event, TimerIntent::Increment))
Some((next_event, TimerIntent::Increment))
}
Comment on lines +33 to +40
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid potential panic by handling None case in suspended_event

Using .unwrap() after checked_add_signed can cause a panic if the date arithmetic results in an overflow. It's safer to handle the Option returned to prevent unexpected panics.

Consider handling the None case explicitly:

 fn suspended_event(&self) -> Option<(DateTime<Utc>, TimerIntent)> {
     let next_event = self
         .last_increment
         .get()
-        .checked_add_signed(Duration::seconds(1))
-        .unwrap();
+        .checked_add_signed(Duration::seconds(1))?;
     Some((next_event, TimerIntent::Increment))
 }

This change ensures that if an overflow occurs, the function gracefully returns None instead of panicking.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
fn suspended_event(&self) -> Option<(DateTime<Utc>, TimerIntent)> {
let next_event = self
.last_increment
.get()
.checked_add_signed(Duration::seconds(1))
.unwrap();
Some(IntentEvent::new(None, next_event, TimerIntent::Increment))
Some((next_event, TimerIntent::Increment))
fn suspended_event(&self) -> Option<(DateTime<Utc>, TimerIntent)> {
let next_event = self
.last_increment
.get()
.checked_add_signed(Duration::seconds(1))?;
Some((next_event, TimerIntent::Increment))
}

}
Loading