Coverage for faststream/nats/helpers/bucket_declarer.py: 90%

17 statements  

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

1from typing import TYPE_CHECKING, Optional 

2 

3from nats.js.api import KeyValueConfig 

4 

5from .state import ConnectedState, ConnectionState, EmptyConnectionState 

6 

7if TYPE_CHECKING: 

8 from nats.js import JetStreamContext 

9 from nats.js.api import Placement, RePublish, StorageType 

10 from nats.js.kv import KeyValue 

11 

12 

13class KVBucketDeclarer: 

14 __slots__ = ( 

15 "__state", 

16 "buckets", 

17 ) 

18 

19 buckets: dict[str, "KeyValue"] 

20 

21 def __init__(self) -> None: 

22 self.buckets = {} 

23 

24 self.__state: ConnectionState[JetStreamContext] = EmptyConnectionState() 

25 

26 def connect(self, connection: "JetStreamContext") -> None: 

27 self.__state = ConnectedState(connection) 

28 

29 def disconnect(self) -> None: 

30 self.__state = EmptyConnectionState() 

31 

32 async def create_key_value( 

33 self, 

34 bucket: str, 

35 *, 

36 description: str | None = None, 

37 max_value_size: int | None = None, 

38 history: int = 1, 

39 ttl: float | None = None, # in seconds 

40 max_bytes: int | None = None, 

41 storage: Optional["StorageType"] = None, 

42 replicas: int = 1, 

43 placement: Optional["Placement"] = None, 

44 republish: Optional["RePublish"] = None, 

45 direct: bool | None = None, 

46 # custom 

47 declare: bool = True, 

48 ) -> "KeyValue": 

49 if (key_value := self.buckets.get(bucket)) is None: 

50 if declare: 50 ↛ 67line 50 didn't jump to line 67 because the condition on line 50 was always true

51 key_value = await self.__state.connection.create_key_value( 

52 config=KeyValueConfig( 

53 bucket=bucket, 

54 description=description, 

55 max_value_size=max_value_size, 

56 history=history, 

57 ttl=ttl, 

58 max_bytes=max_bytes, 

59 storage=storage, 

60 replicas=replicas, 

61 placement=placement, 

62 republish=republish, 

63 direct=direct, 

64 ), 

65 ) 

66 else: 

67 key_value = await self.__state.connection.key_value(bucket) 

68 

69 self.buckets[bucket] = key_value 

70 

71 return key_value