Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / scripts / maps / build_world_transit.ps1

build_world_transit.ps1165 lines · 8.8 KiBRaw
1# build_world_transit.ps1 -- build inputs/world.transit, the single global offline transit pack.
2#
3# Mirrors Transitous' own published GTFS directory (https://api.transitous.org/gtfs/, its
4# already-fetched, already-normalised output; nothing here talks to an agency), unzips every
5# feed, and merges them into one TRIX pack with `gtfs_ingest`.
6#
7# The pack is the build's only transit input: v7 carries RAIL_LINES, the exact shapes
8# `transit_shapes` reads from the feeds, so build_graph.ps1 derives the map's transit layer from
9# world.transit alone. Before the pack replaces inputs/world.transit this script proves that:
10# the layer derived from the pack must be byte-identical to the one derived from the raw feeds.
11# Once it has, the work dir (mirror + unzipped feeds, ~80 GB) is not needed again and can be
12# deleted; a later run re-downloads it.
13#
14# THE FEED ID. A zip is `<region>_<Source>.gtfs.zip` and its MOTIS feed id is `<region>-<Source>`.
15# Only the FIRST underscore is a separator; the rest keeps its own hyphens and case
16# (`us-ca_SF-bayarea` -> `us-ca-SF-bayarea`). Without it the pack carries no MOTIS stop ids and
17# live delays cannot be matched to a stop.
18#
19# Usage (from anywhere):
20# .\scripts\maps\build_world_transit.ps1 # mirror, unzip, merge, verify, install
21# .\scripts\maps\build_world_transit.ps1 -SkipMirror # reuse the mirror already on disk
22# .\scripts\maps\build_world_transit.ps1 -SkipVerify # skip the raw-vs-pack layer proof
23#
24# Work dir: scripts/maps/world_transit_work (transitous/ zips, gtfs/ unzipped, feeds.manifest).
25# Output: scripts/maps/inputs/world.transit (+ .json).
26
27param(
28 # Use the zips already in the work dir instead of refreshing the mirror.
29 [switch] $SkipMirror,
30 # Install the pack without proving the derived transit layer matches the raw feeds.
31 [switch] $SkipVerify,
32 # Feeds unzipped at once. The download itself is always serial; see below.
33 [int] $Jobs = 4
34)
35$ErrorActionPreference = "Stop"
36
37$Here = $PSScriptRoot
38$Repo = (Resolve-Path (Join-Path $Here "../..")).Path
39$Work = Join-Path $Here "world_transit_work"
40$Mirror = Join-Path $Work "transitous"
41$Gtfs = Join-Path $Work "gtfs"
42$Manifest = Join-Path $Work "feeds.manifest"
43$Staging = Join-Path $Work "pack"
44$Inputs = Join-Path $Here "inputs"
45$IndexUrl = "https://api.transitous.org/gtfs/"
46New-Item -ItemType Directory -Force -Path $Work, $Mirror, $Gtfs, $Inputs | Out-Null
47
48# --- 1. Build the tools --------------------------------------------------------------------
49Write-Host "=== [1/5] building gtfs_ingest + transit_shapes (release) ==="
50Push-Location $Repo
51try {
52 cargo build --release -p gtfs_ingest --bin gtfs_ingest --bin transit_shapes
53 if ($LASTEXITCODE -ne 0) { throw "cargo build failed" }
54 # A workspace member: the binaries land in the workspace's target dir, not the crate's.
55 $target = (cargo metadata --format-version 1 --no-deps | ConvertFrom-Json).target_directory
56} finally { Pop-Location }
57$Ingest = Join-Path $target "release/gtfs_ingest.exe"
58$Shapes = Join-Path $target "release/transit_shapes.exe"
59
60# --- 2. Mirror -------------------------------------------------------------------------------
61# ONE host, fetched serially at a fixed rate. Do not parallelise: --limit-rate is per process, so
62# N downloads at once would put N times the load on a volunteer host. Each zip is re-fetched only
63# when upstream is newer than the copy on disk (-z), so a re-run pulls just what changed.
64if ($SkipMirror) {
65 Write-Host "=== [2/5] -SkipMirror: using the zips in $Mirror ==="
66} else {
67 Write-Host "=== [2/5] mirroring $IndexUrl -> $Mirror ==="
68 $index = curl.exe -sS --fail $IndexUrl
69 if ($LASTEXITCODE -ne 0) { throw "cannot read $IndexUrl" }
70 $names = [string[]]([regex]::Matches(($index -join "`n"), 'href="([^"/]+\.gtfs\.zip)"') | ForEach-Object { $_.Groups[1].Value } | Select-Object -Unique)
71 if (-not $names) { throw "$IndexUrl lists no .gtfs.zip files" }
72 $n = 0; $failed = 0
73 foreach ($name in $names) {
74 $n++
75 $dest = Join-Path $Mirror $name
76 $curlArgs = @("-sS", "--fail", "-R", "--limit-rate", "30M", "-o", $dest)
77 if (Test-Path $dest) { $curlArgs += @("-z", $dest) }
78 curl.exe @curlArgs "$IndexUrl$name"
79 # One server error must not lose a 2,000-feed build; the feed count below gates it.
80 if ($LASTEXITCODE -ne 0) { $failed++; Write-Warning "download failed: $name" }
81 Write-Progress -Activity "Mirror" -Status "$n / $($names.Count)" -PercentComplete (100 * $n / $names.Count)
82 }
83 Write-Progress -Activity "Mirror" -Completed
84 Write-Host " $($names.Count) zip(s) listed, $failed failed"
85}
86
87# --- 3. Unzip --------------------------------------------------------------------------------
88# lowercase, every run of non-alphanumerics one `_`: gtfs_ingest's registry::safe_name.
89function Get-SafeName([string] $s) { ($s.ToLowerInvariant() -replace '[^a-z0-9]+', '_').Trim('_') }
90
91Write-Host "=== [3/5] unzipping into $Gtfs ==="
92# Ordinal name order, so the manifest (and the feed order the pack is merged in) is stable.
93$zips = [string[]](Get-ChildItem $Mirror -Filter *.gtfs.zip -File | ForEach-Object Name)
94[Array]::Sort($zips, [StringComparer]::Ordinal)
95$feeds = $zips | ForEach-Object {
96 $stem = $_.Substring(0, $_.Length - ".gtfs.zip".Length)
97 $cut = $stem.IndexOf('_')
98 $safe = Get-SafeName $stem
99 if ($cut -lt 1 -or -not $safe) { Write-Warning "'$stem' has no <region>_<source> split; skipped"; return }
100 [pscustomobject]@{
101 Zip = Join-Path $Mirror $_
102 Name = $safe
103 Prefix = $stem.Substring(0, $cut) + "-" + $stem.Substring($cut + 1)
104 Dir = Join-Path $Gtfs $safe
105 }
106}
107$feeds | ForEach-Object -ThrottleLimit $Jobs -Parallel {
108 $f = $_
109 # The stamp names the zip a directory was unzipped from, so a zip the mirror refreshed is
110 # unzipped again. A directory with tables but no stamp predates stamps and is trusted.
111 $stops = Join-Path $f.Dir "stops.txt"
112 $stampFile = Join-Path $f.Dir ".unzipped"
113 $zip = Get-Item $f.Zip
114 $stamp = "$($zip.Length) $($zip.LastWriteTimeUtc.Ticks)"
115 if ((Test-Path $stops) -and (-not (Test-Path $stampFile) -or (Get-Content $stampFile) -eq $stamp)) { return }
116 if (Test-Path $f.Dir) { Remove-Item -Recurse -Force $f.Dir }
117 New-Item -ItemType Directory -Force -Path $f.Dir | Out-Null
118 tar.exe -xf $f.Zip -C $f.Dir 2>$null
119 if (-not (Test-Path $stops)) {
120 # Some feeds nest their tables one directory deep.
121 $inner = Get-ChildItem $f.Dir -Recurse -Filter stops.txt -File | Select-Object -First 1
122 if ($inner) { Get-ChildItem $inner.DirectoryName | Move-Item -Destination $f.Dir -Force }
123 }
124 if (Test-Path $stops) {
125 Set-Content -Path $stampFile -Value $stamp
126 } else {
127 Write-Warning "no stops.txt in $(Split-Path $f.Zip -Leaf); skipped"
128 Remove-Item -Recurse -Force $f.Dir
129 }
130}
131$usable = $feeds | Where-Object { Test-Path (Join-Path $_.Dir "stops.txt") }
132if (-not $usable) { throw "no usable feeds" }
133[System.IO.File]::WriteAllLines($Manifest, [string[]]($usable | ForEach-Object { "$($_.Name)=$($_.Dir)=$($_.Prefix)" }))
134Write-Host " $($usable.Count) feed(s) usable of $($feeds.Count), listed in $Manifest"
135
136# --- 4. Merge --------------------------------------------------------------------------------
137Write-Host "=== [4/5] merging into one pack ==="
138if (Test-Path $Staging) { Remove-Item -Recurse -Force $Staging }
139New-Item -ItemType Directory -Force -Path $Staging | Out-Null
140& $Ingest $Staging world --manifest $Manifest
141if ($LASTEXITCODE -ne 0) { throw "gtfs_ingest failed with exit code $LASTEXITCODE" }
142$pack = Join-Path $Staging "world.transit"
143
144# --- 5. Prove the pack stands in for the feeds, then install it -------------------------------
145if ($SkipVerify) {
146 Write-Host "=== [5/5] -SkipVerify: not checking the derived transit layer ==="
147} else {
148 Write-Host "=== [5/5] deriving the transit layer from the feeds and from the pack ==="
149 $fromFeeds = Join-Path $Staging "layer.feeds.geojsonseq"
150 $fromPack = Join-Path $Staging "layer.pack.geojsonseq"
151 & $Shapes $fromFeeds --manifest $Manifest
152 if ($LASTEXITCODE -ne 0) { throw "transit_shapes over the feeds failed" }
153 & $Shapes $fromPack --pack $pack
154 if ($LASTEXITCODE -ne 0) { throw "transit_shapes over the pack failed" }
155 if ((Get-FileHash $fromFeeds).Hash -ne (Get-FileHash $fromPack).Hash) {
156 throw "the pack does not reproduce the feeds' transit layer; inputs/world.transit was NOT replaced"
157 }
158 Write-Host " identical: the pack alone rebuilds the transit layer"
159 Remove-Item $fromFeeds, $fromPack
160}
161Move-Item -Force $pack (Join-Path $Inputs "world.transit")
162Move-Item -Force "$pack.json" (Join-Path $Inputs "world.transit.json")
163Remove-Item -Recurse -Force $Staging
164Get-Content (Join-Path $Inputs "world.transit.json") | Select-Object -First 16
165Write-Host "Done: $(Join-Path $Inputs 'world.transit'). $Work is no longer needed by build_graph.ps1."