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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
|
use rusqlite::{params, Connection};
pub fn init_db(conn: &Connection) {
conn.execute(
"CREATE TABLE IF NOT EXISTS users (
username TEXT PRIMARY KEY,
hashed_password TEXT NOT NULL,
account_id INTEGER UNIQUE,
balance INTEGER DEFAULT 1000
)",
[],
)
.unwrap();
// Add column if not exists (for migration)
let _ = conn.execute("ALTER TABLE users ADD COLUMN account_id INTEGER UNIQUE", []);
let _ = conn.execute(
"ALTER TABLE users ADD COLUMN balance INTEGER DEFAULT 1000",
[],
);
conn.execute(
"CREATE TABLE IF NOT EXISTS plays (
session_id TEXT PRIMARY KEY,
username TEXT NOT NULL,
game_type TEXT NOT NULL,
bet_amount INTEGER NOT NULL,
winnings INTEGER NOT NULL,
balance_after INTEGER NOT NULL,
details TEXT NOT NULL DEFAULT '{}',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)",
[],
)
.unwrap();
// A multi-step game's reserved bet is written here in the same transaction
// as the debit, so a crash between reserve and settle is recoverable.
conn.execute(
"CREATE TABLE IF NOT EXISTS pending_plays (
session_id TEXT PRIMARY KEY,
username TEXT NOT NULL,
game_type TEXT NOT NULL,
bet_amount INTEGER NOT NULL,
details TEXT NOT NULL DEFAULT '{}',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)",
[],
)
.unwrap();
}
pub fn add_user(
conn: &Connection,
username: &str,
hashed_password: &str,
) -> Result<(), Box<dyn std::error::Error>> {
if get_hashed_password(conn, username).is_some() {
return Err("user already exists".into());
}
for _ in 0..10 {
let account_id: u32 = rand::random::<u32>();
match conn.execute(
"INSERT INTO users (username, hashed_password, account_id, balance)
VALUES (?1, ?2, ?3, ?4)",
params![username, hashed_password, account_id as i64, 1000i64],
) {
Ok(_) => return Ok(()),
Err(rusqlite::Error::SqliteFailure(error, _))
if error.code == rusqlite::ErrorCode::ConstraintViolation =>
{
continue;
}
Err(error) => return Err(Box::new(error)),
}
}
Err("could not allocate a unique account id".into())
}
pub fn get_hashed_password(conn: &Connection, username: &str) -> Option<String> {
let mut stmt = conn
.prepare("SELECT hashed_password FROM users WHERE username = ?1")
.unwrap();
let mut rows = stmt.query([username]).unwrap();
if let Ok(Some(row)) = rows.next() {
row.get(0).ok()
} else {
None
}
}
pub fn set_hashed_password(
conn: &Connection,
username: &str,
hashed_password: &str,
) -> rusqlite::Result<()> {
conn.execute(
"UPDATE users SET hashed_password = ?1 WHERE username = ?2",
params![hashed_password, username],
)?;
Ok(())
}
pub fn get_account_id(conn: &Connection, username: &str) -> Option<i64> {
let mut stmt = conn
.prepare("SELECT account_id FROM users WHERE username = ?1")
.unwrap();
let mut rows = stmt.query([username]).unwrap();
if let Ok(Some(row)) = rows.next() {
Some(row.get::<_, i64>(0).ok()?)
} else {
None
}
}
pub fn get_balance(conn: &Connection, username: &str) -> Option<i64> {
let mut stmt = conn
.prepare("SELECT balance FROM users WHERE username = ?1")
.unwrap();
let mut rows = stmt.query([username]).unwrap();
if let Ok(Some(row)) = rows.next() {
Some(row.get::<_, i64>(0).ok()?)
} else {
None
}
}
/// Settle one play and record its audit row in a single transaction.
///
/// `details` is a JSON object with game-specific fields (reels, cards,
/// winning number, crash point, ...). All SQL is parameterized: usernames are
/// data, never part of the statement text.
///
/// Returns the balance after the play.
#[allow(clippy::too_many_arguments)]
pub fn apply_play(
conn: &mut Connection,
session_id: &str,
username: &str,
game_type: &str,
bet_amount: i64,
winnings: i64,
details: &str,
) -> rusqlite::Result<i64> {
let tx = conn.transaction()?;
let deducted = tx.execute(
"UPDATE users SET balance = balance - ?1
WHERE username = ?2 AND balance >= ?1",
params![bet_amount, username],
)?;
if deducted != 1 {
return Err(rusqlite::Error::QueryReturnedNoRows);
}
tx.execute(
"UPDATE users SET balance = balance + ?1 WHERE username = ?2",
params![winnings, username],
)?;
let balance_after: i64 = tx.query_row(
"SELECT balance FROM users WHERE username = ?1",
[username],
|row| row.get(0),
)?;
tx.execute(
"INSERT INTO plays
(session_id, username, game_type, bet_amount, winnings,
balance_after, details)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![
session_id,
username,
game_type,
bet_amount,
winnings,
balance_after,
details
],
)?;
tx.commit()?;
Ok(balance_after)
}
pub fn count_plays(conn: &Connection, username: &str) -> i64 {
conn.query_row(
"SELECT COUNT(*) FROM plays WHERE username = ?1",
[username],
|row| row.get(0),
)
.unwrap_or(0)
}
/// Reserve a bet before a multi-step hand starts.
///
/// The debit and the `pending_plays` row are one transaction. If the server
/// dies before the hand settles, the row is what lets the next startup record
/// the lost bet instead of leaving an orphaned deduction.
#[allow(clippy::too_many_arguments)]
pub fn reserve_play(
conn: &mut Connection,
session_id: &str,
username: &str,
game_type: &str,
bet_amount: i64,
details: &str,
) -> rusqlite::Result<i64> {
let tx = conn.transaction()?;
let updated = tx.execute(
"UPDATE users SET balance = balance - ?1
WHERE username = ?2 AND balance >= ?1",
params![bet_amount, username],
)?;
if updated != 1 {
return Err(rusqlite::Error::QueryReturnedNoRows);
}
tx.execute(
"INSERT INTO pending_plays (session_id, username, game_type, bet_amount, details)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![session_id, username, game_type, bet_amount, details],
)?;
let balance = tx.query_row(
"SELECT balance FROM users WHERE username = ?1",
[username],
|row| row.get(0),
)?;
tx.commit()?;
Ok(balance)
}
/// Add to an existing reservation (blackjack double), keeping the pending row
/// and the debit in step.
pub fn extend_reservation(
conn: &mut Connection,
session_id: &str,
amount: i64,
) -> rusqlite::Result<i64> {
let tx = conn.transaction()?;
let updated = tx.execute(
"UPDATE users SET balance = balance - ?1
WHERE balance >= ?1
AND username = (SELECT username FROM pending_plays WHERE session_id = ?2)",
params![amount, session_id],
)?;
if updated != 1 {
return Err(rusqlite::Error::QueryReturnedNoRows);
}
tx.execute(
"UPDATE pending_plays SET bet_amount = bet_amount + ?1 WHERE session_id = ?2",
params![amount, session_id],
)?;
let balance = tx.query_row(
"SELECT balance FROM users
WHERE username = (SELECT username FROM pending_plays WHERE session_id = ?1)",
[session_id],
|row| row.get(0),
)?;
tx.commit()?;
Ok(balance)
}
/// Undo part of a reservation when the action that needed it fails.
pub fn refund_reservation(
conn: &mut Connection,
session_id: &str,
amount: i64,
) -> rusqlite::Result<i64> {
let tx = conn.transaction()?;
tx.execute(
"UPDATE users SET balance = balance + ?1
WHERE username = (SELECT username FROM pending_plays WHERE session_id = ?2)",
params![amount, session_id],
)?;
tx.execute(
"UPDATE pending_plays SET bet_amount = MAX(bet_amount - ?1, 0) WHERE session_id = ?2",
params![amount, session_id],
)?;
let balance = tx.query_row(
"SELECT balance FROM users
WHERE username = (SELECT username FROM pending_plays WHERE session_id = ?1)",
[session_id],
|row| row.get(0),
)?;
tx.commit()?;
Ok(balance)
}
/// Settle a hand whose bet was already reserved: credit winnings, write the
/// audit row, clear the reservation, and return the new balance.
#[allow(clippy::too_many_arguments)]
pub fn settle_play(
conn: &mut Connection,
session_id: &str,
username: &str,
game_type: &str,
bet_amount: i64,
winnings: i64,
details: &str,
) -> rusqlite::Result<i64> {
let tx = conn.transaction()?;
tx.execute(
"UPDATE users SET balance = balance + ?1 WHERE username = ?2",
params![winnings, username],
)?;
let balance_after: i64 = tx.query_row(
"SELECT balance FROM users WHERE username = ?1",
[username],
|row| row.get(0),
)?;
tx.execute(
"INSERT INTO plays
(session_id, username, game_type, bet_amount, winnings,
balance_after, details)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![
session_id,
username,
game_type,
bet_amount,
winnings,
balance_after,
details
],
)?;
tx.execute(
"DELETE FROM pending_plays WHERE session_id = ?1",
[session_id],
)?;
tx.commit()?;
Ok(balance_after)
}
/// Settle reservations left behind by a server restart.
///
/// A round cannot outlive the process that held its in-memory state, so the
/// reserved bet is forfeited and recorded, never refunded. Call this once at
/// startup, before serving players: sweeping while rounds are live would settle
/// someone else's hand. Returns how many orphaned plays were settled.
pub fn abandon_pending(conn: &mut Connection) -> rusqlite::Result<usize> {
let tx = conn.transaction()?;
let pending: Vec<(String, String, String, i64, String)> = {
let mut statement = tx.prepare(
"SELECT session_id, username, game_type, bet_amount, details
FROM pending_plays",
)?;
let rows = statement.query_map([], |row| {
Ok((
row.get(0)?,
row.get(1)?,
row.get(2)?,
row.get(3)?,
row.get(4)?,
))
})?;
rows.collect::<rusqlite::Result<_>>()?
};
for (session_id, username, game_type, bet_amount, details) in &pending {
let balance_after: i64 = tx
.query_row(
"SELECT balance FROM users WHERE username = ?1",
[username],
|row| row.get(0),
)
.unwrap_or(0);
let details = abandoned_details(details);
tx.execute(
"INSERT OR IGNORE INTO plays
(session_id, username, game_type, bet_amount, winnings,
balance_after, details)
VALUES (?1, ?2, ?3, ?4, 0, ?5, ?6)",
params![
session_id,
username,
game_type,
bet_amount,
balance_after,
details
],
)?;
tx.execute(
"DELETE FROM pending_plays WHERE session_id = ?1",
[session_id],
)?;
}
tx.commit()?;
Ok(pending.len())
}
/// Mark a game's own detail blob as abandoned without dropping its payload.
fn abandoned_details(raw: &str) -> String {
let mut value: serde_json::Value = serde_json::from_str(raw)
.unwrap_or_else(|_| serde_json::Value::Object(serde_json::Map::new()));
if let Some(object) = value.as_object_mut() {
object.insert("result".to_string(), serde_json::json!("abandoned"));
object.insert("phase".to_string(), serde_json::json!("abandoned"));
object.insert("reason".to_string(), serde_json::json!("server_restart"));
}
value.to_string()
}
|