Coverage for filter_memory.py: 96.23%

37 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 20:17 +0000

1"""Remembered Table/Matches filters, per account (SB-1715). 

2 

3Stored on ``user_profiles.filter_memory`` as one object per view:: 

4 

5 {"table": {"filters": {...}, "panel_open": true, "saved_at": 1731600000000}} 

6 

7The browser keeps its own copy (``useFilterMemory``) and whichever was saved 

8later wins, so ``saved_at`` is the client's clock in milliseconds. 

9 

10The filters themselves are opaque to the backend: the component that saved 

11them is the one that checks every id against what it fetched before applying 

12any (SB-1112). This module only bounds their size and shape, because the 

13column is written on every filter change and read on every page load. 

14""" 

15 

16from typing import Any, Literal 

17 

18from pydantic import BaseModel, ConfigDict, field_validator 

19 

20View = Literal["table", "matches", "ranking", "tournament"] 

21 

22MAX_KEYS = 16 

23MAX_LIST = 50 

24MAX_STRING = 64 

25 

26 

27def _valid_scalar(value: Any) -> bool: 

28 if value is None or isinstance(value, bool | int): 

29 return True 

30 if isinstance(value, float): 

31 return value == value and abs(value) != float("inf") # no NaN/inf 

32 return isinstance(value, str) and len(value) <= MAX_STRING 

33 

34 

35def validate_filters(filters: dict) -> dict: 

36 """Return ``filters`` if every value is a small scalar or list of them. 

37 

38 Raises ValueError otherwise — a nested object or a long string is not a 

39 filter, and is not something this column should grow to hold. 

40 """ 

41 if len(filters) > MAX_KEYS: 

42 raise ValueError(f"at most {MAX_KEYS} filter keys") 

43 for key, value in filters.items(): 

44 if not isinstance(key, str) or len(key) > MAX_STRING: 44 ↛ 45line 44 didn't jump to line 45 because the condition on line 44 was never true

45 raise ValueError("filter keys must be short strings") 

46 if isinstance(value, list): 

47 if len(value) > MAX_LIST or not all(_valid_scalar(v) for v in value): 

48 raise ValueError(f"{key}: list of up to {MAX_LIST} scalars") 

49 elif not _valid_scalar(value): 

50 raise ValueError(f"{key}: must be a scalar or a list of scalars") 

51 return filters 

52 

53 

54class FilterMemoryUpdate(BaseModel): 

55 """One view's patch. Unsent fields are kept; ``filters: null`` forgets them.""" 

56 

57 model_config = ConfigDict(extra="forbid") 

58 

59 filters: dict[str, Any] | None = None 

60 panel_open: bool | None = None 

61 saved_at: int 

62 

63 @field_validator("filters") 

64 @classmethod 

65 def _check_filters(cls, value: dict | None) -> dict | None: 

66 return None if value is None else validate_filters(value) 

67 

68 def to_patch(self) -> dict: 

69 """The jsonb merged into the view's entry: only what the client sent.""" 

70 return self.model_dump(exclude_unset=True) 

71 

72 

73def read_filter_memory(raw: Any) -> dict: 

74 """Stored memory, or ``{}`` for a row that has none (the normal state).""" 

75 return dict(raw) if isinstance(raw, dict) else {}