Spaces:
Running

File size: 949 Bytes
7ad3e85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
"""In-process reservations: slow object I/O must not take the SQLite writer."""

import asyncio
from contextlib import asynccontextmanager


class Reservations:
    def __init__(self, *, paths=False):
        self.condition = asyncio.Condition()
        self.active = set()
        self.paths = paths

    def conflicts(self, a, b):
        if not self.paths:
            return a == b
        return a[0] == b[0] and (a[1] == b[1] or a[1].startswith(b[1] + "/") or b[1].startswith(a[1] + "/"))

    @asynccontextmanager
    async def hold(self, keys):
        keys = set(keys)
        async with self.condition:
            await self.condition.wait_for(lambda: not any(self.conflicts(a, b) for a in keys for b in self.active))
            self.active.update(keys)
        try:
            yield
        finally:
            async with self.condition:
                self.active.difference_update(keys)
                self.condition.notify_all()