socialcli 0.3.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.
Potentially problematic release.
This version of socialcli might be problematic. Click here for more details.
- socialcli-0.3.0.dist-info/METADATA +168 -0
- socialcli-0.3.0.dist-info/RECORD +224 -0
- socialcli-0.3.0.dist-info/WHEEL +4 -0
- socialcli-0.3.0.dist-info/entry_points.txt +3 -0
- socialcli-0.3.0.dist-info/licenses/LICENSE +21 -0
- socialctl/__init__.py +0 -0
- socialctl/__main__.py +6 -0
- socialctl/adapters/__init__.py +6 -0
- socialctl/adapters/base.py +68 -0
- socialctl/adapters/errores.py +56 -0
- socialctl/adapters/facebook.py +180 -0
- socialctl/adapters/instagram.py +442 -0
- socialctl/adapters/tiktok.py +535 -0
- socialctl/adapters/youtube.py +331 -0
- socialctl/agent_errors.py +176 -0
- socialctl/agent_guide.py +23 -0
- socialctl/approval_cli.py +27 -0
- socialctl/auth.py +139 -0
- socialctl/authflow.py +344 -0
- socialctl/brands.py +194 -0
- socialctl/capabilities.py +57 -0
- socialctl/capabilities.yml +5945 -0
- socialctl/cli.py +1766 -0
- socialctl/connection_service/__init__.py +0 -0
- socialctl/connection_service/__main__.py +33 -0
- socialctl/connection_service/app.py +496 -0
- socialctl/connection_service/assets/PLATFORM-LOGOS-LICENSE.txt +50 -0
- socialctl/connection_service/assets/connection.css +75 -0
- socialctl/connection_service/assets/facebook.webp +0 -0
- socialctl/connection_service/assets/instagram.svg +194 -0
- socialctl/connection_service/assets/socialcli-logo.png +0 -0
- socialctl/connection_service/assets/tiktok.png +0 -0
- socialctl/connection_service/assets/youtube.svg +1 -0
- socialctl/connection_service/landing.py +146 -0
- socialctl/connection_service/legacy.py +48 -0
- socialctl/connection_service/peer.py +13 -0
- socialctl/connection_service/providers.py +324 -0
- socialctl/connection_service/settings.py +76 -0
- socialctl/connection_service/store.py +124 -0
- socialctl/connections/__init__.py +0 -0
- socialctl/connections/account_cli.py +438 -0
- socialctl/connections/cli.py +379 -0
- socialctl/connections/client.py +126 -0
- socialctl/connections/credential_cli.py +224 -0
- socialctl/connections/credential_store.py +49 -0
- socialctl/connections/file_store.py +193 -0
- socialctl/connections/keychain.py +78 -0
- socialctl/connections/meta_user.py +81 -0
- socialctl/connections/rotation_cli.py +116 -0
- socialctl/connections/saas_client.py +91 -0
- socialctl/connections/temporary_media.py +62 -0
- socialctl/delivery_options.py +70 -0
- socialctl/engagement.py +200 -0
- socialctl/engagement_cli.py +50 -0
- socialctl/executor.py +135 -0
- socialctl/formatter.py +291 -0
- socialctl/hosted_media.py +152 -0
- socialctl/identity.py +200 -0
- socialctl/inbox.py +298 -0
- socialctl/inbox_cli.py +46 -0
- socialctl/inventory.py +155 -0
- socialctl/inventory_cli.py +171 -0
- socialctl/inventory_sources.py +101 -0
- socialctl/management/__init__.py +1 -0
- socialctl/management/batch_cli.py +115 -0
- socialctl/management/batches.py +325 -0
- socialctl/management/changes.py +485 -0
- socialctl/management/cli.py +227 -0
- socialctl/management/comments_cli.py +352 -0
- socialctl/management/community_batch_cli.py +63 -0
- socialctl/management/community_batches.py +294 -0
- socialctl/management/community_changes.py +370 -0
- socialctl/management/community_cli.py +142 -0
- socialctl/management/community_schema.py +119 -0
- socialctl/management/facebook_groups.py +1118 -0
- socialctl/management/groups_cli.py +274 -0
- socialctl/management/inbox_readers.py +87 -0
- socialctl/management/meta_changes.py +197 -0
- socialctl/management/meta_cli.py +342 -0
- socialctl/management/meta_client.py +631 -0
- socialctl/management/meta_comment_inbox.py +565 -0
- socialctl/management/meta_comments.py +587 -0
- socialctl/management/meta_errors.py +59 -0
- socialctl/management/meta_pagination.py +52 -0
- socialctl/management/meta_schema.py +128 -0
- socialctl/management/meta_webhooks.py +147 -0
- socialctl/management/metadata_parts.py +144 -0
- socialctl/management/owned_assets.py +85 -0
- socialctl/management/owned_changes.py +470 -0
- socialctl/management/owned_cli.py +128 -0
- socialctl/management/owned_reorder.py +62 -0
- socialctl/management/owned_schema.py +368 -0
- socialctl/management/reply_context.py +24 -0
- socialctl/management/reply_evidence.py +80 -0
- socialctl/management/resource_changes.py +407 -0
- socialctl/management/resource_cli.py +136 -0
- socialctl/management/snippet_readback.py +26 -0
- socialctl/management/stories.py +713 -0
- socialctl/management/stories_cli.py +172 -0
- socialctl/management/youtube.py +323 -0
- socialctl/management/youtube_community.py +326 -0
- socialctl/management/youtube_metadata.py +122 -0
- socialctl/management/youtube_owned.py +259 -0
- socialctl/management/youtube_resources.py +305 -0
- socialctl/media.py +269 -0
- socialctl/media_cli.py +183 -0
- socialctl/media_ingress.py +211 -0
- socialctl/media_preflight.py +114 -0
- socialctl/media_registry.py +301 -0
- socialctl/media_requirements.py +52 -0
- socialctl/metricas/__init__.py +6 -0
- socialctl/metricas/almacen.py +133 -0
- socialctl/metricas/analytics_changes.py +295 -0
- socialctl/metricas/analytics_cli.py +191 -0
- socialctl/metricas/analytics_client.py +304 -0
- socialctl/metricas/analytics_ingest.py +260 -0
- socialctl/metricas/analytics_schema.py +174 -0
- socialctl/metricas/base.py +147 -0
- socialctl/metricas/facebook.py +418 -0
- socialctl/metricas/insights.py +227 -0
- socialctl/metricas/instagram.py +133 -0
- socialctl/metricas/modelos.py +87 -0
- socialctl/metricas/piezas.py +134 -0
- socialctl/metricas/reach.py +94 -0
- socialctl/metricas/reporting_client.py +112 -0
- socialctl/metricas/resumen.py +251 -0
- socialctl/metricas/slugs.py +89 -0
- socialctl/metricas/tiktok.py +185 -0
- socialctl/metricas/youtube.py +403 -0
- socialctl/migration_cli.py +60 -0
- socialctl/migration_files.py +68 -0
- socialctl/models.py +150 -0
- socialctl/native_schedule/__init__.py +13 -0
- socialctl/native_schedule/api_delivery.py +15 -0
- socialctl/native_schedule/api_reconcile.py +40 -0
- socialctl/native_schedule/approval.py +160 -0
- socialctl/native_schedule/cadence.py +73 -0
- socialctl/native_schedule/cli.py +510 -0
- socialctl/native_schedule/dispatcher.py +120 -0
- socialctl/native_schedule/facebook.py +112 -0
- socialctl/native_schedule/facebook_reels.py +140 -0
- socialctl/native_schedule/first_comment.py +181 -0
- socialctl/native_schedule/handoff.py +193 -0
- socialctl/native_schedule/instagram_delivery.py +224 -0
- socialctl/native_schedule/instagram_runtime.py +66 -0
- socialctl/native_schedule/inventory.py +70 -0
- socialctl/native_schedule/migration.py +310 -0
- socialctl/native_schedule/models.py +103 -0
- socialctl/native_schedule/reconcile.py +83 -0
- socialctl/native_schedule/remote_data.py +177 -0
- socialctl/native_schedule/report.py +151 -0
- socialctl/native_schedule/store.py +560 -0
- socialctl/native_schedule/verification.py +32 -0
- socialctl/native_schedule/youtube.py +339 -0
- socialctl/operation_output.py +87 -0
- socialctl/plantillas/accounts.yml +33 -0
- socialctl/plantillas/brand.md +95 -0
- socialctl/plantillas/estrategia.md +64 -0
- socialctl/postfile.py +240 -0
- socialctl/preflight.py +73 -0
- socialctl/publication_policy.py +34 -0
- socialctl/publication_status.py +75 -0
- socialctl/publication_steps.py +398 -0
- socialctl/publish_output.py +96 -0
- socialctl/publisher.py +445 -0
- socialctl/queue_migration.py +302 -0
- socialctl/read_budget.py +224 -0
- socialctl/read_reports.py +91 -0
- socialctl/rutas.py +103 -0
- socialctl/saas/__init__.py +1 -0
- socialctl/saas/access.py +75 -0
- socialctl/saas/auth.py +213 -0
- socialctl/saas/backup.py +124 -0
- socialctl/saas/billing.py +327 -0
- socialctl/saas/billing_enrollment.py +1237 -0
- socialctl/saas/billing_enrollment_schema.py +519 -0
- socialctl/saas/billing_inventory.py +775 -0
- socialctl/saas/billing_reconcile.py +127 -0
- socialctl/saas/billing_routes.py +27 -0
- socialctl/saas/budget.py +66 -0
- socialctl/saas/connections.py +374 -0
- socialctl/saas/consent.py +52 -0
- socialctl/saas/lifecycle.py +341 -0
- socialctl/saas/mail.py +89 -0
- socialctl/saas/maintenance.py +68 -0
- socialctl/saas/meta_user.py +298 -0
- socialctl/saas/meta_webhooks.py +358 -0
- socialctl/saas/migration.py +107 -0
- socialctl/saas/models.py +8 -0
- socialctl/saas/operations.py +102 -0
- socialctl/saas/pages.py +126 -0
- socialctl/saas/pairing.py +158 -0
- socialctl/saas/permissions.py +57 -0
- socialctl/saas/reminders.py +128 -0
- socialctl/saas/renewal.py +74 -0
- socialctl/saas/restore_guard.py +229 -0
- socialctl/saas/revocation.py +97 -0
- socialctl/saas/rotation.py +114 -0
- socialctl/saas/routes.py +221 -0
- socialctl/saas/settings.py +34 -0
- socialctl/saas/store.py +106 -0
- socialctl/saas/temporary_media.py +245 -0
- socialctl/saas/webhooks.py +76 -0
- socialctl/schedule_remote.py +262 -0
- socialctl/schedule_sqlite.py +44 -0
- socialctl/scheduler.py +581 -0
- socialctl/scheduler_launchd.py +319 -0
- socialctl/scheduler_systemd.py +167 -0
- socialctl/source_links.py +119 -0
- socialctl/ui/__init__.py +1 -0
- socialctl/ui/assets/agent-manual.md +850 -0
- socialctl/ui/assets/agents.md +27 -0
- socialctl/ui/assets/components.css +20 -0
- socialctl/ui/assets/connection-layout.css +53 -0
- socialctl/ui/assets/otp.template.html +10 -0
- socialctl/ui/assets/tokens.css +1 -0
- socialctl/ui/assets/trial.template.html +11 -0
- socialctl/ui/assets/web-layout.css +38 -0
- socialctl/ui/email/otp.html +10 -0
- socialctl/ui/email/trial.html +11 -0
- socialctl/upload_consent.py +13 -0
- socialctl/workspace.py +8 -0
- socialctl/youtube_data.py +471 -0
- socialctl/youtube_data_service.py +225 -0
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
"""Verified relocation of existing approvals; never publishes or approves copy."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import hmac
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import uuid
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
|
|
14
|
+
from socialctl.brands import Brand, cargar_brand
|
|
15
|
+
from socialctl.hosted_media import MIMES, attest_public_media, file_digest, public_url
|
|
16
|
+
from socialctl.media import ruta_relativa_efectiva
|
|
17
|
+
from socialctl.migration_files import durable_write, rewrite_media, write_json
|
|
18
|
+
from socialctl.models import Platform
|
|
19
|
+
from socialctl.postfile import cargar_post, _ruta
|
|
20
|
+
from socialctl.publisher import render_preview, validar_todo
|
|
21
|
+
from socialctl.rutas import validar_ruta_relativa
|
|
22
|
+
from socialctl.scheduler import ScheduleEntry, ScheduleError, ScheduleStore, _canonical_json, approval_hash, legacy_approval_hash, now_utc
|
|
23
|
+
|
|
24
|
+
LIMITATION = "The legacy fingerprint did not prove bytes or historical account identity, link or privacy. This operation preserves the currently verified values; it does not create a new social approval."
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _assert_no_native_transfer(store: ScheduleStore) -> None:
|
|
28
|
+
if (store.root / "legacy-tombstones.json").exists() or (store.root / "native-migrations").exists():
|
|
29
|
+
raise ScheduleError("native transfer exists; do not restore legacy data, preserve the ledger and reconcile")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _digest(value: dict) -> str:
|
|
33
|
+
return hashlib.sha256(_canonical_json({k: v for k, v in value.items() if k != "digest"})).hexdigest()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _directory(brand: Brand, proposal_id: str) -> Path:
|
|
37
|
+
try:
|
|
38
|
+
if str(uuid.UUID(proposal_id)) != proposal_id:
|
|
39
|
+
raise ValueError()
|
|
40
|
+
except ValueError:
|
|
41
|
+
raise ScheduleError("proposal ID must be a UUID") from None
|
|
42
|
+
return _safe(brand, f".socialctl/migrations/{proposal_id}")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _safe(brand: Brand, relative: str) -> Path:
|
|
46
|
+
return validar_ruta_relativa(brand.raiz, relative, ScheduleError, "migration path")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def load_proposal(brand: Brand, proposal_id: str) -> dict:
|
|
50
|
+
data = json.loads((_directory(brand, proposal_id) / "proposal.json").read_bytes())
|
|
51
|
+
if data["brand"] != brand.nombre or data["brand_root"] != str(brand.raiz.resolve()) or data["id"] != proposal_id:
|
|
52
|
+
raise ScheduleError("proposal belongs to another brand or root")
|
|
53
|
+
if not hmac.compare_digest(data["digest"], _digest(data)):
|
|
54
|
+
raise ScheduleError("proposal digest does not match")
|
|
55
|
+
if any(item.get("approval_migration") != proposal_id for item in data["approvals"]):
|
|
56
|
+
raise ScheduleError("proposal lacks provenance linkage; prepare the migration again")
|
|
57
|
+
return data
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _originals(brand: Brand, store: ScheduleStore, entries: list[ScheduleEntry]) -> dict:
|
|
61
|
+
paths = [brand.raiz / "accounts.yml", store.database_path if store.database_path.exists() else store.path]
|
|
62
|
+
paths += [_ruta(brand, slug) for slug in sorted({e.slug for e in entries if e.status == "approved"})]
|
|
63
|
+
return {str(path.relative_to(brand.raiz)): file_digest(path) for path in paths}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _verify(brand: Brand, proposal: dict) -> None:
|
|
67
|
+
for relative, expected in proposal["originals"].items():
|
|
68
|
+
if file_digest(_safe(brand, relative)) != expected:
|
|
69
|
+
raise ScheduleError(f"original entry changed: {relative}")
|
|
70
|
+
fresh = cargar_brand(brand.raiz.parent, brand.nombre)
|
|
71
|
+
if fresh.cuentas != proposal["accounts"]:
|
|
72
|
+
raise ScheduleError("account identity changed")
|
|
73
|
+
store = ScheduleStore(brand.raiz)
|
|
74
|
+
if [e.model_dump(mode="json") for e in store.load()] != proposal["entries"]:
|
|
75
|
+
raise ScheduleError("queue changed")
|
|
76
|
+
for item in proposal["media"]:
|
|
77
|
+
if file_digest(_safe(brand, item["source"])) != item["sha256"]:
|
|
78
|
+
raise ScheduleError("supplied bytes changed")
|
|
79
|
+
for item in proposal["approvals"]:
|
|
80
|
+
post = cargar_post(fresh, item["slug"])
|
|
81
|
+
if legacy_approval_hash(post, Platform(item["platform"])) != item["old_hash"]:
|
|
82
|
+
raise ScheduleError("legacy approval evidence changed")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def prepare(brand: Brand, *, backend: str = "json", dry_run: bool = False) -> dict:
|
|
86
|
+
if backend not in ("json", "sqlite"):
|
|
87
|
+
raise ScheduleError("invalid backend")
|
|
88
|
+
store = ScheduleStore(brand.raiz)
|
|
89
|
+
with store.executor_lock(), store._mutation_lock():
|
|
90
|
+
_assert_no_native_transfer(store)
|
|
91
|
+
brand = cargar_brand(brand.raiz.parent, brand.nombre)
|
|
92
|
+
entries = store.load()
|
|
93
|
+
if store.database_path.exists():
|
|
94
|
+
backend = "sqlite"
|
|
95
|
+
active_ids = set()
|
|
96
|
+
approved = []
|
|
97
|
+
for entry in entries:
|
|
98
|
+
if entry.brand != brand.nombre:
|
|
99
|
+
raise ScheduleError("queue contains another brand")
|
|
100
|
+
if entry.status in {"published", "cancelled", "error"}:
|
|
101
|
+
continue
|
|
102
|
+
if entry.status != "approved" or entry.attempts or entry.platform_id or entry.id in active_ids:
|
|
103
|
+
raise ScheduleError("ambiguous active state/identity or entry already attempted")
|
|
104
|
+
active_ids.add(entry.id)
|
|
105
|
+
if not entry.content_hash or not re.fullmatch(r"[0-9a-f]{64}", entry.content_hash):
|
|
106
|
+
raise ScheduleError("existing legacy approval required")
|
|
107
|
+
approved.append(entry)
|
|
108
|
+
if not approved:
|
|
109
|
+
raise ScheduleError("there are no migratable legacy approvals")
|
|
110
|
+
proposal_id = str(uuid.uuid4())
|
|
111
|
+
media, posts, approvals, previews = {}, {}, [], []
|
|
112
|
+
for slug in dict.fromkeys(e.slug for e in approved):
|
|
113
|
+
post = cargar_post(brand, slug)
|
|
114
|
+
selected = [e for e in approved if e.slug == slug]
|
|
115
|
+
replacements = {}
|
|
116
|
+
previews.append(render_preview(post, validar_todo(post, brand), destinos=[Platform(e.platform) for e in selected]))
|
|
117
|
+
for entry in selected:
|
|
118
|
+
platform = Platform(entry.platform)
|
|
119
|
+
if legacy_approval_hash(post, platform) != entry.content_hash:
|
|
120
|
+
raise ScheduleError("legacy fingerprint does not match")
|
|
121
|
+
replacements[entry.platform] = {}
|
|
122
|
+
if not post.platforms[platform].media:
|
|
123
|
+
raise ScheduleError("migration requires supplied media")
|
|
124
|
+
for asset in post.platforms[platform].media:
|
|
125
|
+
sha = file_digest(asset.path)
|
|
126
|
+
extension = asset.path.suffix.lower()
|
|
127
|
+
if extension not in MIMES:
|
|
128
|
+
raise ScheduleError("unsupported media MIME type")
|
|
129
|
+
relative = f"approved/sha256/{sha}{extension}"
|
|
130
|
+
source = str(asset.path.relative_to(brand.raiz))
|
|
131
|
+
media[source] = {"source": source, "relative_path": relative, "sha256": sha, "size": asset.path.stat().st_size, "mime": MIMES[extension],
|
|
132
|
+
"public_url": public_url(brand.cuentas.get("instagram", {}).get("media_url_base", ""), relative)}
|
|
133
|
+
replacements[entry.platform][ruta_relativa_efectiva(asset)] = relative
|
|
134
|
+
projected = post.model_copy(deep=True)
|
|
135
|
+
for asset in projected.platforms[platform].media:
|
|
136
|
+
asset.ruta_relativa = replacements[entry.platform][ruta_relativa_efectiva(asset)]
|
|
137
|
+
approvals.append({"id": entry.id, "slug": entry.slug, "platform": entry.platform, "created_at": entry.created_at.isoformat(), "old_hash": entry.content_hash,
|
|
138
|
+
"new_hash": approval_hash(projected, brand, platform), "approval_migration": proposal_id})
|
|
139
|
+
path = _ruta(brand, slug)
|
|
140
|
+
posts[str(path.relative_to(brand.raiz))] = rewrite_media(path.read_bytes(), replacements).decode("utf-8")
|
|
141
|
+
proposal = {"version": 1, "id": proposal_id, "brand": brand.nombre, "brand_root": str(brand.raiz.resolve()), "created_at": now_utc().isoformat(), "backend": backend,
|
|
142
|
+
"accounts": brand.cuentas, "originals": _originals(brand, store, entries), "entries": [e.model_dump(mode="json") for e in entries],
|
|
143
|
+
"approvals": approvals, "posts": posts, "media": list(media.values()), "preview": "\n\n".join(previews), "legacy_limitation": LIMITATION}
|
|
144
|
+
proposal["digest"] = _digest(proposal)
|
|
145
|
+
_verify(brand, proposal)
|
|
146
|
+
if not dry_run:
|
|
147
|
+
write_json(_directory(brand, proposal["id"]) / "proposal.json", proposal)
|
|
148
|
+
return proposal
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def stage(brand: Brand, proposal_id: str, output: Path) -> dict:
|
|
152
|
+
store = ScheduleStore(brand.raiz)
|
|
153
|
+
# Share the authority-handoff/executor lock and queue mutation lock through
|
|
154
|
+
# the final manifest write; readiness checks inside both locks fail closed.
|
|
155
|
+
with store.executor_lock(), store._mutation_lock():
|
|
156
|
+
_assert_no_native_transfer(store)
|
|
157
|
+
return _stage_locked(brand, proposal_id, output)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _stage_locked(brand: Brand, proposal_id: str, output: Path) -> dict:
|
|
161
|
+
proposal = load_proposal(brand, proposal_id)
|
|
162
|
+
_verify(brand, proposal)
|
|
163
|
+
files = {}
|
|
164
|
+
for item in proposal["media"]:
|
|
165
|
+
raw = _safe(brand, item["source"]).read_bytes()
|
|
166
|
+
if hashlib.sha256(raw).hexdigest() != item["sha256"]:
|
|
167
|
+
raise ScheduleError("supplied bytes changed during staging")
|
|
168
|
+
local = _safe(brand, "media/" + item["relative_path"])
|
|
169
|
+
destination = validar_ruta_relativa(output.resolve(), item["relative_path"], ScheduleError, "staging")
|
|
170
|
+
for path in (local, destination):
|
|
171
|
+
if path.exists() and file_digest(path) != item["sha256"]:
|
|
172
|
+
raise ScheduleError("existing destination contains different bytes")
|
|
173
|
+
if not path.exists():
|
|
174
|
+
durable_write(path, raw)
|
|
175
|
+
files[item["relative_path"]] = {k: v for k, v in item.items() if k != "source"} | {"local_path": str(destination)}
|
|
176
|
+
manifest = {"version": 1, "proposal": proposal_id, "digest": proposal["digest"], "files": list(files.values())}
|
|
177
|
+
write_json(output / "transfer-manifest.json", manifest)
|
|
178
|
+
return manifest
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def apply(brand: Brand, proposal_id: str, digest: str, *, acknowledge_legacy_limitations: bool = False, client: httpx.Client | None = None) -> dict:
|
|
182
|
+
proposal = load_proposal(brand, proposal_id)
|
|
183
|
+
if not hmac.compare_digest(proposal["digest"], digest) or not acknowledge_legacy_limitations:
|
|
184
|
+
raise ScheduleError("requires a digest and explicit acknowledgment of legacy limitations")
|
|
185
|
+
directory = _directory(brand, proposal_id)
|
|
186
|
+
if (directory / "intent.json").exists():
|
|
187
|
+
raise ScheduleError("migration already attempted; use explicit rollback")
|
|
188
|
+
store = ScheduleStore(brand.raiz)
|
|
189
|
+
with store.executor_lock(), store._mutation_lock():
|
|
190
|
+
_assert_no_native_transfer(store)
|
|
191
|
+
_verify(brand, proposal)
|
|
192
|
+
attestations = []
|
|
193
|
+
for item in {m["relative_path"]: m for m in proposal["media"]}.values():
|
|
194
|
+
path = _safe(brand, "media/" + item["relative_path"])
|
|
195
|
+
attestations.append(attest_public_media(path, item["public_url"], client=client))
|
|
196
|
+
_verify(brand, proposal)
|
|
197
|
+
# Back up every replaceable original before intent or mutation.
|
|
198
|
+
backups = {}
|
|
199
|
+
for relative, fingerprint in proposal["originals"].items():
|
|
200
|
+
path = _safe(brand, relative)
|
|
201
|
+
backup = directory / "backup" / relative
|
|
202
|
+
if path == store.database_path:
|
|
203
|
+
from socialctl import schedule_sqlite
|
|
204
|
+
durable_write(backup, b"")
|
|
205
|
+
schedule_sqlite.backup(path, backup)
|
|
206
|
+
with backup.open("rb") as handle:
|
|
207
|
+
os.fsync(handle.fileno())
|
|
208
|
+
store._sync_directory(backup.parent)
|
|
209
|
+
fingerprint = file_digest(backup)
|
|
210
|
+
else:
|
|
211
|
+
durable_write(backup, path.read_bytes())
|
|
212
|
+
if file_digest(backup) != fingerprint:
|
|
213
|
+
raise ScheduleError("backup does not match")
|
|
214
|
+
backups[relative] = fingerprint
|
|
215
|
+
intent = {"proposal": proposal_id, "digest": digest, "status": "applying", "backups": backups,
|
|
216
|
+
"database_existed": store.database_path.exists(), "attestations": attestations,
|
|
217
|
+
"legacy_limitation": LIMITATION, "acknowledged": True, "started_at": now_utc().isoformat()}
|
|
218
|
+
write_json(directory / "intent.json", intent)
|
|
219
|
+
write_json(store.root / "migration-active.json", {"proposal": proposal_id, "digest": digest})
|
|
220
|
+
for relative, text in proposal["posts"].items():
|
|
221
|
+
durable_write(_safe(brand, relative), text.encode("utf-8"))
|
|
222
|
+
fresh = cargar_brand(brand.raiz.parent, brand.nombre)
|
|
223
|
+
entries = [ScheduleEntry.model_validate(item) for item in proposal["entries"]]
|
|
224
|
+
provenance = []
|
|
225
|
+
for item in proposal["approvals"]:
|
|
226
|
+
entry = next(e for e in entries if e.id == item["id"] and e.status == "approved")
|
|
227
|
+
entry.content_hash = approval_hash(cargar_post(fresh, entry.slug), fresh, Platform(entry.platform))
|
|
228
|
+
if entry.content_hash != item["new_hash"]:
|
|
229
|
+
raise ScheduleError("payload, account or bytes changed during application")
|
|
230
|
+
if item["approval_migration"] != proposal_id:
|
|
231
|
+
raise ScheduleError("migration provenance does not match")
|
|
232
|
+
entry.approval_migration = proposal_id
|
|
233
|
+
provenance.append(item | {"new_hash": entry.content_hash})
|
|
234
|
+
if proposal["backend"] == "sqlite" and not store.database_path.exists():
|
|
235
|
+
from socialctl import schedule_sqlite
|
|
236
|
+
pending = directory / "queue.sqlite3"
|
|
237
|
+
schedule_sqlite.save(pending, [e.model_dump(mode="json") for e in entries])
|
|
238
|
+
os.replace(pending, store.database_path)
|
|
239
|
+
store._sync_directory(store.root)
|
|
240
|
+
else:
|
|
241
|
+
store._save_unlocked(entries)
|
|
242
|
+
intent.update(status="committed", completed_at=now_utc().isoformat(), approvals=provenance,
|
|
243
|
+
after={relative: file_digest(_safe(brand, relative)) for relative in proposal["posts"]},
|
|
244
|
+
queue_after=[e.model_dump(mode="json") for e in entries])
|
|
245
|
+
write_json(directory / "intent.json", intent)
|
|
246
|
+
write_json(store.root / "media-attestations.json", {"proposal": proposal_id, "attestations": attestations})
|
|
247
|
+
(store.root / "migration-active.json").unlink()
|
|
248
|
+
store._sync_directory(store.root)
|
|
249
|
+
return intent
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def rollback(brand: Brand, proposal_id: str) -> None:
|
|
253
|
+
from socialctl.schedule_remote import is_remote, REMOTE_NOTICE
|
|
254
|
+
if is_remote(brand.raiz):
|
|
255
|
+
raise ScheduleError(REMOTE_NOTICE)
|
|
256
|
+
proposal = load_proposal(brand, proposal_id)
|
|
257
|
+
directory = _directory(brand, proposal_id)
|
|
258
|
+
intent = json.loads((directory / "intent.json").read_bytes())
|
|
259
|
+
store = ScheduleStore(brand.raiz)
|
|
260
|
+
with store._file_lock(store.executor_lock_path, nonblocking=True), store._file_lock(store.mutation_lock_path, nonblocking=False):
|
|
261
|
+
_assert_no_native_transfer(store)
|
|
262
|
+
if is_remote(brand.raiz):
|
|
263
|
+
raise ScheduleError(REMOTE_NOTICE)
|
|
264
|
+
guard = store.root / "migration-active.json"
|
|
265
|
+
if guard.exists() and json.loads(guard.read_bytes())["proposal"] != proposal_id:
|
|
266
|
+
raise ScheduleError("another migration is pending")
|
|
267
|
+
if intent["status"] == "rolled_back":
|
|
268
|
+
if guard.exists():
|
|
269
|
+
if [e.model_dump(mode="json") for e in store.load()] != proposal["entries"]:
|
|
270
|
+
raise ScheduleError("restored queue changed before guard removal")
|
|
271
|
+
for relative in proposal["posts"]:
|
|
272
|
+
if file_digest(_safe(brand, relative)) != intent["backups"][relative]:
|
|
273
|
+
raise ScheduleError("restored post changed before guard removal")
|
|
274
|
+
guard.unlink()
|
|
275
|
+
store._sync_directory(store.root)
|
|
276
|
+
return
|
|
277
|
+
if intent["status"] == "committed" and not guard.exists():
|
|
278
|
+
if [e.model_dump(mode="json") for e in store.load()] != intent["queue_after"]:
|
|
279
|
+
raise ScheduleError("queue advanced after migration; rollback is unsafe")
|
|
280
|
+
for relative, digest in intent["after"].items():
|
|
281
|
+
if file_digest(_safe(brand, relative)) != digest:
|
|
282
|
+
raise ScheduleError("post changed after migration")
|
|
283
|
+
# Verify ALL backups before restoring anything, including interrupted retries.
|
|
284
|
+
for relative, digest in intent["backups"].items():
|
|
285
|
+
if file_digest(directory / "backup" / relative) != digest:
|
|
286
|
+
raise ScheduleError("backup changed; recovery blocked")
|
|
287
|
+
write_json(guard, {"proposal": proposal_id, "digest": proposal["digest"]})
|
|
288
|
+
intent["status"] = "rolling_back"
|
|
289
|
+
write_json(directory / "intent.json", intent)
|
|
290
|
+
for relative in intent["backups"]:
|
|
291
|
+
if relative == "accounts.yml":
|
|
292
|
+
continue # Accounts were never modified by relocation.
|
|
293
|
+
durable_write(_safe(brand, relative), (directory / "backup" / relative).read_bytes())
|
|
294
|
+
if not intent["database_existed"] and store.database_path.exists():
|
|
295
|
+
os.replace(store.database_path, directory / "rolled-back.sqlite3")
|
|
296
|
+
store._sync_directory(store.root)
|
|
297
|
+
store._sync_directory(directory)
|
|
298
|
+
intent["status"] = "rolled_back"
|
|
299
|
+
intent["rolled_back_at"] = now_utc().isoformat()
|
|
300
|
+
write_json(directory / "intent.json", intent)
|
|
301
|
+
guard.unlink()
|
|
302
|
+
store._sync_directory(store.root)
|
socialctl/read_budget.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""Cancellable wall-clock budgets for bounded metadata reads, never uploads."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import math
|
|
6
|
+
import time
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from email.utils import parsedate_to_datetime
|
|
9
|
+
from typing import Callable
|
|
10
|
+
from contextlib import contextmanager
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
|
|
14
|
+
MAX_READ_BYTES = 8 * 1024 * 1024
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ReadDeadlineExceeded(httpx.TimeoutException):
|
|
18
|
+
def __init__(self):
|
|
19
|
+
super().__init__('Read operation exceeded its total time limit; results may be incomplete')
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ReadResponseTooLarge(httpx.ReadError):
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def transport_label(exc):
|
|
27
|
+
"""Identify failures using fixed labels, never provider text or URLs."""
|
|
28
|
+
for kind in (httpx.ConnectTimeout, httpx.ReadTimeout, httpx.WriteTimeout,
|
|
29
|
+
httpx.PoolTimeout, httpx.ProxyError, httpx.ConnectError,
|
|
30
|
+
httpx.ReadError, httpx.WriteError, httpx.RemoteProtocolError):
|
|
31
|
+
if isinstance(exc, kind):
|
|
32
|
+
return kind.__name__
|
|
33
|
+
return 'TransportError'
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ReadBudget:
|
|
37
|
+
def __init__(self, seconds: float, *, clock=time.monotonic):
|
|
38
|
+
if isinstance(seconds, bool) or not isinstance(seconds, (int, float)) or not math.isfinite(seconds) or seconds <= 0:
|
|
39
|
+
raise ValueError('--timeout must be a finite positive number of seconds')
|
|
40
|
+
self.clock = clock
|
|
41
|
+
self.deadline = clock() + seconds
|
|
42
|
+
|
|
43
|
+
def remaining(self) -> float:
|
|
44
|
+
return max(0.0, self.deadline - self.clock())
|
|
45
|
+
|
|
46
|
+
def check(self) -> None:
|
|
47
|
+
if self.remaining() <= 0:
|
|
48
|
+
raise ReadDeadlineExceeded()
|
|
49
|
+
|
|
50
|
+
@contextmanager
|
|
51
|
+
def share(self, remaining_providers: int):
|
|
52
|
+
"""Reserve equal remaining time for sequential providers, within the total."""
|
|
53
|
+
if type(remaining_providers) is not int or remaining_providers < 1:
|
|
54
|
+
raise ValueError('remaining providers must be a positive integer')
|
|
55
|
+
self.check()
|
|
56
|
+
original = self.deadline
|
|
57
|
+
self.deadline = min(original, self.clock() + self.remaining() / remaining_providers)
|
|
58
|
+
try:
|
|
59
|
+
yield self
|
|
60
|
+
finally:
|
|
61
|
+
self.deadline = original
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def retry_delay(response: httpx.Response, attempt: int) -> float:
|
|
65
|
+
value = response.headers.get('retry-after', '')
|
|
66
|
+
try:
|
|
67
|
+
seconds = float(value)
|
|
68
|
+
if math.isfinite(seconds) and seconds >= 0:
|
|
69
|
+
return seconds
|
|
70
|
+
except ValueError:
|
|
71
|
+
try:
|
|
72
|
+
return max(0, (parsedate_to_datetime(value) - datetime.now(timezone.utc)).total_seconds())
|
|
73
|
+
except (ValueError, TypeError, OverflowError):
|
|
74
|
+
pass
|
|
75
|
+
return min(2, .25 * 2 ** attempt)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class BudgetTransport(httpx.BaseTransport):
|
|
79
|
+
"""Own one async loop so an entire headers/body read can be cancelled."""
|
|
80
|
+
def __init__(self, inner: httpx.AsyncBaseTransport, budget: ReadBudget,
|
|
81
|
+
progress: Callable[[], None] | None = None):
|
|
82
|
+
self.inner, self.budget, self.progress = inner, budget, progress
|
|
83
|
+
self.runner = asyncio.Runner()
|
|
84
|
+
self.closed = False
|
|
85
|
+
|
|
86
|
+
async def _read(self, request: httpx.Request) -> httpx.Response:
|
|
87
|
+
for attempt in range(3):
|
|
88
|
+
self.budget.check()
|
|
89
|
+
if self.progress:
|
|
90
|
+
self.progress()
|
|
91
|
+
extensions = dict(request.extensions)
|
|
92
|
+
extensions.pop('socialcli_read_budget', None)
|
|
93
|
+
existing = extensions.get('timeout', {})
|
|
94
|
+
extensions['timeout'] = {key:min(value if value is not None else 30, self.budget.remaining())
|
|
95
|
+
for key,value in {**dict.fromkeys(('connect','read','write','pool'),30), **existing}.items()}
|
|
96
|
+
async_request = httpx.Request(request.method, request.url, headers=request.headers,
|
|
97
|
+
content=request.content, extensions=extensions)
|
|
98
|
+
try:
|
|
99
|
+
async with asyncio.timeout(self.budget.remaining()):
|
|
100
|
+
response = await self.inner.handle_async_request(async_request)
|
|
101
|
+
try:
|
|
102
|
+
raw = bytearray()
|
|
103
|
+
if response.is_stream_consumed:
|
|
104
|
+
raw.extend(response.content)
|
|
105
|
+
else:
|
|
106
|
+
async for chunk in response.aiter_bytes():
|
|
107
|
+
self.budget.check()
|
|
108
|
+
raw.extend(chunk)
|
|
109
|
+
if len(raw) > MAX_READ_BYTES:
|
|
110
|
+
raise ReadResponseTooLarge('Read response exceeds the 8 MiB metadata limit')
|
|
111
|
+
if len(raw) > MAX_READ_BYTES:
|
|
112
|
+
raise ReadResponseTooLarge('Read response exceeds the 8 MiB metadata limit')
|
|
113
|
+
headers = [(k,v) for k,v in response.headers.multi_items() if k.lower() not in {'content-encoding','content-length'}]
|
|
114
|
+
result = httpx.Response(response.status_code, headers=headers,
|
|
115
|
+
content=bytes(raw), extensions=response.extensions)
|
|
116
|
+
finally:
|
|
117
|
+
await response.aclose()
|
|
118
|
+
except TimeoutError:
|
|
119
|
+
raise ReadDeadlineExceeded() from None
|
|
120
|
+
except (ReadDeadlineExceeded, ReadResponseTooLarge):
|
|
121
|
+
raise
|
|
122
|
+
except httpx.TransportError:
|
|
123
|
+
if request.method != 'GET' or attempt == 2:
|
|
124
|
+
raise
|
|
125
|
+
await self._wait(.25 * 2 ** attempt)
|
|
126
|
+
continue
|
|
127
|
+
if request.method != 'GET' or result.status_code not in {408,429,500,502,503,504} or attempt == 2:
|
|
128
|
+
return result
|
|
129
|
+
await self._wait(retry_delay(result, attempt))
|
|
130
|
+
raise AssertionError('unreachable')
|
|
131
|
+
|
|
132
|
+
async def _wait(self, delay: float) -> None:
|
|
133
|
+
if delay >= self.budget.remaining():
|
|
134
|
+
raise ReadDeadlineExceeded()
|
|
135
|
+
await asyncio.sleep(delay)
|
|
136
|
+
self.budget.check()
|
|
137
|
+
|
|
138
|
+
def handle_request(self, request: httpx.Request) -> httpx.Response:
|
|
139
|
+
self.budget.check()
|
|
140
|
+
request.read()
|
|
141
|
+
original = self.budget
|
|
142
|
+
nested = request.extensions.get('socialcli_read_budget')
|
|
143
|
+
if nested is not None:
|
|
144
|
+
nested.check()
|
|
145
|
+
self.budget = ReadBudget(min(original.remaining(), nested.remaining()))
|
|
146
|
+
try:
|
|
147
|
+
return self.runner.run(self._read(request))
|
|
148
|
+
finally:
|
|
149
|
+
self.budget = original
|
|
150
|
+
|
|
151
|
+
def close(self) -> None:
|
|
152
|
+
if not self.closed:
|
|
153
|
+
self.closed = True
|
|
154
|
+
try:
|
|
155
|
+
self.runner.run(self.inner.aclose())
|
|
156
|
+
finally:
|
|
157
|
+
self.runner.close()
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class _EnvironmentTransport(httpx.AsyncBaseTransport):
|
|
161
|
+
"""Keep HTTPX's public proxy/NO_PROXY/CA routing inside the cancellable loop."""
|
|
162
|
+
def __init__(self):
|
|
163
|
+
try:
|
|
164
|
+
self.client = httpx.AsyncClient(timeout=30, follow_redirects=False, trust_env=True)
|
|
165
|
+
except (httpx.InvalidURL, ValueError, OSError, ImportError) as exc:
|
|
166
|
+
raise LocalConfigurationError('Check local proxy, CA and HTTP transport configuration; no request was sent.') from None
|
|
167
|
+
|
|
168
|
+
async def handle_async_request(self, request):
|
|
169
|
+
return await self.client.send(request, stream=True, follow_redirects=False)
|
|
170
|
+
|
|
171
|
+
async def aclose(self):
|
|
172
|
+
await self.client.aclose()
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def read_client(budget: ReadBudget, *, progress=None) -> httpx.Client:
|
|
176
|
+
return httpx.Client(transport=BudgetTransport(_EnvironmentTransport(), budget, progress),
|
|
177
|
+
timeout=30, follow_redirects=False, trust_env=False)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
# Context is opt-in for command-level reads; apply/publication paths keep their transports.
|
|
181
|
+
from contextvars import ContextVar
|
|
182
|
+
|
|
183
|
+
active_read_budget: ContextVar[ReadBudget | None] = ContextVar('socialcli_read_budget', default=None)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
@contextmanager
|
|
187
|
+
def bounded_read(seconds: float):
|
|
188
|
+
budget = ReadBudget(seconds)
|
|
189
|
+
token = active_read_budget.set(budget)
|
|
190
|
+
try:
|
|
191
|
+
yield budget
|
|
192
|
+
finally:
|
|
193
|
+
active_read_budget.reset(token)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
class LocalConfigurationError(ValueError):
|
|
197
|
+
"""Local HTTP configuration failed before a request could be sent."""
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
class ReadProgress:
|
|
201
|
+
"""TTY liveness every five seconds; one final summary for agent pipes."""
|
|
202
|
+
def __init__(self, label, *, clock=time.monotonic):
|
|
203
|
+
self.label, self.clock = label, clock
|
|
204
|
+
self.count, self.last = 0, None
|
|
205
|
+
self.started = clock()
|
|
206
|
+
|
|
207
|
+
def __enter__(self):
|
|
208
|
+
return self
|
|
209
|
+
|
|
210
|
+
def __exit__(self, *_):
|
|
211
|
+
import typer
|
|
212
|
+
elapsed = max(0, self.clock() - self.started)
|
|
213
|
+
typer.echo(f'Read {self.label}: {self.count} requests in {elapsed:.1f}s; see result for coverage.', err=True)
|
|
214
|
+
|
|
215
|
+
def __call__(self):
|
|
216
|
+
import typer
|
|
217
|
+
self.count += 1
|
|
218
|
+
import sys
|
|
219
|
+
if not sys.stderr.isatty():
|
|
220
|
+
return
|
|
221
|
+
now = self.clock()
|
|
222
|
+
if self.last is None or now - self.last >= 5:
|
|
223
|
+
typer.echo(f'Reading {self.label}: {self.count} requests...', err=True)
|
|
224
|
+
self.last = now
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Versioned read envelopes and bounded, credential-safe diagnostics."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
from typing import Any, Literal
|
|
7
|
+
from urllib.parse import quote
|
|
8
|
+
|
|
9
|
+
import typer
|
|
10
|
+
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
|
11
|
+
|
|
12
|
+
from socialctl.agent_errors import error_document, error_for_code
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def safe_error(message: str, *, secrets: tuple[str, ...] = ()) -> str:
|
|
16
|
+
text = str(message)
|
|
17
|
+
for secret in secrets:
|
|
18
|
+
if secret:
|
|
19
|
+
text = text.replace(secret, '[REDACTED]').replace(quote(secret, safe=''), '[REDACTED]')
|
|
20
|
+
text = re.sub(r'(?i)\b(access_token|refresh_token|client_secret|connection_secret|poll_secret)\s*[=:]\s*[^&\s"\'<>]+', r'\1=[REDACTED]', text)
|
|
21
|
+
text = re.sub(r'(?i)([?&]code=)[^&\s"\'<>]+', r'\1[REDACTED]', text)
|
|
22
|
+
text = re.sub(r'(?i)(Authorization\s*:\s*Bearer\s+)[^\s"\'<>]+', r'\1[REDACTED]', text)
|
|
23
|
+
return ''.join(c if c.isprintable() else ' ' for c in text)[:1000]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ReadReport(BaseModel):
|
|
27
|
+
model_config = ConfigDict(extra='forbid')
|
|
28
|
+
version: Literal[1] = 1
|
|
29
|
+
status: Literal['ok', 'partial', 'error']
|
|
30
|
+
observed_at: datetime = Field(default_factory=lambda:datetime.now(timezone.utc))
|
|
31
|
+
coverage: list[dict[str, Any]] = Field(default_factory=list)
|
|
32
|
+
data: dict[str, Any] = Field(default_factory=dict)
|
|
33
|
+
errors: list[dict[str, Any]] = Field(default_factory=list)
|
|
34
|
+
cursor: str | None = None
|
|
35
|
+
|
|
36
|
+
@field_validator('errors')
|
|
37
|
+
@classmethod
|
|
38
|
+
def actions(cls, rows):
|
|
39
|
+
result = []
|
|
40
|
+
for row in rows:
|
|
41
|
+
detail = error_for_code(row.get('code', 'read_partial'), read_only=True)
|
|
42
|
+
result.append({**row, **detail,
|
|
43
|
+
'message':safe_error(row.get('message', detail['message'])),
|
|
44
|
+
'guidance':detail['message']})
|
|
45
|
+
return result
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def annotate_partial_read(result):
|
|
49
|
+
"""Add guidance without changing legacy items, cursor or completion fields."""
|
|
50
|
+
if not isinstance(result, dict) or result.get('complete') is not False:
|
|
51
|
+
return result
|
|
52
|
+
code = ('read_interrupted' if result.get('interrupted') is True else
|
|
53
|
+
'read_deadline' if result.get('timed_out') is True else 'read_partial')
|
|
54
|
+
detail = result.get('error_detail')
|
|
55
|
+
if isinstance(detail, dict) and code == 'read_partial':
|
|
56
|
+
code = detail.get('code', code)
|
|
57
|
+
return {**result, 'error_detail':error_for_code(code, read_only=True)}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def load_read_brand(root, brand):
|
|
61
|
+
"""JSON read entry points must keep a structured error before any request."""
|
|
62
|
+
from socialctl.brands import cargar_brand, BrandNoEncontrada, NombreDeMarcaInvalido, AccountsInvalido
|
|
63
|
+
from socialctl.youtube_data import YouTubeDataCleanupError
|
|
64
|
+
try:
|
|
65
|
+
return cargar_brand(root, brand)
|
|
66
|
+
except YouTubeDataCleanupError as exc:
|
|
67
|
+
emit_report(ReadReport(status='error', errors=[error_document(exc,read_only=True)]))
|
|
68
|
+
raise typer.Exit(1) from None
|
|
69
|
+
except (BrandNoEncontrada, NombreDeMarcaInvalido, AccountsInvalido, OSError):
|
|
70
|
+
emit_report(ReadReport(status='error', errors=[error_for_code('invalid_input')]))
|
|
71
|
+
raise typer.Exit(1) from None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def emit_report(report: ReadReport) -> int:
|
|
75
|
+
typer.echo(report.model_dump_json(indent=2))
|
|
76
|
+
return read_exit_code(report.status)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def fail_read(exc: Exception, *, json_output: bool) -> None:
|
|
80
|
+
detail = error_document(exc, read_only=True)
|
|
81
|
+
message = detail['message'] if detail['code'] == 'local_configuration' else safe_error(str(exc))
|
|
82
|
+
code = 2 if message.startswith('--timeout must') else 1
|
|
83
|
+
if json_output:
|
|
84
|
+
emit_report(ReadReport(status='error', errors=[{**detail, 'message':message}]))
|
|
85
|
+
else:
|
|
86
|
+
typer.echo(message)
|
|
87
|
+
raise typer.Exit(code)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def read_exit_code(status: str) -> int:
|
|
91
|
+
return {'ok': 0, 'partial': 3, 'error': 1}[status]
|