@@ -29,6 +29,7 @@ def _object_store():
2929class GcsStateStore :
3030 bucket : str
3131 prefix : str = "firstrade-platform"
32+ client_factory : Callable [..., Any ] | None = None
3233
3334 def __post_init__ (self ) -> None :
3435 if not str (self .bucket or "" ).strip ():
@@ -74,8 +75,27 @@ def create_json(self, key: str, payload: dict[str, Any]) -> bool:
7475 """Atomically create a JSON object; return False if it already exists."""
7576 uri = self ._object_uri (key )
7677 data = json .dumps (payload , ensure_ascii = False , separators = ("," , ":" ))
78+ bucket_name , separator , object_name = uri [5 :].partition ("/" )
79+ if not separator or not bucket_name or not object_name :
80+ raise StatePersistenceError (f"Invalid GCS state URI for { key } " )
7781 try :
78- return bool (_object_store ().create_text (uri , data , content_type = "application/json" ))
82+ from google .api_core .exceptions import Conflict , PreconditionFailed
83+ from google .cloud import storage
84+
85+ factory = self .client_factory or storage .Client
86+ try :
87+ client = factory ()
88+ except TypeError :
89+ client = factory (project = None )
90+ blob = client .bucket (bucket_name ).blob (object_name )
91+ blob .upload_from_string (
92+ data ,
93+ content_type = "application/json" ,
94+ if_generation_match = 0 ,
95+ )
96+ return True
97+ except (Conflict , PreconditionFailed ):
98+ return False
7999 except Exception as exc :
80100 raise StatePersistenceError (f"GCS atomic create failed for { key } : { exc } " ) from exc
81101
0 commit comments