mirror of
https://github.com/bitbaum/solon.git
synced 2026-12-04 05:07:04 +01:00
* perf(places): place pages kept for an hour; the run log indexed and bounded; a place's country by its ISO code - A place's country (its profile, budget, photograph and share card) is its own ISO 3166-1 code, else its pack's root, else a world nation's slug, never the last slug segment: the Djibouti Region (world/djibouti/djibouti), the City of San Marino and the US state of Georgia showed a country's page. - /places/[...slug] is ISR for an hour with nothing built ahead, instead of force-dynamic: its queries run about once an hour per place and language. - place_import_runs gets indexes on (source_key, started_at) and (status, finished_at); sourceRuns is one DISTINCT ON query, read once per call and passed to the worker. - Runs a stopped process left `running` are closed as failed after two worker budgets, so they are reported once and backed off. - The worker starts on a day with nothing due as well, for the daily rebuild of the ancestors view. - verify runs places:world-countries --check, now comparing the countries the file holds rather than CLDR's names; geography:world writes its registry as Prettier formats it. The engineering audit's claim that both were checked is corrected. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k * feat(places): a source a publisher refuses to the box is fetched daily from a runner The World Bank's API answers the box HTTP 403 (2026-11-10), and its source is the only one for eight statistics in about 210 countries: none had ever loaded in production, and the box's queue failed it and alerted every cycle. - A source may say `fetchFrom: "runner"`. The box's worker leaves it out of its queue; `pnpm run places:queue --from runner` drains it, with the same cadence, retries and run log. - places-load-cloud.yml runs that daily (and on dispatch with kind=queue), through its SSH tunnel to the production database, copying the snapshots back to the box as it already did for hand-dispatched loads. - The World Bank's source is the one runner source; a test fails if another side gets it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k * refactor(statistics): a governance indicator is five lines; shared scopes and sentence() - statistic-templates.ts holds sentence() (moved from the budgets' metrics), the scope of general government at every level and the scope of a perception score, and wgiMetric({ key, code, name }). - The six Worldwide Governance Indicators are written with wgiMetric: 204 lines become 66, and the generated metrics were checked identical to the hand-written ones, word for word in every language. - Government consumption and tax revenue share one scope sentence instead of two copies. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k * perf(statistics): every statistic in one query; a new statistic adds no queries - loadSeriesFor(db, config, keys, locale, { latestOnly }) reads any number of metrics in one facts query and names their places once. latestOnly keeps each place's latest value within the metric's plausible band, as a chart's screening leaves it. - /statistics: 4 queries instead of 136 (34 statistics x loadSeries + placeLabels); 104-131 ms instead of 325-548 ms on a database holding the live OECD, Eurostat and World Bank figures. Checked identical to the old per-metric query for all 34 statistics (2,403 series), and latest-only identical to the screened full series. - The dimension, event, compare and saved-view pages load their metrics in one call each. - placeLabels groups names and codes once instead of filtering every row per place, and builds one Intl.DisplayNames for the list. - facts gets a partial index on (metric_key, jurisdiction_id, valid_from DESC) for current, unvaried figures. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k * perf(ci): a deploy that touched no Places data clones, installs and reads nothing places-data.yml ran after every deploy: a full clone and pnpm install on the memory-tight box, a runner install, and 798 image requests through the live site, though most deploys change no Places data and no photograph. - A first job diffs the deployed commit against the one this workflow last loaded successfully (a failed load is retried by the next deploy; a dispatch, perhaps a dry run, does not count). The import runs when Places data, its config, adapters or importer changed; the photo warm-up when photos.json or the photo code changed. A dispatch runs both. - The box fetches the deployed commit at depth 1 instead of cloning the repository's history. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k * perf(places): an old /places/<slug> link is redirected after a two-query lookup It ran the full place-page load (about 17 queries) only to learn whether the world pack holds the place. Links no longer point there (#572); the redirect stays for old ones. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k * perf(law): a register import reads only its own register, and stops when nothing changed About 34 register imports run every week. Each made one query per law authority (311, one after another) and read every current act, title, number and page in the law database, however small its register; and missingFromSource counted every act sharing the identity scheme, so it was wrong for every publisher_ref register. - A retrieval whose acts, as read, are those the register last applied is recorded as applied and `unchanged` and goes no further. The recorded importer version carries a hash of the rows read, so the same bytes read by a changed reader are applied again. - The authorities the retrieval names are resolved to places in one query. - Known acts are read for the identities the retrieval lists, a thousand at a time, with their titles, numbers and pages for those acts only. - missingFromSource counts only the identities this register itself stated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k * fix(law): the weekly sync waits for a heavy load; verify reads a sample, a second apart - law-sync.yml took /tmp/solon-law-load.lock while a heavy load dispatched by hand (law-text.yml) takes /tmp/solon-law-load-heavy.lock, so the two never excluded each other, the pairing that ran the box out of memory on 2026-11-08. The sync now takes the heavy lock, and after two hours' wait leaves that week's sync be, saying so. - `law:text verify` read its sample size from --limit, which the workflow passes every source (1,500 by default): a dispatch read 1,500 publisher pages back to back. It reads --sample (30 by default) and pauses a second between reads. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k * fix(law): an act held in two languages is listed once, titled in the reader's language recentChanges joined every current title to every current version, so an act held in German and French appeared up to four times in a place's recent changes (with repeated React keys), and a constitution's title on the profile card came out in whichever language the database returned first. - actTitleSql (src/lib/law/act-title.ts): an act's current title in the reader's language, else its first other language, as one value. - recentChanges takes the reader's language and keeps one row an act, its latest current version; the profile's constitution lookup uses the same title rule. - An integration test holds one act in two languages. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k * refactor(generators): one polite Wikidata client; scratch scripts removed world-profiles, places-photos and law-plan each carried their own SPARQL helper: world-profiles retried any error four times (a 400 included), law-plan did not retry at all, and each sent its own user agent. They use the shared client (src/lib/wikidata/query.ts), which waits as long as the server asks on a 429 or 503 and fails at once on anything else. law-plan now checks that Constitute's index answered before reading it. scripts/_ws.ts and _ws2.ts, committed scratch files, are deleted. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k * refactor(statistics): one rule a unit, so a statistic in a new unit is a line in units.ts What a unit means was decided in six places: the chart scale (present.ts), the label (shared.ts), the brief's value text and points (brief.ts), the profile figure's format (place-figures.tsx), the axis panel's percent sign and the divisor a published percentage is stored with (sources.ts). A statistic in a count or a currency would have been shown with no unit, or scaled wrong, in some of them. src/lib/config/places/units.ts holds, per unit, its scale and decimals, whether publishers print it in per cent, whether it is a percentage, and the key of its words under Statistics.units; every site reads it. A test fails when a unit's words are missing in a language. Nothing shown changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k * perf(law): a place's page counts its own authorities' acts, not the whole register's loadPlaceLaw ran loadLawCoverage, three aggregates over every act and version in the law database, to show the counts of a handful of authorities: the place's chain and the parts of its nearest. loadLawCoverage takes an optional list of authorities and counts only theirs; a place's page passes the ones it shows. Checked against a database of 9,119 acts in 14 authorities: the counts of all 132 shown authorities are the same as before. The pages that show the whole register still count it all. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k * fix: findings of an adversarial review of this stack - Place pages are rendered on every visit again: ISR made Next keep every rendered URL on the server's disk (a few thousand places in five languages, and any made-up path besides, with no bound), and kept a not-found path as not found for an hour. A view's cost is cut where it is spent instead. - A failed source retried by a once-a-day queue (the runner's) waited a full 24 hours from the failed run's start, so the next day's run, starting a few minutes earlier, missed it: retries allow two hours' slack. - Abandoned runs are closed after eight hours, longer than any import runs from the box or a runner (a workflow job stops at six), instead of after two worker budgets. - One concurrency group for every cloud load, so the daily queue and a fetch dispatched by hand never write the same source at once. - The saved-axis page scores, as the index does, on each place's latest plausible value; loadSeriesFor dedupes its keys. - places-data runs the import weekly whatever changed, for a file applied while some of its places were not held (`+partial`) or one whose import failed. - An unchanged register import still reports what the register no longer lists. - The shared Wikidata client retries 500, 502 and 504 too, as world-profiles did; a bad query still fails at once. - The weekly law sync waits 45 minutes for the heavy lock, not two hours. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmuJdjaMYdbLjujoC3k --------- Co-authored-by: Claude <noreply@anthropic.com>
259 lines
11 KiB
TypeScript
259 lines
11 KiB
TypeScript
/**
|
|
* Every place's profile, written to data/world/profiles.json:
|
|
*
|
|
* pnpm run world:profiles
|
|
*
|
|
* - The United Nations' member states and their day of admission, from
|
|
* un.org's list (each entry carries its ISO code in its flag's class).
|
|
* - For every place of the world list and every extra (src/lib/config/world/extras.ts):
|
|
* its Wikidata facts (CC0): names, capital, population and its year, area,
|
|
* official languages, currency, form of government, heads of state and
|
|
* government, the day it was founded or proclaimed, its website, a point to
|
|
* mark it by, and the country it lies in.
|
|
* - The proclaimed states the rule in extras.ts picks.
|
|
*
|
|
* Facts change; the file records the day they were read, and the page says so.
|
|
*/
|
|
import { writeFileSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
import { WORLD } from "@/lib/config/world";
|
|
import { EXTRA_PLACES } from "@/lib/config/world/kinds";
|
|
import {
|
|
NAMED_EXTRAS,
|
|
PROCLAIMED_MIN_WIKIPEDIAS,
|
|
SELF_GOVERNING_ITEMS,
|
|
} from "@/lib/config/world/extras";
|
|
import { sparql } from "@/lib/wikidata/query";
|
|
|
|
const UA = "SolonLawReader/1.0 (https://solon.orangecat.ch; world profiles)";
|
|
const LANGS = ["en", "de", "fr", "it", "ru"] as const;
|
|
const OUT = join(process.cwd(), "data", "world", "profiles.json");
|
|
const EXTRAS_OUT = join(process.cwd(), "src", "lib", "config", "world", "extras.json");
|
|
|
|
type Row = Record<string, string | undefined>;
|
|
|
|
const q = (uri: string | undefined) => uri?.replace(/^.*\//, "");
|
|
|
|
async function unMembers(): Promise<Record<string, string>> {
|
|
const response = await fetch("https://www.un.org/en/about-us/member-states", {
|
|
headers: { "user-agent": `Mozilla/5.0 (compatible; ${UA})` },
|
|
signal: AbortSignal.timeout(60_000),
|
|
});
|
|
if (!response.ok) throw new Error(`un.org: HTTP ${response.status}`);
|
|
const html = await response.text();
|
|
const out: Record<string, string> = {};
|
|
for (const m of html.matchAll(
|
|
/flags flags-([a-z]{2})\b[\s\S]*?Date of Admission: (\d\d)-(\d\d)-(\d{4})/g,
|
|
)) {
|
|
out[m[1]!.toUpperCase()] = `${m[4]}-${m[3]}-${m[2]}`;
|
|
}
|
|
if (Object.keys(out).length < 190) {
|
|
throw new Error(`un.org: only ${Object.keys(out).length} members read`);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
async function main() {
|
|
const read = new Date().toISOString().slice(0, 10);
|
|
const un = await unMembers();
|
|
console.error(`UN: ${Object.keys(un).length} members`);
|
|
|
|
// Items: ISO places by their code; the self-governing places without one; the extras; the proclaimed.
|
|
const isoRows = await sparql(`
|
|
SELECT ?iso ?c ?links WHERE {
|
|
?c wdt:P297 ?iso ; wikibase:sitelinks ?links .
|
|
FILTER NOT EXISTS { ?c wdt:P576 ?end }
|
|
}`);
|
|
const byIso = new Map<string, { item: string; links: number }>();
|
|
for (const r of isoRows) {
|
|
const prev = byIso.get(r.iso!);
|
|
const links = Number(r.links);
|
|
if (!prev || links > prev.links) byIso.set(r.iso!, { item: q(r.c)!, links });
|
|
}
|
|
const proclaimed = await sparql(`
|
|
SELECT DISTINCT ?i ?links WHERE {
|
|
?i wdt:P31/wdt:P279* wd:Q188443 ; wikibase:sitelinks ?links .
|
|
FILTER NOT EXISTS { ?i wdt:P576 ?end }
|
|
FILTER(?links >= ${PROCLAIMED_MIN_WIKIPEDIAS})
|
|
} ORDER BY DESC(?links)`);
|
|
|
|
const entries: { slug: string; item: string; kind: string | null; code: string | null }[] = [];
|
|
// The world list includes the extras read last time; they are found again by their own rule below.
|
|
const extraSlugs = new Set(EXTRA_PLACES.map((p) => p.slug));
|
|
for (const w of WORLD.filter((r) => !extraSlugs.has(r.slug))) {
|
|
const item = w.code
|
|
? byIso.get(w.code)?.item
|
|
: (SELF_GOVERNING_ITEMS[w.slug] ?? q(w.ref?.value));
|
|
if (item) entries.push({ slug: w.slug, item, kind: null, code: w.code ?? null });
|
|
else console.error(`no Wikidata item for ${w.slug}`);
|
|
}
|
|
for (const x of NAMED_EXTRAS)
|
|
entries.push({ slug: x.slug, item: x.wikidata, kind: x.kind, code: null });
|
|
const taken = new Set(entries.map((e) => e.item));
|
|
const proclaimedItems = proclaimed.map((r) => q(r.i)!).filter((i) => !taken.has(i));
|
|
|
|
// Facts, in chunks the query service answers within its limit.
|
|
const items = [...entries.map((e) => e.item), ...proclaimedItems];
|
|
const facts = new Map<string, Row[]>();
|
|
for (let i = 0; i < items.length; i += 40) {
|
|
const chunk = items
|
|
.slice(i, i + 40)
|
|
.map((x) => `wd:${x}`)
|
|
.join(" ");
|
|
const rows = await sparql(`
|
|
SELECT ?i ?prop ?value ?valueLang ?extra WHERE {
|
|
VALUES ?i { ${chunk} }
|
|
{
|
|
?i rdfs:label ?value . BIND("label" AS ?prop) BIND(LANG(?value) AS ?valueLang)
|
|
FILTER(LANG(?value) IN (${LANGS.map((l) => `"${l}"`).join(",")}))
|
|
} UNION {
|
|
?i schema:description ?value . BIND("description" AS ?prop) BIND(LANG(?value) AS ?valueLang)
|
|
FILTER(LANG(?value) IN (${LANGS.map((l) => `"${l}"`).join(",")}))
|
|
} UNION {
|
|
VALUES (?p ?prop) { (wdt:P36 "capital") (wdt:P122 "government") (wdt:P35 "headOfState") (wdt:P6 "headOfGovernment") }
|
|
?i ?p ?o . ?o rdfs:label ?value . BIND(LANG(?value) AS ?valueLang)
|
|
FILTER(LANG(?value) IN (${LANGS.map((l) => `"${l}"`).join(",")}))
|
|
BIND(STR(?o) AS ?extra)
|
|
} UNION {
|
|
?i p:P1082 ?st . ?st wikibase:rank wikibase:PreferredRank ; ps:P1082 ?value .
|
|
OPTIONAL { ?st pq:P585 ?when } BIND("population" AS ?prop) BIND(STR(?when) AS ?extra)
|
|
} UNION {
|
|
?i p:P1082 ?st . ?st wikibase:rank wikibase:NormalRank ; ps:P1082 ?value .
|
|
FILTER NOT EXISTS { ?i p:P1082/wikibase:rank wikibase:PreferredRank }
|
|
OPTIONAL { ?st pq:P585 ?when } BIND("population" AS ?prop) BIND(STR(?when) AS ?extra)
|
|
} UNION {
|
|
?i p:P2046 ?ast . ?ast wikibase:rank ?arank ; psv:P2046 ?node .
|
|
?node wikibase:quantityAmount ?value ; wikibase:quantityUnit ?unit .
|
|
FILTER(?unit = wd:Q712226 && ?arank != wikibase:DeprecatedRank)
|
|
BIND("areaKm2" AS ?prop) BIND(STR(?arank) AS ?extra)
|
|
} UNION {
|
|
?i wdt:P37 ?l . ?l wdt:P218 ?value . BIND("language" AS ?prop)
|
|
} UNION {
|
|
?i wdt:P38 ?cur . ?cur wdt:P498 ?value . BIND("currency" AS ?prop)
|
|
} UNION {
|
|
?i wdt:P571 ?value . BIND("inception" AS ?prop)
|
|
} UNION {
|
|
?i wdt:P856 ?value . BIND("website" AS ?prop)
|
|
} UNION {
|
|
?i wdt:P625 ?value . BIND("point" AS ?prop)
|
|
} UNION {
|
|
?i wdt:P17 ?country . ?country wdt:P297 ?value . BIND("country" AS ?prop)
|
|
} UNION {
|
|
?i wikibase:sitelinks ?value . BIND("links" AS ?prop)
|
|
}
|
|
}`);
|
|
for (const r of rows) facts.set(q(r.i)!, [...(facts.get(q(r.i)!) ?? []), r]);
|
|
console.error(`facts ${Math.min(i + 40, items.length)}/${items.length}`);
|
|
}
|
|
|
|
const profileOf = (item: string) => {
|
|
const rows = facts.get(item) ?? [];
|
|
const named = (prop: string) => {
|
|
const byItem = new Map<string, Record<string, string>>();
|
|
for (const r of rows.filter((x) => x.prop === prop)) {
|
|
const key = r.extra ?? "";
|
|
byItem.set(key, { ...(byItem.get(key) ?? {}), [r.valueLang!]: r.value! });
|
|
}
|
|
return [...byItem.values()];
|
|
};
|
|
const one = (prop: string) => rows.find((r) => r.prop === prop)?.value;
|
|
const all = (prop: string) =>
|
|
[...new Set(rows.filter((r) => r.prop === prop).map((r) => r.value!))].sort();
|
|
const texts = (prop: string) =>
|
|
Object.fromEntries(rows.filter((r) => r.prop === prop).map((r) => [r.valueLang!, r.value!]));
|
|
const pops = rows
|
|
.filter((r) => r.prop === "population")
|
|
.map((r) => ({ value: Number(r.value), year: r.extra ? Number(r.extra.slice(0, 4)) : null }))
|
|
.sort((a, b) => (b.year ?? 0) - (a.year ?? 0));
|
|
const point = one("point")?.match(/Point\(([-\d.]+) ([-\d.]+)\)/);
|
|
// The preferred figure where Wikidata ranks one; else the smallest, so a claimed territory
|
|
// larger than the one governed (Taiwan's, 11.4 million km²) is never shown as its area.
|
|
const areas = rows.filter((r) => r.prop === "areaKm2");
|
|
const preferred = areas.filter((r) => r.extra?.endsWith("PreferredRank"));
|
|
const area = (preferred.length ? preferred : areas)
|
|
.map((r) => Number(r.value))
|
|
.sort((x, y) => x - y)[0];
|
|
return {
|
|
wikidata: item,
|
|
names: texts("label"),
|
|
description: texts("description"),
|
|
capital: named("capital"),
|
|
government: named("government"),
|
|
headOfState: named("headOfState"),
|
|
headOfGovernment: named("headOfGovernment"),
|
|
population: pops[0] && Number.isFinite(pops[0].value) ? pops[0] : null,
|
|
areaKm2: area !== undefined && Number.isFinite(area) ? Math.round(area * 100) / 100 : null,
|
|
languages: all("language"),
|
|
currencies: all("currency"),
|
|
inception: one("inception")?.slice(0, 10) ?? null,
|
|
website: one("website") ?? null,
|
|
point: point ? [Number(point[1]), Number(point[2])] : null,
|
|
country: all("country")[0] ?? null,
|
|
wikipedias: Number(one("links") ?? 0),
|
|
};
|
|
};
|
|
|
|
const places: Record<string, unknown> = {};
|
|
for (const e of entries) places[e.slug] = { ...profileOf(e.item), kind: e.kind };
|
|
const slugOf = (names: Record<string, string>, item: string) =>
|
|
(names.en ?? item)
|
|
.normalize("NFD")
|
|
.replace(/[̀-ͯ]/g, "")
|
|
.toLowerCase()
|
|
.replace(/[^a-z0-9]+/g, "-")
|
|
.replace(/^-|-$/g, "");
|
|
for (const item of proclaimedItems) {
|
|
const p = profileOf(item);
|
|
places[slugOf(p.names, item)] = { ...p, kind: "proclaimed" };
|
|
}
|
|
writeFileSync(
|
|
OUT,
|
|
`${JSON.stringify(
|
|
{
|
|
read,
|
|
sources: {
|
|
un: "https://www.un.org/en/about-us/member-states",
|
|
wikidata: "https://query.wikidata.org/ (CC0)",
|
|
},
|
|
proclaimedRule: `Wikidata micronation (Q188443), not dissolved, in at least ${PROCLAIMED_MIN_WIKIPEDIAS} Wikipedias`,
|
|
un,
|
|
places,
|
|
},
|
|
null,
|
|
2,
|
|
)}\n`,
|
|
);
|
|
// The places beyond the ISO list, small enough for the map in the browser: who, what kind, where.
|
|
const extras = Object.entries(
|
|
places as Record<string, ReturnType<typeof profileOf> & { kind: string | null }>,
|
|
)
|
|
.filter(([, p]) => p.kind)
|
|
.map(([slug, p]) => ({
|
|
slug,
|
|
wikidata: p.wikidata,
|
|
kind: p.kind,
|
|
names: p.names,
|
|
// A project's coordinates are an office, not a place it governs: it gets no point.
|
|
point: p.kind === "project" ? null : p.point,
|
|
country: p.country,
|
|
}));
|
|
// A point for each place that governs itself without UN membership, for the map to mark the
|
|
// ones its outlines do not draw (Abkhazia, South Ossetia, Transnistria).
|
|
const points = Object.fromEntries(
|
|
Object.keys(SELF_GOVERNING_ITEMS).flatMap((slug) => {
|
|
const point = (places[slug] as { point: [number, number] | null } | undefined)?.point;
|
|
return point ? [[slug, point]] : [];
|
|
}),
|
|
);
|
|
writeFileSync(
|
|
EXTRAS_OUT,
|
|
`${JSON.stringify({ read, un: Object.keys(un).sort(), points, extras }, null, 2)}\n`,
|
|
);
|
|
console.log(`${Object.keys(places).length} places; ${proclaimedItems.length} proclaimed`);
|
|
}
|
|
|
|
main().catch((error) => {
|
|
console.error(error);
|
|
process.exit(1);
|
|
});
|