Skip to content

Commit

Permalink
Implement step8 Restore
Browse files Browse the repository at this point in the history
  • Loading branch information
ngokchaoho committed Dec 25, 2023
1 parent bc8980b commit c971087
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
6 changes: 6 additions & 0 deletions pyredis/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ async def amain(args):

datastore = DataStore()

if args.restore and not AppendOnlyPersister.restore_from_file(
"ccdb.aof", datastore
):
return -1

loop = asyncio.get_running_loop()

loop.create_task(acheck_expiry_task(datastore))
Expand Down Expand Up @@ -76,6 +81,7 @@ def main(args):
)
parser.add_argument("--asyncio", action=argparse.BooleanOptionalAction)
parser.add_argument("--trio", action=argparse.BooleanOptionalAction)
parser.add_argument("--restore", action=argparse.BooleanOptionalAction)
parser.add_argument(
"-v",
"--verbose",
Expand Down
24 changes: 24 additions & 0 deletions pyredis/persistence.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
from pyredis.commands import handle_command
from pyredis.protocol import extract_frame_from_buffer


class AppendOnlyPersister:
def __init__(self, filename):
self._filename = filename
Expand All @@ -8,3 +12,23 @@ def log_command(self, command):

for item in command:
self._file.write(item.resp_encode())

@staticmethod
def restore_from_file(filename=None, database=None):
buffer = bytearray()
with open(filename, "rb") as f:
while True:
data = f.read(1024)
if data:
buffer.extend(data)
else:
break
while True:
frame, frame_size = extract_frame_from_buffer(buffer)

if frame:
buffer = buffer[frame_size:]
handle_command(frame, database, None)
else:
break
return True

0 comments on commit c971087

Please sign in to comment.