apify-bot-guard 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,27 @@
1
+ """Fair free-plan allowances for Apify Actors, with a per-Actor pool that keeps
2
+ farms of free accounts from draining your data and your budget."""
3
+
4
+ from .backends import ApifyKvBackend, Backend, MemoryBackend, RedisBackend
5
+ from .core import DEFAULTS, Allowance, Config, Entry, Ledger, allowance_of, env_name, is_free_plan, plan_of, user_hash
6
+ from .guard import BotGuard, Decision, push_data
7
+
8
+ __all__ = [
9
+ "DEFAULTS",
10
+ "Allowance",
11
+ "ApifyKvBackend",
12
+ "Backend",
13
+ "BotGuard",
14
+ "Config",
15
+ "Decision",
16
+ "Entry",
17
+ "Ledger",
18
+ "MemoryBackend",
19
+ "RedisBackend",
20
+ "allowance_of",
21
+ "env_name",
22
+ "is_free_plan",
23
+ "plan_of",
24
+ "push_data",
25
+ "user_hash",
26
+ ]
27
+ __version__ = "0.1.1"
@@ -0,0 +1,228 @@
1
+ """Where ledgers live. A backend stores, per key, a map of run id -> entry.
2
+
3
+ Every backend works in batches, so a run costs a fixed, small number of round
4
+ trips: one batch read at start, one batch write for the hold, one batch write
5
+ at the end.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import json
12
+ from collections.abc import Sequence
13
+ from typing import Any, Protocol
14
+
15
+ from .core import Entry, Ledger, ledger_month
16
+
17
+ LEDGER_TTL_SECONDS = 45 * 24 * 3600 # a month plus slack
18
+ SEEN_TTL_SECONDS = 400 * 24 * 3600
19
+
20
+ Put = tuple[str, str, Entry] # (key, run id, entry)
21
+
22
+
23
+ class Backend(Protocol):
24
+ async def get_ledgers(self, keys: Sequence[str]) -> list[Ledger]:
25
+ """Ledgers for `keys`, in order; empty ledgers for missing keys."""
26
+ ...
27
+
28
+ async def put_entries(self, puts: Sequence[Put], known: dict[str, Ledger] | None = None) -> None:
29
+ """Set one entry per (key, run id). `known`: ledgers just read, which a
30
+ backend without per-entry writes may merge into instead of re-reading."""
31
+ ...
32
+
33
+ async def first_seen(self, user_key: str, today: str) -> str | None:
34
+ """The stored first-seen day for a user, recording `today` if none."""
35
+ ...
36
+
37
+ async def prune(self, before_month: str) -> int:
38
+ """Delete ledgers of months before `before_month` (YYYY-MM); return how many."""
39
+ ...
40
+
41
+
42
+ class MemoryBackend:
43
+ """In-process store for tests and local runs."""
44
+
45
+ def __init__(self) -> None:
46
+ self.data: dict[str, Any] = {}
47
+
48
+ async def get_ledgers(self, keys: Sequence[str]) -> list[Ledger]:
49
+ return [Ledger.from_raw(self.data.get(k)) for k in keys]
50
+
51
+ async def put_entries(self, puts: Sequence[Put], known: dict[str, Ledger] | None = None) -> None:
52
+ for key, run_id, entry in puts:
53
+ self.data.setdefault(key, {})[run_id] = entry.to_json()
54
+
55
+ async def first_seen(self, user_key: str, today: str) -> str | None:
56
+ return str(self.data.setdefault(f"seen.{user_key}", today))
57
+
58
+ async def prune(self, before_month: str) -> int:
59
+ old = [k for k in self.data if (ledger_month(k) or "9999") < before_month]
60
+ for k in old:
61
+ del self.data[k]
62
+ return len(old)
63
+
64
+
65
+ def record_key(key: str) -> str:
66
+ """Apify record keys allow a-zA-Z0-9!-_.'() and at most 256 characters."""
67
+ return "".join(c if c.isascii() and (c.isalnum() or c in "!-_.'()") else "_" for c in key)[:256]
68
+
69
+
70
+ class ApifyKvBackend:
71
+ """Ledgers as JSON records in a key-value store on YOUR Apify account.
72
+
73
+ The run's own token belongs to the user and cannot write to your stores,
74
+ so pass your token (an Actor secret env var). Writes are read-merge-write:
75
+ two runs saving in the same instant can lose one entry. The hold booked at
76
+ run start keeps parallel runs from each taking the whole allowance, so the
77
+ worst case is a small overshoot. Use RedisBackend for exact counts.
78
+
79
+ `client`: an ApifyClientAsync; built from `token` when omitted.
80
+ """
81
+
82
+ def __init__(
83
+ self,
84
+ token: str | None = None,
85
+ store: str = "bot-guard",
86
+ *,
87
+ client: Any = None,
88
+ api_url: str | None = None,
89
+ ) -> None:
90
+ if client is None: # pragma: no cover - needs the optional dependency
91
+ from apify_client import ApifyClientAsync
92
+
93
+ client = ApifyClientAsync(token=token, **({"api_url": api_url} if api_url else {}))
94
+ self._client = client
95
+ self._store_name = store
96
+ self._store: Any = None
97
+ self._lock = asyncio.Lock()
98
+
99
+ async def _kv(self) -> Any:
100
+ # One lookup even when the first reads run in parallel.
101
+ async with self._lock:
102
+ if self._store is None:
103
+ got = await self._client.key_value_stores().get_or_create(name=self._store_name)
104
+ self._store = self._client.key_value_store(got["id"])
105
+ return self._store
106
+
107
+ async def _get(self, key: str) -> Any:
108
+ rec = await (await self._kv()).get_record(record_key(key))
109
+ return rec["value"] if rec else None
110
+
111
+ async def get_ledgers(self, keys: Sequence[str]) -> list[Ledger]:
112
+ raws = await asyncio.gather(*(self._get(k) for k in keys))
113
+ return [Ledger.from_raw(r) for r in raws]
114
+
115
+ async def put_entries(self, puts: Sequence[Put], known: dict[str, Ledger] | None = None) -> None:
116
+ by_key: dict[str, list[tuple[str, Entry]]] = {}
117
+ for key, run_id, entry in puts:
118
+ by_key.setdefault(key, []).append((run_id, entry))
119
+ kv = await self._kv()
120
+
121
+ async def save(key: str, items: list[tuple[str, Entry]]) -> None:
122
+ base = known.get(key) if known else None
123
+ ledger = base if base is not None else Ledger.from_raw(await self._get(key))
124
+ runs = {k: e.to_json() for k, e in ledger.runs.items()}
125
+ runs.update({run_id: e.to_json() for run_id, e in items})
126
+ await kv.set_record(record_key(key), {"v": 1, "runs": runs})
127
+
128
+ await asyncio.gather(*(save(k, v) for k, v in by_key.items()))
129
+
130
+ async def first_seen(self, user_key: str, today: str) -> str | None:
131
+ key = f"seen.{user_key}"
132
+ got = await self._get(key)
133
+ if isinstance(got, dict) and got.get("first"):
134
+ return str(got["first"])
135
+ await (await self._kv()).set_record(record_key(key), {"first": today})
136
+ return today
137
+
138
+ async def prune(self, before_month: str) -> int:
139
+ """Key-value records never expire on their own, so old months are deleted
140
+ here: every key is listed (one call per 1,000 keys), old ledgers removed."""
141
+ kv = await self._kv()
142
+ old: list[str] = []
143
+ start: str | None = None
144
+ while True:
145
+ page = await kv.list_keys(limit=1000, exclusive_start_key=start)
146
+ old += [i["key"] for i in page.get("items", []) if (ledger_month(i["key"]) or "9999") < before_month]
147
+ start = page.get("nextExclusiveStartKey")
148
+ if not page.get("isTruncated") or not start:
149
+ break
150
+ for i in range(0, len(old), 20):
151
+ await asyncio.gather(*(kv.delete_record(k) for k in old[i : i + 20]))
152
+ return len(old)
153
+
154
+
155
+ def _text(v: Any) -> Any:
156
+ return v.decode() if isinstance(v, bytes) else v
157
+
158
+
159
+ class RedisBackend:
160
+ """Redis, Valkey or Upstash. One hash field per run: concurrent runs never
161
+ overwrite each other, so counts are exact.
162
+
163
+ `client`: redis.asyncio.Redis (pipelined: one round trip per batch), or any
164
+ client with async hgetall/hset/expire/set/get such as
165
+ upstash_redis.asyncio.Redis (calls made concurrently). `pipelined`
166
+ overrides the detection.
167
+ """
168
+
169
+ def __init__(self, client: Any, prefix: str = "bot-guard:", *, pipelined: bool | None = None) -> None:
170
+ self._r = client
171
+ self._prefix = prefix
172
+ self._pipelined = _supports_pipeline(client) if pipelined is None else pipelined
173
+
174
+ async def get_ledgers(self, keys: Sequence[str]) -> list[Ledger]:
175
+ full = [self._prefix + k for k in keys]
176
+ if self._pipelined:
177
+ pipe = self._r.pipeline(transaction=False)
178
+ for k in full:
179
+ pipe.hgetall(k)
180
+ raws = await pipe.execute()
181
+ else:
182
+ raws = await asyncio.gather(*(self._r.hgetall(k) for k in full))
183
+ out = []
184
+ for raw in raws:
185
+ runs: dict[str, Any] = {}
186
+ for f, v in (raw or {}).items():
187
+ try:
188
+ runs[_text(f)] = json.loads(_text(v))
189
+ except (TypeError, ValueError):
190
+ continue
191
+ out.append(Ledger.from_raw({"runs": runs}))
192
+ return out
193
+
194
+ async def put_entries(self, puts: Sequence[Put], known: dict[str, Ledger] | None = None) -> None:
195
+ if self._pipelined:
196
+ pipe = self._r.pipeline(transaction=False)
197
+ for key, run_id, entry in puts:
198
+ pipe.hset(self._prefix + key, run_id, json.dumps(entry.to_json()))
199
+ pipe.expire(self._prefix + key, LEDGER_TTL_SECONDS)
200
+ await pipe.execute()
201
+ return
202
+
203
+ async def one(key: str, run_id: str, entry: Entry) -> None:
204
+ await self._r.hset(self._prefix + key, run_id, json.dumps(entry.to_json()))
205
+ await self._r.expire(self._prefix + key, LEDGER_TTL_SECONDS)
206
+
207
+ await asyncio.gather(*(one(*p) for p in puts))
208
+
209
+ async def first_seen(self, user_key: str, today: str) -> str | None:
210
+ k = f"{self._prefix}seen.{user_key}"
211
+ await self._r.set(k, today, nx=True, ex=SEEN_TTL_SECONDS)
212
+ got = _text(await self._r.get(k))
213
+ return str(got) if got else None
214
+
215
+ async def prune(self, before_month: str) -> int:
216
+ """Nothing to do: every ledger expires on its own (LEDGER_TTL_SECONDS)."""
217
+ return 0
218
+
219
+
220
+ def _supports_pipeline(client: Any) -> bool:
221
+ """redis-py style: pipeline(transaction=False) with an async execute()."""
222
+ make = getattr(client, "pipeline", None)
223
+ if not callable(make):
224
+ return False
225
+ try:
226
+ return callable(getattr(make(transaction=False), "execute", None))
227
+ except TypeError:
228
+ return False
@@ -0,0 +1,386 @@
1
+ """Pure allowance logic. No I/O; kept identical to the JavaScript package (docs/DESIGN.md)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import calendar
6
+ import hashlib
7
+ import math
8
+ import os
9
+ import re
10
+ from collections.abc import Callable, Iterable, Mapping
11
+ from dataclasses import dataclass, field, fields
12
+ from datetime import date, datetime, timedelta, timezone
13
+
14
+ Env = Mapping[str, str]
15
+
16
+ # Limits, in the order ties are broken. Each is a number (0 allowed) or None (no limit).
17
+ # "actor_*" count one user's runs of this scope; "user_*" count one user's runs of every scope
18
+ # sharing the backend; "run_*" cap a single run; "pool_*" count every limited user together.
19
+ WINDOWS = ("month", "week", "day")
20
+ _GRID = tuple(f"{who}_{w}_{unit}" for w in WINDOWS for who in ("actor", "user") for unit in ("results", "usd"))
21
+ LIMIT_FIELDS = (*_GRID, "run_results", "run_usd", "pool_month_results")
22
+
23
+ DEFAULTS: dict[str, float | None] = {
24
+ "actor_month_results": 100.0,
25
+ "actor_month_usd": 0.05,
26
+ "user_month_results": 300.0,
27
+ "user_month_usd": 0.25,
28
+ "pool_month_results": 3000.0,
29
+ "daily_share": 0.34,
30
+ "new_account_days": 7.0,
31
+ "new_account_share": 0.25,
32
+ "cost_per_result": 0.0005,
33
+ "auto_prune": 0.02,
34
+ }
35
+
36
+ NUMBER_FIELDS = (*LIMIT_FIELDS, "daily_share", "new_account_days", "new_account_share", "cost_per_result", "auto_prune")
37
+ LIST_FIELDS = ("plans", "exempt_users", "blocked_users")
38
+ TEXT_FIELDS = ("mode", "message", "salt", "track_from")
39
+ NO_LIMIT = {"none", "off", "unlimited", "no", "-"}
40
+ MODES = ("enforce", "observe")
41
+
42
+
43
+ def env_name(name: str) -> str:
44
+ """`actor_week_results` -> `BOT_GUARD_ACTOR_WEEK_RESULTS`."""
45
+ return f"BOT_GUARD_{name.upper()}"
46
+
47
+
48
+ @dataclass
49
+ class Config:
50
+ """Every control the guard has. Unset limits (None) do not apply. See docs/CONFIGURATION.md."""
51
+
52
+ scope: str
53
+ actor_month_results: float | None = DEFAULTS["actor_month_results"]
54
+ actor_month_usd: float | None = DEFAULTS["actor_month_usd"]
55
+ user_month_results: float | None = DEFAULTS["user_month_results"]
56
+ user_month_usd: float | None = DEFAULTS["user_month_usd"]
57
+ actor_week_results: float | None = None
58
+ actor_week_usd: float | None = None
59
+ user_week_results: float | None = None
60
+ user_week_usd: float | None = None
61
+ actor_day_results: float | None = None
62
+ actor_day_usd: float | None = None
63
+ user_day_results: float | None = None
64
+ user_day_usd: float | None = None
65
+ run_results: float | None = None
66
+ run_usd: float | None = None
67
+ pool_month_results: float | None = DEFAULTS["pool_month_results"]
68
+ daily_share: float | None = DEFAULTS["daily_share"]
69
+ new_account_days: float | None = DEFAULTS["new_account_days"]
70
+ new_account_share: float | None = DEFAULTS["new_account_share"]
71
+ cost_per_result: float | None = DEFAULTS["cost_per_result"]
72
+ plans: tuple[str, ...] = ("FREE",)
73
+ exempt_users: frozenset[str] = frozenset()
74
+ blocked_users: frozenset[str] = frozenset()
75
+ mode: str = "enforce"
76
+ message: str | None = None
77
+ salt: str = ""
78
+ track_from: str | None = None
79
+ auto_prune: float | None = DEFAULTS["auto_prune"]
80
+ problems: list[str] = field(default_factory=list, compare=False, repr=False)
81
+
82
+ def __post_init__(self) -> None:
83
+ for name in NUMBER_FIELDS:
84
+ v = getattr(self, name)
85
+ ok = isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) and v >= 0
86
+ if v is not None and not ok:
87
+ self.problems.append(f"{name}: {v!r} is not a number >= 0; using no limit")
88
+ setattr(self, name, None)
89
+ if self.daily_share is not None:
90
+ self.daily_share = min(self.daily_share, 1.0)
91
+ self.new_account_share = 1.0 if self.new_account_share is None else min(self.new_account_share, 1.0)
92
+ self.new_account_days = self.new_account_days or 0.0
93
+ self.cost_per_result = max(self.cost_per_result or 0.0, 1e-7)
94
+ self.auto_prune = min(self.auto_prune or 0.0, 1.0)
95
+ self.plans = tuple(p.strip().upper() for p in self.plans if p.strip())
96
+ self.exempt_users = frozenset(u.strip() for u in self.exempt_users if u.strip())
97
+ self.blocked_users = frozenset(u.strip() for u in self.blocked_users if u.strip())
98
+ self.mode = (self.mode or "enforce").strip().lower()
99
+ if self.mode not in MODES:
100
+ self.problems.append(f"mode: {self.mode!r} is not enforce or observe; using enforce")
101
+ self.mode = "enforce"
102
+
103
+ @property
104
+ def has_limits(self) -> bool:
105
+ return any(getattr(self, n) is not None for n in LIMIT_FIELDS)
106
+
107
+ @classmethod
108
+ def from_env(cls, scope: str, env: Env | None = None, **overrides: object) -> Config | None:
109
+ """Controls from `BOT_GUARD_*` env vars, then keyword overrides (which win).
110
+ None when BOT_GUARD is off, 0 or false. Unreadable values are skipped and listed
111
+ in `problems` (the guard logs them); they never stop a run."""
112
+ env = os.environ if env is None else env
113
+ if str(env.get("BOT_GUARD", "")).strip().lower() in ("off", "0", "false"):
114
+ return None
115
+ values, problems = _read_env(env)
116
+ known = {f.name for f in fields(cls)} - {"problems", "scope"}
117
+ for k, v in overrides.items():
118
+ if k not in known:
119
+ raise TypeError(f"unknown bot-guard setting: {k}")
120
+ values[k] = _as_list(k, v)
121
+ cfg = cls(scope=str(env.get("BOT_GUARD_SCOPE") or scope), **values) # type: ignore[arg-type]
122
+ cfg.problems[:0] = problems
123
+ return cfg
124
+
125
+
126
+ def _as_list(name: str, v: object) -> object:
127
+ if name not in LIST_FIELDS or v is None or isinstance(v, (tuple, frozenset)):
128
+ return v
129
+ items = [str(x) for x in v] if isinstance(v, Iterable) and not isinstance(v, str) else str(v).split(",")
130
+ return tuple(items) if name == "plans" else frozenset(items)
131
+
132
+
133
+ def _read_env(env: Env) -> tuple[dict[str, object], list[str]]:
134
+ values: dict[str, object] = {}
135
+ problems: list[str] = []
136
+ for name in NUMBER_FIELDS:
137
+ raw = str(env.get(env_name(name), "")).strip()
138
+ if not raw:
139
+ continue
140
+ if raw.lower() in NO_LIMIT:
141
+ values[name] = None
142
+ continue
143
+ try:
144
+ v = float(raw)
145
+ except ValueError:
146
+ v = math.nan
147
+ if math.isfinite(v) and v >= 0:
148
+ values[name] = v
149
+ else:
150
+ problems.append(f"{env_name(name)}={raw!r} is not a number >= 0; ignored")
151
+ for name in LIST_FIELDS:
152
+ raw = str(env.get(env_name(name), "")).strip()
153
+ if raw:
154
+ values[name] = _as_list(name, raw)
155
+ for name in TEXT_FIELDS:
156
+ raw = str(env.get(env_name(name), ""))
157
+ if raw.strip():
158
+ values[name] = raw if name == "message" else raw.strip()
159
+ return values, problems
160
+
161
+
162
+ def plan_of(env: Env | None = None) -> str | None:
163
+ """The user's plan on Apify, upper case: the pricing tier (FREE, STARTER, ...), else
164
+ FREE or PAID from APIFY_USER_IS_PAYING ("1" for paying users, set but EMPTY for free
165
+ ones). None when unknown."""
166
+ env = os.environ if env is None else env
167
+ tier = str(env.get("APIFY_USER_PRICING_TIER", "")).strip()
168
+ if tier:
169
+ return tier.upper()
170
+ if "APIFY_USER_IS_PAYING" in env:
171
+ return "PAID" if str(env["APIFY_USER_IS_PAYING"]).strip() == "1" else "FREE"
172
+ return None
173
+
174
+
175
+ def is_free_plan(env: Env | None = None) -> bool | None:
176
+ """True on Apify's free plan, False on any other plan, None when unknown."""
177
+ plan = plan_of(env)
178
+ return None if plan is None else plan == "FREE"
179
+
180
+
181
+ def _num(x: object) -> float:
182
+ try:
183
+ v = float(x) # type: ignore[arg-type]
184
+ except (TypeError, ValueError):
185
+ return 0.0
186
+ return v if math.isfinite(v) else 0.0
187
+
188
+
189
+ @dataclass
190
+ class Entry:
191
+ """One run booked against an allowance."""
192
+
193
+ a: str = "" # scope ("" in pool ledgers)
194
+ d: str = "" # day, YYYY-MM-DD
195
+ n: int = 0 # results
196
+ usd: float = 0.0 # your cost
197
+ h: bool = False # hold for a run still going
198
+
199
+ def to_json(self) -> dict[str, object]:
200
+ out: dict[str, object] = {"a": self.a, "d": self.d, "n": self.n, "usd": round(self.usd, 6)}
201
+ if self.h:
202
+ out["h"] = True
203
+ return out
204
+
205
+ @classmethod
206
+ def from_json(cls, v: Mapping[str, object]) -> Entry:
207
+ return cls(
208
+ a=str(v.get("a", "")),
209
+ d=str(v.get("d", "")),
210
+ n=int(_num(v.get("n"))),
211
+ usd=_num(v.get("usd")),
212
+ h=v.get("h") is True,
213
+ )
214
+
215
+
216
+ @dataclass
217
+ class Ledger:
218
+ """Runs in one month: one user's runs, or all limited runs of one scope."""
219
+
220
+ runs: dict[str, Entry] = field(default_factory=dict)
221
+
222
+ @classmethod
223
+ def from_raw(cls, raw: object) -> Ledger:
224
+ """From a stored record: {"runs": {...}} or a bare {run id: entry}."""
225
+ if not isinstance(raw, Mapping):
226
+ return cls()
227
+ runs = raw.get("runs", raw)
228
+ if not isinstance(runs, Mapping):
229
+ return cls()
230
+ return cls({str(k): Entry.from_json(v) for k, v in runs.items() if isinstance(v, Mapping)})
231
+
232
+ @classmethod
233
+ def merged(cls, ledgers: Iterable[Ledger]) -> Ledger:
234
+ out = cls()
235
+ for led in ledgers:
236
+ out.runs.update(led.runs)
237
+ return out
238
+
239
+ def drop_stale_holds(self, today: str) -> None:
240
+ self.runs = {k: e for k, e in self.runs.items() if not e.h or e.d == today}
241
+
242
+ def _sum(self, keep: Callable[[Entry], bool], of: Callable[[Entry], float]) -> float:
243
+ return sum(of(e) for e in self.runs.values() if keep(e))
244
+
245
+ def used(self, scope: str | None = None, since: str = "") -> tuple[float, float]:
246
+ """(results, usd) of runs on or after day `since`, for one scope or (None) all."""
247
+
248
+ def keep(e: Entry) -> bool:
249
+ return (scope is None or e.a == scope) and e.d >= since
250
+
251
+ return self._sum(keep, lambda e: e.n), self._sum(keep, lambda e: e.usd)
252
+
253
+ def results(self) -> float:
254
+ return self.used()[0]
255
+
256
+
257
+ @dataclass(frozen=True)
258
+ class Allowance:
259
+ results_left: int
260
+ usd_left: float | None # None: no cost limit applies
261
+ bound: str # "month" | "week" | "day" | "run" | "pool" | "blocked"
262
+ week_start: str = "" # first day of the rolling week (for the reset day)
263
+
264
+ @property
265
+ def exhausted(self) -> bool:
266
+ return self.results_left == 0
267
+
268
+
269
+ def day_of_month(today: str) -> tuple[int, int]:
270
+ try:
271
+ d = date.fromisoformat(today)
272
+ except ValueError:
273
+ return 30, 30
274
+ return d.day, calendar.monthrange(d.year, d.month)[1]
275
+
276
+
277
+ def shift_day(day: str, days: int) -> str:
278
+ return (date.fromisoformat(day) + timedelta(days=days)).isoformat()
279
+
280
+
281
+ def needs_last_month(cfg: Config, today: str) -> bool:
282
+ """A rolling week that starts last month needs last month's user ledger too."""
283
+ weekly = any(getattr(cfg, f"{who}_week_{u}") is not None for who in ("actor", "user") for u in ("results", "usd"))
284
+ return weekly and day_of_month(today)[0] < 7
285
+
286
+
287
+ def allowance_of(
288
+ cfg: Config, user: Ledger, pool: Ledger, today: str, share: float = 1.0, *, last_month: Ledger | None = None
289
+ ) -> Allowance:
290
+ """What a run may still take. The tightest limit wins; ties go to the earlier of
291
+ month, week, day, run, pool. `share` scales the actor and user limits (new accounts).
292
+ `last_month`: last month's user ledger, for a rolling week that starts there."""
293
+ s = cfg.scope
294
+ cost = float(cfg.cost_per_result or 1e-7)
295
+ week_start = shift_day(today, -6)
296
+ starts = {"month": "", "week": week_start, "day": today}
297
+ ledgers = {"month": user, "week": Ledger.merged([last_month or Ledger(), user]), "day": user}
298
+ usd_lefts: list[float] = []
299
+ candidates: list[tuple[float, str]] = []
300
+ for w in WINDOWS:
301
+ best = math.inf
302
+ for who, scope in (("actor", s), ("user", None)):
303
+ used_n, used_usd = ledgers[w].used(scope, starts[w])
304
+ lim_n = getattr(cfg, f"{who}_{w}_results")
305
+ lim_usd = getattr(cfg, f"{who}_{w}_usd")
306
+ if lim_n is not None:
307
+ best = min(best, lim_n * share - used_n)
308
+ if lim_usd is not None:
309
+ left = max(0.0, lim_usd * share - used_usd)
310
+ usd_lefts.append(left)
311
+ best = min(best, left / cost)
312
+ if w == "day" and cfg.daily_share is not None and cfg.actor_month_results is not None:
313
+ best = min(best, math.ceil(cfg.actor_month_results * share * cfg.daily_share) - user.used(s, today)[0])
314
+ candidates.append((best, w))
315
+ run = math.inf
316
+ if cfg.run_results is not None:
317
+ run = cfg.run_results
318
+ if cfg.run_usd is not None:
319
+ usd_lefts.append(cfg.run_usd)
320
+ run = min(run, cfg.run_usd / cost)
321
+ candidates.append((run, "run"))
322
+ pool_left = math.inf
323
+ if cfg.pool_month_results is not None:
324
+ d, days = day_of_month(today)
325
+ pool_left = math.ceil(cfg.pool_month_results * d / days) - pool.results()
326
+ candidates.append((pool_left, "pool"))
327
+ best_n, bound = candidates[0]
328
+ for c in candidates[1:]:
329
+ if c[0] < best_n:
330
+ best_n, bound = c
331
+ usd_left = max(0.0, min(usd_lefts)) if usd_lefts else None
332
+ # A hair of slack so 0.05 / 0.0005 is 100, not 99.
333
+ return Allowance(max(0, math.floor(best_n + 1e-6)), usd_left, bound, week_start)
334
+
335
+
336
+ def week_reset(user: Ledger, last_month: Ledger | None, week_start: str) -> str:
337
+ """The day the oldest run in the rolling week leaves it."""
338
+ days = [e.d for e in Ledger.merged([last_month or Ledger(), user]).runs.values() if e.d >= week_start and e.n > 0]
339
+ return shift_day(min(days), 7) if days else shift_day(week_start, 7)
340
+
341
+
342
+ def account_share(cfg: Config, created: str | None, today: str) -> float:
343
+ """Share of the actor and user limits for an account created on `created`."""
344
+ if not created:
345
+ return 1.0
346
+ try:
347
+ c = datetime.fromisoformat(created.replace("Z", "+00:00")).date()
348
+ t = date.fromisoformat(today)
349
+ except ValueError:
350
+ return 1.0
351
+ young = (t - c).days < float(cfg.new_account_days or 0)
352
+ return float(cfg.new_account_share if cfg.new_account_share is not None else 1.0) if young else 1.0
353
+
354
+
355
+ def user_hash(user_id: str, salt: str = "") -> str:
356
+ """Store keys never hold raw user ids. Same value in the JavaScript package."""
357
+ return hashlib.sha256(f"bot-guard:{salt}:{user_id}".encode()).hexdigest()[:32]
358
+
359
+
360
+ def utc_today() -> str:
361
+ return datetime.now(timezone.utc).date().isoformat()
362
+
363
+
364
+ def next_reset(month: str) -> str:
365
+ y, m = (int(x) for x in month.split("-")[:2])
366
+ y, m = (y + 1, 1) if m >= 12 else (y, m + 1)
367
+ return f"{y:04d}-{m:02d}-01"
368
+
369
+
370
+ def next_day(today: str) -> str:
371
+ return shift_day(today, 1)
372
+
373
+
374
+ def previous_month(month: str) -> str:
375
+ y, m = (int(x) for x in month.split("-")[:2])
376
+ y, m = (y - 1, 12) if m <= 1 else (y, m - 1)
377
+ return f"{y:04d}-{m:02d}"
378
+
379
+
380
+ _LEDGER_KEY = re.compile(r"^(?:user|pool)\.(\d{4}-\d{2})\.")
381
+
382
+
383
+ def ledger_month(key: str) -> str | None:
384
+ """`2026-11` for a ledger key like `user.2026-11.<hash>`; None for other keys."""
385
+ m = _LEDGER_KEY.match(key)
386
+ return m.group(1) if m else None
@@ -0,0 +1,324 @@
1
+ """The run-time guard: load the allowance at start, cut deliveries, book at end."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ import os
8
+ import random
9
+ import uuid
10
+ from collections.abc import Iterable
11
+ from dataclasses import dataclass, replace
12
+ from typing import Any
13
+
14
+ from .backends import Backend
15
+ from .core import (
16
+ Allowance,
17
+ Config,
18
+ Entry,
19
+ Env,
20
+ Ledger,
21
+ account_share,
22
+ allowance_of,
23
+ needs_last_month,
24
+ next_day,
25
+ next_reset,
26
+ plan_of,
27
+ previous_month,
28
+ user_hash,
29
+ utc_today,
30
+ week_reset,
31
+ )
32
+
33
+ log = logging.getLogger("apify_bot_guard")
34
+
35
+ WHEN = {
36
+ "day": "tomorrow (UTC)",
37
+ "pool": "tomorrow (UTC), when more of this month's free share opens",
38
+ "run": "in a new run",
39
+ }
40
+ DEFAULT_MESSAGE = (
41
+ "Free plan limit reached: {delivered} results this run. More are available {when}, or right away on a paid plan."
42
+ )
43
+ BLOCKED_MESSAGE = "Free use of this Actor is not available for this account. It works on a paid plan."
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class Decision:
48
+ """Whether a run may go ahead, and on what terms.
49
+
50
+ `allowed`: deliver results (False: nothing left; end the run with `message`).
51
+ `unlimited`: no limit applies (plan not limited, exempt user, guard off, storage unreadable).
52
+ `remaining`: results this run may deliver (None when unlimited or not enforced).
53
+ `enforced`: False in observe mode: limits are measured and logged, never applied.
54
+ """
55
+
56
+ allowed: bool
57
+ unlimited: bool
58
+ remaining: int | None = None
59
+ bound: str | None = None
60
+ message: str | None = None
61
+ resets_on: str | None = None
62
+ enforced: bool = True
63
+ guard: BotGuard | None = None
64
+
65
+
66
+ def _limited_user(
67
+ cfg: Config, env: Env, *, user_id: str | None, plan: str | None, free: bool | None, force: bool
68
+ ) -> str | None:
69
+ """The user id when this run is limited; None when it is not (unknown, exempt, plan not limited)."""
70
+ user = (user_id or str(env.get("APIFY_USER_ID", ""))).strip()
71
+ if not user or user in cfg.exempt_users:
72
+ return None
73
+ if plan is None and free is not None:
74
+ plan = "FREE" if free else "PAID"
75
+ plan = (plan or plan_of(env) or "").strip().upper()
76
+ return user if force or plan in cfg.plans else None
77
+
78
+
79
+ class BotGuard:
80
+ """One run's allowance. Create it with `await BotGuard.admit(...)` or `open(...)`."""
81
+
82
+ def __init__(
83
+ self,
84
+ cfg: Config,
85
+ backend: Backend,
86
+ allowance: Allowance,
87
+ *,
88
+ user_key: str,
89
+ pool_key: str,
90
+ run_id: str,
91
+ today: str,
92
+ resets_on: str | None = None,
93
+ logger: logging.Logger = log,
94
+ ) -> None:
95
+ self.cfg = cfg
96
+ self.allowance = allowance
97
+ self.delivered = 0
98
+ self.limited = False # a take() was cut (enforce mode)
99
+ self.over = False # the run went past its allowance (either mode)
100
+ self.user_key = user_key
101
+ self.pool_key = pool_key
102
+ self.run_id = run_id
103
+ self.today = today
104
+ self.enforced = cfg.mode == "enforce"
105
+ self._resets_on = resets_on
106
+ self._backend = backend
107
+ self._log = logger
108
+ self._booked = allowance.bound == "blocked"
109
+
110
+ @classmethod
111
+ async def admit(cls, scope: str, backend: Backend, **kwargs: Any) -> Decision:
112
+ """`open()` as one answer. Keep `decision.guard` (when set): call `take()` while
113
+ delivering and `close()` at the end."""
114
+ guard = await cls.open(scope, backend, **kwargs)
115
+ return guard.decision if guard else Decision(allowed=True, unlimited=True)
116
+
117
+ @property
118
+ def decision(self) -> Decision:
119
+ left = self.remaining
120
+ return Decision(
121
+ allowed=left > 0 or not self.enforced,
122
+ unlimited=False,
123
+ remaining=left if self.enforced else None,
124
+ bound=self.allowance.bound,
125
+ message=None if left > 0 else self.message,
126
+ resets_on=self.resets_on,
127
+ enforced=self.enforced,
128
+ guard=self,
129
+ )
130
+
131
+ @property
132
+ def resets_on(self) -> str | None:
133
+ """The UTC day more becomes available (None when blocked)."""
134
+ if self._resets_on is not None or self.allowance.bound == "blocked":
135
+ return self._resets_on
136
+ if self.allowance.bound == "month":
137
+ return next_reset(self.today[:7])
138
+ if self.allowance.bound == "run":
139
+ return self.today
140
+ return next_day(self.today)
141
+
142
+ @classmethod
143
+ async def open(
144
+ cls,
145
+ scope: str,
146
+ backend: Backend,
147
+ *,
148
+ user_id: str | None = None,
149
+ plan: str | None = None,
150
+ free: bool | None = None,
151
+ run_id: str | None = None,
152
+ env: Env | None = None,
153
+ config: Config | None = None,
154
+ account_created: str | None = None,
155
+ today: str | None = None,
156
+ force: bool = False,
157
+ logger: logging.Logger = log,
158
+ **settings: Any,
159
+ ) -> BotGuard | None:
160
+ """Load this run's allowance. Returns None (no limit) when the user's plan is not in
161
+ `plans`, the plan or user id is unknown, the user is exempt, BOT_GUARD=off, no limit is
162
+ set, or the backend cannot be read: a storage problem never blocks a customer.
163
+
164
+ On Apify, `user_id`, the plan and `run_id` come from the run's env vars. Elsewhere,
165
+ pass them yourself: `plan` is your own plan name (matched against `plans`); `free`
166
+ is a shorthand for plan FREE (True) or PAID (False).
167
+
168
+ Settings: `config`, else `BOT_GUARD_*` env vars with `**settings` on top (any field
169
+ of `Config`, e.g. `actor_week_results=50`). See docs/CONFIGURATION.md.
170
+
171
+ `account_created`: the account's creation date, if you can read it. Otherwise the
172
+ day the user was first seen on any Actor sharing this backend stands in.
173
+ """
174
+ env = os.environ if env is None else env
175
+ cfg = replace(config, **settings) if config and settings else config or Config.from_env(scope, env, **settings)
176
+ if cfg is None:
177
+ return None
178
+ for problem in cfg.problems:
179
+ logger.warning("bot-guard: %s", problem)
180
+ user = _limited_user(cfg, env, user_id=user_id, plan=plan, free=free, force=force)
181
+ if user is None:
182
+ return None
183
+ today = today or utc_today()
184
+ month = today[:7]
185
+ h = user_hash(user, cfg.salt)
186
+ user_key = f"user.{month}.{h}"
187
+ pool_key = f"pool.{month}.{cfg.scope}"
188
+ run = run_id or env.get("ACTOR_RUN_ID") or env.get("APIFY_ACTOR_RUN_ID") or f"local-{uuid.uuid4().hex[:12]}"
189
+ common: dict[str, Any] = {"user_key": user_key, "pool_key": pool_key, "run_id": str(run), "today": today}
190
+ if user in cfg.blocked_users:
191
+ logger.info("bot-guard: user is blocked")
192
+ return cls(cfg, backend, Allowance(0, 0.0, "blocked"), logger=logger, **common)
193
+ if not cfg.has_limits:
194
+ return None
195
+ keys = [user_key, pool_key]
196
+ if needs_last_month(cfg, today):
197
+ keys.append(f"user.{previous_month(month)}.{h}")
198
+
199
+ async def no_seen() -> str | None:
200
+ return None
201
+
202
+ try:
203
+ ledgers, seen = await asyncio.gather(
204
+ backend.get_ledgers(keys),
205
+ no_seen() if account_created else backend.first_seen(h, today),
206
+ )
207
+ except Exception as e: # noqa: BLE001 - fail open on any storage error
208
+ logger.warning("bot-guard: allowance unreadable, no limit this run: %s", e)
209
+ return None
210
+ u, p = ledgers[0], ledgers[1]
211
+ last = ledgers[2] if len(ledgers) > 2 else None
212
+ for led in filter(None, (u, p, last)):
213
+ led.drop_stale_holds(today)
214
+ if seen and cfg.track_from and seen < cfg.track_from:
215
+ seen = None
216
+ share = account_share(cfg, account_created or seen, today)
217
+ allowance = allowance_of(cfg, u, p, today, share, last_month=last)
218
+ resets = week_reset(u, last, allowance.week_start) if allowance.bound == "week" else None
219
+ guard = cls(cfg, backend, allowance, resets_on=resets, logger=logger, **common)
220
+ logger.info(
221
+ "bot-guard: %s results left (bound: %s, new account: %s, mode: %s)",
222
+ allowance.results_left,
223
+ allowance.bound,
224
+ share < 1,
225
+ cfg.mode,
226
+ )
227
+ if not allowance.exhausted:
228
+ usd = allowance.usd_left
229
+ if usd is None:
230
+ usd = allowance.results_left * float(cfg.cost_per_result or 0)
231
+ try:
232
+ await guard._save(allowance.results_left, usd, hold=True, known={user_key: u, pool_key: p})
233
+ except Exception as e: # noqa: BLE001
234
+ logger.warning("bot-guard: hold not saved: %s", e)
235
+ return guard
236
+
237
+ def take(self, wanted: int, cost_so_far: float | None = None) -> int:
238
+ """How many of `wanted` more results may be delivered now; counts them as delivered.
239
+ `cost_so_far`: the run's own cost in USD, if you track it. In observe mode returns
240
+ `wanted` and only logs when the run goes past its allowance."""
241
+ left = max(0, self.allowance.results_left - self.delivered)
242
+ n = max(0, min(wanted, left))
243
+ usd_left = self.allowance.usd_left
244
+ if cost_so_far is not None and usd_left is not None and cost_so_far >= usd_left:
245
+ n = 0
246
+ if n < wanted:
247
+ if not self.over:
248
+ self._log.info(
249
+ "bot-guard: allowance used up (bound: %s, enforced: %s)",
250
+ self.allowance.bound,
251
+ self.enforced,
252
+ )
253
+ self.over = True
254
+ if self.enforced:
255
+ self.limited = True
256
+ else:
257
+ n = wanted
258
+ self.delivered += n
259
+ return n
260
+
261
+ @property
262
+ def remaining(self) -> int:
263
+ return max(0, self.allowance.results_left - self.delivered)
264
+
265
+ @property
266
+ def message(self) -> str:
267
+ """A status line for the user when the run was cut or had nothing left."""
268
+ b = self.allowance.bound
269
+ when = WHEN.get(b) or f"on {self.resets_on} (UTC)"
270
+ template = self.cfg.message or (BLOCKED_MESSAGE if b == "blocked" else DEFAULT_MESSAGE)
271
+ values = {"delivered": str(self.delivered), "when": when, "resets_on": self.resets_on or "", "bound": b}
272
+ for k, v in values.items():
273
+ template = template.replace("{" + k + "}", v)
274
+ return template
275
+
276
+ async def close(self, usd: float | None = None) -> None:
277
+ """Book what the run delivered, replacing the hold. Safe to call twice."""
278
+ if self._booked:
279
+ return
280
+ self._booked = True
281
+ cost = usd if usd is not None else self.delivered * float(self.cfg.cost_per_result or 0)
282
+ try:
283
+ await self._save(self.delivered, cost, hold=False)
284
+ except Exception as e: # noqa: BLE001
285
+ self._log.warning("bot-guard: run not booked: %s", e)
286
+ chance = float(self.cfg.auto_prune or 0)
287
+ if chance > 0 and random.random() < chance:
288
+ await self.prune()
289
+
290
+ async def prune(self) -> int:
291
+ """Delete ledgers older than last month. Never raises."""
292
+ try:
293
+ n = await self._backend.prune(previous_month(self.today[:7]))
294
+ except Exception as e: # noqa: BLE001
295
+ self._log.warning("bot-guard: prune failed: %s", e)
296
+ return 0
297
+ if n:
298
+ self._log.info("bot-guard: pruned %s old ledgers", n)
299
+ return n
300
+
301
+ async def _save(self, n: int, usd: float, *, hold: bool, known: dict[str, Ledger] | None = None) -> None:
302
+ mine = Entry(a=self.cfg.scope, d=self.today, n=int(n), usd=usd, h=hold)
303
+ pool = Entry(a="", d=self.today, n=int(n), usd=0.0, h=hold)
304
+ await self._backend.put_entries([(self.user_key, self.run_id, mine), (self.pool_key, self.run_id, pool)], known)
305
+
306
+ async def __aenter__(self) -> BotGuard:
307
+ return self
308
+
309
+ async def __aexit__(self, *exc: object) -> None:
310
+ await self.close()
311
+
312
+
313
+ async def push_data(guard: BotGuard | None, items: Iterable[Any] | dict[str, Any]) -> int:
314
+ """Push to the run's default dataset through the Apify SDK, cut to the
315
+ allowance; sets the status message when it cuts. Returns how many were pushed."""
316
+ from apify import Actor # optional dependency
317
+
318
+ batch = [items] if isinstance(items, dict) else list(items)
319
+ n = guard.take(len(batch)) if guard else len(batch)
320
+ if n:
321
+ await Actor.push_data(batch[:n])
322
+ if guard and guard.limited:
323
+ await Actor.set_status_message(guard.message)
324
+ return n
File without changes
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.5
2
+ Name: apify-bot-guard
3
+ Version: 0.1.1
4
+ Summary: Fair free-plan allowances for Apify Actors, with a per-Actor pool against farms of free accounts.
5
+ Project-URL: Homepage, https://github.com/tacps126/apify-bot-guard
6
+ Project-URL: Issues, https://github.com/tacps126/apify-bot-guard/issues
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Keywords: abuse,actor,apify,free-tier,rate-limit,redis,upstash
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Framework :: AsyncIO
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.10
16
+ Provides-Extra: apify
17
+ Requires-Dist: apify-client>=1.8; extra == 'apify'
18
+ Requires-Dist: apify>=2; extra == 'apify'
19
+ Provides-Extra: dev
20
+ Requires-Dist: coverage>=7.6; extra == 'dev'
21
+ Requires-Dist: mypy>=1.13; extra == 'dev'
22
+ Requires-Dist: ruff>=0.8; extra == 'dev'
23
+ Provides-Extra: redis
24
+ Requires-Dist: redis>=5; extra == 'redis'
25
+ Provides-Extra: upstash
26
+ Requires-Dist: upstash-redis>=1; extra == 'upstash'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # apify-bot-guard (Python)
30
+
31
+ Fair free-plan allowances for Apify Actors, with a per-Actor pool against farms of free accounts.
32
+
33
+ ```bash
34
+ pip install "apify-bot-guard[apify]"
35
+ ```
36
+
37
+ ```python
38
+ from apify_bot_guard import ApifyKvBackend, BotGuard, push_data
39
+
40
+ guard = await BotGuard.open("my-actor", ApifyKvBackend(token=os.environ["GUARD_TOKEN"]))
41
+ await push_data(guard, items)
42
+ if guard:
43
+ await guard.close()
44
+ ```
45
+
46
+ Full documentation: https://github.com/tacps126/apify-bot-guard
47
+
48
+ Using an AI assistant? Point it at
49
+ https://github.com/tacps126/apify-bot-guard/blob/main/docs/AI-INTEGRATION.md
@@ -0,0 +1,9 @@
1
+ apify_bot_guard/__init__.py,sha256=tjswlZUsNXeTwMntkgd-QaoeCeIu7oWxOqmE4Qfo61E,717
2
+ apify_bot_guard/backends.py,sha256=waCjll-VeRZPb3vYg42xP_WHmd936o2rcKRP9eVto2w,9133
3
+ apify_bot_guard/core.py,sha256=gEL6DRtkuy5qN4fOf19CNpYUb3mvg2Yc77HUikU7l-A,15154
4
+ apify_bot_guard/guard.py,sha256=SRgVyKN4fpwEYC0iSzliQGwS1z23mYqjynlIpppIQo0,12652
5
+ apify_bot_guard/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ apify_bot_guard-0.1.1.dist-info/METADATA,sha256=6UvpmgHKLiCY7S92usZi36HgeP7HQjZjQHXHKZvRmFo,1665
7
+ apify_bot_guard-0.1.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ apify_bot_guard-0.1.1.dist-info/licenses/LICENSE,sha256=ORtt9qEuW8Cc2SSbEsoLPqZK1FN8VmaURVfAcD0qrUA,1065
9
+ apify_bot_guard-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tacps126
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.