Created
September 24, 2021 16:30
-
-
Save zeryx/c7d17f8aa03ec8d7e6146e4a8d2db42d to your computer and use it in GitHub Desktop.
This algorithm synchronously checks a resource file by ensuing a lock file doesn't already exist.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from Algorithmia import ADK | |
import Algorithmia | |
from time import sleep, time | |
state_file_path = "data://.my/locking/resource.json" | |
lock_file_path = "data://.my/locking/lock" | |
client = Algorithmia.client() | |
class AlgorithmiaLock(object): | |
def __init__(self, file_path, client): | |
self.lock = None | |
self.filepath = file_path | |
self.client = client | |
def __enter__(self): | |
self.lock_trap() | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
self.lock.delete() | |
self.lock = None | |
def lock_trap(self): | |
lock_file = self.client.file(self.filepath) | |
while True: | |
if lock_file.exists(): | |
sleep(0.5) | |
else: | |
break | |
lock_file.putJson({}) | |
self.lock = lock_file | |
def apply(input): | |
with AlgorithmiaLock(lock_file_path, client): | |
state_file = client.file(state_file_path) | |
if state_file.exists(): | |
state_data = client.file(state_file_path).getJson() | |
else: | |
state_data = {"count": 0, "time": None} | |
state_data['count'] += 1 | |
state_data['time'] = str(time()) | |
client.file(state_file_path).putJson(state_data) | |
# This sleep is to replicate business logic processing on the data recieved. | |
sleep(1) | |
return state_data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment