11
11
from deps import get_deps , get_constants
12
12
from tasks import reconcile_transaction
13
13
14
- app = FastAPI ()
14
+ api_app = FastAPI ()
15
15
16
16
17
- @app .post ("/transactions" )
18
- async def transaction (
17
+ @api_app .post ("/transactions" )
18
+ async def create_transaction (
19
19
req : utils .TransactionRequest ,
20
20
db : Session = Depends (get_deps ().get_db_session ),
21
21
df : Dragonfly = Depends (get_deps ().get_dragonfly ),
22
22
w3 : Web3 = Depends (get_deps ().get_web3 ),
23
23
) -> utils .TransactionResponse :
24
24
# Try to acquire a lock on the user account.
25
25
lock_key = utils .user_account_lock_key (req .user_account_id )
26
- lock = df .set (name = lock_key , value = utils .LOCK_VALUE , nx = True , ex = utils .LOCK_EXPIRATION_SECONDS )
27
- if not lock :
26
+ locked = df .set (
27
+ name = lock_key , value = utils .LOCK_VALUE ,
28
+ nx = True , ex = utils .LOCK_EXPIRATION_SECONDS ,
29
+ )
30
+
31
+ if not locked :
28
32
raise HTTPException (
29
33
status_code = 409 ,
30
34
detail = "User account is locked since a transaction is submitted very recently. Please try again later." ,
@@ -81,8 +85,8 @@ async def transaction(
81
85
82
86
# Cache the transaction in Dragonfly.
83
87
cache_key = utils .txn_cache_key (txn .id )
84
- _ = df . hset ( cache_key , mapping = utils .txn_to_dict (txn ) )
85
- _ = df . expire ( cache_key , utils .CACHE_NORMAL_EXPIRATION_SECONDS )
88
+ mapping = utils .txn_to_dict (txn )
89
+ utils . hset_and_expire ( df , cache_key , mapping , utils .CACHE_NORMAL_EXPIRATION_SECONDS )
86
90
87
91
# Start the transaction reconciliation task.
88
92
reconcile_transaction .delay (txn .id )
@@ -91,7 +95,7 @@ async def transaction(
91
95
return utils .txn_to_response (txn )
92
96
93
97
94
- @app .get ("/transactions/{txn_id}" )
98
+ @api_app .get ("/transactions/{txn_id}" )
95
99
async def get_transaction (
96
100
txn_id : int ,
97
101
db : Session = Depends (get_deps ().get_db_session ),
@@ -115,11 +119,10 @@ async def get_transaction(
115
119
# If the transaction is not found, cache an empty value with only the ID and return a 404.
116
120
# Caching an empty value is important to prevent cache penetrations.
117
121
if txn is None :
118
- _ = df .hset (cache_key , mapping = {"id" : txn_id })
119
- _ = df .expire (cache_key , utils .CACHE_EMPTY_EXPIRATION_SECONDS )
122
+ utils .hset_and_expire (df , cache_key , {"id" : txn_id }, utils .CACHE_EMPTY_EXPIRATION_SECONDS )
120
123
raise HTTPException (status_code = 404 , detail = "Transaction not found" )
121
124
122
125
# Cache the transaction in Dragonfly and return the response.
123
- _ = df . hset ( cache_key , mapping = utils .txn_to_dict (txn ) )
124
- _ = df . expire ( cache_key , utils .CACHE_NORMAL_EXPIRATION_SECONDS )
126
+ mapping = utils .txn_to_dict (txn )
127
+ utils . hset_and_expire ( df , cache_key , mapping , utils .CACHE_NORMAL_EXPIRATION_SECONDS )
125
128
return utils .txn_to_response (txn )
0 commit comments