55import os
66import secrets
77import threading
8+ from copy import deepcopy
89from datetime import datetime
910from pathlib import Path
1011
@@ -94,50 +95,39 @@ def _attempt_payload(event: dict) -> dict:
9495 }
9596
9697
97- def _matching_attempt (f , event : dict ) -> dict | None :
98+ def _matching_attempt (events : list [ dict ] , event : dict ) -> dict | None :
9899 attempt = event .get ("attempt" )
99100 if not attempt :
100101 return None
101- f .seek (0 )
102- for raw in f :
103- try :
104- existing = json .loads (raw )
105- except (json .JSONDecodeError , UnicodeDecodeError ):
106- continue
102+ for existing in events :
107103 if existing .get ("attempt" ) != attempt :
108104 continue
109105 if _attempt_payload (existing ) != _attempt_payload (event ):
110106 raise AttemptConflict (
111107 f"attempt { attempt !r} already belongs to another event"
112108 )
113- return existing
109+ accepted = deepcopy (existing )
110+ accepted .pop ("seq" , None )
111+ return accepted
114112 return None
115113
116114
117- def _event_id_exists (f , event_id : str ) -> bool :
115+ def _event_id_exists (events : list [ dict ] , event_id : str ) -> bool :
118116 """Whether this log already owns an event identity."""
119- f .seek (0 )
120- for raw in f :
121- try :
122- existing = json .loads (raw )
123- except (json .JSONDecodeError , UnicodeDecodeError ):
124- continue
125- if existing .get ("id" ) == event_id :
126- return True
127- return False
117+ return any (existing .get ("id" ) == event_id for existing in events )
128118
129119
130- def _append_event_unlocked (f , event : dict ) -> dict :
120+ def _append_event_unlocked (f , event : dict , events : list [ dict ] ) -> tuple [ dict , bool ] :
131121 """Append while the caller holds this log file's exclusive lease."""
132122 # Attempt identity is checked under the log's append lock. Checking before
133123 # this point would leave two server threads free to observe absence together
134124 # and append together. Content and time deliberately play no part: an
135125 # intentional later identical message has a fresh attempt and is a second
136126 # event.
137- if event .get ("attempt" ) and (existing := _matching_attempt (f , event )):
138- return existing
127+ if event .get ("attempt" ) and (existing := _matching_attempt (events , event )):
128+ return existing , False
139129 if "id" in event :
140- if _event_id_exists (f , event ["id" ]):
130+ if _event_id_exists (events , event ["id" ]):
141131 raise ValueError (f"event id { event ['id' ]!r} already exists" )
142132 else :
143133 # Event ids escape the page with host requests as durable idempotency and
@@ -146,7 +136,7 @@ def _append_event_unlocked(f, event: dict) -> dict:
146136 # probability as an invariant.
147137 while True :
148138 candidate = secrets .token_hex (16 )
149- if not _event_id_exists (f , candidate ):
139+ if not _event_id_exists (events , candidate ):
150140 event ["id" ] = candidate
151141 break
152142 event .setdefault ("ts" , now_iso ())
@@ -165,7 +155,7 @@ def _append_event_unlocked(f, event: dict) -> dict:
165155 # and events are rare enough that a flush per append costs nothing.
166156 f .flush ()
167157 os .fsync (f .fileno ())
168- return event
158+ return event , True
169159
170160
171161def append_event (page_dir : Path , event : dict ) -> dict :
@@ -174,13 +164,13 @@ def append_event(page_dir: Path, event: dict) -> dict:
174164 with open (log , "a" , encoding = "utf-8" ):
175165 pass
176166 with flocked (log ) as f :
177- return _append_event_unlocked (f , event )
167+ f .seek (0 )
168+ events = _parse_events (f .read ())
169+ accepted , _appended = _append_event_unlocked (f , event , events )
170+ return accepted
178171
179172
180- def read_events (page_dir : Path ) -> list :
181- path = page_dir / "comments.jsonl"
182- if not path .exists ():
183- return []
173+ def _parse_events (data : bytes ) -> list [dict ]:
184174 events = []
185175 # The log's grammar is events joined by "\n" — the writer's own separator,
186176 # not splitlines()'s wider class, which once read a U+2028 inside a comment's
@@ -189,7 +179,7 @@ def read_events(page_dir: Path) -> list:
189179 # mid-line (ensure_ascii=False writes multi-byte UTF-8), and one strict
190180 # read_text of the file would raise on the tear before any line-level
191181 # tolerance could reach it.
192- lines = path . read_bytes () .split (b"\n " )
182+ lines = data .split (b"\n " )
193183 if lines and lines [- 1 ] == b"" :
194184 lines .pop ()
195185 for i , line in enumerate (lines ):
@@ -208,3 +198,10 @@ def read_events(page_dir: Path) -> list:
208198 event ["seq" ] = i + 1
209199 events .append (event )
210200 return events
201+
202+
203+ def read_events (page_dir : Path ) -> list :
204+ path = page_dir / "comments.jsonl"
205+ if not path .exists ():
206+ return []
207+ return _parse_events (path .read_bytes ())
0 commit comments