Created
November 22, 2024 17:54
-
-
Save joseph-crowley/c9850118bb526aa95dcc0539aec9449e to your computer and use it in GitHub Desktop.
Cyberhaven Backend Engineer - Coding Problem
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
import uuid | |
import flask | |
# JSONRESPONSE | |
app = flask.Flask(__name__) | |
MAX_TIME = 10 | |
START_PAIR_TIME = 0 | |
PAIR_ID = None | |
NUM_PAIRS = 0 | |
# use a multiprocessing memory manager | |
import multiprocessing | |
import queue | |
call_queue = multiprocessing.Queue() | |
def reset_globals(): | |
global PAIR_ID | |
pair_id = PAIR_ID | |
PAIR_ID = None | |
return pair_id | |
import time | |
#atomic operation - mutexes and locks | |
import threading | |
lock = threading.Lock() | |
stats_dict = [0]*50000 | |
@app.route("/join", methods=["POST"]) | |
def join(): | |
# accept a POST Request with empty payload | |
global PAIR_ID, START_PAIR_TIME | |
with lock: | |
if PAIR_ID: | |
pair_id = reset_globals() | |
call_queue.put(pair_id) | |
NUM_PAIRS += 1 | |
if NUM_PAIRS < 50000: | |
stats_dict[NUM_PAIRS] = (PAIR_ID, time.time()-START_PAIR_TIME) | |
return pair_id+ "SECOND" | |
# create a PAIR ID, You are FIRST | |
PAIR_ID = str(uuid.uuid4()) | |
START_PAIR_TIME = time.time() | |
# wait for 10 seconds for the second client to connect | |
try: | |
result_pair_id = call_queue.get(timeout=MAX_TIME) | |
if result_pair_id: | |
# we have second | |
return result_pair_id+ "FIRST" | |
except queue.Empty as e: | |
reset_globals() | |
return "Timeout. No More Connected Clients." | |
# Scenario: one client connects and times out. next client connects and the third client connnects. What happens? | |
# stats endpoint | |
@app.route("/stats", methods=["GET"]) | |
def stats(): | |
return stats_dict | |
if __name__ == "__main__": | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment