diff --git a/README.md b/README.md index bbd1f8c..39768f2 100644 --- a/README.md +++ b/README.md @@ -58,8 +58,18 @@ docker compose up -d --build | `GET` | `/u/{slug}/graph/{source}/edges?bbox=&token=` | рёбра в bbox | | `GET` | `/api/v1/sources` | extract’ы и статус воркера | | `PUT` | `/api/v1/sources/{id}` | добавить регион (ещё одна ссылка на PBF) | -| `POST` | `/api/v1/sync` | прогнать все extract’ы сейчас | -| `POST` | `/api/v1/sync/{id}` | прогнать один extract | +| `POST` | `/api/v1/sync?rebuildGraph=` | прогнать все extract’ы сейчас | +| `POST` | `/api/v1/sync/{id}?rebuildGraph=` | прогнать один extract | + +Скрипт `scripts/sync-all-sources.sh` ждёт воркер и печатает статусы. Для полилиний графа: + +```bash +API=https://tile-server.ru ./scripts/sync-all-sources.sh --rebuild-graph +# локальный compose: +API=http://127.0.0.1:51300 ./scripts/sync-all-sources.sh --rebuild-graph +``` + +`rebuildGraph=true` пересобирает `graphs/{id}.sqlite`, тайлы не трогает, если они уже Ready. Публичные `/api/v1/tiles` и `/api/v1/styles` закрыты (401). Граф — только по токену. MVT графа: слой `roads`, z 6–14 (ниже z12 только крупные highway, с z12 все улицы; полилиния после пересборки графа). JSON `bbox=minLon,minLat,maxLon,maxLat`, сторона ≤ 2°. Выключается: `TileServer:BuildRoadGraph=false`. diff --git a/context/2026-09-21_14-10-00_sync-all-sources-script.md b/context/2026-09-21_14-10-00_sync-all-sources-script.md new file mode 100644 index 0000000..8607196 --- /dev/null +++ b/context/2026-09-21_14-10-00_sync-all-sources-script.md @@ -0,0 +1,9 @@ +# Script: sync all sources + +Date: 2026-09-21 + +## What + +`scripts/sync-all-sources.sh` POSTs `/api/v1/sync`, polls until the worker is idle, prints extract status. `--rebuild-graph` → `?rebuildGraph=true` so Ready extracts still rebuild `graphs/{id}.sqlite` (polyline geom) without forcing Planetiler. + +API: `IMapSyncService.RunAllAsync/RunOneAsync(..., rebuildGraph)`. diff --git a/scripts/sync-all-sources.sh b/scripts/sync-all-sources.sh new file mode 100644 index 0000000..ee3f34b --- /dev/null +++ b/scripts/sync-all-sources.sh @@ -0,0 +1,144 @@ +#!/usr/bin/env bash +# Kick off OSM extract sync for every enabled source, wait until the worker is idle, +# then print per-source status. +# +# Usage: +# ./scripts/sync-all-sources.sh +# ./scripts/sync-all-sources.sh --rebuild-graph +# API=http://127.0.0.1:51300 ./scripts/sync-all-sources.sh --rebuild-graph +# +# --rebuild-graph rebuilds graphs/{id}.sqlite even if tiles are already Ready +# (needed after geom/polyline changes). Does not rebuild MBTiles +# unless the extract would rebuild them anyway. +set -euo pipefail + +API="${API:-${TILE_SERVER_API:-https://tile-server.ru}}" +API="${API%/}" +POLL="${POLL:-20}" +REBUILD_GRAPH=0 + +usage() { + sed -n '2,14p' "$0" | sed 's/^# \{0,1\}//' +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --rebuild-graph|-g) REBUILD_GRAPH=1 ;; + --api) API="${2%/}"; shift ;; + --poll) POLL="$2"; shift ;; + -h|--help) usage; exit 0 ;; + *) + echo "Unknown argument: $1" >&2 + usage >&2 + exit 2 + ;; + esac + shift +done + +py() { + if command -v python3 >/dev/null 2>&1; then + python3 "$@" + elif command -v python >/dev/null 2>&1; then + python "$@" + elif command -v py >/dev/null 2>&1; then + py -3 "$@" + else + echo "Need python3 to parse JSON." >&2 + exit 1 + fi +} + +json_field() { + py -c 'import json,sys; d=json.load(sys.stdin); print(d.get(sys.argv[1], "") if d is not None else "")' "$1" +} + +is_running() { + local body + body="$(curl -fsS "$API/api/v1/sync/status")" + printf '%s' "$body" | json_field isRunning | grep -qi '^true$' +} + +print_sources() { + curl -fsS "$API/api/v1/sources" | py -c ' +import json, sys +rows = json.load(sys.stdin) +print("{:<32} {:<16} {:<6} {}".format("id", "status", "graph", "error")) +print("-" * 88) +for item in rows: + if not item.get("enabled", True): + continue + err = (item.get("lastError") or "").replace("\n", " ")[:60] + graph = "yes" if item.get("graphReady") else "no" + print("{:<32} {:<16} {:<6} {}".format(item.get("id", ""), item.get("status", ""), graph, err)) +' +} + +wait_idle() { + local reason="$1" + if ! is_running; then + return 0 + fi + echo "Worker is busy ($reason). Polling every ${POLL}s…" + while is_running; do + print_sources || true + echo + sleep "$POLL" + done +} + +echo "API $API" +echo "Mode $([[ "$REBUILD_GRAPH" -eq 1 ]] && echo rebuild-graph || echo normal)" +echo + +echo "Sources before:" +print_sources +echo + +wait_idle "previous job" + +query="" +if [[ "$REBUILD_GRAPH" -eq 1 ]]; then + query="?rebuildGraph=true" +fi + +echo "POST $API/api/v1/sync$query" +http="$(curl -sS -o /tmp/tile-sync-body.json -w '%{http_code}' -X POST "$API/api/v1/sync$query")" +body="$(cat /tmp/tile-sync-body.json 2>/dev/null || true)" +echo "HTTP $http $body" + +if [[ "$http" == "409" ]]; then + echo "Conflict — waiting for the running job, then retrying once." + wait_idle "409" + http="$(curl -sS -o /tmp/tile-sync-body.json -w '%{http_code}' -X POST "$API/api/v1/sync$query")" + body="$(cat /tmp/tile-sync-body.json 2>/dev/null || true)" + echo "HTTP $http $body" +fi + +if [[ "$http" != "202" ]]; then + echo "Failed to start sync." >&2 + exit 1 +fi + +# Give Kestrel a moment to flip isRunning. +sleep 2 +wait_idle "this job" + +echo +echo "Sources after:" +print_sources + +failed="$(curl -fsS "$API/api/v1/sources" | py -c ' +import json, sys +rows = json.load(sys.stdin) +ids = [r["id"] for r in rows if r.get("enabled", True) and r.get("status") == "Failed"] +print(" ".join(ids)) +')" +if [[ -n "${failed// }" ]]; then + echo >&2 + echo "Failed extracts: $failed" >&2 + exit 1 +fi + +echo +echo "All enabled extracts are not Failed." diff --git a/src/TileServer.Api/Controllers/SyncController.cs b/src/TileServer.Api/Controllers/SyncController.cs index 17e3d1b..c257a4a 100644 --- a/src/TileServer.Api/Controllers/SyncController.cs +++ b/src/TileServer.Api/Controllers/SyncController.cs @@ -15,14 +15,22 @@ public sealed class SyncController(IMapSyncService sync, ILogger [HttpPost] [ProducesResponseType(StatusCodes.Status202Accepted)] [ProducesResponseType(StatusCodes.Status409Conflict)] - public IActionResult RunAll() - => Start(() => sync.RunAllAsync(CancellationToken.None), "Synchronization started for all extracts."); + public IActionResult RunAll([FromQuery] bool rebuildGraph = false) + => Start( + () => sync.RunAllAsync(CancellationToken.None, rebuildGraph), + rebuildGraph + ? "Synchronization started for all extracts (rebuild graph)." + : "Synchronization started for all extracts."); [HttpPost("{extractId}")] [ProducesResponseType(StatusCodes.Status202Accepted)] [ProducesResponseType(StatusCodes.Status409Conflict)] - public IActionResult RunOne(string extractId) - => Start(() => sync.RunOneAsync(extractId, CancellationToken.None), $"Synchronization started for '{extractId}'."); + public IActionResult RunOne(string extractId, [FromQuery] bool rebuildGraph = false) + => Start( + () => sync.RunOneAsync(extractId, CancellationToken.None, rebuildGraph), + rebuildGraph + ? $"Synchronization started for '{extractId}' (rebuild graph)." + : $"Synchronization started for '{extractId}'."); private IActionResult Start(Func work, string message) { diff --git a/src/TileServer.Application/Sync/IMapSyncService.cs b/src/TileServer.Application/Sync/IMapSyncService.cs index d6da38c..074221e 100644 --- a/src/TileServer.Application/Sync/IMapSyncService.cs +++ b/src/TileServer.Application/Sync/IMapSyncService.cs @@ -9,9 +9,9 @@ public sealed record SyncJobStatus( public interface IMapSyncService { - Task RunAllAsync(CancellationToken ct); + Task RunAllAsync(CancellationToken ct, bool rebuildGraph = false); - Task RunOneAsync(string extractId, CancellationToken ct); + Task RunOneAsync(string extractId, CancellationToken ct, bool rebuildGraph = false); SyncJobStatus GetStatus(); diff --git a/src/TileServer.Application/Sync/MapSyncService.cs b/src/TileServer.Application/Sync/MapSyncService.cs index 710a3c7..2e71a6f 100644 --- a/src/TileServer.Application/Sync/MapSyncService.cs +++ b/src/TileServer.Application/Sync/MapSyncService.cs @@ -53,7 +53,7 @@ public sealed class MapSyncService( } } - public async Task RunAllAsync(CancellationToken ct) + public async Task RunAllAsync(CancellationToken ct, bool rebuildGraph = false) { if (!await _gate.WaitAsync(0, ct).ConfigureAwait(false)) { @@ -71,11 +71,14 @@ public sealed class MapSyncService( return; } - logger.LogInformation("Starting sync for {Count} OSM extract(s).", extracts.Length); + logger.LogInformation( + "Starting sync for {Count} OSM extract(s) (rebuildGraph={RebuildGraph}).", + extracts.Length, + rebuildGraph); foreach (var extract in extracts) { ct.ThrowIfCancellationRequested(); - await SyncExtractAsync(extract, ct).ConfigureAwait(false); + await SyncExtractAsync(extract, rebuildGraph, ct).ConfigureAwait(false); } Finish(null); @@ -97,7 +100,7 @@ public sealed class MapSyncService( } } - public async Task RunOneAsync(string extractId, CancellationToken ct) + public async Task RunOneAsync(string extractId, CancellationToken ct, bool rebuildGraph = false) { var extract = catalog.GetRequired(extractId); if (!await _gate.WaitAsync(0, ct).ConfigureAwait(false)) @@ -108,7 +111,7 @@ public sealed class MapSyncService( try { Begin(); - await SyncExtractAsync(extract, ct).ConfigureAwait(false); + await SyncExtractAsync(extract, rebuildGraph, ct).ConfigureAwait(false); Finish(null); } catch (OperationCanceledException) @@ -128,7 +131,7 @@ public sealed class MapSyncService( } } - private async Task SyncExtractAsync(Extract extract, CancellationToken ct) + private async Task SyncExtractAsync(Extract extract, bool rebuildGraph, CancellationToken ct) { var state = await stateStore.GetAsync(extract.Id, ct).ConfigureAwait(false); var pbfPath = dataPaths.OsmPbf(extract.Id); @@ -159,7 +162,7 @@ public sealed class MapSyncService( || (tilesMissing && options.Value.Sync.RebuildIfTilesMissing) || zoomRaised; var shouldBuildGraph = options.Value.BuildRoadGraph - && (shouldBuildTiles || graphMissing || previousStatus == ExtractSyncState.Failed); + && (shouldBuildTiles || graphMissing || previousStatus == ExtractSyncState.Failed || rebuildGraph); if (!shouldBuildTiles && !shouldBuildGraph) { @@ -169,6 +172,11 @@ public sealed class MapSyncService( return; } + if (rebuildGraph && !shouldBuildTiles) + { + logger.LogInformation("Rebuilding road graph for {ExtractId}: requested by API.", extract.Id); + } + if (zoomRaised) { logger.LogInformation( diff --git a/web-demo/src/App.tsx b/web-demo/src/App.tsx index 1712135..3b6f15d 100644 --- a/web-demo/src/App.tsx +++ b/web-demo/src/App.tsx @@ -128,7 +128,7 @@ function styleWithGraph(style: StyleSpecification, access: Access, extracts: Sou "source-layer": "roads", layout: { "line-cap": "round", "line-join": "round" }, paint: { - "line-color": "#ffb45a", + "line-color": "#0004ff", "line-width": ["interpolate", ["linear"], ["zoom"], 6, 1, 10, 2, 14, 3.6], "line-opacity": 1 }