GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — policyengine.py/scripts/release_consumers.py at main · PolicyEngine/policyengine.py

Expand file tree

/

release_consumers.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
200 lines (170 loc) · 6.87 KB
/

release_consumers.py

Copy path

File metadata and controls

200 lines (170 loc) · 6.87 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""Build the post-release dispatches for policyengine.py consumers.
Run by the NotifyConsumers job in ``.github/workflows/push.yaml`` after a
release is visible on PyPI::
python scripts/release_consumers.py payload --version 6.2.7 > payload.json
python scripts/release_consumers.py scorecard-request --version 6.2.7 > request.json
``payload`` is the ``policyengine-release`` repository dispatch (version,
certified UK bundle identity, qualification digests). ``scorecard-request``
is the scorecard's ``released_bundle`` replay request; it needs the release
installed (``pip install "policyengine[uk]==<version>"``) and
``HUGGING_FACE_TOKEN``.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import subprocess
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO_ROOT / "src"))
os.environ.setdefault("POLICYENGINE_SKIP_COUNTRY_IMPORTS", "1")
import requests # noqa: E402
from policyengine.provenance.manifest import ( # noqa: E402
https_dataset_uri,
hugging_face_auth_headers,
)
from policyengine.provenance.qualification_ledger import ( # noqa: E402
fetch_ledger_receipt,
)
from policyengine.provenance.uk_qualification import ( # noqa: E402
release_dispatch_payload,
released_bundle_request,
)
BUNDLE_PATH = REPO_ROOT / "src" / "policyengine" / "data" / "bundle" / "manifest.json"
TIMEOUT = 60
TOKEN_VARIABLES = ("HF_TOKEN", "HUGGING_FACE_TOKEN", "HUGGINGFACE_HUB_TOKEN")
def _bundle() -> dict:
return json.loads(BUNDLE_PATH.read_text())
def _pypi(path: str) -> dict:
response = requests.get(f"https://pypi.org/pypi/{path}/json", timeout=TIMEOUT)
response.raise_for_status()
return response.json()
def _hf_file(repo_id: str, revision: str, path: str, repo_type: str = "model") -> bytes:
response = requests.get(
https_dataset_uri(repo_id, path, revision, repo_type=repo_type),
headers=hugging_face_auth_headers(),
timeout=TIMEOUT,
)
response.raise_for_status()
return response.content
def _hf_size(repo_id: str, revision: str, path: str, repo_type: str = "model") -> int:
"""A file's size from Hugging Face's response headers, without downloading it.
A large-file pointer answers HEAD with a redirect that carries
``X-Linked-Size``. A small file answers with its own ``Content-Length``,
or with a redirect that leads to it, which is then followed.
"""
url = https_dataset_uri(repo_id, path, revision, repo_type=repo_type)
# A compressed answer has no Content-Length, so ask for the bytes as they
# are, as huggingface_hub does.
headers = {**hugging_face_auth_headers(), "Accept-Encoding": "identity"}
response = requests.head(
url, headers=headers, timeout=TIMEOUT, allow_redirects=False
)
response.raise_for_status()
size = response.headers.get("X-Linked-Size")
if size is None and response.status_code == 200:
size = response.headers.get("Content-Length")
elif size is None:
followed = requests.head(
url, headers=headers, timeout=TIMEOUT, allow_redirects=True
)
followed.raise_for_status()
size = followed.headers.get("Content-Length")
if not size:
raise SystemExit(
f"Hugging Face reports no size for {repo_id}/{path}@{revision}."
)
return int(size)
def cmd_payload(args: argparse.Namespace) -> int:
payload = release_dispatch_payload(
_bundle(), version=args.version, fetch_receipt=fetch_ledger_receipt
)
print(json.dumps(payload, sort_keys=True))
return 0
def _installed(code: str, *, strip_tokens: bool) -> str:
"""Run ``code`` against the installed release, outside the checkout."""
env = dict(os.environ)
env.pop("POLICYENGINE_SKIP_COUNTRY_IMPORTS", None)
if strip_tokens:
for key in TOKEN_VARIABLES:
env.pop(key, None)
return subprocess.run(
[sys.executable, "-c", code],
env=env,
cwd="/",
check=True,
capture_output=True,
text=True,
).stdout.strip()
def cmd_scorecard_request(args: argparse.Namespace) -> int:
release = _pypi(f"policyengine/{args.version}")
wheels = [item for item in release["urls"] if item["packagetype"] == "bdist_wheel"]
if len(wheels) != 1:
raise SystemExit(f"policyengine {args.version} must publish exactly one wheel.")
installed_version = _installed(
"from importlib.metadata import version; print(version('policyengine'))",
strip_tokens=False,
)
if installed_version != args.version:
raise SystemExit(
f"policyengine {installed_version} is installed, not {args.version}."
)
manifest_path = _installed(
"from importlib.resources import files; "
"print(files('policyengine').joinpath('data', 'bundle', 'manifest.json'))",
strip_tokens=False,
)
release_bundle = json.loads(
_installed(
"import json, policyengine as pe; "
"print(json.dumps(dict(pe.uk.uk_latest.release_bundle), sort_keys=True))",
strip_tokens=True,
).splitlines()[-1]
)
server = os.environ.get("GITHUB_SERVER_URL", "https://github.com")
repository = os.environ.get("GITHUB_REPOSITORY", "PolicyEngine/policyengine.py")
run_id = os.environ.get("GITHUB_RUN_ID", "1")
request = released_bundle_request(
json.loads(Path(manifest_path).read_text()),
version=args.version,
wheel_sha256=wheels[0]["digests"]["sha256"],
packaged_manifest_sha256=hashlib.sha256(
Path(manifest_path).read_bytes()
).hexdigest(),
release_bundle=release_bundle,
hf_file=_hf_file,
hf_size=_hf_size,
pypi_project=_pypi,
requested_by={
"repository": repository,
"workflow_run_id": int(run_id),
"run_attempt": int(os.environ.get("GITHUB_RUN_ATTEMPT", "1")),
"commit": os.environ.get("GITHUB_SHA", "0" * 40),
"run_url": f"{server}/{repository}/actions/runs/{run_id}",
},
)
print(
json.dumps(
{
"event_type": "uk-replay-qualification-request",
"client_payload": {"request": request.document()},
},
sort_keys=True,
)
)
return 0
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
commands = parser.add_subparsers(dest="command", required=True)
payload = commands.add_parser("payload")
payload.add_argument("--version", required=True)
payload.set_defaults(func=cmd_payload)
scorecard = commands.add_parser("scorecard-request")
scorecard.add_argument("--version", required=True)
scorecard.set_defaults(func=cmd_scorecard_request)
args = parser.parse_args(argv)
return int(args.func(args) or 0)
if __name__ == "__main__":
raise SystemExit(main())
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.