27 lines
640 B
Python
27 lines
640 B
Python
import datetime
|
|
|
|
from app.storage.mongo import database
|
|
from app.utils import time
|
|
from bson import codec_options
|
|
|
|
from pymongo import errors
|
|
|
|
|
|
class ConflictException(Exception):
|
|
pass
|
|
|
|
|
|
collection = database.get_collection("locks", codec_options=codec_options.CodecOptions(tz_aware=True))
|
|
|
|
|
|
async def acquire(name: str, ttl: int):
|
|
locked_until = time.now() + datetime.timedelta(seconds=ttl)
|
|
try:
|
|
await collection.insert_one({'name': name, 'locked_until': locked_until})
|
|
except errors.DuplicateKeyError:
|
|
raise ConflictException
|
|
|
|
|
|
async def release(name: str):
|
|
await collection.delete_one({'name': name})
|