File size: 46,546 Bytes
aec61e4 | 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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 | """Versioned async repository contract for Change.org clone expansion.
The offline profile executes a fixed operation vocabulary against SQLite. The
protected public profile sends the same operation and validated parameters to
``db.internal``; it never accepts or transports SQL. This module deliberately
contains no production provider credentials.
"""
from __future__ import annotations
import asyncio
import base64
import hashlib
import json
import os
import re
import secrets
import sqlite3
import urllib.error
import urllib.request
from contextlib import closing
from datetime import datetime, timedelta, timezone
from typing import Any, Callable, Mapping, Protocol
from . import db
PROTOCOL_VERSION = "change.repository.v1"
SITE_NAMESPACE = "change"
FOLLOW_TYPES = {"petition", "organization", "topic"}
CHANNELS = {"copy", "email", "facebook", "x", "whatsapp", "other"}
EMAIL_MODES = {"off", "immediate", "digest"}
OPERATIONS = frozenset(
{
"moderation.publish",
"target.upsert",
"follow.create",
"follow.delete",
"follow.list",
"preferences.get",
"preferences.update",
"notification.list",
"notification.unread_count",
"notification.read",
"notification.read_all",
"share.create",
"share.click",
"share.attribute",
"event.record",
"growth.dashboard",
"search.petitions",
"retention.cleanup",
}
)
class RepositoryError(RuntimeError):
"""A typed repository refusal safe to map to an HTTP response."""
def __init__(self, code: str, message: str, *, status: int = 400):
super().__init__(message)
self.code = code
self.status = status
class AsyncRepository(Protocol):
async def execute(
self,
operation: str,
parameters: Mapping[str, Any],
*,
idempotency_key: str = "",
) -> dict[str, Any]: ...
def _now_iso() -> str:
return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
def _stable_id(prefix: str, *parts: object) -> str:
framed = "\x1f".join(str(part) for part in parts)
digest = hashlib.sha256(framed.encode("utf-8")).hexdigest()[:24]
return f"{prefix}-{digest}"
def _normalize(value: object, *, maximum: int = 160) -> str:
normalized = " ".join(str(value or "").split()).strip()
if len(normalized) > maximum:
raise RepositoryError("invalid-parameter", f"value exceeds {maximum} characters")
return normalized
def _required(parameters: Mapping[str, Any], key: str, *, maximum: int = 160) -> str:
value = _normalize(parameters.get(key), maximum=maximum)
if not value:
raise RepositoryError("invalid-parameter", f"{key} is required")
return value
def _positive_limit(parameters: Mapping[str, Any], default: int = 20) -> int:
try:
limit = int(parameters.get("limit", default))
except (TypeError, ValueError) as exc:
raise RepositoryError("invalid-parameter", "limit must be an integer") from exc
if limit < 1 or limit > 100:
raise RepositoryError("invalid-parameter", "limit must be between 1 and 100")
return limit
def _cursor_encode(payload: Mapping[str, Any]) -> str:
raw = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
def _cursor_decode(value: object) -> dict[str, Any]:
if not value:
return {}
text = str(value)
if len(text) > 500:
raise RepositoryError("invalid-cursor", "cursor is too long")
try:
raw = base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
result = json.loads(raw)
except (ValueError, json.JSONDecodeError) as exc:
raise RepositoryError("invalid-cursor", "cursor is invalid") from exc
if not isinstance(result, dict):
raise RepositoryError("invalid-cursor", "cursor is invalid")
return result
class SQLiteRepository:
"""SQLite implementation of the versioned operation contract."""
def __init__(self, clock: Callable[[], str] = _now_iso):
self.clock = clock
async def execute(
self,
operation: str,
parameters: Mapping[str, Any],
*,
idempotency_key: str = "",
) -> dict[str, Any]:
if operation not in OPERATIONS:
raise RepositoryError("unsupported-operation", "operation is not allowed")
if not isinstance(parameters, Mapping):
raise RepositoryError("invalid-parameters", "parameters must be an object")
if len(json.dumps(parameters, default=str)) > 32_000:
raise RepositoryError("payload-too-large", "operation payload exceeds 32KB", status=413)
handler = getattr(self, "_" + operation.replace(".", "_"))
return await asyncio.to_thread(handler, dict(parameters), idempotency_key)
def _moderation_publish(self, p: dict[str, Any], key: str) -> dict[str, Any]:
actor_id = _required(p, "actor_id")
subject_id = _required(p, "subject_id")
text = _required(p, "text", maximum=8_000)
key = _normalize(key or p.get("idempotency_key"), maximum=120)
if not key:
raise RepositoryError("invalid-idempotency-key", "idempotency key is required")
with closing(db.connect()) as connection:
existing = connection.execute(
"SELECT decision, reasons_json FROM moderation_results "
"WHERE actor_id=? AND subject_type='petition' AND idempotency_key=?",
(actor_id, key),
).fetchone()
if existing:
return {
"decision": existing["decision"],
"reasons": json.loads(existing["reasons_json"]),
"replayed": True,
}
matches: list[dict[str, Any]] = []
for rule in connection.execute(
"SELECT id, version, kind, pattern, reason FROM moderation_rules "
"WHERE active=1 ORDER BY id, version DESC"
).fetchall():
matched = (
rule["pattern"].casefold() in text.casefold()
if rule["kind"] == "keyword"
else re.search(rule["pattern"], text, re.IGNORECASE) is not None
)
if matched:
matches.append(
{
"rule_id": rule["id"],
"rule_version": int(rule["version"]),
"reason": rule["reason"],
}
)
decision = "rejected" if matches else "approved"
first = matches[0] if matches else {}
connection.execute(
"INSERT INTO moderation_results "
"(id,subject_type,subject_id,actor_id,rule_id,rule_version,"
"decision,reasons_json,idempotency_key,created_at) "
"VALUES (?, 'petition', ?, ?, ?, ?, ?, ?, ?, ?)",
(
_stable_id("mod", actor_id, subject_id, key),
subject_id,
actor_id,
first.get("rule_id"),
first.get("rule_version"),
decision,
json.dumps(matches, sort_keys=True),
key,
self.clock(),
),
)
connection.commit()
return {"decision": decision, "reasons": matches, "replayed": False}
def _target_upsert(self, p: dict[str, Any], key: str) -> dict[str, Any]:
actor = _required(p, "actor_id")
slug = _required(p, "petition_slug")
target_type = _normalize(p.get("type") or "organization").casefold()
if target_type not in {"organization", "government", "person", "other"}:
raise RepositoryError("invalid-target-type", "unsupported target type")
name = _required(p, "name", maximum=120)
location = _normalize(p.get("location"), maximum=120)
contact_label = _normalize(p.get("contact_label"), maximum=120)
expected = int(p.get("expected_version", 0) or 0)
key = _normalize(key or p.get("idempotency_key"), maximum=120)
if not key:
raise RepositoryError("invalid-idempotency-key", "idempotency key is required")
now = self.clock()
with closing(db.connect()) as connection:
petition = connection.execute(
"SELECT owner_id FROM petitions WHERE slug=?", (slug,)
).fetchone()
if not petition:
raise RepositoryError("not-found", "petition was not found", status=404)
if petition["owner_id"] != actor:
raise RepositoryError("foreign-owner", "only the petition owner may set its target", status=403)
existing = connection.execute(
"SELECT * FROM organization_targets WHERE petition_slug=?", (slug,)
).fetchone()
if existing:
if existing["idempotency_key"] == key:
same = (
existing["type"] == target_type
and existing["name"] == name
and existing["location"] == location
and existing["contact_label"] == contact_label
)
if not same:
raise RepositoryError(
"idempotency-conflict",
"target key already belongs to different values",
status=409,
)
return {
"id": existing["id"],
"petition_slug": existing["petition_slug"],
"type": existing["type"],
"name": existing["name"],
"location": existing["location"],
"contact_label": existing["contact_label"],
"row_version": int(existing["row_version"]),
"replayed": True,
}
if expected and int(existing["row_version"]) != expected:
raise RepositoryError("stale-version", "target version is stale", status=409)
connection.execute(
"UPDATE organization_targets SET type=?,name=?,normalized_name=?,"
"location=?,contact_label=?,row_version=row_version+1,updated_at=? "
"WHERE petition_slug=?",
(
target_type,
name,
_normalize(name).casefold(),
location,
contact_label,
now,
slug,
),
)
else:
connection.execute(
"INSERT INTO organization_targets "
"(id,petition_slug,owner_id,type,name,normalized_name,location,"
"contact_label,row_version,idempotency_key,created_at,updated_at) "
"VALUES (?,?,?,?,?,?,?,?,1,?,?,?)",
(
_stable_id("target", slug), slug, actor, target_type, name,
_normalize(name).casefold(), location, contact_label, key, now, now,
),
)
connection.execute("DELETE FROM petition_search WHERE slug=?", (slug,))
row = connection.execute(
"SELECT title,body,target,status FROM petitions WHERE slug=?", (slug,)
).fetchone()
connection.execute(
"INSERT INTO petition_search "
"(slug,title,body,target,topic,location,organization,status) "
"VALUES (?,?,?,?,?,?,?,?)",
(slug, row["title"], row["body"], row["target"], p.get("topic", ""),
location, name, row["status"]),
)
result = connection.execute(
"SELECT id,petition_slug,type,name,location,contact_label,row_version "
"FROM organization_targets WHERE petition_slug=?", (slug,)
).fetchone()
connection.commit()
return dict(result)
def _validate_follow_object(self, connection: sqlite3.Connection, kind: str, object_id: str) -> None:
if kind == "petition":
found = connection.execute(
"SELECT 1 FROM petitions WHERE slug=? AND moderation_status='approved'",
(object_id,),
).fetchone()
elif kind == "organization":
found = connection.execute(
"SELECT 1 FROM organization_targets WHERE normalized_name=?",
(_normalize(object_id).casefold(),),
).fetchone()
else:
found = bool(object_id)
if not found:
raise RepositoryError("not-found", "follow target was not found", status=404)
def _follow_create(self, p: dict[str, Any], key: str) -> dict[str, Any]:
account = _required(p, "account_id")
kind = _required(p, "object_type").casefold()
object_id = _required(p, "object_id")
if kind not in FOLLOW_TYPES:
raise RepositoryError("invalid-follow-type", "unsupported follow type")
key = _normalize(key or p.get("idempotency_key"), maximum=120)
if not key:
raise RepositoryError("invalid-idempotency-key", "idempotency key is required")
with closing(db.connect()) as connection:
self._validate_follow_object(connection, kind, object_id)
existing = connection.execute(
"SELECT idempotency_key,created_at,row_version FROM follows "
"WHERE account_id=? AND object_type=? AND object_id=?",
(account, kind, object_id),
).fetchone()
if existing:
return {
"object_type": kind, "object_id": object_id,
"row_version": int(existing["row_version"]), "created": False,
}
try:
connection.execute(
"INSERT INTO follows "
"(account_id,object_type,object_id,row_version,idempotency_key,created_at) "
"VALUES (?,?,?,1,?,?)",
(account, kind, object_id, key, self.clock()),
)
connection.commit()
except sqlite3.IntegrityError as exc:
raise RepositoryError("idempotency-conflict", "follow key already has another target", status=409) from exc
return {"object_type": kind, "object_id": object_id, "row_version": 1, "created": True}
def _follow_delete(self, p: dict[str, Any], _key: str) -> dict[str, Any]:
account = _required(p, "account_id")
kind = _required(p, "object_type").casefold()
object_id = _required(p, "object_id")
if kind not in FOLLOW_TYPES:
raise RepositoryError("invalid-follow-type", "unsupported follow type")
with closing(db.connect()) as connection:
cursor = connection.execute(
"DELETE FROM follows WHERE account_id=? AND object_type=? AND object_id=?",
(account, kind, object_id),
)
connection.commit()
return {"deleted": cursor.rowcount == 1}
def _follow_list(self, p: dict[str, Any], _key: str) -> dict[str, Any]:
account = _required(p, "account_id")
limit = _positive_limit(p)
kind = _normalize(p.get("object_type")).casefold()
if kind and kind not in FOLLOW_TYPES:
raise RepositoryError("invalid-follow-type", "unsupported follow type")
cursor = _cursor_decode(p.get("cursor"))
after_type = str(cursor.get("type", ""))
after_id = str(cursor.get("id", ""))
where = ["account_id=?"]
values: list[Any] = [account]
if kind:
where.append("object_type=?")
values.append(kind)
if after_type:
where.append("(object_type > ? OR (object_type=? AND object_id>?))")
values.extend([after_type, after_type, after_id])
values.append(limit + 1)
with closing(db.connect()) as connection:
rows = connection.execute(
"SELECT object_type,object_id,row_version,created_at FROM follows WHERE "
+ " AND ".join(where)
+ " ORDER BY object_type,object_id LIMIT ?",
values,
).fetchall()
items = [dict(row) for row in rows[:limit]]
next_cursor = None
if len(rows) > limit and items:
next_cursor = _cursor_encode({"type": items[-1]["object_type"], "id": items[-1]["object_id"]})
return {"items": items, "next_cursor": next_cursor}
def _preference_row(self, connection: sqlite3.Connection, account: str) -> sqlite3.Row:
connection.execute(
"INSERT OR IGNORE INTO notification_preferences(account_id,updated_at) VALUES (?,?)",
(account, db.FROZEN_CLOCK),
)
row = connection.execute(
"SELECT * FROM notification_preferences WHERE account_id=?", (account,)
).fetchone()
assert row is not None
return row
@staticmethod
def _preference_dict(row: sqlite3.Row) -> dict[str, Any]:
return {
"in_app_enabled": bool(row["in_app_enabled"]),
"email_mode": row["email_mode"],
"petition_updates": bool(row["petition_updates"]),
"organization_updates": bool(row["organization_updates"]),
"topic_recommendations": bool(row["topic_recommendations"]),
"growth_tips": bool(row["growth_tips"]),
"double_opt_in": bool(row["double_opt_in"]),
"row_version": int(row["row_version"]),
"updated_at": row["updated_at"],
}
def _preferences_get(self, p: dict[str, Any], _key: str) -> dict[str, Any]:
account = _required(p, "account_id")
with closing(db.connect()) as connection:
row = self._preference_row(connection, account)
connection.commit()
return self._preference_dict(row)
def _preferences_update(self, p: dict[str, Any], _key: str) -> dict[str, Any]:
account = _required(p, "account_id")
mode = _normalize(p.get("email_mode") or "off").casefold()
if mode not in EMAIL_MODES:
raise RepositoryError("invalid-email-mode", "email_mode is invalid")
expected = int(p.get("row_version", 0) or 0)
fields = (
"in_app_enabled", "petition_updates", "organization_updates",
"topic_recommendations", "growth_tips", "double_opt_in",
)
with closing(db.connect()) as connection:
current = self._preference_row(connection, account)
if expected and int(current["row_version"]) != expected:
raise RepositoryError("stale-version", "preference version is stale", status=409)
values = {field: int(bool(p.get(field, current[field]))) for field in fields}
connection.execute(
"UPDATE notification_preferences SET in_app_enabled=?,email_mode=?,"
"petition_updates=?,organization_updates=?,topic_recommendations=?,"
"growth_tips=?,double_opt_in=?,row_version=row_version+1,updated_at=? "
"WHERE account_id=?",
(
values["in_app_enabled"], mode, values["petition_updates"],
values["organization_updates"], values["topic_recommendations"],
values["growth_tips"], values["double_opt_in"], self.clock(), account,
),
)
row = connection.execute(
"SELECT * FROM notification_preferences WHERE account_id=?", (account,)
).fetchone()
connection.commit()
return self._preference_dict(row)
def _notification_list(self, p: dict[str, Any], _key: str) -> dict[str, Any]:
account = _required(p, "account_id")
limit = _positive_limit(p)
unread_only = bool(p.get("unread_only", False))
after_id = _normalize(p.get("after_id"), maximum=120)
cursor = _cursor_decode(p.get("cursor"))
where = ["account_id=?"]
values: list[Any] = [account]
if unread_only:
where.append("read_at IS NULL")
ascending = False
if after_id:
with closing(db.connect()) as cursor_connection:
after = cursor_connection.execute(
"SELECT created_at FROM notifications WHERE id=? AND account_id=?",
(after_id, account),
).fetchone()
if after:
where.append("(created_at > ? OR (created_at=? AND id>?))")
values.extend([after["created_at"], after["created_at"], after_id])
ascending = True
elif cursor.get("created_at") and cursor.get("id"):
where.append("(created_at < ? OR (created_at=? AND id<?))")
values.extend([cursor["created_at"], cursor["created_at"], cursor["id"]])
values.append(limit + 1)
with closing(db.connect()) as connection:
rows = connection.execute(
"SELECT id,category,event_type,object_type,object_id,title,body,"
"created_at,read_at FROM notifications WHERE " + " AND ".join(where)
+ (
" ORDER BY created_at ASC,id ASC LIMIT ?"
if ascending
else " ORDER BY created_at DESC,id DESC LIMIT ?"
),
values,
).fetchall()
items = [dict(row) for row in rows[:limit]]
next_cursor = None
if len(rows) > limit and items:
next_cursor = _cursor_encode({"created_at": items[-1]["created_at"], "id": items[-1]["id"]})
return {"items": items, "next_cursor": next_cursor}
def _notification_unread_count(self, p: dict[str, Any], _key: str) -> dict[str, Any]:
account = _required(p, "account_id")
with closing(db.connect()) as connection:
count = connection.execute(
"SELECT COUNT(*) AS n FROM notifications WHERE account_id=? AND read_at IS NULL",
(account,),
).fetchone()["n"]
return {"unread_count": int(count)}
def _notification_read(self, p: dict[str, Any], _key: str) -> dict[str, Any]:
account = _required(p, "account_id")
notification_id = _required(p, "notification_id")
with closing(db.connect()) as connection:
exists = connection.execute(
"SELECT account_id,read_at FROM notifications WHERE id=?", (notification_id,)
).fetchone()
if not exists:
raise RepositoryError("not-found", "notification was not found", status=404)
if exists["account_id"] != account:
raise RepositoryError("foreign-owner", "notification belongs to another account", status=403)
connection.execute(
"UPDATE notifications SET read_at=COALESCE(read_at,?) WHERE id=?",
(self.clock(), notification_id),
)
connection.commit()
return {"read": True, "already_read": exists["read_at"] is not None}
def _notification_read_all(self, p: dict[str, Any], _key: str) -> dict[str, Any]:
account = _required(p, "account_id")
with closing(db.connect()) as connection:
cursor = connection.execute(
"UPDATE notifications SET read_at=? WHERE account_id=? AND read_at IS NULL",
(self.clock(), account),
)
connection.commit()
return {"read_count": cursor.rowcount}
def _share_create(self, p: dict[str, Any], key: str) -> dict[str, Any]:
account = _required(p, "account_id")
slug = _required(p, "petition_slug")
channel = _normalize(p.get("channel") or "copy").casefold()
if channel not in CHANNELS:
raise RepositoryError("invalid-channel", "share channel is invalid")
key = _normalize(key or p.get("idempotency_key"), maximum=120)
if not key:
raise RepositoryError("invalid-idempotency-key", "idempotency key is required")
now = datetime.fromisoformat(self.clock())
with closing(db.connect()) as connection:
petition = connection.execute(
"SELECT 1 FROM petitions WHERE slug=? AND status='open' AND moderation_status='approved'",
(slug,),
).fetchone()
if not petition:
raise RepositoryError("not-found", "shareable petition was not found", status=404)
existing = connection.execute(
"SELECT token,channel,created_at,expires_at FROM share_links "
"WHERE owner_id=? AND petition_slug=? AND idempotency_key=?",
(account, slug, key),
).fetchone()
if existing:
if existing["channel"] != channel:
raise RepositoryError("idempotency-conflict", "share key already has another channel", status=409)
return {**dict(existing), "created": False, "path": f"/s/{existing['token']}"}
token = secrets.token_urlsafe(24)
expires = (now + timedelta(days=30)).isoformat()
connection.execute(
"INSERT INTO share_links(token,petition_slug,owner_id,channel,"
"idempotency_key,created_at,expires_at) VALUES (?,?,?,?,?,?,?)",
(token, slug, account, channel, key, now.isoformat(), expires),
)
connection.commit()
return {"token": token, "channel": channel, "created_at": now.isoformat(), "expires_at": expires, "created": True, "path": f"/s/{token}"}
def _share_click(self, p: dict[str, Any], _key: str) -> dict[str, Any]:
token = _required(p, "token", maximum=100)
visitor_hash = _required(p, "visitor_hash", maximum=128)
now = datetime.fromisoformat(self.clock())
with closing(db.connect()) as connection:
link = connection.execute(
"SELECT petition_slug,expires_at FROM share_links WHERE token=?", (token,)
).fetchone()
if not link:
raise RepositoryError("not-found", "share link was not found", status=404)
if datetime.fromisoformat(link["expires_at"]) < now:
raise RepositoryError("expired", "share link has expired", status=410)
cursor = connection.execute(
"INSERT OR IGNORE INTO share_clicks(id,token,visitor_hash,clicked_at) VALUES (?,?,?,?)",
(_stable_id("click", token, visitor_hash), token, visitor_hash, now.isoformat()),
)
connection.commit()
return {"petition_slug": link["petition_slug"], "recorded": cursor.rowcount == 1}
def _share_attribute(self, p: dict[str, Any], _key: str) -> dict[str, Any]:
account = _required(p, "account_id")
token = _required(p, "token", maximum=100)
event_type = _required(p, "event_type").casefold()
if event_type not in {"login", "signature"}:
raise RepositoryError("invalid-event", "attribution event is invalid")
now = datetime.fromisoformat(self.clock())
with closing(db.connect()) as connection:
link = connection.execute(
"SELECT expires_at FROM share_links WHERE token=?", (token,)
).fetchone()
if not link or datetime.fromisoformat(link["expires_at"]) < now:
return {"attributed": False}
cursor = connection.execute(
"INSERT OR IGNORE INTO share_attributions(account_id,token,event_type,converted_at) "
"VALUES (?,?,?,?)", (account, token, event_type, now.isoformat()),
)
connection.commit()
return {"attributed": cursor.rowcount == 1}
def _create_notification(
self,
connection: sqlite3.Connection,
*,
account_id: str,
category: str,
event_type: str,
object_type: str,
object_id: str,
title: str,
body: str,
dedupe_key: str,
now: str,
) -> bool:
preference = self._preference_row(connection, account_id)
category_column = {
"petition_update": "petition_updates",
"organization_update": "organization_updates",
"topic_recommendation": "topic_recommendations",
"growth_tip": "growth_tips",
}.get(category)
if not preference["in_app_enabled"] or (category_column and not preference[category_column]):
return False
notification_id = _stable_id("notification", account_id, dedupe_key)
cursor = connection.execute(
"INSERT OR IGNORE INTO notifications "
"(id,account_id,category,event_type,object_type,object_id,title,body,"
"dedupe_key,created_at) VALUES (?,?,?,?,?,?,?,?,?,?)",
(notification_id, account_id, category, event_type, object_type, object_id,
title, body, dedupe_key, now),
)
if cursor.rowcount != 1:
return False
if (
preference["email_mode"] != "off"
and preference["double_opt_in"]
):
account = connection.execute(
"SELECT email,email_verified FROM accounts WHERE id=?", (account_id,)
).fetchone()
suppressed = account and connection.execute(
"SELECT 1 FROM email_suppressions WHERE normalized_email=?",
(account["email"].casefold(),),
).fetchone()
if account and account["email_verified"] and not suppressed:
connection.execute(
"INSERT OR IGNORE INTO mail_outbox "
"(id,account_id,notification_id,category,recipient_email,template_id,"
"status,idempotency_key,created_at) VALUES (?,?,?,?,?,?,"
"'LOCAL_ONLY',?,?)",
(_stable_id("mail", notification_id), account_id, notification_id,
category, account["email"], f"change-{category}-v1",
f"notification:{notification_id}", now),
)
return True
def _event_record(self, p: dict[str, Any], key: str) -> dict[str, Any]:
event_type = _required(p, "event_type")
object_type = _required(p, "object_type")
object_id = _required(p, "object_id")
account = _normalize(p.get("account_id")) or None
metadata = p.get("metadata") or {}
if not isinstance(metadata, Mapping):
raise RepositoryError("invalid-metadata", "metadata must be an object")
key = _normalize(key or p.get("idempotency_key"), maximum=120)
if not key:
raise RepositoryError("invalid-idempotency-key", "idempotency key is required")
now = self.clock()
event_id = _stable_id("event", event_type, object_type, object_id, key)
notifications = 0
recommendations = 0
with closing(db.connect()) as connection:
cursor = connection.execute(
"INSERT OR IGNORE INTO activity_events "
"(id,account_id,event_type,object_type,object_id,metadata_json,"
"attribution_token,idempotency_key,created_at) VALUES (?,?,?,?,?,?,?,?,?)",
(event_id, account, event_type, object_type, object_id,
json.dumps(metadata, sort_keys=True, separators=(",", ":")),
_normalize(p.get("attribution_token"), maximum=100) or None, key, now),
)
if cursor.rowcount != 1:
return {"event_id": event_id, "created": False, "notifications": 0, "recommendations": 0}
petition = connection.execute(
"SELECT slug,title,owner_id,target,baseline_signatures FROM petitions WHERE slug=?",
(object_id,),
).fetchone() if object_type == "petition" else None
if petition and event_type in {"petition_published", "signature_created", "share_created", "share_clicked", "supporter_update"}:
if event_type == "petition_published":
rule_id, milestone = "launch-share", 0
rec_title = "Share your petition with the first supporters"
rationale = "New campaigns grow when their first-party share link reaches people who care."
else:
signatures = int(metadata.get("signatures", petition["baseline_signatures"]))
milestone = db.next_goal(signatures)
rule_id = "next-signature-goal"
rec_title = f"Work toward {milestone:,} signatures"
rationale = f"Your current signature count makes {milestone:,} the next visible milestone."
rec_id = _stable_id("growth", object_id, rule_id, milestone)
rec_cursor = connection.execute(
"INSERT OR IGNORE INTO growth_recommendations "
"(id,petition_slug,owner_id,rule_id,milestone,title,rationale,created_at) "
"VALUES (?,?,?,?,?,?,?,?)",
(rec_id, object_id, petition["owner_id"], rule_id, milestone,
rec_title, rationale, now),
)
recommendations += int(rec_cursor.rowcount == 1)
if rec_cursor.rowcount == 1:
notifications += int(self._create_notification(
connection, account_id=petition["owner_id"], category="growth_tip",
event_type="growth_recommendation", object_type="petition",
object_id=object_id, title=rec_title, body=rationale,
dedupe_key=f"growth:{object_id}:{rule_id}:{milestone}", now=now,
))
if petition and event_type == "supporter_update":
followers = connection.execute(
"SELECT account_id FROM follows WHERE object_type='petition' AND object_id=?",
(object_id,),
).fetchall()
for follower in followers:
if follower["account_id"] == petition["owner_id"]:
continue
notifications += int(self._create_notification(
connection, account_id=follower["account_id"], category="petition_update",
event_type=event_type, object_type="petition", object_id=object_id,
title=f"Update from {petition['title']}",
body=_normalize(metadata.get("body"), maximum=500),
dedupe_key=f"update:{object_id}:{key}", now=now,
))
if petition and event_type == "petition_published":
organization = _normalize(metadata.get("organization") or petition["target"]).casefold()
topic = _normalize(metadata.get("topic")).casefold()
follower_rows = connection.execute(
"SELECT account_id,object_type FROM follows WHERE "
"(object_type='organization' AND lower(object_id)=?) OR "
"(object_type='topic' AND lower(object_id)=?)",
(organization, topic),
).fetchall()
for follower in follower_rows:
category = "organization_update" if follower["object_type"] == "organization" else "topic_recommendation"
notifications += int(self._create_notification(
connection, account_id=follower["account_id"], category=category,
event_type=event_type, object_type="petition", object_id=object_id,
title=f"New petition: {petition['title']}",
body=f"A new petition matches a {follower['object_type']} you follow.",
dedupe_key=f"published:{follower['object_type']}:{object_id}", now=now,
))
metric = {
"petition_published": "publishes", "signature_created": "signatures",
"share_created": "shares", "share_clicked": "share_clicks",
"supporter_update": "updates", "follow_created": "follows",
}.get(event_type)
if metric and object_type == "petition":
day = now[:10]
connection.execute(
"INSERT INTO daily_analytics_aggregates(day,petition_slug,metric,value,updated_at) "
"VALUES (?,?,?,1,?) ON CONFLICT(day,petition_slug,metric) DO UPDATE SET "
"value=value+1,updated_at=excluded.updated_at",
(day, object_id, metric, now),
)
connection.commit()
return {"event_id": event_id, "created": True, "notifications": notifications, "recommendations": recommendations}
def _growth_dashboard(self, p: dict[str, Any], _key: str) -> dict[str, Any]:
account = _required(p, "account_id")
slug = _normalize(p.get("petition_slug"))
with closing(db.connect()) as connection:
where = "owner_id=?"
values: list[Any] = [account]
if slug:
petition = connection.execute(
"SELECT owner_id FROM petitions WHERE slug=?", (slug,)
).fetchone()
if not petition:
raise RepositoryError("not-found", "petition was not found", status=404)
if petition["owner_id"] != account:
raise RepositoryError("foreign-owner", "growth dashboard belongs to another owner", status=403)
where += " AND petition_slug=?"
values.append(slug)
rows = connection.execute(
"SELECT id,petition_slug,rule_id,milestone,title,rationale,status,created_at "
"FROM growth_recommendations WHERE " + where + " ORDER BY created_at DESC,id",
values,
).fetchall()
analytics = connection.execute(
"SELECT petition_slug,metric,SUM(value) AS value FROM daily_analytics_aggregates "
"WHERE petition_slug IN (SELECT slug FROM petitions WHERE owner_id=?) "
"GROUP BY petition_slug,metric ORDER BY petition_slug,metric", (account,),
).fetchall()
return {"recommendations": [dict(row) for row in rows], "analytics": [dict(row) for row in analytics]}
def _search_petitions(self, p: dict[str, Any], _key: str) -> dict[str, Any]:
query = _normalize(p.get("query"), maximum=200)
limit = _positive_limit(p)
cursor = _cursor_decode(p.get("cursor"))
tokens = re.findall(r"[\w-]+", query, flags=re.UNICODE)
match_query = " AND ".join(f'"{token.replace(chr(34), "")}"' for token in tokens)
filters: list[str] = ["p.moderation_status='approved'", "p.status != 'closed'"]
values: list[Any] = []
for key, column in (("topic", "s.topic"), ("location", "s.location"), ("organization", "s.organization"), ("status", "p.status")):
value = _normalize(p.get(key), maximum=120)
if value:
filters.append(f"lower({column}) LIKE ?")
values.append(f"%{value.casefold()}%")
with closing(db.connect()) as connection:
if match_query:
cursor_filter = ""
cursor_values: list[Any] = []
if cursor:
try:
after_relevance = float(cursor["relevance"])
after_created = str(cursor["created_at"])
after_slug = str(cursor["slug"])
except (KeyError, TypeError, ValueError) as exc:
raise RepositoryError("invalid-cursor", "search cursor is invalid") from exc
cursor_filter = (
" WHERE (relevance > ? OR (relevance=? AND "
"(created_at < ? OR (created_at=? AND slug>?))))"
)
cursor_values.extend(
[after_relevance, after_relevance, after_created, after_created, after_slug]
)
sql = (
"SELECT * FROM (SELECT p.slug,p.title,p.target,p.body,p.status,p.created_at,"
"s.location,s.organization,bm25(petition_search) AS relevance "
"FROM petition_search s JOIN petitions p ON p.slug=s.slug "
"WHERE petition_search MATCH ? AND " + " AND ".join(filters) + ") ranked"
+ cursor_filter
+ " ORDER BY relevance ASC,created_at DESC,slug ASC LIMIT ?"
)
rows = connection.execute(
sql, [match_query, *values, *cursor_values, limit + 1]
).fetchall()
else:
if cursor:
try:
after_created = str(cursor["created_at"])
after_slug = str(cursor["slug"])
except (KeyError, TypeError) as exc:
raise RepositoryError("invalid-cursor", "search cursor is invalid") from exc
filters.append("(p.created_at < ? OR (p.created_at=? AND p.slug>?))")
values.extend([after_created, after_created, after_slug])
sql = (
"SELECT p.slug,p.title,p.target,p.body,p.status,p.created_at,"
"s.location,s.organization,0.0 AS relevance FROM petitions p "
"JOIN petition_search s ON s.slug=p.slug WHERE " + " AND ".join(filters)
+ " ORDER BY p.created_at DESC,p.slug ASC LIMIT ?"
)
rows = connection.execute(sql, [*values, limit + 1]).fetchall()
items = [dict(row) for row in rows[:limit]]
next_cursor = None
if len(rows) > limit and items:
next_cursor = _cursor_encode(
{
"created_at": items[-1]["created_at"],
"relevance": items[-1]["relevance"],
"slug": items[-1]["slug"],
}
)
return {"items": items, "next_cursor": next_cursor}
def _retention_cleanup(self, p: dict[str, Any], _key: str) -> dict[str, Any]:
now = datetime.fromisoformat(_normalize(p.get("now")) or self.clock())
raw_before = (now - timedelta(days=30)).isoformat()
aggregate_before = (now - timedelta(days=90)).date().isoformat()
with closing(db.connect()) as connection:
raw = 0
for table, column in (
("share_attributions", "converted_at"),
("share_clicks", "clicked_at"),
("activity_events", "created_at"),
):
cursor = connection.execute(f"DELETE FROM {table} WHERE {column} < ?", (raw_before,))
raw += cursor.rowcount
aggregate = connection.execute(
"DELETE FROM daily_analytics_aggregates WHERE day < ?", (aggregate_before,)
).rowcount
connection.commit()
return {"raw_events_deleted": raw, "aggregates_deleted": aggregate}
class WorkerOperationRepository:
"""Public-profile repository that sends only allowlisted operations."""
def __init__(self, endpoint: str = "http:" + "/" + "/db.internal/v1/operations"):
self.endpoint = endpoint
async def execute(
self,
operation: str,
parameters: Mapping[str, Any],
*,
idempotency_key: str = "",
) -> dict[str, Any]:
if operation not in OPERATIONS:
raise RepositoryError("unsupported-operation", "operation is not allowed")
body = json.dumps(
{
"protocol": PROTOCOL_VERSION,
"site_namespace": SITE_NAMESPACE,
"operation": operation,
"parameters": dict(parameters),
"idempotency_key": idempotency_key,
},
separators=(",", ":"),
).encode()
if len(body) > 32_000:
raise RepositoryError("payload-too-large", "operation payload exceeds 32KB", status=413)
def send() -> dict[str, Any]:
request = urllib.request.Request(
self.endpoint,
data=body,
method="POST",
headers={"Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(request, timeout=8) as response:
payload = json.load(response)
except urllib.error.HTTPError as exc:
try:
payload = json.load(exc)
except (ValueError, TypeError):
payload = {"error": "repository-unavailable"}
raise RepositoryError(
str(payload.get("error", "repository-refused")),
str(payload.get("message", "repository operation was refused")),
status=exc.code,
) from exc
if not isinstance(payload, dict) or payload.get("ok") is not True:
raise RepositoryError("invalid-response", "repository returned an invalid response", status=502)
result = payload.get("result")
if not isinstance(result, dict):
raise RepositoryError("invalid-response", "repository result is invalid", status=502)
return result
return await asyncio.to_thread(send)
def build_repository() -> AsyncRepository:
profile = os.environ.get("WEBSITEBENCH_CHANGE_REPOSITORY_PROFILE", "sqlite").strip().casefold()
if profile == "worker-d1":
return WorkerOperationRepository()
if profile != "sqlite":
raise RuntimeError(f"unsupported Change repository profile: {profile}")
return SQLiteRepository()
|