forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredis_db.py
More file actions
1605 lines (1219 loc) · 56.8 KB
/
Copy pathredis_db.py
File metadata and controls
1605 lines (1219 loc) · 56.8 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
import ast
import base64
import json
import os
import secrets
from typing import Any, Callable, Dict, List, Optional, TypeVar, Union, cast
from datetime import datetime, timedelta, timezone
import redis
import logging
from database.api_key_metadata import (
DEV_API_KEY_AUTH_CONTEXT_VERSION,
MCP_API_KEY_AUTH_CONTEXT_VERSION,
ApiKeyCacheReadMode,
ApiKeyCacheReadResult,
)
logger = logging.getLogger(__name__)
# redis.Redis is untyped under strict Pyright; treat the client as Any at this
# SDK boundary. Downstream callers narrow results via the adapter pattern.
_redis_host: Optional[str] = os.getenv('REDIS_DB_HOST')
_redis_port_env: Optional[str] = os.getenv('REDIS_DB_PORT')
r: Any = redis.Redis(
host=cast(str, _redis_host),
port=int(_redis_port_env) if _redis_port_env is not None else 6379,
username='default',
password=os.getenv('REDIS_DB_PASSWORD'),
health_check_interval=30,
)
# Longer than the 10-minute max approval TTL (contract §5) plus clock-skew
# slack, so a jti cannot become reusable while its approval could still be
# considered valid by a verifier with a slow clock.
APPROVAL_JTI_CONSUME_TTL_SECONDS = 900
T = TypeVar("T")
def _decode_redis_value(raw: Union[bytes, str]) -> str:
return raw.decode('utf-8') if isinstance(raw, bytes) else raw
_MAX_LEGACY_LITERAL_CHARS = 64 * 1024
def _fail_open_raw_text(text: str, reason: str) -> str:
try:
from utils.observability.fallback import record_fallback
record_fallback(
component='redis_cache',
from_mode='json',
to_mode='raw_text',
reason=reason,
outcome='degraded',
log=logger,
)
except Exception:
logger.warning('redis cache deserialize fail-open reason=%s', reason)
return text
def _deserialize_cache_value(raw: Union[bytes, str, None]) -> Any:
"""Deserialize a Redis cache value using JSON, with safe fallback for legacy Python literals."""
if raw is None:
return None
text = _decode_redis_value(raw)
try:
return json.loads(text)
except (TypeError, ValueError, json.JSONDecodeError):
if len(text) > _MAX_LEGACY_LITERAL_CHARS:
return _fail_open_raw_text(text, 'oversized')
try:
class _SafeLiteralVisitor(ast.NodeVisitor):
def generic_visit(self, node: ast.AST) -> Any:
raise ValueError('unsupported ast node')
def visit_Expression(self, node: ast.Expression) -> Any:
return self.visit(node.body)
def visit_Dict(self, node: ast.Dict) -> dict[Any, Any]:
out: dict[Any, Any] = {}
for key_node, value_node in zip(node.keys, node.values):
if key_node is None:
raise ValueError('dict unpacking is not a literal')
out[self.visit(key_node)] = self.visit(value_node)
return out
def visit_List(self, node: ast.List) -> list[Any]:
return [self.visit(elt) for elt in node.elts]
def visit_Tuple(self, node: ast.Tuple) -> tuple[Any, ...]:
return tuple(self.visit(elt) for elt in node.elts)
def visit_Set(self, node: ast.Set) -> set[Any]:
return {self.visit(elt) for elt in node.elts}
def visit_Constant(self, node: ast.Constant) -> Any:
return node.value
def visit_UnaryOp(self, node: ast.UnaryOp) -> Any:
if type(node.op) not in (ast.UAdd, ast.USub):
raise ValueError('unsupported unary op')
operand = self.visit(node.operand)
if type(operand) not in (int, float):
raise ValueError('unsupported unary operand')
return operand if type(node.op) is ast.UAdd else -operand
return _SafeLiteralVisitor().visit(ast.parse(text, mode='eval'))
except Exception:
return _fail_open_raw_text(text, 'parse_error')
def _serialize_cache_value(value: Any) -> str:
return json.dumps(value, default=str)
def try_catch_decorator(func: Callable[..., T]) -> Callable[..., Optional[T]]:
"""Wrap func so any exception is logged and returns None (fail-open).
The wrapped callable returns Optional[T] because a failure yields None even
when the underlying function's declared return type is T. Callers must narrow
away None before treating the result as T.
"""
def wrapper(*args: Any, **kwargs: Any) -> Optional[T]:
try:
return func(*args, **kwargs)
except Exception as e:
logger.error(f'Error calling {func.__name__} {e}')
return None
return wrapper
@try_catch_decorator
def get_generic_cache(path: str) -> Any:
key = base64.b64encode(f'{path}'.encode('utf-8'))
key = key.decode('utf-8')
data = r.get(f'cache:{key}')
return json.loads(data) if data else None
@try_catch_decorator
def set_generic_cache(path: str, data: object, ttl: Optional[int] = None) -> None:
key = base64.b64encode(f'{path}'.encode('utf-8'))
key = key.decode('utf-8')
r.set(f'cache:{key}', json.dumps(data, default=str))
if ttl:
r.expire(f'cache:{key}', ttl)
@try_catch_decorator
def delete_generic_cache(path: str) -> None:
key = base64.b64encode(f'{path}'.encode('utf-8'))
key = key.decode('utf-8')
r.delete(f'cache:{key}')
# ******************************************************
# ********************* APP BY ID **********************
# ******************************************************
def set_app_cache_by_id(app_id: str, app: Dict[str, Any]) -> None:
r.set(f'apps:{app_id}', json.dumps(app, default=str), ex=60 * 10) # 10 minutes cached
def get_app_cache_by_id(app_id: str) -> Optional[Dict[str, Any]]:
raw = r.get(f'apps:{app_id}')
if not raw:
return None
loaded: object = json.loads(raw)
return cast(Dict[str, Any], loaded) if isinstance(loaded, dict) else None
def delete_app_cache_by_id(app_id: str) -> None:
r.delete(f'apps:{app_id}')
# ******************************************************
# ********************** PERSONA ***********************
# ******************************************************
def is_username_taken(username: str) -> bool:
"""Check if username is taken by checking if it exists in the username:uid mapping"""
value = r.exists(f'username:{username}:uid')
if value == 0:
return False
return True
def get_uid_by_username(username: str) -> Optional[str]:
"""Get the UID that owns this username"""
uid = r.get(f'username:{username}:uid')
return uid.decode() if uid else None
def save_username(username: str, uid: str) -> None:
"""Save username and add to owner's set"""
# Save username:uid mapping
r.set(f'username:{username}:uid', uid)
# Add to owner's set of usernames
r.sadd(f'uid:{uid}:usernames', username)
# ******************************************************
# *********************** APPS *************************
# ******************************************************
def set_app_usage_count_cache(app_id: str, count: int) -> None:
r.set(f'apps:{app_id}:usage_count', _serialize_cache_value(count), ex=60 * 15) # 15 minutes
def get_app_usage_count_cache(app_id: str) -> Optional[int]:
count = r.get(f'apps:{app_id}:usage_count')
if not count:
return None
loaded = _deserialize_cache_value(count)
if isinstance(loaded, bool):
return None
if isinstance(loaded, int):
return loaded
if isinstance(loaded, float):
return int(loaded)
return None
def set_app_money_made_amount_cache(app_id: str, amount: float) -> None:
r.set(f'apps:{app_id}:money_made', _serialize_cache_value(amount), ex=60 * 15) # 15 minutes
def get_app_money_made_amount_cache(app_id: str) -> Optional[float]:
amount = r.get(f'apps:{app_id}:money_made')
if not amount:
return None
loaded = _deserialize_cache_value(amount)
if isinstance(loaded, bool):
return None
if isinstance(loaded, (int, float)):
return float(loaded)
return None
def set_app_usage_history_cache(app_id: str, usage: List[Dict[str, Any]]) -> None:
r.set(f'apps:{app_id}:usage', json.dumps(usage, default=str), ex=60 * 10) # 10 minutes
def get_app_usage_history_cache(app_id: str) -> List[Dict[str, Any]]:
raw = r.get(f'apps:{app_id}:usage')
if raw is None:
return []
loaded: object = json.loads(raw)
if not loaded:
return []
return cast(List[Dict[str, Any]], loaded)
def get_app_money_made_cache(app_id: str) -> Dict[str, Any]:
raw = r.get(f'apps:{app_id}:money')
if raw is None:
return {}
loaded: object = json.loads(raw)
if not loaded:
return {}
return cast(Dict[str, Any], loaded)
def set_app_money_made_cache(app_id: str, money: Dict[str, Any]) -> None:
r.set(f'apps:{app_id}:money', json.dumps(money, default=str), ex=60 * 10) # 10 minutes
def set_app_review_cache(app_id: str, uid: str, data: Dict[str, Any]) -> None:
raw = r.get(f'plugins:{app_id}:reviews')
loaded = _deserialize_cache_value(raw)
reviews: Dict[str, Any] = cast(Dict[str, Any], loaded) if isinstance(loaded, dict) else {}
reviews[uid] = data
r.set(f'plugins:{app_id}:reviews', _serialize_cache_value(reviews))
def get_specific_user_review(app_id: str, uid: str) -> Dict[str, Any]:
raw = r.get(f'plugins:{app_id}:reviews')
if not raw:
return {}
loaded = _deserialize_cache_value(raw)
if not isinstance(loaded, dict):
return {}
return cast(Dict[str, Any], loaded.get(uid, {}))
def set_user_paid_app(app_id: str, uid: str, ttl: int) -> None:
r.set(f'users:{uid}:paid_apps:{app_id}', app_id, ex=ttl)
def get_user_paid_app(app_id: str, uid: str) -> Optional[str]:
val = r.get(f'users:{uid}:paid_apps:{app_id}')
if not val:
return None
return val.decode()
def set_user_app_subscription_customer_id(app_id: str, uid: str, customer_id: str) -> None:
"""Store the Stripe customer ID for a user's app subscription"""
r.set(f'users:{uid}:app_subs:{app_id}:customer_id', customer_id)
def get_user_app_subscription_customer_id(app_id: str, uid: str) -> Optional[str]:
"""Get the Stripe customer ID for a user's app subscription"""
val = r.get(f'users:{uid}:app_subs:{app_id}:customer_id')
if not val:
return None
return val.decode()
def enable_app(uid: str, app_id: str) -> None:
r.sadd(f'users:{uid}:enabled_plugins', app_id)
def disable_app(uid: str, app_id: str) -> None:
r.srem(f'users:{uid}:enabled_plugins', app_id)
def is_app_enabled(uid: str, app_id: str) -> bool:
return r.sismember(f'users:{uid}:enabled_plugins', app_id)
def get_enabled_apps(uid: str) -> List[str]:
val = r.smembers(f'users:{uid}:enabled_plugins')
if not val:
return []
return [x.decode() for x in val]
def get_app_reviews(app_id: str) -> Dict[str, Any]:
raw = r.get(f'plugins:{app_id}:reviews')
if not raw:
return {}
loaded = _deserialize_cache_value(raw)
return cast(Dict[str, Any], loaded) if isinstance(loaded, dict) else {}
def get_apps_reviews(app_ids: List[str]) -> Dict[str, Any]:
if not app_ids:
return {}
keys = [f'plugins:{app_id}:reviews' for app_id in app_ids]
reviews = r.mget(keys)
if reviews is None:
return {}
result: Dict[str, Any] = {}
for app_id, review in zip(app_ids, reviews):
if not review:
result[app_id] = {}
continue
loaded = _deserialize_cache_value(review)
result[app_id] = cast(Dict[str, Any], loaded) if isinstance(loaded, dict) else {}
return result
def set_app_installs_count(app_id: str, count: int) -> None:
r.set(f'plugins:{app_id}:installs', count)
def increase_app_installs_count(app_id: str) -> None:
r.incr(f'plugins:{app_id}:installs')
def decrease_app_installs_count(app_id: str) -> None:
r.decr(f'plugins:{app_id}:installs')
def get_apps_installs_count(app_ids: List[str]) -> Dict[str, int]:
if not app_ids:
return {}
keys = [f'plugins:{app_id}:installs' for app_id in app_ids]
counts = r.mget(keys)
if counts is None:
return {}
# Clamp to >= 0: the install counter is a plain INCR/DECR with no floor, so drift (a disable with no
# matching enable, or a DECR on an evicted key) can leave a negative value. A negative install count
# would later hit math.log(1 + installs) in compute_app_score and 500 the whole marketplace sort.
return {app_id: max(0, int(count)) if count else 0 for app_id, count in zip(app_ids, counts)}
def cache_user_name(uid: str, name: str, ttl: int = 60 * 60 * 24 * 7) -> None:
r.set(f'users:{uid}:name', name)
r.expire(f'users:{uid}:name', ttl)
def cache_signed_url(blob_path: str, signed_url: str, ttl: int = 60 * 60) -> None:
r.set(f'urls:{blob_path}', signed_url)
r.expire(f'urls:{blob_path}', ttl - 1)
def get_cached_signed_url(blob_path: str) -> str:
signed_url = r.get(f'urls:{blob_path}')
if not signed_url:
return ''
return signed_url.decode()
def delete_cached_signed_url(blob_path: str) -> None:
"""Evict a cached signed URL. Callers deleting the underlying blob must call
this too — a delete that leaves a still-live cached signed URL handing out
reads of a (now 404ing, or worse, since-overwritten) object is a bug."""
r.delete(f'urls:{blob_path}')
def cache_user_geolocation(uid: str, geolocation: Dict[str, Any]) -> None:
# Unset optional fields are dropped rather than serialized as JSON ``null``.
# This key is written by the API tier and read by pusher, which deploys on its
# own cadence; a reader still on the pre-JSON ``eval()`` reader raises
# ``NameError: name 'null' is not defined`` and discards the conversation it
# was finalizing. Every reader rebuilds ``Geolocation`` from this dict, whose
# optional fields already default to ``None`` when absent.
present_fields = {key: value for key, value in geolocation.items() if value is not None}
r.set(f'users:{uid}:geolocation', _serialize_cache_value(present_fields))
# 30m: conversation/tool place tagging does not need second-level freshness;
# clients re-upload on significant moves and at recording start. Keeps the
# last-known coords available without inventing a tighter freshness policy.
r.expire(f'users:{uid}:geolocation', 60 * 30)
def get_cached_user_geolocation(uid: str) -> Optional[Dict[str, Any]]:
raw = r.get(f'users:{uid}:geolocation')
if not raw:
return None
loaded = _deserialize_cache_value(raw)
return cast(Dict[str, Any], loaded) if isinstance(loaded, dict) else None
def delete_cached_user_geolocation(uid: str) -> None:
r.delete(f'users:{uid}:geolocation')
# DAILY SUMMARY UID LOOKUP
def store_daily_summary_to_uid(summary_id: str, uid: str) -> None:
r.set(f'daily-summary:{summary_id}', uid)
def get_daily_summary_uid(summary_id: str) -> str:
uid = r.get(f'daily-summary:{summary_id}')
if not uid:
return ''
return uid.decode()
def remove_daily_summary_to_uid(summary_id: str) -> None:
r.delete(f'daily-summary:{summary_id}')
# VISIIBILTIY OF CONVERSATIONS
def store_conversation_to_uid(conversation_id: str, uid: str) -> None:
r.set(f'memories-visibility:{conversation_id}', uid)
def remove_conversation_to_uid(conversation_id: str) -> None:
r.delete(f'memories-visibility:{conversation_id}')
def get_conversation_uid(conversation_id: str) -> str:
uid = r.get(f'memories-visibility:{conversation_id}')
if not uid:
return ''
return uid.decode()
def add_public_conversation(conversation_id: str) -> None:
r.sadd('public-memories', conversation_id)
def remove_public_conversation(conversation_id: str) -> None:
r.srem('public-memories', conversation_id)
def set_in_progress_conversation_id(uid: str, conversation_id: str, ttl: int = 300) -> None:
r.set(f'users:{uid}:in_progress_memory_id', conversation_id)
r.expire(f'users:{uid}:in_progress_memory_id', ttl)
def remove_in_progress_conversation_id(uid: str) -> None:
r.delete(f'users:{uid}:in_progress_memory_id')
def get_in_progress_conversation_id(uid: str) -> str:
conversation_id = r.get(f'users:{uid}:in_progress_memory_id')
if not conversation_id:
return ''
return conversation_id.decode()
def set_conversation_meeting_id(conversation_id: str, meeting_id: str, ttl: int = 86400) -> None:
"""Store the meeting_id for a conversation. TTL defaults to 24 hours."""
r.set(f'conversation:{conversation_id}:meeting_id', meeting_id)
r.expire(f'conversation:{conversation_id}:meeting_id', ttl)
def get_conversation_meeting_id(conversation_id: str) -> Optional[str]:
"""Retrieve the meeting_id associated with a conversation."""
meeting_id = r.get(f'conversation:{conversation_id}:meeting_id')
if not meeting_id:
return None
return meeting_id.decode()
def set_user_webhook_db(uid: str, wtype: str, url: str) -> None:
r.set(f'users:{uid}:developer:webhook:{wtype}', url)
def disable_user_webhook_db(uid: str, wtype: str) -> None:
r.set(f'users:{uid}:developer:webhook_status:{wtype}', str(False).lower())
def enable_user_webhook_db(uid: str, wtype: str) -> None:
r.set(f'users:{uid}:developer:webhook_status:{wtype}', str(True).lower())
def user_webhook_status_db(uid: str, wtype: str) -> Optional[bool]:
status = r.get(f'users:{uid}:developer:webhook_status:{wtype}')
if status is None:
return None
return status.decode() == str(True).lower()
def get_user_webhook_db(uid: str, wtype: str) -> str:
url = r.get(f'users:{uid}:developer:webhook:{wtype}')
if not url:
return ''
return url.decode()
def get_filter_category_items(uid: str, category: str, limit: Optional[int] = None) -> List[str]:
key = f'users:{uid}:filters:{category}'
if limit:
# Get random sample if limit specified
val = r.srandmember(key, limit)
else:
# Get all items (existing behavior)
val = r.smembers(key)
if not val:
return []
return [x.decode() for x in val]
def add_filter_category_item(uid: str, category: str, item: str) -> None:
r.sadd(f'users:{uid}:filters:{category}', item)
def save_migrated_retrieval_conversation_id(conversation_id: str) -> None:
r.sadd('migrated_retrieval_memory_ids', conversation_id)
r.expire('migrated_retrieval_memory_ids', 60 * 60 * 24 * 7)
def set_proactive_noti_sent_at(uid: str, *, app_id: str, ts: int, ttl: int = 30) -> None:
r.set(f'{uid}:{app_id}:proactive_noti_sent_at', ts, ex=ttl)
def get_proactive_noti_sent_at(uid: str, app_id: str) -> Optional[int]:
val = r.get(f'{uid}:{app_id}:proactive_noti_sent_at')
if not val:
return None
return int(val)
def get_proactive_noti_sent_at_ttl(uid: str, app_id: str) -> int:
return r.ttl(f'{uid}:{app_id}:proactive_noti_sent_at')
PROACTIVE_MESSAGE_CHANNEL = 'proactive_message:listen'
@try_catch_decorator
def publish_proactive_message(
uid: str, app_id: str, title: str, message: str, conversation_id: Optional[str] = None
) -> None:
payload = {
'uid': uid,
'app_id': app_id,
'title': title,
'message': message,
'conversation_id': conversation_id,
}
r.publish(PROACTIVE_MESSAGE_CHANNEL, json.dumps(payload))
_async_redis_client: Optional[Any] = None
async def get_async_redis_client() -> Any:
global _async_redis_client
if _async_redis_client is None:
import redis.asyncio as _asyncio_redis
_async_redis_client = _asyncio_redis.Redis(
host=cast(str, _redis_host),
port=int(_redis_port_env) if _redis_port_env is not None else 6379,
username='default',
password=os.getenv('REDIS_DB_PASSWORD'),
decode_responses=True,
)
return _async_redis_client
@try_catch_decorator
def incr_daily_notification_count(uid: str) -> int:
"""Atomically increment the daily proactive-notification count for a user (mentor + third-party apps). Returns new count."""
from datetime import datetime, timezone
key = f'{uid}:daily_noti_count:{datetime.now(timezone.utc).strftime("%Y-%m-%d")}'
count = r.incr(key)
r.expire(key, 90000) # 25 hours TTL
return count
@try_catch_decorator
def get_daily_notification_count(uid: str) -> int:
"""Get the current daily proactive-notification count for a user (mentor + third-party apps)."""
from datetime import datetime, timezone
key = f'{uid}:daily_noti_count:{datetime.now(timezone.utc).strftime("%Y-%m-%d")}'
val = r.get(key)
if not val:
return 0
return int(val)
def set_user_preferred_app(uid: str, app_id: str) -> None:
"""Stores the user's preferred app ID."""
key = f'user:{uid}:preferred_app'
r.set(key, app_id)
def get_user_preferred_app(uid: str) -> Optional[str]:
"""Retrieves the user's preferred app ID, if set."""
key = f'user:{uid}:preferred_app'
app_id = r.get(key)
return app_id.decode() if app_id else None
@try_catch_decorator
def set_user_data_protection_level(uid: str, level: str) -> None:
"""Caches the user's data protection level."""
key = f'user:{uid}:data_protection_level'
r.set(key, level)
@try_catch_decorator
def get_user_data_protection_level(uid: str) -> Optional[str]:
"""Retrieves the user's cached data protection level."""
key = f'user:{uid}:data_protection_level'
level = r.get(key)
return level.decode() if level else None
# ******************************************************
# ******************* MCP API KEYS *********************
# ******************************************************
@try_catch_decorator
def cache_mcp_api_key(hashed_key: str, user_id: str, ttl: int = 3600) -> None:
"""Caches the user_id for a given hashed MCP API key."""
r.set(f'mcp_api_key:{hashed_key}', user_id, ex=ttl)
@try_catch_decorator
def cache_mcp_api_key_auth_context(
hashed_key: str,
user_id: str,
scopes: Optional[List[str]] = None,
key_id: Optional[str] = None,
app_id: Optional[str] = None,
memory_grant_seeded: bool = True,
auth_context_version: int = MCP_API_KEY_AUTH_CONTEXT_VERSION,
ttl: int = 3600,
) -> bool:
"""Caches the user_id, key identity, and scopes for a given MCP API key."""
cache_data = {
"user_id": user_id,
"scopes": scopes,
"key_id": key_id,
"app_id": app_id,
"memory_grant_seeded": memory_grant_seeded,
"auth_context_version": auth_context_version,
}
r.set(f'mcp_api_key_auth:{hashed_key}', json.dumps(cache_data), ex=ttl)
r.set(f'mcp_api_key:{hashed_key}', user_id, ex=ttl)
return True
@try_catch_decorator
def get_cached_mcp_api_key_user_id(hashed_key: str) -> Optional[str]:
"""Retrieves the user_id for a given hashed MCP API key from cache."""
auth_context = get_cached_mcp_api_key_auth_context(hashed_key)
return auth_context.get("user_id") if auth_context else None
def read_cached_mcp_api_key_auth_context(hashed_key: str) -> ApiKeyCacheReadResult:
"""Read MCP auth context while distinguishing cache absence from failure."""
try:
cached = r.get(f'mcp_api_key_auth:{hashed_key}')
if cached:
decoded = cached.decode() if isinstance(cached, bytes) else cached
cache_data: object = json.loads(decoded)
if not isinstance(cache_data, dict):
return ApiKeyCacheReadResult(mode=ApiKeyCacheReadMode.ERROR)
return ApiKeyCacheReadResult(
mode=ApiKeyCacheReadMode.HIT,
data=cast(Dict[str, Any], cache_data),
)
legacy_cached = r.get(f'mcp_api_key:{hashed_key}')
if not legacy_cached:
return ApiKeyCacheReadResult(mode=ApiKeyCacheReadMode.MISS)
legacy_user_id = legacy_cached.decode() if isinstance(legacy_cached, bytes) else legacy_cached
if not isinstance(legacy_user_id, str):
return ApiKeyCacheReadResult(mode=ApiKeyCacheReadMode.ERROR)
return ApiKeyCacheReadResult(
mode=ApiKeyCacheReadMode.HIT,
data={"user_id": legacy_user_id, "scopes": None, "key_id": None, "app_id": None},
)
except Exception as exc:
logger.error("Error reading MCP API key auth cache: %s", exc)
return ApiKeyCacheReadResult(mode=ApiKeyCacheReadMode.ERROR)
def get_cached_mcp_api_key_auth_context(hashed_key: str) -> Optional[Dict[str, Any]]:
"""Compatibility adapter returning data only for a successful cache hit."""
result = read_cached_mcp_api_key_auth_context(hashed_key)
return result.data if result.mode == ApiKeyCacheReadMode.HIT else None
def delete_cached_mcp_api_key_strict(hashed_key: str) -> bool:
"""Atomically delete both MCP auth cache keys, raising on Redis failure."""
r.delete(f'mcp_api_key:{hashed_key}', f'mcp_api_key_auth:{hashed_key}')
return True
# ******************************************************
# ****************** DEV API KEYS **********************
# ******************************************************
@try_catch_decorator
def cache_dev_api_key(
hashed_key: str,
user_id: str,
scopes: Optional[List[str]] = None,
ttl: int = 3600,
key_id: Optional[str] = None,
app_id: Optional[str] = None,
auth_context_version: int = DEV_API_KEY_AUTH_CONTEXT_VERSION,
) -> bool:
"""Caches Developer API key auth context for uid-only and memory app/key authorization."""
cache_data = {
"user_id": user_id,
"scopes": scopes,
"key_id": key_id,
"app_id": app_id,
"auth_context_version": auth_context_version,
}
r.set(f'dev_api_key:{hashed_key}', json.dumps(cache_data), ex=ttl)
return True
def read_cached_dev_api_key_data(hashed_key: str) -> ApiKeyCacheReadResult:
"""Read Developer auth context while distinguishing absence from failure."""
try:
cached = r.get(f'dev_api_key:{hashed_key}')
if not cached:
return ApiKeyCacheReadResult(mode=ApiKeyCacheReadMode.MISS)
decoded = cached.decode() if isinstance(cached, bytes) else cached
loaded: object = json.loads(decoded)
if not isinstance(loaded, dict):
return ApiKeyCacheReadResult(mode=ApiKeyCacheReadMode.ERROR)
return ApiKeyCacheReadResult(mode=ApiKeyCacheReadMode.HIT, data=cast(Dict[str, Any], loaded))
except Exception as exc:
logger.error("Error reading Developer API key auth cache: %s", exc)
return ApiKeyCacheReadResult(mode=ApiKeyCacheReadMode.ERROR)
def get_cached_dev_api_key_data(hashed_key: str) -> Optional[Dict[str, Any]]:
"""Compatibility adapter returning data only for a successful cache hit."""
result = read_cached_dev_api_key_data(hashed_key)
return result.data if result.mode == ApiKeyCacheReadMode.HIT else None
def delete_cached_dev_api_key_strict(hashed_key: str) -> bool:
"""Delete a Developer auth cache key, raising on Redis failure."""
r.delete(f'dev_api_key:{hashed_key}')
return True
# ******************************************************
# **************** DATA MIGRATION STATUS ***************
# ******************************************************
def set_migration_status(
uid: str,
status: str,
processed: Optional[int] = None,
total: Optional[int] = None,
error: Optional[str] = None,
) -> None:
key = f"migration_status:{uid}"
data: Dict[str, Any] = {"status": status}
if processed is not None:
data["processed"] = processed
if total is not None:
data["total"] = total
if error is not None:
data["error"] = error
r.set(key, json.dumps(data), ex=3600) # Expire after 1 hour
# ******************************************************
# ******************* AUTH SESSION *********************
# ******************************************************
@try_catch_decorator
def set_auth_session(session_id: str, session_data: Dict[str, Any], ttl: int = 600) -> None:
"""Store auth session data with expiration (default 10 minutes)"""
r.set(f'auth_session:{session_id}', json.dumps(session_data), ex=ttl)
@try_catch_decorator
def get_auth_session(session_id: str) -> Optional[Dict[str, Any]]:
"""Retrieve auth session data"""
data = r.get(f'auth_session:{session_id}')
if not data:
return None
loaded: object = json.loads(data.decode('utf-8'))
return cast(Dict[str, Any], loaded) if isinstance(loaded, dict) else None
@try_catch_decorator
def set_auth_code(auth_code: str, firebase_token: str, ttl: int = 300) -> None:
"""Store auth code with Firebase token (default 5 minutes)"""
r.set(f'auth_code:{auth_code}', firebase_token, ex=ttl)
@try_catch_decorator
def get_auth_code(auth_code: str) -> Optional[str]:
"""Retrieve Firebase token by auth code"""
token = r.get(f'auth_code:{auth_code}')
return token.decode('utf-8') if token else None
@try_catch_decorator
def delete_auth_code(auth_code: str) -> None:
"""Delete used auth code"""
r.delete(f'auth_code:{auth_code}')
# ******************************************************
# ************** CREDIT LIMIT NOTIFICATIONS ************
# ******************************************************
def set_credit_limit_notification_sent(uid: str, ttl: int = 60 * 60 * 24) -> None:
"""Cache that credit limit notification was sent to user (24 hours TTL by default)"""
r.set(f'users:{uid}:credit_limit_notification_sent', '1', ex=ttl)
def has_credit_limit_notification_been_sent(uid: str) -> bool:
"""Check if credit limit notification was already sent to user recently"""
return r.exists(f'users:{uid}:credit_limit_notification_sent')
def set_silent_user_notification_sent(uid: str, ttl: int = 60 * 60 * 24) -> None:
"""Cache that silent user notification was sent to user (24 hours TTL by default)"""
r.set(f'users:{uid}:silent_notification_sent', '1', ex=ttl)
def has_silent_user_notification_been_sent(uid: str) -> bool:
"""Check if silent user notification was already sent to user recently"""
return r.exists(f'users:{uid}:silent_notification_sent')
def try_acquire_byok_llm_error_notification_lock(uid: str, provider: str, reason: str, ttl: int = 60 * 60 * 24) -> bool:
"""Return True once per BYOK provider/error reason per TTL window."""
return bool(r.set(f'users:{uid}:byok_llm_error:{provider}:{reason}', '1', ex=ttl, nx=True))
def release_byok_llm_error_notification_lock(uid: str, provider: str, reason: str) -> None:
"""Release the dedupe lock so a failed notification can be retried."""
r.delete(f'users:{uid}:byok_llm_error:{provider}:{reason}')
# ******************************************************
# ******* IMPORTANT CONVERSATION NOTIFICATIONS *********
# ******************************************************
def set_important_conversation_notification_sent(uid: str, conversation_id: str) -> None:
"""Mark that important conversation notification was sent for this conversation (no expiry - one-time per conversation)"""
r.set(f'users:{uid}:important_conv_notif:{conversation_id}', '1')
def has_important_conversation_notification_been_sent(uid: str, conversation_id: str) -> bool:
"""Check if important conversation notification was already sent for this conversation"""
return r.exists(f'users:{uid}:important_conv_notif:{conversation_id}')
# ******************************************************
# ******** CONVERSATION SUMMARY APP IDS ****************
# ******************************************************
CONVERSATION_SUMMARY_APPS_KEY = 'conversation_summary_app_ids'
@try_catch_decorator
def get_conversation_summary_app_ids() -> List[str]:
"""Get list of conversation summary app IDs from Redis"""
app_ids = r.smembers(CONVERSATION_SUMMARY_APPS_KEY)
return [app_id.decode('utf-8') if isinstance(app_id, bytes) else app_id for app_id in app_ids] if app_ids else []
@try_catch_decorator
def add_conversation_summary_app_id(app_id: str) -> bool:
"""Add an app ID to the conversation summary apps set"""
result = r.sadd(CONVERSATION_SUMMARY_APPS_KEY, app_id)
return result > 0
@try_catch_decorator
def remove_conversation_summary_app_id(app_id: str) -> bool:
"""Remove an app ID from the conversation summary apps set"""
result = r.srem(CONVERSATION_SUMMARY_APPS_KEY, app_id)
return result > 0
# ******************************************************
# *************** RATE LIMITING ************************
# ******************************************************
# Lua script: atomic increment + TTL in a single round-trip.
# Returns [current_count, ttl_remaining]. Sets TTL on first hit
# and self-heals any key that lost its TTL (prevents permanent buckets).
_RATE_LIMIT_LUA = r.register_script("""
local key = KEYS[1]
local window = tonumber(ARGV[1])
local current = redis.call('INCR', key)
if current == 1 then
redis.call('EXPIRE', key, window)
end
local ttl = redis.call('TTL', key)
if ttl < 0 then
redis.call('EXPIRE', key, window)
ttl = window
end
return {current, ttl}
""")
# Proactive LLM calls need a reversible reservation: provider/schema failures
# must not consume a user's successful-completion allowance. Unlike the legacy
# increment-first limiter, a rejected reservation does not inflate the counter,
# so releasing one admitted request remains exact under concurrency.
_RATE_LIMIT_RESERVE_LUA = r.register_script("""
local key = KEYS[1]
local window = tonumber(ARGV[1])
local limit = tonumber(ARGV[2])
local current = tonumber(redis.call('GET', key) or '0')
local ttl = redis.call('TTL', key)
if current >= limit then
if ttl < 0 then
redis.call('EXPIRE', key, window)
ttl = window
end
return {0, current, ttl}
end
current = redis.call('INCR', key)
if current == 1 or ttl < 0 then
redis.call('EXPIRE', key, window)
ttl = window
end
return {1, current, ttl}
""")
_RATE_LIMIT_RELEASE_LUA_SOURCE = """
local key = KEYS[1]
local current = tonumber(redis.call('GET', key) or '0') or 0
if current <= 1 then
redis.call('DEL', key)
return 0
end
local remaining = tonumber(redis.call('DECR', key) or '0') or 0