apify-bot-guard 0.1.1__tar.gz

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,7 @@
1
+ node_modules/
2
+ __pycache__/
3
+ *.egg-info/
4
+ dist/
5
+ .venv/
6
+ .coverage
7
+ coverage/
@@ -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.
@@ -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,21 @@
1
+ # apify-bot-guard (Python)
2
+
3
+ Fair free-plan allowances for Apify Actors, with a per-Actor pool against farms of free accounts.
4
+
5
+ ```bash
6
+ pip install "apify-bot-guard[apify]"
7
+ ```
8
+
9
+ ```python
10
+ from apify_bot_guard import ApifyKvBackend, BotGuard, push_data
11
+
12
+ guard = await BotGuard.open("my-actor", ApifyKvBackend(token=os.environ["GUARD_TOKEN"]))
13
+ await push_data(guard, items)
14
+ if guard:
15
+ await guard.close()
16
+ ```
17
+
18
+ Full documentation: https://github.com/tacps126/apify-bot-guard
19
+
20
+ Using an AI assistant? Point it at
21
+ https://github.com/tacps126/apify-bot-guard/blob/main/docs/AI-INTEGRATION.md
@@ -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