pyjs-extras 0.4.0__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,210 @@
1
+ """Deterministic webhook delivery for the local Stripe simulator."""
2
+
3
+ import hashlib
4
+ import hmac
5
+ import json
6
+ import threading
7
+ import time
8
+ from collections import deque
9
+ from collections.abc import Mapping
10
+ from typing import Any
11
+ from urllib.error import HTTPError, URLError
12
+ from urllib.request import Request, urlopen
13
+
14
+ from .simulator_store import SimulatorStore
15
+
16
+ DELIVERY_MODES = {"automatic", "manual", "paused"}
17
+ SIGNATURE_MODES = {"valid", "invalid", "stale"}
18
+
19
+
20
+ class WebhookDelivery:
21
+ """Record events and forward them without blocking simulator requests."""
22
+
23
+ def __init__(self, store: SimulatorStore, url: str, secret: str):
24
+ self.store = store
25
+ self.url = url
26
+ self.secret = secret
27
+ self._condition = threading.Condition()
28
+ self._queue: deque[tuple[str, str]] = deque()
29
+ self._queued: set[str] = set()
30
+ self._active_deliveries = 0
31
+ self._closed = False
32
+ self._worker = threading.Thread(
33
+ target=self._work,
34
+ name="pyjs-stripe-webhooks",
35
+ daemon=True,
36
+ )
37
+ self._worker.start()
38
+ if self.mode == "automatic":
39
+ self.enqueue_pending()
40
+
41
+ @property
42
+ def mode(self) -> str:
43
+ return self.store.metadata("delivery_mode") or "automatic"
44
+
45
+ def set_mode(self, mode: str) -> None:
46
+ if mode not in DELIVERY_MODES:
47
+ raise ValueError(f"Unsupported delivery mode: {mode}")
48
+ with self._condition:
49
+ self.store.set_metadata("delivery_mode", mode)
50
+ if mode == "manual":
51
+ self._queue.clear()
52
+ self._queued.clear()
53
+ self._condition.notify_all()
54
+ if mode == "automatic":
55
+ self.enqueue_pending()
56
+
57
+ def record(self, event: Mapping[str, Any]) -> None:
58
+ pending = bool(self.url)
59
+ self.store.add_event(event, pending=pending)
60
+ if pending and self.mode == "automatic":
61
+ self.enqueue(str(event["id"]))
62
+
63
+ def enqueue(self, event_id: str, signature_mode: str = "valid") -> None:
64
+ if signature_mode not in SIGNATURE_MODES:
65
+ raise ValueError(f"Unsupported signature mode: {signature_mode}")
66
+ key = f"{event_id}:{signature_mode}"
67
+ with self._condition:
68
+ if key not in self._queued:
69
+ self._queue.append((event_id, signature_mode))
70
+ self._queued.add(key)
71
+ self._condition.notify_all()
72
+
73
+ def enqueue_pending(self, *, newest_first: bool = False) -> None:
74
+ events = [
75
+ event
76
+ for event in self.store.events()
77
+ if event["delivery_state"] in {"pending", "failed"}
78
+ ]
79
+ if newest_first:
80
+ events.reverse()
81
+ for event in events:
82
+ self.enqueue(event["id"])
83
+
84
+ def deliver(
85
+ self,
86
+ event: Mapping[str, Any],
87
+ *,
88
+ signature_mode: str = "valid",
89
+ retries: int = 1,
90
+ ) -> bool:
91
+ if not self.url:
92
+ return False
93
+ if signature_mode not in SIGNATURE_MODES:
94
+ raise ValueError(f"Unsupported signature mode: {signature_mode}")
95
+ with self._condition:
96
+ if self._closed:
97
+ return False
98
+ self._active_deliveries += 1
99
+ try:
100
+ return self._deliver(event, signature_mode=signature_mode, retries=retries)
101
+ finally:
102
+ self._finish_delivery()
103
+
104
+ def _deliver(
105
+ self,
106
+ event: Mapping[str, Any],
107
+ *,
108
+ signature_mode: str,
109
+ retries: int,
110
+ ) -> bool:
111
+ payload = json.dumps(event, separators=(",", ":")).encode()
112
+ timestamp = int(time.time())
113
+ if signature_mode == "stale":
114
+ timestamp -= 10 * 60
115
+ signed = str(timestamp).encode() + b"." + payload
116
+ digest = hmac.new(self.secret.encode(), signed, hashlib.sha256).hexdigest()
117
+ if signature_mode == "invalid":
118
+ digest = "0" * len(digest)
119
+ signature = f"t={timestamp},v1={digest}"
120
+ delivered = False
121
+ self.store.set_event_state(str(event["id"]), "delivering")
122
+ for attempt in range(retries):
123
+ request = Request(
124
+ self.url,
125
+ data=payload,
126
+ method="POST",
127
+ headers={
128
+ "Content-Type": "application/json",
129
+ "Stripe-Signature": signature,
130
+ },
131
+ )
132
+ status: int | None = None
133
+ error = ""
134
+ try:
135
+ with urlopen(request, timeout=2) as response:
136
+ status = response.status
137
+ delivered = 200 <= response.status < 300
138
+ except HTTPError as exception:
139
+ status = exception.code
140
+ error = f"HTTP {exception.code}"
141
+ except (URLError, TimeoutError) as exception:
142
+ error = f"{type(exception).__name__}: {exception}"
143
+ self.store.event_attempt(
144
+ str(event["id"]),
145
+ delivered,
146
+ signature_mode=signature_mode,
147
+ status=status,
148
+ error=error,
149
+ )
150
+ with self._condition:
151
+ closed = self._closed
152
+ if delivered or closed:
153
+ break
154
+ if attempt + 1 < retries:
155
+ time.sleep(0.05 * (attempt + 1))
156
+ return delivered
157
+
158
+ def wait_for_idle(self, timeout: float = 5) -> bool:
159
+ deadline = time.monotonic() + timeout
160
+ with self._condition:
161
+ while self._queue or self._active_deliveries:
162
+ remaining = deadline - time.monotonic()
163
+ if remaining <= 0:
164
+ return False
165
+ self._condition.wait(remaining)
166
+ return True
167
+
168
+ def close(self) -> None:
169
+ with self._condition:
170
+ self._closed = True
171
+ self._queue.clear()
172
+ self._queued.clear()
173
+ self._condition.notify_all()
174
+ self._worker.join(timeout=3)
175
+ self.wait_for_idle(timeout=3)
176
+
177
+ def prepare_reset(self, timeout: float = 6) -> bool:
178
+ deadline = time.monotonic() + timeout
179
+ with self._condition:
180
+ self._queue.clear()
181
+ self._queued.clear()
182
+ while self._active_deliveries:
183
+ remaining = deadline - time.monotonic()
184
+ if remaining <= 0:
185
+ return False
186
+ self._condition.wait(remaining)
187
+ return True
188
+
189
+ def _work(self) -> None:
190
+ while True:
191
+ with self._condition:
192
+ self._condition.wait_for(
193
+ lambda: self._closed or (self._queue and self.mode == "automatic")
194
+ )
195
+ if self._closed:
196
+ return
197
+ event_id, signature_mode = self._queue.popleft()
198
+ self._queued.discard(f"{event_id}:{signature_mode}")
199
+ self._active_deliveries += 1
200
+ try:
201
+ event = self.store.event(event_id)
202
+ if event is not None:
203
+ self._deliver(event, signature_mode=signature_mode, retries=3)
204
+ finally:
205
+ self._finish_delivery()
206
+
207
+ def _finish_delivery(self) -> None:
208
+ with self._condition:
209
+ self._active_deliveries -= 1
210
+ self._condition.notify_all()
@@ -0,0 +1,288 @@
1
+ """Persistent object and event storage for the local Stripe simulator."""
2
+
3
+ import json
4
+ import sqlite3
5
+ import threading
6
+ import time
7
+ from collections.abc import Mapping
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+
12
+ class SimulatorStore:
13
+ """Small SQLite object and event store shared by simulator requests."""
14
+
15
+ def __init__(self, database: str | Path = ":memory:"):
16
+ self.connection = sqlite3.connect(str(database), check_same_thread=False)
17
+ self.connection.row_factory = sqlite3.Row
18
+ self.lock = threading.RLock()
19
+ with self.connection:
20
+ self.connection.executescript(
21
+ """
22
+ CREATE TABLE IF NOT EXISTS objects (
23
+ kind TEXT NOT NULL,
24
+ id TEXT PRIMARY KEY,
25
+ data TEXT NOT NULL
26
+ );
27
+ CREATE TABLE IF NOT EXISTS events (
28
+ id TEXT PRIMARY KEY,
29
+ type TEXT NOT NULL,
30
+ data TEXT NOT NULL,
31
+ attempts INTEGER NOT NULL DEFAULT 0,
32
+ delivered INTEGER NOT NULL DEFAULT 0,
33
+ last_status INTEGER,
34
+ last_error TEXT NOT NULL DEFAULT '',
35
+ last_attempt_at INTEGER,
36
+ delivery_state TEXT NOT NULL DEFAULT 'pending'
37
+ );
38
+ CREATE TABLE IF NOT EXISTS delivery_attempts (
39
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
40
+ event_id TEXT NOT NULL,
41
+ attempted_at INTEGER NOT NULL,
42
+ signature_mode TEXT NOT NULL,
43
+ status INTEGER,
44
+ error TEXT NOT NULL DEFAULT '',
45
+ delivered INTEGER NOT NULL DEFAULT 0
46
+ );
47
+ CREATE TABLE IF NOT EXISTS idempotency (
48
+ path TEXT NOT NULL,
49
+ key TEXT NOT NULL,
50
+ data TEXT NOT NULL,
51
+ PRIMARY KEY (path, key)
52
+ );
53
+ CREATE TABLE IF NOT EXISTS metadata (
54
+ key TEXT PRIMARY KEY,
55
+ value TEXT NOT NULL
56
+ );
57
+ """
58
+ )
59
+ event_columns = {
60
+ row["name"]
61
+ for row in self.connection.execute("PRAGMA table_info(events)")
62
+ }
63
+ for name, definition in {
64
+ "last_status": "INTEGER",
65
+ "last_error": "TEXT NOT NULL DEFAULT ''",
66
+ "last_attempt_at": "INTEGER",
67
+ "delivery_state": "TEXT NOT NULL DEFAULT 'pending'",
68
+ }.items():
69
+ if name not in event_columns:
70
+ self.connection.execute(
71
+ f"ALTER TABLE events ADD COLUMN {name} {definition}"
72
+ )
73
+ self.connection.execute(
74
+ """
75
+ UPDATE events SET delivery_state = CASE
76
+ WHEN delivered = 1 THEN 'delivered'
77
+ WHEN attempts > 0 THEN 'failed'
78
+ ELSE 'pending'
79
+ END
80
+ WHERE delivery_state IS NULL OR delivery_state = 'pending'
81
+ """
82
+ )
83
+ if self.metadata("clock") is None:
84
+ self.set_metadata("clock", str(int(time.time())))
85
+ if self.metadata("delivery_mode") is None:
86
+ self.set_metadata("delivery_mode", "automatic")
87
+
88
+ def close(self) -> None:
89
+ self.connection.close()
90
+
91
+ def reset(self) -> None:
92
+ with self.lock, self.connection:
93
+ self.connection.execute("DELETE FROM objects")
94
+ self.connection.execute("DELETE FROM events")
95
+ self.connection.execute("DELETE FROM delivery_attempts")
96
+ self.connection.execute("DELETE FROM idempotency")
97
+ self.connection.execute("DELETE FROM metadata")
98
+ self.set_metadata("clock", str(int(time.time())))
99
+ self.set_metadata("delivery_mode", "automatic")
100
+
101
+ def metadata(self, key: str) -> str | None:
102
+ with self.lock:
103
+ row = self.connection.execute(
104
+ "SELECT value FROM metadata WHERE key = ?", (key,)
105
+ ).fetchone()
106
+ return None if row is None else str(row["value"])
107
+
108
+ def set_metadata(self, key: str, value: str) -> None:
109
+ with self.lock, self.connection:
110
+ self.connection.execute(
111
+ """
112
+ INSERT INTO metadata (key, value) VALUES (?, ?)
113
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value
114
+ """,
115
+ (key, value),
116
+ )
117
+
118
+ def now(self) -> int:
119
+ return int(self.metadata("clock") or time.time())
120
+
121
+ def advance(self, seconds: int) -> int:
122
+ value = self.now() + seconds
123
+ self.set_metadata("clock", str(value))
124
+ return value
125
+
126
+ def new_id(self, prefix: str) -> str:
127
+ key = f"counter:{prefix}"
128
+ with self.lock:
129
+ value = int(self.metadata(key) or "0") + 1
130
+ self.set_metadata(key, str(value))
131
+ return f"{prefix}_local_{value:08d}"
132
+
133
+ def put(self, kind: str, value: Mapping[str, Any]) -> dict[str, Any]:
134
+ result = dict(value)
135
+ with self.lock, self.connection:
136
+ self.connection.execute(
137
+ """
138
+ INSERT INTO objects (kind, id, data) VALUES (?, ?, ?)
139
+ ON CONFLICT(id) DO UPDATE SET
140
+ kind = excluded.kind,
141
+ data = excluded.data
142
+ """,
143
+ (kind, result["id"], json.dumps(result)),
144
+ )
145
+ return result
146
+
147
+ def get(self, kind: str, object_id: str) -> dict[str, Any] | None:
148
+ with self.lock:
149
+ row = self.connection.execute(
150
+ "SELECT data FROM objects WHERE kind = ? AND id = ?",
151
+ (kind, object_id),
152
+ ).fetchone()
153
+ return None if row is None else json.loads(row["data"])
154
+
155
+ def list(self, kind: str) -> list[dict[str, Any]]:
156
+ with self.lock:
157
+ rows = self.connection.execute(
158
+ "SELECT data FROM objects WHERE kind = ? ORDER BY rowid",
159
+ (kind,),
160
+ ).fetchall()
161
+ return [json.loads(row["data"]) for row in rows]
162
+
163
+ def idempotent(self, path: str, key: str) -> dict[str, Any] | None:
164
+ if not key:
165
+ return None
166
+ with self.lock:
167
+ row = self.connection.execute(
168
+ "SELECT data FROM idempotency WHERE path = ? AND key = ?",
169
+ (path, key),
170
+ ).fetchone()
171
+ return None if row is None else json.loads(row["data"])
172
+
173
+ def remember(self, path: str, key: str, value: Mapping[str, Any]) -> None:
174
+ if not key:
175
+ return
176
+ with self.lock, self.connection:
177
+ self.connection.execute(
178
+ "INSERT OR IGNORE INTO idempotency (path, key, data) VALUES (?, ?, ?)",
179
+ (path, key, json.dumps(dict(value))),
180
+ )
181
+
182
+ def add_event(self, event: Mapping[str, Any], *, pending: bool = False) -> None:
183
+ state = "pending" if pending else "not_configured"
184
+ with self.lock, self.connection:
185
+ self.connection.execute(
186
+ """
187
+ INSERT INTO events (id, type, data, delivery_state)
188
+ VALUES (?, ?, ?, ?)
189
+ """,
190
+ (event["id"], event["type"], json.dumps(dict(event)), state),
191
+ )
192
+
193
+ def set_event_state(self, event_id: str, state: str) -> None:
194
+ with self.lock, self.connection:
195
+ self.connection.execute(
196
+ "UPDATE events SET delivery_state = ? WHERE id = ?",
197
+ (state, event_id),
198
+ )
199
+
200
+ def event_attempt(
201
+ self,
202
+ event_id: str,
203
+ delivered: bool,
204
+ *,
205
+ signature_mode: str = "valid",
206
+ status: int | None,
207
+ error: str,
208
+ ) -> None:
209
+ attempted_at = int(time.time())
210
+ with self.lock, self.connection:
211
+ self.connection.execute(
212
+ """
213
+ INSERT INTO delivery_attempts (
214
+ event_id, attempted_at, signature_mode, status, error, delivered
215
+ ) VALUES (?, ?, ?, ?, ?, ?)
216
+ """,
217
+ (
218
+ event_id,
219
+ attempted_at,
220
+ signature_mode,
221
+ status,
222
+ error,
223
+ int(delivered),
224
+ ),
225
+ )
226
+ self.connection.execute(
227
+ """
228
+ UPDATE events
229
+ SET attempts = attempts + 1,
230
+ delivered = CASE WHEN delivered = 1 THEN 1 ELSE ? END,
231
+ last_status = ?,
232
+ last_error = ?,
233
+ last_attempt_at = ?,
234
+ delivery_state = CASE
235
+ WHEN delivered = 1 OR ? = 1 THEN 'delivered'
236
+ ELSE 'failed'
237
+ END
238
+ WHERE id = ?
239
+ """,
240
+ (
241
+ int(delivered),
242
+ status,
243
+ error,
244
+ attempted_at,
245
+ int(delivered),
246
+ event_id,
247
+ ),
248
+ )
249
+
250
+ def events(self) -> list[dict[str, Any]]:
251
+ with self.lock:
252
+ rows = self.connection.execute(
253
+ """
254
+ SELECT data, attempts, delivered, last_status, last_error,
255
+ last_attempt_at, delivery_state
256
+ FROM events ORDER BY rowid
257
+ """
258
+ ).fetchall()
259
+ return [
260
+ {
261
+ **json.loads(row["data"]),
262
+ "delivery_attempts": row["attempts"],
263
+ "delivery_state": row["delivery_state"],
264
+ "delivered": bool(row["delivered"]),
265
+ "last_status": row["last_status"],
266
+ "last_error": row["last_error"],
267
+ "last_attempt_at": row["last_attempt_at"],
268
+ }
269
+ for row in rows
270
+ ]
271
+
272
+ def event(self, event_id: str) -> dict[str, Any] | None:
273
+ with self.lock:
274
+ row = self.connection.execute(
275
+ "SELECT data FROM events WHERE id = ?", (event_id,)
276
+ ).fetchone()
277
+ return None if row is None else json.loads(row["data"])
278
+
279
+ def delivery_attempts(self, event_id: str) -> list[dict[str, Any]]:
280
+ with self.lock:
281
+ rows = self.connection.execute(
282
+ """
283
+ SELECT attempted_at, signature_mode, status, error, delivered
284
+ FROM delivery_attempts WHERE event_id = ? ORDER BY id
285
+ """,
286
+ (event_id,),
287
+ ).fetchall()
288
+ return [dict(row) for row in rows]
@@ -0,0 +1,50 @@
1
+ """Shared types and constants for the local Stripe simulator."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ SUCCESS_CARD = "4242424242424242"
6
+ DECLINED_CARD = "4000000000000002"
7
+ AUTHENTICATION_CARD = "4000002500003155"
8
+ RENEWAL_FAILURE_CARD = "4000000000000341"
9
+ RENEWAL_BEHAVIORS = {
10
+ "success",
11
+ "soft_decline",
12
+ "hard_decline",
13
+ "authentication_required",
14
+ }
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class SimulatorOptions:
19
+ public_url: str
20
+ webhook_url: str = ""
21
+ webhook_secret: str = "whsec_local"
22
+ api_key: str = "sk_test_local"
23
+ product_id: str = "prod_local_membership"
24
+ price_id: str = "price_local_monthly"
25
+ product_name: str = "Example membership"
26
+ unit_amount: int = 500
27
+ currency: str = "usd"
28
+ max_payment_attempts: int = 3
29
+
30
+ def __post_init__(self) -> None:
31
+ if self.max_payment_attempts < 1:
32
+ raise ValueError("max_payment_attempts must be at least 1")
33
+
34
+
35
+ class SimulatorHTTPError(Exception):
36
+ def __init__(self, status: int, error_type: str, message: str):
37
+ super().__init__(message)
38
+ self.status = status
39
+ self.error_type = error_type
40
+ self.message = message
41
+
42
+
43
+ def status_text(status: int) -> str:
44
+ return {
45
+ 200: "OK",
46
+ 400: "Bad Request",
47
+ 401: "Unauthorized",
48
+ 402: "Payment Required",
49
+ 404: "Not Found",
50
+ }.get(status, "OK")