-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathdb.rs
More file actions
6774 lines (6192 loc) · 218 KB
/
db.rs
File metadata and controls
6774 lines (6192 loc) · 218 KB
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{
collections::HashMap,
env::{self},
fmt::Display,
path::Path,
str::FromStr,
};
use futures::TryStreamExt;
use futures_core::stream::BoxStream;
use itertools::Itertools;
use rand::{distributions::WeightedIndex, prelude::Distribution};
use rust_decimal::{Decimal, RoundingStrategy};
use rust_decimal_macros::dec;
use sqlx::{
sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous},
types::{time::OffsetDateTime, Text},
Connection, FromRow, Sqlite, SqliteConnection, SqlitePool, Transaction,
};
use tokio::sync::broadcast::error::RecvError;
use tracing::instrument;
use crate::websocket_api;
// should hopefully keep the WAL size nice and small and avoid blocking writers
const CHECKPOINT_PAGE_LIMIT: i64 = 512;
const ARBOR_PIXIE_ACCOUNT_NAME: &str = "Arbor Pixie";
#[derive(Clone, Debug)]
pub struct DB {
arbor_pixie_account_id: i64,
pool: SqlitePool,
}
type SqlxResult<T> = Result<T, sqlx::Error>;
pub type ValidationResult<T> = Result<T, ValidationFailure>;
impl DB {
#[instrument(err)]
pub async fn init() -> anyhow::Result<Self> {
let connection_options = SqliteConnectOptions::from_str(&env::var("DATABASE_URL")?)?
.create_if_missing(true)
.journal_mode(SqliteJournalMode::Wal)
.synchronous(SqliteSynchronous::Normal)
// Wait up to 5 seconds for locks instead of failing immediately
.busy_timeout(std::time::Duration::from_secs(5))
// This should work with the default idle timeout and max lifetime
.optimize_on_close(true, None)
.pragma("optimize", "0x10002")
// already checkpointing in the background
.pragma("wal_autocheckpoint", "0");
let mut management_conn = SqliteConnection::connect_with(&connection_options).await?;
// Ignore missing to enable migration squashing
let mut migrator = sqlx::migrate::Migrator::new(Path::new("./migrations")).await?;
migrator
.set_ignore_missing(true)
.run(&mut management_conn)
.await?;
let (release_tx, mut release_rx) = tokio::sync::broadcast::channel(1);
let pool = SqlitePoolOptions::new()
.min_connections(8)
.max_connections(64)
.after_release(move |_, _| {
let release_tx = release_tx.clone();
Box::pin(async move {
if let Err(e) = release_tx.send(()) {
tracing::error!("release_tx.send failed: {:?}", e);
}
Ok(true)
})
})
.connect_with(connection_options)
.await?;
let arbor_pixie_account_id = sqlx::query_scalar!(
r#"SELECT id as "id!: i64" FROM account WHERE name = ?"#,
ARBOR_PIXIE_ACCOUNT_NAME
)
.fetch_one(&mut management_conn)
.await?;
// checkpointing task
tokio::spawn(async move {
let mut released_connections = 0;
let mut remaining_pages = 0;
loop {
match release_rx.recv().await {
Ok(()) => {
released_connections += 1;
}
#[allow(clippy::cast_possible_wrap)]
Err(RecvError::Lagged(n)) => {
released_connections += n as i64;
}
Err(RecvError::Closed) => {
break;
}
}
let approx_wal_pages = remaining_pages + released_connections * 8;
if approx_wal_pages < CHECKPOINT_PAGE_LIMIT {
continue;
}
match sqlx::query_as::<_, WalCheckPointRow>("PRAGMA wal_checkpoint(PASSIVE)")
.fetch_one(&mut management_conn)
.await
{
Err(e) => {
tracing::error!("wal_checkpoint failed: {:?}", e);
}
Ok(row) => {
released_connections = 0;
remaining_pages = row.log - row.checkpointed;
tracing::info!(
"wal_checkpoint: busy={} log={} checkpointed={}",
row.busy,
row.log,
row.checkpointed
);
}
}
}
});
let db = Self {
arbor_pixie_account_id,
pool,
};
// Seed development data if in dev-mode
#[cfg(feature = "dev-mode")]
{
if let Err(e) = crate::seed::seed_dev_data(&db, &db.pool).await {
tracing::error!("Failed to seed development data: {:?}", e);
}
}
Ok(db)
}
/// Creates a DB instance for testing with a pre-configured pool.
#[cfg(feature = "dev-mode")]
#[must_use]
pub fn new_for_tests(arbor_pixie_account_id: i64, pool: SqlitePool) -> Self {
Self {
arbor_pixie_account_id,
pool,
}
}
#[instrument(err, skip(self))]
pub async fn get_account(&self, account_id: i64) -> SqlxResult<Option<Account>> {
sqlx::query_as!(
Account,
r#"
SELECT
id,
name,
(kinde_id IS NOT NULL OR email IS NOT NULL) AS "is_user: bool",
universe_id,
color
FROM account
WHERE id = ?
"#,
account_id
)
.fetch_optional(&self.pool)
.await
}
#[instrument(err, skip(self))]
pub async fn redeem(
&self,
redeemer_id: i64,
redeem: websocket_api::Redeem,
) -> SqlxResult<ValidationResult<Redeemed>> {
let Ok(amount) = Decimal::try_from(redeem.amount) else {
return Ok(Err(ValidationFailure::InvalidAmount));
};
let fund_id = redeem.fund_id;
if amount.scale() > 2 || amount.is_zero() {
return Ok(Err(ValidationFailure::InvalidAmount));
}
let (mut transaction, transaction_info) = self.begin_write().await?;
let redeemables = sqlx::query!(
r#"
SELECT
*
FROM "redeemable"
WHERE "fund_id" = ?
"#,
fund_id
)
.fetch_all(transaction.as_mut())
.await?;
if redeemables.is_empty() {
return Ok(Err(ValidationFailure::MarketNotRedeemable));
}
let settled = sqlx::query_scalar!(
r#"
SELECT EXISTS (
SELECT 1
FROM market
JOIN redeemable ON (market.id = fund_id OR market.id = constituent_id)
WHERE fund_id = ? AND settled_price IS NOT NULL
) AS "exists!: bool"
"#,
fund_id
)
.fetch_one(transaction.as_mut())
.await?;
if settled {
return Ok(Err(ValidationFailure::MarketSettled));
}
let fund_position_change = -amount;
let amount = Text(amount);
sqlx::query!(
r#"
INSERT INTO "redemption" (
"redeemer_id",
"fund_id",
"transaction_id",
"amount"
)
VALUES (?, ?, ?, ?)
"#,
redeemer_id,
fund_id,
transaction_info.id,
amount
)
.execute(transaction.as_mut())
.await?;
let Text(current_fund_position) = sqlx::query_scalar!(
r#"SELECT position as "position: Text<Decimal>" FROM "exposure_cache" WHERE "account_id" = ? AND "market_id" = ?"#,
redeemer_id,
fund_id,
)
.fetch_optional(transaction.as_mut())
.await?
.unwrap_or_default();
let new_fund_position = Text(current_fund_position + fund_position_change);
sqlx::query!(
r#"
INSERT INTO exposure_cache (
account_id,
market_id,
position,
total_bid_size,
total_offer_size,
total_bid_value,
total_offer_value
) VALUES (?, ?, ?, '0', '0', '0', '0')
ON CONFLICT DO UPDATE SET position = ?
"#,
redeemer_id,
fund_id,
new_fund_position,
new_fund_position
)
.execute(transaction.as_mut())
.await?;
for redeemable in redeemables {
let constituent_position_change = amount.0 * Decimal::from(redeemable.multiplier);
let Text(current_exposure) = sqlx::query_scalar!(
r#"SELECT position as "position: Text<Decimal>" FROM "exposure_cache" WHERE "account_id" = ? AND "market_id" = ?"#,
redeemer_id,
redeemable.constituent_id,
)
.fetch_optional(transaction.as_mut())
.await?
.unwrap_or_default();
let new_exposure = Text(current_exposure + constituent_position_change);
sqlx::query!(
r#"
INSERT INTO exposure_cache (
account_id,
market_id,
position,
total_bid_size,
total_offer_size,
total_bid_value,
total_offer_value
) VALUES (?, ?, ?, '0', '0', '0', '0')
ON CONFLICT DO UPDATE SET position = ?
"#,
redeemer_id,
redeemable.constituent_id,
new_exposure,
new_exposure
)
.execute(transaction.as_mut())
.await?;
}
let Text(redeem_fee) = sqlx::query_scalar!(
r#"SELECT redeem_fee as "redeem_fee: Text<Decimal>" FROM market WHERE id = ?"#,
fund_id
)
.fetch_one(transaction.as_mut())
.await?;
let Some(portfolio) = get_portfolio(&mut transaction, redeemer_id).await? else {
return Ok(Err(ValidationFailure::AccountNotFound));
};
if portfolio.available_balance < redeem_fee {
return Ok(Err(ValidationFailure::InsufficientFunds));
}
let new_balance = Text(portfolio.total_balance - redeem_fee);
sqlx::query!(
r#"UPDATE account SET balance = ? WHERE id = ?"#,
new_balance,
redeemer_id,
)
.execute(transaction.as_mut())
.await?;
transaction.commit().await?;
Ok(Ok(Redeemed {
account_id: redeemer_id,
fund_id,
amount,
transaction_info,
}))
}
#[instrument(err, skip(self))]
pub async fn exercise_option(
&self,
exerciser_id: i64,
exercise: websocket_api::ExerciseOption,
) -> SqlxResult<ValidationResult<OptionExerciseResult>> {
let Ok(amount) = Decimal::try_from(exercise.amount) else {
return Ok(Err(ValidationFailure::InvalidAmount));
};
let amount = amount.normalize();
if amount.is_zero() || amount.is_sign_negative() || amount.scale() > 2 {
return Ok(Err(ValidationFailure::InvalidAmount));
}
let (mut transaction, transaction_info) = self.begin_write().await?;
// Fetch the contract
let contract = sqlx::query!(
r#"
SELECT
id,
option_market_id,
buyer_id,
writer_id,
remaining_amount as "remaining_amount: Text<Decimal>"
FROM option_contract
WHERE id = ?
"#,
exercise.contract_id
)
.fetch_optional(transaction.as_mut())
.await?;
let Some(contract) = contract else {
return Ok(Err(ValidationFailure::ContractNotFound));
};
if contract.buyer_id != exerciser_id {
return Ok(Err(ValidationFailure::NotContractBuyer));
}
if contract.option_market_id != exercise.option_market_id {
return Ok(Err(ValidationFailure::ContractNotFound));
}
if amount > contract.remaining_amount.0 {
return Ok(Err(ValidationFailure::InvalidAmount));
}
let writer_id = contract.writer_id;
// Fetch the option market info
let option = sqlx::query!(
r#"
SELECT
underlying_market_id,
strike_price as "strike_price: Text<Decimal>",
is_call as "is_call: bool",
expiration_date as "expiration_date: OffsetDateTime"
FROM option_market
WHERE market_id = ?
"#,
exercise.option_market_id
)
.fetch_optional(transaction.as_mut())
.await?;
let Some(option) = option else {
return Ok(Err(ValidationFailure::NotOptionMarket));
};
// Check if option market is settled
let option_settled = sqlx::query_scalar!(
r#"SELECT settled_price IS NOT NULL as "settled: bool" FROM market WHERE id = ?"#,
exercise.option_market_id
)
.fetch_one(transaction.as_mut())
.await?;
if option_settled {
return Ok(Err(ValidationFailure::MarketSettled));
}
// Check underlying market settled status
let underlying_settled_price = sqlx::query_scalar!(
r#"SELECT settled_price as "settled_price: Text<Decimal>" FROM market WHERE id = ?"#,
option.underlying_market_id
)
.fetch_one(transaction.as_mut())
.await?;
let is_cash_settled = underlying_settled_price.is_some();
// Determine exercise type
if !is_cash_settled {
// Physical exercise: check expiration
if let Some(expiration) = option.expiration_date {
if transaction_info.timestamp > expiration {
return Ok(Err(ValidationFailure::OptionExpired));
}
}
}
// Cash exercise (underlying settled) is always allowed regardless of expiration
let strike = option.strike_price.0;
let amount_text = Text(amount);
// Update option market positions for both parties
// Exerciser: position decreases by amount
let Text(exerciser_option_pos) = sqlx::query_scalar!(
r#"SELECT position as "position: Text<Decimal>" FROM exposure_cache WHERE account_id = ? AND market_id = ?"#,
exerciser_id,
exercise.option_market_id,
)
.fetch_optional(transaction.as_mut())
.await?
.unwrap_or_default();
let new_exerciser_option_pos = Text(exerciser_option_pos - amount);
sqlx::query!(
r#"
INSERT INTO exposure_cache (account_id, market_id, position, total_bid_size, total_offer_size, total_bid_value, total_offer_value)
VALUES (?, ?, ?, '0', '0', '0', '0')
ON CONFLICT DO UPDATE SET position = ?
"#,
exerciser_id,
exercise.option_market_id,
new_exerciser_option_pos,
new_exerciser_option_pos
)
.execute(transaction.as_mut())
.await?;
// Writer: position increases by amount
let Text(writer_option_pos) = sqlx::query_scalar!(
r#"SELECT position as "position: Text<Decimal>" FROM exposure_cache WHERE account_id = ? AND market_id = ?"#,
writer_id,
exercise.option_market_id,
)
.fetch_optional(transaction.as_mut())
.await?
.unwrap_or_default();
let new_writer_option_pos = Text(writer_option_pos + amount);
sqlx::query!(
r#"
INSERT INTO exposure_cache (account_id, market_id, position, total_bid_size, total_offer_size, total_bid_value, total_offer_value)
VALUES (?, ?, ?, '0', '0', '0', '0')
ON CONFLICT DO UPDATE SET position = ?
"#,
writer_id,
exercise.option_market_id,
new_writer_option_pos,
new_writer_option_pos
)
.execute(transaction.as_mut())
.await?;
// Calculate cash transfer and update underlying positions
let (exerciser_cash_change, exerciser_underlying_change) = if is_cash_settled {
// Cash exercise: transfer intrinsic value
let settled = underlying_settled_price.unwrap().0;
let intrinsic = if option.is_call {
Decimal::ZERO.max(settled - strike)
} else {
Decimal::ZERO.max(strike - settled)
};
(amount * intrinsic, Decimal::ZERO)
} else {
// Physical exercise
if option.is_call {
// Call: exerciser pays strike, gets underlying
(-amount * strike, amount)
} else {
// Put: exerciser receives strike, gives underlying
(amount * strike, -amount)
}
};
let writer_cash_change = -exerciser_cash_change;
let writer_underlying_change = -exerciser_underlying_change;
// Update underlying positions (physical exercise only)
if !is_cash_settled {
// Exerciser underlying position
let Text(exerciser_underlying_pos) = sqlx::query_scalar!(
r#"SELECT position as "position: Text<Decimal>" FROM exposure_cache WHERE account_id = ? AND market_id = ?"#,
exerciser_id,
option.underlying_market_id,
)
.fetch_optional(transaction.as_mut())
.await?
.unwrap_or_default();
let new_exerciser_underlying_pos = Text(exerciser_underlying_pos + exerciser_underlying_change);
sqlx::query!(
r#"
INSERT INTO exposure_cache (account_id, market_id, position, total_bid_size, total_offer_size, total_bid_value, total_offer_value)
VALUES (?, ?, ?, '0', '0', '0', '0')
ON CONFLICT DO UPDATE SET position = ?
"#,
exerciser_id,
option.underlying_market_id,
new_exerciser_underlying_pos,
new_exerciser_underlying_pos
)
.execute(transaction.as_mut())
.await?;
// Writer underlying position
let Text(writer_underlying_pos) = sqlx::query_scalar!(
r#"SELECT position as "position: Text<Decimal>" FROM exposure_cache WHERE account_id = ? AND market_id = ?"#,
writer_id,
option.underlying_market_id,
)
.fetch_optional(transaction.as_mut())
.await?
.unwrap_or_default();
let new_writer_underlying_pos = Text(writer_underlying_pos + writer_underlying_change);
sqlx::query!(
r#"
INSERT INTO exposure_cache (account_id, market_id, position, total_bid_size, total_offer_size, total_bid_value, total_offer_value)
VALUES (?, ?, ?, '0', '0', '0', '0')
ON CONFLICT DO UPDATE SET position = ?
"#,
writer_id,
option.underlying_market_id,
new_writer_underlying_pos,
new_writer_underlying_pos
)
.execute(transaction.as_mut())
.await?;
}
// Update cash balances
let Text(exerciser_balance) = sqlx::query_scalar!(
r#"SELECT balance as "balance: Text<Decimal>" FROM account WHERE id = ?"#,
exerciser_id
)
.fetch_one(transaction.as_mut())
.await?;
let new_exerciser_balance = Text(exerciser_balance + exerciser_cash_change);
sqlx::query!(
r#"UPDATE account SET balance = ? WHERE id = ?"#,
new_exerciser_balance,
exerciser_id,
)
.execute(transaction.as_mut())
.await?;
let Text(writer_balance) = sqlx::query_scalar!(
r#"SELECT balance as "balance: Text<Decimal>" FROM account WHERE id = ?"#,
writer_id
)
.fetch_one(transaction.as_mut())
.await?;
let new_writer_balance = Text(writer_balance + writer_cash_change);
sqlx::query!(
r#"UPDATE account SET balance = ? WHERE id = ?"#,
new_writer_balance,
writer_id,
)
.execute(transaction.as_mut())
.await?;
// Check available balance for both parties
let Some(exerciser_portfolio) = get_portfolio(&mut transaction, exerciser_id).await? else {
return Ok(Err(ValidationFailure::AccountNotFound));
};
if exerciser_portfolio.available_balance.is_sign_negative() {
return Ok(Err(ValidationFailure::InsufficientFunds));
}
let Some(writer_portfolio) = get_portfolio(&mut transaction, writer_id).await? else {
return Ok(Err(ValidationFailure::AccountNotFound));
};
if writer_portfolio.available_balance.is_sign_negative() {
return Ok(Err(ValidationFailure::InsufficientFunds));
}
// Update contract remaining amount
let new_remaining = Text(contract.remaining_amount.0 - amount);
sqlx::query!(
r#"UPDATE option_contract SET remaining_amount = ? WHERE id = ?"#,
new_remaining,
contract.id,
)
.execute(transaction.as_mut())
.await?;
// Record the exercise
let is_cash_settled_db = is_cash_settled;
sqlx::query!(
r#"
INSERT INTO option_exercise (option_market_id, contract_id, exerciser_id, counterparty_id, amount, transaction_id, is_cash_settled)
VALUES (?, ?, ?, ?, ?, ?, ?)
"#,
exercise.option_market_id,
contract.id,
exerciser_id,
writer_id,
amount_text,
transaction_info.id,
is_cash_settled_db,
)
.execute(transaction.as_mut())
.await?;
transaction.commit().await?;
Ok(Ok(OptionExerciseResult {
option_market_id: exercise.option_market_id,
exerciser_id,
counterparty_id: writer_id,
amount: Text(amount),
is_cash_settled,
contract_id: contract.id,
transaction_info,
}))
}
#[instrument(err, skip(self))]
pub async fn get_option_contracts(
&self,
market_id: i64,
account_id: i64,
) -> SqlxResult<Vec<OptionContract>> {
sqlx::query_as!(
OptionContract,
r#"
SELECT
id as "id!",
option_market_id as "option_market_id!",
buyer_id as "buyer_id!",
writer_id as "writer_id!",
remaining_amount as "remaining_amount: _"
FROM option_contract
WHERE option_market_id = ?
AND (buyer_id = ? OR writer_id = ?)
AND CAST(remaining_amount AS REAL) > 0
"#,
market_id,
account_id,
account_id,
)
.fetch_all(&self.pool)
.await
}
#[instrument(err, skip(self))]
pub async fn market_has_hide_account_ids(&self, market_id: i64) -> SqlxResult<bool> {
sqlx::query_scalar!(
r#"SELECT hide_account_ids as "hide_account_ids!: bool" FROM market WHERE id = ?"#,
market_id
)
.fetch_one(&self.pool)
.await
}
#[instrument(err, skip(self))]
pub async fn create_account(
&self,
user_id: i64,
create_account: websocket_api::CreateAccount,
) -> SqlxResult<ValidationResult<Account>> {
let owner_id = create_account.owner_id;
let account_name = create_account.name;
if account_name.trim().is_empty() {
return Ok(Err(ValidationFailure::EmptyName));
}
let universe_id = create_account.universe_id;
let initial_balance = create_account.initial_balance;
let color = match create_account.color {
Some(color) => {
let trimmed = color.trim();
if trimmed.is_empty() {
None
} else if is_valid_account_color(trimmed) {
Some(trimmed.to_ascii_lowercase())
} else {
return Ok(Err(ValidationFailure::InvalidAccountColor));
}
}
None => None,
};
let mut transaction = self.pool.begin().await?;
// Validate universe exists
let universe_owner = sqlx::query_scalar!(
r#"SELECT owner_id FROM universe WHERE id = ?"#,
universe_id
)
.fetch_optional(transaction.as_mut())
.await?;
let Some(universe_owner) = universe_owner else {
return Ok(Err(ValidationFailure::UniverseNotFound));
};
// For non-main universes, only the universe owner can create accounts
// (they can then share ownership to give others access)
if universe_id != 0 {
let user_owns_universe = universe_owner == Some(user_id);
if !user_owns_universe {
return Ok(Err(ValidationFailure::NotUniverseOwner));
}
}
// For main universe, initial_balance must be 0 (no one owns it)
if universe_id == 0 && initial_balance > 0.0 {
return Ok(Err(ValidationFailure::NotUniverseOwner));
}
let balance = initial_balance.to_string();
let color_for_insert = color.clone();
let result = sqlx::query_scalar!(
r#"
INSERT INTO account (name, balance, universe_id, color)
VALUES (?, ?, ?, ?)
RETURNING id
"#,
account_name,
balance,
universe_id,
color_for_insert
)
.fetch_one(transaction.as_mut())
.await;
let is_valid_owner = owner_id == user_id
|| sqlx::query_scalar!(
r#"
SELECT EXISTS(
SELECT 1
FROM account_owner
WHERE account_id = ? AND owner_id = ?
) as "exists!: bool"
"#,
owner_id,
user_id
)
.fetch_one(transaction.as_mut())
.await?;
if !is_valid_owner {
return Ok(Err(ValidationFailure::InvalidOwner));
}
// Owner must be in universe 0 or in the same universe as the new account
let (owner_universe, owner_is_user) = sqlx::query_as::<_, (i64, bool)>(
r#"SELECT universe_id, (kinde_id IS NOT NULL OR email IS NOT NULL) as "is_user" FROM account WHERE id = ?"#,
)
.bind(owner_id)
.fetch_one(transaction.as_mut())
.await?;
if owner_universe != 0 && owner_universe != universe_id {
return Ok(Err(ValidationFailure::OwnerInDifferentUniverse));
}
// If creating account in non-zero universe with owner from universe 0,
// the owner must be a user account (not an alt account)
if universe_id != 0 && owner_universe == 0 && !owner_is_user {
return Ok(Err(ValidationFailure::OwnerMustBeUser));
}
match result {
Ok(account_id) => {
sqlx::query!(
r#"INSERT INTO account_owner (owner_id, account_id) VALUES (?, ?)"#,
owner_id,
account_id
)
.execute(transaction.as_mut())
.await?;
transaction.commit().await?;
Ok(Ok(Account {
id: account_id,
name: account_name,
is_user: false,
universe_id,
color,
}))
}
Err(sqlx::Error::Database(db_err)) => {
if db_err.message().contains("UNIQUE constraint failed") {
transaction.rollback().await?;
Ok(Err(ValidationFailure::NameAlreadyExists))
} else {
Err(sqlx::Error::Database(db_err))
}
}
Err(e) => Err(e),
}
}
#[instrument(err, skip(self))]
pub async fn create_universe(
&self,
owner_id: i64,
name: String,
description: String,
) -> SqlxResult<ValidationResult<Universe>> {
if name.trim().is_empty() {
return Ok(Err(ValidationFailure::EmptyName));
}
let result = sqlx::query_as!(
Universe,
r#"
INSERT INTO universe (name, description, owner_id)
VALUES (?, ?, ?)
RETURNING id, name, description, owner_id
"#,
name,
description,
owner_id
)
.fetch_one(&self.pool)
.await;
match result {
Ok(universe) => Ok(Ok(universe)),
Err(sqlx::Error::Database(db_err)) => {
if db_err.message().contains("UNIQUE constraint failed") {
Ok(Err(ValidationFailure::UniverseNameExists))
} else {
Err(sqlx::Error::Database(db_err))
}
}
Err(e) => Err(e),
}
}
#[instrument(err, skip(self))]
pub async fn get_all_universes(&self) -> SqlxResult<Vec<Universe>> {
sqlx::query_as!(
Universe,
r#"SELECT id, name, description, owner_id FROM universe ORDER BY id"#
)
.fetch_all(&self.pool)
.await
}
#[instrument(err, skip(self))]
pub async fn get_accessible_universes(&self, user_id: i64) -> SqlxResult<Vec<Universe>> {
// User can access universes they own OR universes that contain accounts they own
sqlx::query_as!(
Universe,
r#"
SELECT DISTINCT u.id, u.name, u.description, u.owner_id
FROM universe u
WHERE u.owner_id = ?
OR u.id IN (
SELECT a.universe_id
FROM account a
WHERE a.id = ?
OR a.id IN (
SELECT ao.account_id
FROM account_owner ao
WHERE ao.owner_id = ?
)
)
ORDER BY u.id
"#,
user_id,
user_id,
user_id
)
.fetch_all(&self.pool)
.await
}
#[instrument(err, skip(self))]
pub async fn get_account_universe_id(&self, account_id: i64) -> SqlxResult<Option<i64>> {
sqlx::query_scalar!(
r#"SELECT universe_id FROM account WHERE id = ?"#,
account_id
)
.fetch_optional(&self.pool)
.await
}
#[instrument(err, skip(self))]
pub async fn get_market_universe_id(&self, market_id: i64) -> SqlxResult<Option<i64>> {
sqlx::query_scalar!(
r#"SELECT universe_id FROM market WHERE id = ?"#,
market_id
)
.fetch_optional(&self.pool)
.await
}
#[instrument(err, skip(self))]
pub async fn share_ownership(
&self,
existing_owner_id: i64,
share_ownership: websocket_api::ShareOwnership,
) -> SqlxResult<ValidationResult<()>> {
let of_account_id = share_ownership.of_account_id;
let to_account_id = share_ownership.to_account_id;
let owner_is_user = sqlx::query_scalar!(
r#"
SELECT EXISTS (
SELECT 1
FROM account
WHERE id = ? AND (kinde_id IS NOT NULL OR email IS NOT NULL)
) AS "exists!: bool"
"#,
existing_owner_id
)
.fetch_one(&self.pool)
.await?;
if !owner_is_user {
return Ok(Err(ValidationFailure::OwnerNotAUser));
}
let is_direct_owner = sqlx::query_scalar!(
r#"
SELECT EXISTS(
SELECT 1
FROM account_owner
WHERE owner_id = ? AND account_id = ?
) as "exists!: bool"
"#,
existing_owner_id,
of_account_id
)
.fetch_one(&self.pool)
.await?;
if !is_direct_owner {
return Ok(Err(ValidationFailure::NotOwner));
}
let recipient_is_user = sqlx::query_scalar!(
r#"
SELECT EXISTS(
SELECT 1
FROM account
WHERE id = ? AND (kinde_id IS NOT NULL OR email IS NOT NULL)
) as "exists!: bool"
"#,
to_account_id
)
.fetch_one(&self.pool)
.await?;
if !recipient_is_user {
return Ok(Err(ValidationFailure::RecipientNotAUser));
}
let res = sqlx::query!(
r#"INSERT INTO account_owner (account_id, owner_id) VALUES (?, ?) ON CONFLICT DO NOTHING"#,
of_account_id,
to_account_id
)
.execute(&self.pool)
.await?;
if res.rows_affected() == 0 {
Ok(Err(ValidationFailure::AlreadyOwner))
} else {
Ok(Ok(()))
}
}
#[instrument(err, skip(self))]