fix(graph): resync

This commit is contained in:
vl.arkhangelskii
2026-09-21 14:08:00 +03:00
parent 2bbd4c4ca1
commit dd4b2924ee
7 changed files with 195 additions and 16 deletions
+12 -2
View File
@@ -58,8 +58,18 @@ docker compose up -d --build
| `GET` | `/u/{slug}/graph/{source}/edges?bbox=&token=` | рёбра в bbox | | `GET` | `/u/{slug}/graph/{source}/edges?bbox=&token=` | рёбра в bbox |
| `GET` | `/api/v1/sources` | extract’ы и статус воркера | | `GET` | `/api/v1/sources` | extract’ы и статус воркера |
| `PUT` | `/api/v1/sources/{id}` | добавить регион (ещё одна ссылка на PBF) | | `PUT` | `/api/v1/sources/{id}` | добавить регион (ещё одна ссылка на PBF) |
| `POST` | `/api/v1/sync` | прогнать все extract’ы сейчас | | `POST` | `/api/v1/sync?rebuildGraph=` | прогнать все extract’ы сейчас |
| `POST` | `/api/v1/sync/{id}` | прогнать один 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`. Публичные `/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`.
@@ -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)`.
+144
View File
@@ -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."
@@ -15,14 +15,22 @@ public sealed class SyncController(IMapSyncService sync, ILogger<SyncController>
[HttpPost] [HttpPost]
[ProducesResponseType(StatusCodes.Status202Accepted)] [ProducesResponseType(StatusCodes.Status202Accepted)]
[ProducesResponseType(StatusCodes.Status409Conflict)] [ProducesResponseType(StatusCodes.Status409Conflict)]
public IActionResult RunAll() public IActionResult RunAll([FromQuery] bool rebuildGraph = false)
=> Start(() => sync.RunAllAsync(CancellationToken.None), "Synchronization started for all extracts."); => Start(
() => sync.RunAllAsync(CancellationToken.None, rebuildGraph),
rebuildGraph
? "Synchronization started for all extracts (rebuild graph)."
: "Synchronization started for all extracts.");
[HttpPost("{extractId}")] [HttpPost("{extractId}")]
[ProducesResponseType(StatusCodes.Status202Accepted)] [ProducesResponseType(StatusCodes.Status202Accepted)]
[ProducesResponseType(StatusCodes.Status409Conflict)] [ProducesResponseType(StatusCodes.Status409Conflict)]
public IActionResult RunOne(string extractId) public IActionResult RunOne(string extractId, [FromQuery] bool rebuildGraph = false)
=> Start(() => sync.RunOneAsync(extractId, CancellationToken.None), $"Synchronization started for '{extractId}'."); => Start(
() => sync.RunOneAsync(extractId, CancellationToken.None, rebuildGraph),
rebuildGraph
? $"Synchronization started for '{extractId}' (rebuild graph)."
: $"Synchronization started for '{extractId}'.");
private IActionResult Start(Func<Task> work, string message) private IActionResult Start(Func<Task> work, string message)
{ {
@@ -9,9 +9,9 @@ public sealed record SyncJobStatus(
public interface IMapSyncService 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(); SyncJobStatus GetStatus();
@@ -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)) if (!await _gate.WaitAsync(0, ct).ConfigureAwait(false))
{ {
@@ -71,11 +71,14 @@ public sealed class MapSyncService(
return; 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) foreach (var extract in extracts)
{ {
ct.ThrowIfCancellationRequested(); ct.ThrowIfCancellationRequested();
await SyncExtractAsync(extract, ct).ConfigureAwait(false); await SyncExtractAsync(extract, rebuildGraph, ct).ConfigureAwait(false);
} }
Finish(null); 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); var extract = catalog.GetRequired(extractId);
if (!await _gate.WaitAsync(0, ct).ConfigureAwait(false)) if (!await _gate.WaitAsync(0, ct).ConfigureAwait(false))
@@ -108,7 +111,7 @@ public sealed class MapSyncService(
try try
{ {
Begin(); Begin();
await SyncExtractAsync(extract, ct).ConfigureAwait(false); await SyncExtractAsync(extract, rebuildGraph, ct).ConfigureAwait(false);
Finish(null); Finish(null);
} }
catch (OperationCanceledException) 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 state = await stateStore.GetAsync(extract.Id, ct).ConfigureAwait(false);
var pbfPath = dataPaths.OsmPbf(extract.Id); var pbfPath = dataPaths.OsmPbf(extract.Id);
@@ -159,7 +162,7 @@ public sealed class MapSyncService(
|| (tilesMissing && options.Value.Sync.RebuildIfTilesMissing) || (tilesMissing && options.Value.Sync.RebuildIfTilesMissing)
|| zoomRaised; || zoomRaised;
var shouldBuildGraph = options.Value.BuildRoadGraph var shouldBuildGraph = options.Value.BuildRoadGraph
&& (shouldBuildTiles || graphMissing || previousStatus == ExtractSyncState.Failed); && (shouldBuildTiles || graphMissing || previousStatus == ExtractSyncState.Failed || rebuildGraph);
if (!shouldBuildTiles && !shouldBuildGraph) if (!shouldBuildTiles && !shouldBuildGraph)
{ {
@@ -169,6 +172,11 @@ public sealed class MapSyncService(
return; return;
} }
if (rebuildGraph && !shouldBuildTiles)
{
logger.LogInformation("Rebuilding road graph for {ExtractId}: requested by API.", extract.Id);
}
if (zoomRaised) if (zoomRaised)
{ {
logger.LogInformation( logger.LogInformation(
+1 -1
View File
@@ -128,7 +128,7 @@ function styleWithGraph(style: StyleSpecification, access: Access, extracts: Sou
"source-layer": "roads", "source-layer": "roads",
layout: { "line-cap": "round", "line-join": "round" }, layout: { "line-cap": "round", "line-join": "round" },
paint: { paint: {
"line-color": "#ffb45a", "line-color": "#0004ff",
"line-width": ["interpolate", ["linear"], ["zoom"], 6, 1, 10, 2, 14, 3.6], "line-width": ["interpolate", ["linear"], ["zoom"], 6, 1, 10, 2, 14, 3.6],
"line-opacity": 1 "line-opacity": 1
} }