@@ -99,10 +99,10 @@ def auth():
9999 return
100100
101101
102- async def fetch () -> list [User ]:
102+ async def fetch (timeout = 60.0 ) -> list [User ]:
103103 async with httpx .AsyncClient (
104104 headers = {"Authorization" : f"Bearer { config .authentik_token } " },
105- timeout = 60.0 ,
105+ timeout = timeout ,
106106 ) as client :
107107 url = (
108108 "https://auth.apps.hskrk.pl/api/v3/core/users/?"
@@ -120,8 +120,9 @@ async def fetch() -> list[User]:
120120 next_page = parsed_response ["pagination" ]["next" ]
121121 except httpx .ReadTimeout as t :
122122 logging .warning (
123- f"[HTTP] Timeout reached on fetching users data, page: { next_page } , { t } "
123+ f"[HTTP] Timeout { timeout } reached on fetching users data, page: { next_page } , { t } "
124124 )
125+ raise t
125126 return [User (** u ) for u in results ]
126127
127128
@@ -203,35 +204,31 @@ async def get_user_by_card(card_id: str):
203204 return user
204205
205206
206- @app .get ("/user /-/sync" )
207+ @app .get ("/users /-/sync" )
207208async def sync_on_demand ():
208209 global users_last_success_run
210+ global users_last_failed_run
209211 current_run = datetime .now (tz = UTC )
210- diff_seconds = (current_run - users_last_success_run ).seconds
212+ diff_seconds = (
213+ current_run - users_last_success_run
214+ if users_last_success_run
215+ else datetime (2026 , 1 , 1 )
216+ ).seconds
211217 if diff_seconds < 30 :
212218 logging .debug ("Skipping fetching users, data fresh" )
213- return {
214- "cached" : True ,
215- "last_success_run" : (
216- users_last_success_run .isoformat ().replace ("+00:00" , "Z" )
217- if users_last_success_run
218- else None
219- ),
220- "users" : {
221- "count" : len (users ),
222- },
223- "last_failed_run" : (
224- users_last_failed_run .isoformat ().replace ("+00:00" , "Z" )
225- if users_last_failed_run
226- else None
227- ),
228- }
219+ return {"cached" : True , "status" : "success" }.update (get_user_stats ())
229220 else :
230221 logging .debug (
231222 "Last successful fetch {diff_seconds}s before. Fetching on demand"
232223 )
233- fetch_users ()
234- return get_user_stats ()
224+ status = "succes"
225+ try :
226+ await fetch_users (timeout = 120.0 )
227+ except httpx .HTTPError as err :
228+ logging .error (f"Failed to fetch users: { err .message } " )
229+ users_last_failed_run = current_run
230+ status = "failed"
231+ return {"cached" : False , "status" : status }.update (get_user_stats ())
235232
236233
237234@app .websocket ("/ws" )
0 commit comments