summaryrefslogtreecommitdiff
path: root/server/src/play.rs
blob: 9ea2f42787f5dceecae493881aa03c13cd9525d8 (plain)
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
use async_trait::async_trait;
use protocol::{bridge_engine::{GameState, Player, Bid, Deal}};
use rand::random;
use serde::{Deserialize, Serialize};
use serde_json::json;
use sqlx::{query, PgPool};
use uuid::Uuid;

use crate::error::BridgeError;

#[async_trait]
pub trait Journal {
    // Next sequence number to use.
    fn next(&self) -> i64;

    // Append payload to the journal at sequence number `seq`.
    async fn append(&mut self, seq: i64, payload: serde_json::Value) -> Result<(), BridgeError>;

    // Fetch all journal entries with sequence number greater or equal to `seq`.
    async fn replay(&mut self, seq: i64) -> Result<Vec<serde_json::Value>, BridgeError>;
}

pub struct DbJournal {
    db: PgPool,
    id: Uuid,
    seq: i64
}

impl DbJournal {
    pub fn new(db: PgPool, id: Uuid) -> Self {
        Self { db, id, seq: -1 }
    }
}

#[async_trait]
impl Journal for DbJournal {
    async fn append(&mut self, seq: i64, payload: serde_json::Value) -> Result<(), BridgeError> {
        let result = query!(
            r#"
              insert into object_journal (id, seq, payload)
              values ($1, $2, $3)
            "#,
            self.id,
            seq,
            payload,
        )
        .execute(&self.db)
            .await;
        if let Err(sqlx::Error::Database(e)) = result {
            if e.constraint() == Some("journal_entry") {
                return Err(BridgeError::JournalConflict(format!("{}", self.id), seq));
            }
        }
        Ok(())
    }

    async fn replay(&mut self, seq: i64) -> Result<Vec<serde_json::Value>, BridgeError> {
        let results = query!(
            r#"
              select payload from object_journal
              where id = $1 and seq >= $2
              order by seq
            "#,
            self.id,
            seq
        )
        .fetch_all(&self.db)
        .await?;
        Ok(results.into_iter().map(|v| v.payload).collect())
    }

    fn next(&self) -> i64 {
        self.seq + 1
    }
}

#[derive(PartialEq, Eq, Clone, Debug, Serialize, Deserialize)]
pub enum TableUpdate {
    NewDeal(Deal, Player),
    ChangeSettings(TableSettings),
    Bid(Bid),
}

#[derive(PartialEq, Eq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct TableSettings {
    west_player: Option<String>,
    nort_player: Option<String>,
    east_player: Option<String>,
    south_player: Option<String>,
}

pub struct Table<J>
where
    J: Journal,
{
    journal: J,
    settings: TableSettings,
    game: GameState,
}

impl<J: Journal> Table<J> {
    pub fn game(&self) -> &GameState { &self.game }
}

impl<J: Journal> Table<J> {
    pub async fn new(mut journal: J) -> Result<Self, BridgeError> {
        let game = Self::init(&mut journal).await?;
        Ok(Table { journal, game, settings: Default::default() })
    }

    async fn init(journal: &mut J) -> Result<GameState, BridgeError> {
        let game = GameState::new(random(), random());
        journal.append(0, json!(game)).await?;
        Ok(game)
    }

    pub async fn replay(mut journal: J) -> Result<Self, BridgeError> {
        let games = journal.replay(0).await?;
        if games.is_empty() {
            return Err(BridgeError::NotFound("table journal missing".to_string()));
        }
        let game = serde_json::from_value(games[games.len() - 1].clone())?;
        Ok(Table { journal, game, settings: Default::default() } )
    }

    pub async fn new_or_replay(mut journal: J) -> Result<Self, BridgeError> {
        let game = Self::init(&mut journal).await;
        if let Err(BridgeError::JournalConflict(..)) = game {
            return Self::replay(journal).await;
        }
        Ok(Self { journal, game: game?, settings: Default::default() } )
    }
}


pub fn advance_play<J: Journal>(table: &mut Table<J>) {
    todo!()
}

#[cfg(test)]
mod test {
    use super::*;

    #[derive(Default)]
    pub struct TestJournal {
        log: Vec<Option<serde_json::Value>>,
    }

    #[async_trait]
    impl Journal for TestJournal {
        async fn append(
            &mut self,
            seq: i64,
            payload: serde_json::Value,
        ) -> Result<(), BridgeError> {
            if seq != self.log.len() as i64 {
                return Err(BridgeError::UpdateConflict(self.log.len() as i64, seq));
            }
            self.log.push(Some(payload));
            Ok(())
        }

        async fn replay(&mut self, seq: i64) -> Result<Vec<serde_json::Value>, BridgeError> {
            Ok(self.log[seq as usize..]
                .into_iter()
                .filter_map(|e| e.clone())
                .collect())
        }

        fn next(&self) -> i64 {
            self.log.len() as i64
        }
    }

    #[tokio::test]
    async fn test_journal() {
        let mut jnl: TestJournal = Default::default();
        let seq = jnl.next();
        assert_eq!(jnl.next(), 0);
        assert_eq!(jnl.append(seq, json!(10)).await.unwrap(), ());
        assert_eq!(jnl.next(), 1);
        assert!(jnl.append(0, json!(0)).await.is_err());
        let seq = jnl.next();
        assert_eq!(jnl.append(seq, json!(20)).await.unwrap(), ());
        assert_eq!(jnl.replay(1).await.unwrap(), vec!(json!(20)));
    }

    #[tokio::test]
    async fn test_new_table() {
        let t1: Table<TestJournal> = Table::new(Default::default()).await.unwrap();
        match t1.game {
            GameState::Bidding { .. } => (),
            _ => panic!("should be Bidding"),
        };
    }

    #[tokio::test]
    async fn test_replay_table() {
        let t1: Table<TestJournal> = Table::new(Default::default()).await.unwrap();
        let game = t1.game;
        let journal = t1.journal;

        let t2 = Table::replay(journal).await.unwrap();
        assert_eq!(game, t2.game);
    }

    #[tokio::test]
    async fn test_advance_play() {
        let mut t1: Table<TestJournal> = Table::new(Default::default()).await.unwrap();
        let player = t1.game().current_player();
        advance_play(&mut t1);
        assert_ne!(player, t1.game().current_player());
    }
}