Skip to content

Instantly share code, notes, and snippets.

@suhailpatel
Last active October 27, 2022 19:57
Show Gist options
  • Save suhailpatel/331ffa65f434a9743dfb1db893931361 to your computer and use it in GitHub Desktop.
Save suhailpatel/331ffa65f434a9743dfb1db893931361 to your computer and use it in GitHub Desktop.
Implementation of a database for "Dissecting the humble LSM Tree and SSTable" for SRECon EMEA 2022
The MIT License (MIT)
Copyright (c) 2022 Suhail Patel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
from dataclasses import dataclass
import time
from typing import Optional
@dataclass
class Item(object):
key: str
value: Optional[str]
timestamp: int
is_deleted: bool = False
def sort_key(self):
return (self.key, self.value, self.timestamp, self.is_deleted)
def to_line(self) -> str:
deletion = "1" if self.is_deleted else "0"
value = self.value if self.value else ""
return f"{self.key},{value},{self.timestamp},{deletion}"
def from_line(line):
bag = line.split(',')
is_deleted = True if bag[3] == "1" else False
return Item(key=bag[0], value=bag[1], timestamp=int(bag[2]), is_deleted=is_deleted)
class SRECon2022Database(object):
memtable, sstables = [], []
def insert(self, key: str, value: str):
if len(self.memtable) >= 5:
self.flush()
self.memtable.append(Item(key=key, value=value, timestamp=time.time_ns()))
def update(self, key: str, new_value: str):
self.insert(key, new_value)
def delete(self, key: str):
if len(self.memtable) >= 5:
self.flush()
self.memtable.append(Item(key=key, value="", timestamp=time.time_ns(), is_deleted=True))
def flush(self):
filename = f"fancy-{int(time.time_ns())}-sstable.db"
with open(filename, "a") as f:
for item in sorted(self.memtable, key=lambda x: x.sort_key()):
f.write(item.to_line())
f.write('\n')
self.memtable = []
self.sstables.append(filename)
def search(self, key) -> Optional[Item]:
records = []
# Read all our items from our SSTables and find any that match
# this particular key
for sstable in self.sstables:
records.extend(self.search_in_sstable(sstable, key))
# Read all our records from our Memtable and find any that match
# this particular key
records.extend(filter(lambda x: x.key == key, self.memtable))
# Sort by timestamp ascending so that we can just cherry pick
# the last record when evaluating
records = sorted(records, key=lambda x: x.timestamp)
# Apply some logic to see what we return:
# - If we found no matches, return nothing
# - If our last item was a deletion event, return nothing
# - Otherwise, return the most recent result
if not records:
return None
elif records[-1].is_deleted:
return None
else:
return records[-1]
def search_in_sstable(self, sstable, key) -> list[Item]:
records = []
with open(sstable) as f:
for line in f.readlines():
if not line.strip():
continue
item = Item.from_line(line.strip())
if item.key == key:
records.append(item)
return records
if __name__ == "__main__":
db = SRECon2022Database()
db.insert(key="1", value="a")
db.insert(key="2", value="b")
db.insert(key="3", value="c")
db.insert(key="4", value="d")
db.insert(key="5", value="e")
db.insert(key="6", value="f")
db.update(key="1", new_value="g")
db.delete(key="3")
db.flush()
db.update(key="3", new_value="h")
print(db.search("1"))
print(db.search("3"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment