Skip to content
This repository was archived by the owner on Apr 4, 2024. It is now read-only.

Commit 8f7528a

Browse files
authored
WriteTracker and DiskWriteTracker (#42)
2 parents 6e1e5fe + 69da5d5 commit 8f7528a

File tree

1 file changed

+60
-2
lines changed

1 file changed

+60
-2
lines changed

python/selfie-lib/selfie_lib/WriteTracker.py

Lines changed: 60 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
1-
from typing import List, Optional
1+
from typing import List, Optional, Generic, TypeVar, Dict
22
from selfie_lib.CommentTracker import SnapshotFileLayout
3-
import inspect
3+
from abc import ABC, abstractmethod
4+
import inspect, threading
45
from functools import total_ordering
56

7+
T = TypeVar("T")
8+
U = TypeVar("U")
9+
610

711
@total_ordering
812
class CallLocation:
@@ -56,6 +60,17 @@ def ide_link(self, layout: "SnapshotFileLayout") -> str:
5660
]
5761
return "\n".join(links)
5862

63+
def __eq__(self, other):
64+
if not isinstance(other, CallStack):
65+
return NotImplemented
66+
return (
67+
self.location == other.location
68+
and self.rest_of_stack == other.rest_of_stack
69+
)
70+
71+
def __hash__(self):
72+
return hash((self.location, tuple(self.rest_of_stack)))
73+
5974

6075
def recordCall(callerFileOnly: bool = False) -> CallStack:
6176
stack_frames = inspect.stack()[1:]
@@ -74,3 +89,46 @@ def recordCall(callerFileOnly: bool = False) -> CallStack:
7489
rest_of_stack = call_locations[1:]
7590

7691
return CallStack(location, rest_of_stack)
92+
93+
94+
class FirstWrite(Generic[U]):
95+
def __init__(self, snapshot: U, call_stack: CallStack):
96+
self.snapshot = snapshot
97+
self.call_stack = call_stack
98+
99+
100+
class WriteTracker(ABC, Generic[T, U]):
101+
def __init__(self):
102+
self.lock = threading.Lock()
103+
self.writes: Dict[T, FirstWrite[U]] = {}
104+
105+
@abstractmethod
106+
def record(self, key: T, snapshot: U, call: CallStack, layout: SnapshotFileLayout):
107+
pass
108+
109+
def recordInternal(
110+
self,
111+
key: T,
112+
snapshot: U,
113+
call: CallStack,
114+
layout: SnapshotFileLayout,
115+
allow_multiple_equivalent_writes: bool = True,
116+
):
117+
with self.lock:
118+
this_write = FirstWrite(snapshot, call)
119+
if key not in self.writes:
120+
self.writes[key] = this_write
121+
return
122+
123+
existing = self.writes[key]
124+
if existing.snapshot != snapshot:
125+
raise ValueError(
126+
f"Snapshot was set to multiple values!\n first time: {existing.call_stack.location.ide_link(layout)}\n this time: {call.location.ide_link(layout)}\n"
127+
)
128+
elif not allow_multiple_equivalent_writes:
129+
raise ValueError("Snapshot was set to the same value multiple times.")
130+
131+
132+
class DiskWriteTracker(WriteTracker[T, U]):
133+
def record(self, key: T, snapshot: U, call: CallStack, layout: SnapshotFileLayout):
134+
super().recordInternal(key, snapshot, call, layout)

0 commit comments

Comments
 (0)