yogies commited on
Commit
ef5d919
·
verified ·
1 Parent(s): 469c080

Delete usage_counter.py

Browse files
Files changed (1) hide show
  1. usage_counter.py +0 -58
usage_counter.py DELETED
@@ -1,58 +0,0 @@
1
- # -------------------------------------------------
2
- # usage_counter.py
3
- # -------------------------------------------------
4
- import json
5
- import os
6
- import pathlib
7
- import portalocker
8
- from typing import Optional
9
-
10
- # ----------------------------------------------------------------------
11
- # Where the counter lives – /run is a persistent volume on HF Spaces.
12
- # ----------------------------------------------------------------------
13
- COUNTER_PATH = pathlib.Path("/run/counter.json")
14
-
15
- # ----------------------------------------------------------------------
16
- # Read the hard limit from the secret (fallback to 50 if not set).
17
- # ----------------------------------------------------------------------
18
- MAX_LIMIT = int(os.getenv("MAX_REQUEST_LIMIT", "50")) # default 50
19
-
20
- def _ensure_file_exists() -> None:
21
- """Create an empty counter file the first time the container runs."""
22
- if not COUNTER_PATH.exists():
23
- COUNTER_PATH.write_text(json.dumps({"cnt": 0}))
24
-
25
- def increment_and_check() -> bool:
26
- """
27
- Atomically:
28
- 1️⃣ read the current counter,
29
- 2️⃣ verify it is < MAX_LIMIT,
30
- 3️⃣ increment it and write back.
31
-
32
- Returns True → request is allowed (counter was incremented)
33
- False → limit already reached (counter unchanged)
34
- """
35
- _ensure_file_exists()
36
-
37
- # -------------------------------------------------
38
- # Exclusive lock – blocks any other request until we release it.
39
- # -------------------------------------------------
40
- with portalocker.Lock(str(COUNTER_PATH), mode="r+", timeout=10) as fh:
41
- # 1️⃣ read the JSON payload (tiny – a few bytes)
42
- data = json.loads(fh.read() or '{"cnt":0}')
43
-
44
- # 2️⃣ check the limit
45
- if data["cnt"] >= MAX_LIMIT:
46
- return False
47
-
48
- # 3️⃣ increment
49
- data["cnt"] += 1
50
-
51
- # 4️⃣ write the updated JSON back atomically
52
- fh.seek(0) # go back to start of file
53
- fh.truncate() # drop old content
54
- fh.write(json.dumps(data))
55
- fh.flush() # ensure OS buffers are flushed
56
-
57
- # lock released automatically when we exit the `with` block
58
- return True