diff --git a/README.md b/README.md
index d4c6285..0efbad4 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,8 @@ ASP.NET Core сервер векторных тайлов для клиенто
1. Скачивает все настроенные OSM-extract’ы с Geofabrik (и любых других HTTP-ссылок на `.osm.pbf`).
2. Собирает из них OpenMapTiles MBTiles через [planetiler-openmaptiles](https://github.com/openmaptiles/planetiler-openmaptiles).
-3. Отдаёт тайлы, TileJSON и стили карты.
+3. Параллельно (после тайлов или если графа ещё нет) строит лёгкий граф дорог `data/graphs/{id}.sqlite` из того же PBF.
+4. Отдаёт тайлы, стили и граф по персональному токену.
## Что нужно
@@ -48,18 +49,17 @@ docker compose up -d --build
| Метод | URL | Назначение |
| --- | --- | --- |
-| `GET` | `/api/v1/tiles/{source}/{z}/{x}/{y}.pbf` | векторный тайл (MapLibre XYZ) |
-| `GET` | `/api/v1/tiles/{source}.json` | TileJSON |
-| `GET` | `/api/v1/styles` | список стилей |
-| `GET` | `/api/v1/styles/{name}?source={source}` | MapLibre style JSON |
-| `PUT` | `/api/v1/styles/{name}` | добавить/обновить стиль |
+| `GET` | `/u/{slug}/tiles/{source}/{z}/{x}/{y}.pbf?token=` | персональные тайлы |
+| `GET` | `/u/{slug}/styles/{name}?source=&token=` | персональный стиль |
+| `GET` | `/u/{slug}/graph/{source}?token=` | метаданные графа дорог |
+| `GET` | `/u/{slug}/graph/{source}/nodes?bbox=&token=` | узлы в bbox (пагинация `after`) |
+| `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 |
-| `GET` | `/` | демо MapLibre |
-Алиасы без `/api/v1`: `/tiles/{source}/{z}/{x}/{y}.pbf`.
+Публичные `/api/v1/tiles` и `/api/v1/styles` закрыты (401). Граф — только по токену. `bbox=minLon,minLat,maxLon,maxLat`, сторона ≤ 2°. Выключается: `TileServer:BuildRoadGraph=false`.
## Несколько регионов
diff --git a/context/2026-09-21_11-00-00_osm-road-graph-feasibility.md b/context/2026-09-21_11-00-00_osm-road-graph-feasibility.md
new file mode 100644
index 0000000..71d2826
--- /dev/null
+++ b/context/2026-09-21_11-00-00_osm-road-graph-feasibility.md
@@ -0,0 +1,3 @@
+# Вопрос: граф дорог из OSM при sync
+
+Можно. Источник — тот же `.osm.pbf`, не MBTiles (тайлы режут топологию). Параллельный артефакт на sync: узлы/рёбра `highway=*`. Варианты: свой граф (OsmSharp/Osmium), Valhalla/OSRM/GraphHopper. На ЦФО/СЗФО — отдельный CPU/RAM бюджет, не в том же JVM что Planetiler.
diff --git a/context/2026-09-21_11-10-00_road-graph-sync-api.md b/context/2026-09-21_11-10-00_road-graph-sync-api.md
new file mode 100644
index 0000000..5f182df
--- /dev/null
+++ b/context/2026-09-21_11-10-00_road-graph-sync-api.md
@@ -0,0 +1,10 @@
+# 2026-09-21 — Road graph из PBF + personal API
+
+На sync после (или вместо только) тайлов: OsmSharp two-pass → `data/graphs/{id}.sqlite` (nodes/edges, highway motorway…service, рёбра между перекрёстками, length_m, oneway).
+
+API (токен как у тайлов):
+- `GET /u/{slug}/graph/{source}?token=`
+- `GET /u/{slug}/graph/{source}/nodes?bbox=&after=&limit=`
+- `GET /u/{slug}/graph/{source}/edges?bbox=&after=&limit=`
+
+bbox ≤ 2°. `TileServer:BuildRoadGraph` (compose/env). Если тайлы уже есть, а графа нет — rebuild только графа. Instruct + README.
diff --git a/docker-compose.yml b/docker-compose.yml
index 26a696b..8a85067 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -61,6 +61,7 @@ services:
TileServer__JvmMaxHeap: 4g
TileServer__PlanetilerThreads: "8"
TileServer__PlanetilerMmapTemp: "false"
+ TileServer__BuildRoadGraph: "true"
TileServer__Sync__RunOnStartup: "true"
TileServer__Sync__Cron: "0 3 * * *"
TileServer__Sync__TimeZone: UTC
diff --git a/src/TileServer.Api/Controllers/PersonalDeliveryController.cs b/src/TileServer.Api/Controllers/PersonalDeliveryController.cs
index d2cbe9c..86d43cd 100644
--- a/src/TileServer.Api/Controllers/PersonalDeliveryController.cs
+++ b/src/TileServer.Api/Controllers/PersonalDeliveryController.cs
@@ -1,3 +1,4 @@
+using System.Globalization;
using System.Text;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -6,9 +7,11 @@ using TileServer.Api.Http;
using TileServer.Application.Accounts;
using TileServer.Application.Configuration;
using TileServer.Application.Extracts;
+using TileServer.Application.Graph;
using TileServer.Application.Styles;
using TileServer.Application.Tiles;
using TileServer.Domain.Exceptions;
+using TileServer.Domain.Graph;
using TileServer.Domain.Tiles;
namespace TileServer.Api.Controllers;
@@ -20,6 +23,7 @@ public sealed class PersonalDeliveryController(
IApiTokenService tokens,
ITileQueryService tiles,
IUserStyleService styles,
+ IRoadGraphQueryService graphs,
IExtractCatalog extracts,
IUsageRecorder usage,
IOptions options) : ControllerBase
@@ -92,6 +96,86 @@ public sealed class PersonalDeliveryController(
return new JsonResult(style);
}
+ [HttpGet("graph/{source}")]
+ [Produces("application/json")]
+ public async Task GetGraph(string slug, string source, CancellationToken ct)
+ {
+ var access = await ResolveAsync(slug, ct).ConfigureAwait(false);
+ var token = AccessToken.Read(Request) ?? string.Empty;
+ var meta = graphs.GetMetadata(source);
+ var root = PublicUrl.GetBase(Request, options);
+ var escaped = Uri.EscapeDataString(token);
+ var payload = new
+ {
+ extractId = meta.ExtractId,
+ nodeCount = meta.NodeCount,
+ edgeCount = meta.EdgeCount,
+ bounds = meta.Bounds,
+ builtAt = meta.BuiltAt,
+ links = new
+ {
+ nodes = $"{root}/u/{access.User.Slug}/graph/{source}/nodes?bbox={{minLon}},{{minLat}},{{maxLon}},{{maxLat}}&token={escaped}",
+ edges = $"{root}/u/{access.User.Slug}/graph/{source}/edges?bbox={{minLon}},{{minLat}},{{maxLon}},{{maxLat}}&token={escaped}"
+ }
+ };
+ usage.RecordGraph(access.User.Id, access.Token.Id, Encoding.UTF8.GetByteCount(System.Text.Json.JsonSerializer.Serialize(payload)));
+ return Ok(payload);
+ }
+
+ [HttpGet("graph/{source}/nodes")]
+ [Produces("application/json")]
+ public async Task GetGraphNodes(
+ string slug,
+ string source,
+ [FromQuery] string bbox,
+ [FromQuery] long after = 0,
+ [FromQuery] int limit = RoadGraphQueryService.DefaultLimit,
+ CancellationToken ct = default)
+ {
+ var access = await ResolveAsync(slug, ct).ConfigureAwait(false);
+ var page = await graphs.GetNodesAsync(source, ParseBbox(bbox), after, limit, ct).ConfigureAwait(false);
+ usage.RecordGraph(access.User.Id, access.Token.Id, EstimatePageBytes(page.Items.Count));
+ return Ok(page);
+ }
+
+ [HttpGet("graph/{source}/edges")]
+ [Produces("application/json")]
+ public async Task GetGraphEdges(
+ string slug,
+ string source,
+ [FromQuery] string bbox,
+ [FromQuery] long after = 0,
+ [FromQuery] int limit = RoadGraphQueryService.DefaultLimit,
+ CancellationToken ct = default)
+ {
+ var access = await ResolveAsync(slug, ct).ConfigureAwait(false);
+ var page = await graphs.GetEdgesAsync(source, ParseBbox(bbox), after, limit, ct).ConfigureAwait(false);
+ usage.RecordGraph(access.User.Id, access.Token.Id, EstimatePageBytes(page.Items.Count));
+ return Ok(page);
+ }
+
private Task ResolveAsync(string slug, CancellationToken ct)
=> tokens.ResolveAsync(slug, AccessToken.Read(Request), bearer: null, ct);
+
+ private static RoadGraphBounds ParseBbox(string? bbox)
+ {
+ if (string.IsNullOrWhiteSpace(bbox))
+ {
+ throw new DomainValidationException("Query parameter 'bbox' is required (minLon,minLat,maxLon,maxLat).");
+ }
+
+ var parts = bbox.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
+ if (parts.Length != 4
+ || !double.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out var minLon)
+ || !double.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var minLat)
+ || !double.TryParse(parts[2], NumberStyles.Float, CultureInfo.InvariantCulture, out var maxLon)
+ || !double.TryParse(parts[3], NumberStyles.Float, CultureInfo.InvariantCulture, out var maxLat))
+ {
+ throw new DomainValidationException("bbox must be minLon,minLat,maxLon,maxLat.");
+ }
+
+ return new RoadGraphBounds(minLon, minLat, maxLon, maxLat);
+ }
+
+ private static long EstimatePageBytes(int itemCount) => Math.Max(256, itemCount * 64L);
}
diff --git a/src/TileServer.Api/appsettings.json b/src/TileServer.Api/appsettings.json
index 0d154eb..04a224c 100644
--- a/src/TileServer.Api/appsettings.json
+++ b/src/TileServer.Api/appsettings.json
@@ -30,6 +30,7 @@
"DefaultMinZoom": 0,
"DefaultMaxZoom": 15,
"OverzoomMaxZoom": 18,
+ "BuildRoadGraph": true,
"GlyphsUrl": "https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf",
"Yandex": {
"RedirectUri": "https://tile-server.ru"
diff --git a/src/TileServer.Application/Accounts/IUsageRecorder.cs b/src/TileServer.Application/Accounts/IUsageRecorder.cs
index 26c2321..de71e3d 100644
--- a/src/TileServer.Application/Accounts/IUsageRecorder.cs
+++ b/src/TileServer.Application/Accounts/IUsageRecorder.cs
@@ -6,6 +6,8 @@ public interface IUsageRecorder
void RecordStyle(Guid userId, Guid tokenId, long bytes);
+ void RecordGraph(Guid userId, Guid tokenId, long bytes);
+
IReadOnlyList Drain();
}
diff --git a/src/TileServer.Application/Accounts/UsageAccumulator.cs b/src/TileServer.Application/Accounts/UsageAccumulator.cs
index 459dd68..61eaafd 100644
--- a/src/TileServer.Application/Accounts/UsageAccumulator.cs
+++ b/src/TileServer.Application/Accounts/UsageAccumulator.cs
@@ -12,6 +12,9 @@ public sealed class UsageAccumulator : IUsageRecorder
public void RecordStyle(Guid userId, Guid tokenId, long bytes)
=> Record(userId, tokenId, tileRequests: 0, styleRequests: 1, bytes);
+ public void RecordGraph(Guid userId, Guid tokenId, long bytes)
+ => Record(userId, tokenId, tileRequests: 0, styleRequests: 0, bytes);
+
public void Restore(UsageDelta delta)
=> Record(delta.UserId, delta.TokenId, delta.TileRequests, delta.StyleRequests, delta.Bytes);
diff --git a/src/TileServer.Application/Configuration/TileServerOptions.cs b/src/TileServer.Application/Configuration/TileServerOptions.cs
index e539964..2b75910 100644
--- a/src/TileServer.Application/Configuration/TileServerOptions.cs
+++ b/src/TileServer.Application/Configuration/TileServerOptions.cs
@@ -108,6 +108,9 @@ public sealed class TileServerOptions
public SyncOptions Sync { get; set; } = new();
+ /// Build a light highway graph (SQLite) from each PBF during sync.
+ public bool BuildRoadGraph { get; set; } = true;
+
public YandexOAuthOptions Yandex { get; set; } = new();
public List Extracts { get; set; } = [];
diff --git a/src/TileServer.Application/DependencyInjection.cs b/src/TileServer.Application/DependencyInjection.cs
index 0b1712a..d4dcbba 100644
--- a/src/TileServer.Application/DependencyInjection.cs
+++ b/src/TileServer.Application/DependencyInjection.cs
@@ -1,6 +1,7 @@
using Microsoft.Extensions.DependencyInjection;
using TileServer.Application.Accounts;
using TileServer.Application.Extracts;
+using TileServer.Application.Graph;
using TileServer.Application.Styles;
using TileServer.Application.Sync;
using TileServer.Application.Tiles;
@@ -14,6 +15,7 @@ public static class DependencyInjection
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
+ services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton(sp => sp.GetRequiredService());
diff --git a/src/TileServer.Application/Graph/IRoadGraph.cs b/src/TileServer.Application/Graph/IRoadGraph.cs
new file mode 100644
index 0000000..218f3d5
--- /dev/null
+++ b/src/TileServer.Application/Graph/IRoadGraph.cs
@@ -0,0 +1,55 @@
+using TileServer.Domain.Extracts;
+using TileServer.Domain.Graph;
+
+namespace TileServer.Application.Graph;
+
+public interface IRoadGraphBuilder
+{
+ Task BuildAsync(Extract extract, string osmPbfPath, string outputSqlitePath, CancellationToken ct);
+}
+
+public interface IRoadGraphStore
+{
+ bool Exists(string extractId);
+
+ string GetActivePath(string extractId);
+
+ string GetStagingPath(string extractId);
+
+ void Activate(string extractId, string stagingPath);
+
+ RoadGraphMetadata? GetMetadata(string extractId);
+
+ Task> QueryNodesAsync(
+ string extractId,
+ RoadGraphBounds bounds,
+ long afterId,
+ int limit,
+ CancellationToken ct);
+
+ Task> QueryEdgesAsync(
+ string extractId,
+ RoadGraphBounds bounds,
+ long afterId,
+ int limit,
+ CancellationToken ct);
+}
+
+public interface IRoadGraphQueryService
+{
+ RoadGraphMetadata GetMetadata(string extractId);
+
+ Task> GetNodesAsync(
+ string extractId,
+ RoadGraphBounds bounds,
+ long afterId,
+ int limit,
+ CancellationToken ct);
+
+ Task> GetEdgesAsync(
+ string extractId,
+ RoadGraphBounds bounds,
+ long afterId,
+ int limit,
+ CancellationToken ct);
+}
diff --git a/src/TileServer.Application/Graph/RoadGraphQueryService.cs b/src/TileServer.Application/Graph/RoadGraphQueryService.cs
new file mode 100644
index 0000000..9097d43
--- /dev/null
+++ b/src/TileServer.Application/Graph/RoadGraphQueryService.cs
@@ -0,0 +1,83 @@
+using TileServer.Domain.Exceptions;
+using TileServer.Domain.Graph;
+
+namespace TileServer.Application.Graph;
+
+public sealed class RoadGraphQueryService(IRoadGraphStore store) : IRoadGraphQueryService
+{
+ public const int DefaultLimit = 5_000;
+ public const int MaxLimit = 20_000;
+ public const double MaxBboxSpanDegrees = 2.0;
+
+ public RoadGraphMetadata GetMetadata(string extractId)
+ {
+ var meta = store.GetMetadata(extractId);
+ if (meta is null)
+ {
+ throw new ResourceNotFoundException("RoadGraph", extractId);
+ }
+
+ return meta;
+ }
+
+ public Task> GetNodesAsync(
+ string extractId,
+ RoadGraphBounds bounds,
+ long afterId,
+ int limit,
+ CancellationToken ct)
+ {
+ EnsureExists(extractId);
+ ValidateBounds(bounds);
+ return store.QueryNodesAsync(extractId, bounds, Math.Max(0, afterId), ClampLimit(limit), ct);
+ }
+
+ public Task> GetEdgesAsync(
+ string extractId,
+ RoadGraphBounds bounds,
+ long afterId,
+ int limit,
+ CancellationToken ct)
+ {
+ EnsureExists(extractId);
+ ValidateBounds(bounds);
+ return store.QueryEdgesAsync(extractId, bounds, Math.Max(0, afterId), ClampLimit(limit), ct);
+ }
+
+ private void EnsureExists(string extractId)
+ {
+ if (!store.Exists(extractId))
+ {
+ throw new ResourceNotFoundException("RoadGraph", extractId);
+ }
+ }
+
+ private static int ClampLimit(int limit)
+ {
+ if (limit <= 0)
+ {
+ return DefaultLimit;
+ }
+
+ return Math.Min(limit, MaxLimit);
+ }
+
+ internal static void ValidateBounds(RoadGraphBounds bounds)
+ {
+ if (bounds.MinLon >= bounds.MaxLon || bounds.MinLat >= bounds.MaxLat)
+ {
+ throw new DomainValidationException("bbox must be minLon,minLat,maxLon,maxLat with positive span.");
+ }
+
+ if (bounds.MinLon < -180 || bounds.MaxLon > 180 || bounds.MinLat < -90 || bounds.MaxLat > 90)
+ {
+ throw new DomainValidationException("bbox coordinates are out of range.");
+ }
+
+ if (bounds.MaxLon - bounds.MinLon > MaxBboxSpanDegrees || bounds.MaxLat - bounds.MinLat > MaxBboxSpanDegrees)
+ {
+ throw new DomainValidationException(
+ $"bbox span must be ≤ {MaxBboxSpanDegrees:0.#}° on each axis (paginate with after=).");
+ }
+ }
+}
diff --git a/src/TileServer.Application/IDataPaths.cs b/src/TileServer.Application/IDataPaths.cs
index d0d0d8c..f06aac0 100644
--- a/src/TileServer.Application/IDataPaths.cs
+++ b/src/TileServer.Application/IDataPaths.cs
@@ -28,5 +28,11 @@ public interface IDataPaths
string StagingMbtiles(string extractId);
+ string Graphs { get; }
+
+ string RoadGraph(string extractId);
+
+ string StagingRoadGraph(string extractId);
+
void EnsureCreated();
}
diff --git a/src/TileServer.Application/Sync/MapSyncService.cs b/src/TileServer.Application/Sync/MapSyncService.cs
index adf231c..710a3c7 100644
--- a/src/TileServer.Application/Sync/MapSyncService.cs
+++ b/src/TileServer.Application/Sync/MapSyncService.cs
@@ -3,6 +3,7 @@ using Microsoft.Extensions.Options;
using TileServer.Application.Configuration;
using TileServer.Application;
using TileServer.Application.Extracts;
+using TileServer.Application.Graph;
using TileServer.Application.Tiles;
using TileServer.Domain.Exceptions;
using TileServer.Domain.Extracts;
@@ -15,6 +16,8 @@ public sealed class MapSyncService(
IExtractStateStore stateStore,
ITileBuilder tileBuilder,
ITileStore tileStore,
+ IRoadGraphBuilder roadGraphBuilder,
+ IRoadGraphStore roadGraphStore,
IPlanetilerBootstrapper planetiler,
IPlanetilerSourceBootstrapper planetilerSources,
IDataPaths dataPaths,
@@ -148,13 +151,17 @@ public sealed class MapSyncService(
}
var tilesMissing = !tileStore.Exists(extract.Id);
+ var graphMissing = options.Value.BuildRoadGraph && !roadGraphStore.Exists(extract.Id);
var metadata = tileStore.GetMetadata(extract.Id);
var zoomRaised = metadata is not null && extract.MaxZoom > metadata.MaxZoom;
- var shouldBuild = download.Changed
+ var shouldBuildTiles = download.Changed
|| previousStatus == ExtractSyncState.Failed
|| (tilesMissing && options.Value.Sync.RebuildIfTilesMissing)
|| zoomRaised;
- if (!shouldBuild)
+ var shouldBuildGraph = options.Value.BuildRoadGraph
+ && (shouldBuildTiles || graphMissing || previousStatus == ExtractSyncState.Failed);
+
+ if (!shouldBuildTiles && !shouldBuildGraph)
{
state.Status = ExtractSyncState.Ready;
await stateStore.SaveAsync(state, ct).ConfigureAwait(false);
@@ -174,27 +181,44 @@ public sealed class MapSyncService(
{
logger.LogInformation("Rebuilding {ExtractId}: previous run failed.", extract.Id);
}
-
- if (!planetiler.IsJavaAvailable())
+ else if (graphMissing && !shouldBuildTiles)
{
- throw new InvalidOperationException(
- "Java 21+ is required to build tiles with planetiler-openmaptiles. Install a JDK and set TileServer:JavaPath.");
+ logger.LogInformation("Building road graph for {ExtractId}: graph missing.", extract.Id);
}
- await planetiler.EnsureJarAsync(ct).ConfigureAwait(false);
+ if (shouldBuildTiles)
+ {
+ if (!planetiler.IsJavaAvailable())
+ {
+ throw new InvalidOperationException(
+ "Java 21+ is required to build tiles with planetiler-openmaptiles. Install a JDK and set TileServer:JavaPath.");
+ }
- state.Status = ExtractSyncState.PreparingSources;
- await stateStore.SaveAsync(state, ct).ConfigureAwait(false);
- logger.LogInformation("Preparing Planetiler sidecar sources for {ExtractId}.", extract.Id);
- await planetilerSources.EnsureAsync(ct).ConfigureAwait(false);
+ await planetiler.EnsureJarAsync(ct).ConfigureAwait(false);
- state.Status = ExtractSyncState.Building;
- await stateStore.SaveAsync(state, ct).ConfigureAwait(false);
+ state.Status = ExtractSyncState.PreparingSources;
+ await stateStore.SaveAsync(state, ct).ConfigureAwait(false);
+ logger.LogInformation("Preparing Planetiler sidecar sources for {ExtractId}.", extract.Id);
+ await planetilerSources.EnsureAsync(ct).ConfigureAwait(false);
- var staging = tileStore.GetStagingPath(extract.Id);
- logger.LogInformation("Building vector tiles for {ExtractId} -> {Path}", extract.Id, staging);
- await tileBuilder.BuildAsync(extract, pbfPath, staging, ct).ConfigureAwait(false);
- tileStore.Activate(extract.Id, staging);
+ state.Status = ExtractSyncState.Building;
+ await stateStore.SaveAsync(state, ct).ConfigureAwait(false);
+
+ var staging = tileStore.GetStagingPath(extract.Id);
+ logger.LogInformation("Building vector tiles for {ExtractId} -> {Path}", extract.Id, staging);
+ await tileBuilder.BuildAsync(extract, pbfPath, staging, ct).ConfigureAwait(false);
+ tileStore.Activate(extract.Id, staging);
+ }
+
+ if (shouldBuildGraph)
+ {
+ state.Status = ExtractSyncState.Building;
+ await stateStore.SaveAsync(state, ct).ConfigureAwait(false);
+ var graphStaging = roadGraphStore.GetStagingPath(extract.Id);
+ logger.LogInformation("Building road graph for {ExtractId} -> {Path}", extract.Id, graphStaging);
+ await roadGraphBuilder.BuildAsync(extract, pbfPath, graphStaging, ct).ConfigureAwait(false);
+ roadGraphStore.Activate(extract.Id, graphStaging);
+ }
state.BuiltAt = DateTimeOffset.UtcNow;
state.Status = ExtractSyncState.Ready;
diff --git a/src/TileServer.Application/TileServer.Application.csproj b/src/TileServer.Application/TileServer.Application.csproj
index 53322e2..03cb368 100644
--- a/src/TileServer.Application/TileServer.Application.csproj
+++ b/src/TileServer.Application/TileServer.Application.csproj
@@ -8,4 +8,7 @@
+
+
+
diff --git a/src/TileServer.Domain/Graph/RoadGraphModels.cs b/src/TileServer.Domain/Graph/RoadGraphModels.cs
new file mode 100644
index 0000000..fd7607a
--- /dev/null
+++ b/src/TileServer.Domain/Graph/RoadGraphModels.cs
@@ -0,0 +1,23 @@
+namespace TileServer.Domain.Graph;
+
+public sealed record RoadGraphBounds(double MinLon, double MinLat, double MaxLon, double MaxLat);
+
+public sealed record RoadGraphMetadata(
+ string ExtractId,
+ long NodeCount,
+ long EdgeCount,
+ RoadGraphBounds? Bounds,
+ DateTimeOffset BuiltAt);
+
+public sealed record RoadGraphNode(long Id, double Lon, double Lat);
+
+public sealed record RoadGraphEdge(
+ long Id,
+ long FromId,
+ long ToId,
+ string Highway,
+ string? Name,
+ bool Oneway,
+ double LengthM);
+
+public sealed record RoadGraphPage(IReadOnlyList Items, long? NextAfter);
diff --git a/src/TileServer.Infrastructure/DependencyInjection.cs b/src/TileServer.Infrastructure/DependencyInjection.cs
index 3270d3d..c33270f 100644
--- a/src/TileServer.Infrastructure/DependencyInjection.cs
+++ b/src/TileServer.Infrastructure/DependencyInjection.cs
@@ -5,6 +5,7 @@ using TileServer.Application;
using TileServer.Application.Accounts;
using TileServer.Application.Configuration;
using TileServer.Application.Extracts;
+using TileServer.Application.Graph;
using TileServer.Application.Styles;
using TileServer.Application.Sync;
using TileServer.Application.Tiles;
@@ -13,6 +14,7 @@ using TileServer.Infrastructure.Auth;
using TileServer.Infrastructure.Data;
using TileServer.Infrastructure.Downloads;
using TileServer.Infrastructure.Extracts;
+using TileServer.Infrastructure.Graph;
using TileServer.Infrastructure.Storage;
using TileServer.Infrastructure.Styles;
using TileServer.Infrastructure.Sync;
@@ -74,6 +76,8 @@ public static class DependencyInjection
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
+ services.AddSingleton();
+ services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
diff --git a/src/TileServer.Infrastructure/Graph/OsmSharpRoadGraphBuilder.cs b/src/TileServer.Infrastructure/Graph/OsmSharpRoadGraphBuilder.cs
new file mode 100644
index 0000000..4b12b9f
--- /dev/null
+++ b/src/TileServer.Infrastructure/Graph/OsmSharpRoadGraphBuilder.cs
@@ -0,0 +1,482 @@
+using System.Buffers.Binary;
+using System.Globalization;
+using Microsoft.Data.Sqlite;
+using Microsoft.Extensions.Logging;
+using OsmSharp;
+using OsmSharp.Streams;
+using OsmSharp.Tags;
+using TileServer.Application.Graph;
+using TileServer.Domain.Extracts;
+
+namespace TileServer.Infrastructure.Graph;
+
+///
+/// Two-pass PBF scan: highway ways → degree map + packed node refs; nodes → coords;
+/// then collapse chains between intersections into edges with Haversine length.
+///
+public sealed class OsmSharpRoadGraphBuilder(ILogger logger) : IRoadGraphBuilder
+{
+ private static readonly HashSet HighwayTypes = new(StringComparer.Ordinal)
+ {
+ "motorway", "motorway_link",
+ "trunk", "trunk_link",
+ "primary", "primary_link",
+ "secondary", "secondary_link",
+ "tertiary", "tertiary_link",
+ "unclassified", "residential", "living_street",
+ "service", "road"
+ };
+
+ public async Task BuildAsync(Extract extract, string osmPbfPath, string outputSqlitePath, CancellationToken ct)
+ {
+ if (!File.Exists(osmPbfPath))
+ {
+ throw new FileNotFoundException("OSM PBF was not downloaded.", osmPbfPath);
+ }
+
+ Directory.CreateDirectory(Path.GetDirectoryName(outputSqlitePath)!);
+ if (File.Exists(outputSqlitePath))
+ {
+ File.Delete(outputSqlitePath);
+ }
+
+ var stagingDir = Path.Combine(Path.GetDirectoryName(outputSqlitePath)!, $".{extract.Id}.graph-build");
+ if (Directory.Exists(stagingDir))
+ {
+ Directory.Delete(stagingDir, recursive: true);
+ }
+
+ Directory.CreateDirectory(stagingDir);
+ var waysDbPath = Path.Combine(stagingDir, "ways.sqlite");
+
+ try
+ {
+ logger.LogInformation("Road graph pass 1 (ways) for {ExtractId}", extract.Id);
+ var degrees = await CollectWaysAsync(osmPbfPath, waysDbPath, ct).ConfigureAwait(false);
+ logger.LogInformation(
+ "Road graph pass 1 done for {ExtractId}: {WayNodes} referenced nodes",
+ extract.Id,
+ degrees.Count);
+
+ logger.LogInformation("Road graph pass 2 (nodes) for {ExtractId}", extract.Id);
+ var coords = await CollectCoordsAsync(osmPbfPath, degrees, ct).ConfigureAwait(false);
+ logger.LogInformation(
+ "Road graph pass 2 done for {ExtractId}: {CoordCount}/{Wanted} coordinates",
+ extract.Id,
+ coords.Count,
+ degrees.Count);
+
+ logger.LogInformation("Road graph materialize for {ExtractId} -> {Path}", extract.Id, outputSqlitePath);
+ await MaterializeAsync(extract.Id, waysDbPath, degrees, coords, outputSqlitePath, ct).ConfigureAwait(false);
+ }
+ finally
+ {
+ try
+ {
+ if (Directory.Exists(stagingDir))
+ {
+ Directory.Delete(stagingDir, recursive: true);
+ }
+ }
+ catch (Exception ex)
+ {
+ logger.LogWarning(ex, "Could not remove graph staging dir {Dir}", stagingDir);
+ }
+ }
+ }
+
+ private static async Task> CollectWaysAsync(string pbfPath, string waysDbPath, CancellationToken ct)
+ {
+ var degrees = new Dictionary();
+ await using var connection = new SqliteConnection(new SqliteConnectionStringBuilder
+ {
+ DataSource = waysDbPath,
+ Mode = SqliteOpenMode.ReadWriteCreate
+ }.ToString());
+ await connection.OpenAsync(ct).ConfigureAwait(false);
+ await using (var pragma = connection.CreateCommand())
+ {
+ pragma.CommandText = "PRAGMA journal_mode=OFF; PRAGMA synchronous=OFF;";
+ await pragma.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
+ }
+
+ await using (var create = connection.CreateCommand())
+ {
+ create.CommandText =
+ """
+ CREATE TABLE ways (
+ id INTEGER PRIMARY KEY,
+ highway TEXT NOT NULL,
+ name TEXT,
+ oneway INTEGER NOT NULL,
+ nodes BLOB NOT NULL
+ );
+ """;
+ await create.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
+ }
+
+ var tx = (SqliteTransaction)await connection.BeginTransactionAsync(ct).ConfigureAwait(false);
+ await using var insert = connection.CreateCommand();
+ insert.Transaction = tx;
+ insert.CommandText =
+ """
+ INSERT INTO ways (id, highway, name, oneway, nodes)
+ VALUES ($id, $highway, $name, $oneway, $nodes);
+ """;
+ var pId = insert.Parameters.Add("$id", SqliteType.Integer);
+ var pHighway = insert.Parameters.Add("$highway", SqliteType.Text);
+ var pName = insert.Parameters.Add("$name", SqliteType.Text);
+ var pOneway = insert.Parameters.Add("$oneway", SqliteType.Integer);
+ var pNodes = insert.Parameters.Add("$nodes", SqliteType.Blob);
+
+ await using var file = File.OpenRead(pbfPath);
+ var source = new PBFOsmStreamSource(file);
+ var batch = 0;
+ foreach (var geo in source)
+ {
+ ct.ThrowIfCancellationRequested();
+ if (geo is not Way way || way.Id is null || way.Nodes is null || way.Nodes.Length < 2 || way.Tags is null)
+ {
+ continue;
+ }
+
+ if (!TryGetTag(way.Tags, "highway", out var highway) || !HighwayTypes.Contains(highway))
+ {
+ continue;
+ }
+
+ if (TryGetTag(way.Tags, "area", out var area) && area is "yes" or "true" or "1")
+ {
+ continue;
+ }
+
+ TryGetTag(way.Tags, "name", out var name);
+ var oneway = ParseOneway(way.Tags);
+ pId.Value = way.Id.Value;
+ pHighway.Value = highway;
+ pName.Value = string.IsNullOrWhiteSpace(name) ? DBNull.Value : name;
+ pOneway.Value = oneway;
+ pNodes.Value = PackNodeIds(way.Nodes);
+ await insert.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
+
+ foreach (var nodeId in way.Nodes)
+ {
+ degrees[nodeId] = degrees.TryGetValue(nodeId, out var count) ? count + 1 : 1;
+ }
+
+ if (++batch % 5_000 != 0)
+ {
+ continue;
+ }
+
+ await tx.CommitAsync(ct).ConfigureAwait(false);
+ await tx.DisposeAsync().ConfigureAwait(false);
+ tx = (SqliteTransaction)await connection.BeginTransactionAsync(ct).ConfigureAwait(false);
+ insert.Transaction = tx;
+ }
+
+ await tx.CommitAsync(ct).ConfigureAwait(false);
+ await tx.DisposeAsync().ConfigureAwait(false);
+ return degrees;
+ }
+
+ private static async Task> CollectCoordsAsync(
+ string pbfPath,
+ Dictionary degrees,
+ CancellationToken ct)
+ {
+ var coords = new Dictionary(degrees.Count);
+ await using var file = File.OpenRead(pbfPath);
+ var source = new PBFOsmStreamSource(file);
+ foreach (var geo in source)
+ {
+ ct.ThrowIfCancellationRequested();
+ if (geo is not Node node || node.Id is null || node.Longitude is null || node.Latitude is null)
+ {
+ continue;
+ }
+
+ if (!degrees.ContainsKey(node.Id.Value))
+ {
+ continue;
+ }
+
+ coords[node.Id.Value] = (node.Longitude.Value, node.Latitude.Value);
+ if (coords.Count == degrees.Count)
+ {
+ break;
+ }
+ }
+
+ return coords;
+ }
+
+ private static async Task MaterializeAsync(
+ string extractId,
+ string waysDbPath,
+ Dictionary degrees,
+ Dictionary coords,
+ string outputPath,
+ CancellationToken ct)
+ {
+ await using var output = new SqliteConnection(new SqliteConnectionStringBuilder
+ {
+ DataSource = outputPath,
+ Mode = SqliteOpenMode.ReadWriteCreate
+ }.ToString());
+ await output.OpenAsync(ct).ConfigureAwait(false);
+ await using (var pragma = output.CreateCommand())
+ {
+ pragma.CommandText = "PRAGMA journal_mode=OFF; PRAGMA synchronous=OFF; PRAGMA temp_store=MEMORY;";
+ await pragma.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
+ }
+
+ await using (var schema = output.CreateCommand())
+ {
+ schema.CommandText =
+ """
+ CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
+ CREATE TABLE nodes (
+ id INTEGER PRIMARY KEY,
+ lon REAL NOT NULL,
+ lat REAL NOT NULL
+ );
+ CREATE TABLE edges (
+ id INTEGER PRIMARY KEY,
+ from_id INTEGER NOT NULL,
+ to_id INTEGER NOT NULL,
+ highway TEXT NOT NULL,
+ name TEXT,
+ oneway INTEGER NOT NULL,
+ length_m REAL NOT NULL
+ );
+ CREATE INDEX edges_from ON edges(from_id);
+ CREATE INDEX edges_to ON edges(to_id);
+ CREATE INDEX nodes_lonlat ON nodes(lon, lat);
+ """;
+ await schema.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
+ }
+
+ var vertexIds = new HashSet();
+ await using var ways = new SqliteConnection(new SqliteConnectionStringBuilder
+ {
+ DataSource = waysDbPath,
+ Mode = SqliteOpenMode.ReadOnly
+ }.ToString());
+ await ways.OpenAsync(ct).ConfigureAwait(false);
+
+ long edgeId = 0;
+ double minLon = 180, minLat = 90, maxLon = -180, maxLat = -90;
+ await using var outTx = (SqliteTransaction)await output.BeginTransactionAsync(ct).ConfigureAwait(false);
+ await using var insertNode = output.CreateCommand();
+ insertNode.Transaction = outTx;
+ insertNode.CommandText = "INSERT OR IGNORE INTO nodes (id, lon, lat) VALUES ($id, $lon, $lat);";
+ var nId = insertNode.Parameters.Add("$id", SqliteType.Integer);
+ var nLon = insertNode.Parameters.Add("$lon", SqliteType.Real);
+ var nLat = insertNode.Parameters.Add("$lat", SqliteType.Real);
+
+ await using var insertEdge = output.CreateCommand();
+ insertEdge.Transaction = outTx;
+ insertEdge.CommandText =
+ """
+ INSERT INTO edges (id, from_id, to_id, highway, name, oneway, length_m)
+ VALUES ($id, $from, $to, $highway, $name, $oneway, $length);
+ """;
+ var eId = insertEdge.Parameters.Add("$id", SqliteType.Integer);
+ var eFrom = insertEdge.Parameters.Add("$from", SqliteType.Integer);
+ var eTo = insertEdge.Parameters.Add("$to", SqliteType.Integer);
+ var eHighway = insertEdge.Parameters.Add("$highway", SqliteType.Text);
+ var eName = insertEdge.Parameters.Add("$name", SqliteType.Text);
+ var eOneway = insertEdge.Parameters.Add("$oneway", SqliteType.Integer);
+ var eLength = insertEdge.Parameters.Add("$length", SqliteType.Real);
+
+ await using (var readWays = ways.CreateCommand())
+ {
+ readWays.CommandText = "SELECT highway, name, oneway, nodes FROM ways;";
+ await using var reader = await readWays.ExecuteReaderAsync(ct).ConfigureAwait(false);
+ while (await reader.ReadAsync(ct).ConfigureAwait(false))
+ {
+ ct.ThrowIfCancellationRequested();
+ var highway = reader.GetString(0);
+ var name = reader.IsDBNull(1) ? null : reader.GetString(1);
+ var onewayCode = reader.GetInt32(2);
+ var nodeIds = UnpackNodeIds((byte[])reader.GetValue(3));
+ if (nodeIds.Length < 2)
+ {
+ continue;
+ }
+
+ long? segmentFrom = null;
+ double segmentLength = 0;
+ (double Lon, double Lat)? prevCoord = null;
+
+ for (var i = 0; i < nodeIds.Length; i++)
+ {
+ var nodeId = nodeIds[i];
+ if (!coords.TryGetValue(nodeId, out var coord))
+ {
+ segmentFrom = null;
+ prevCoord = null;
+ segmentLength = 0;
+ continue;
+ }
+
+ if (prevCoord is { } previous)
+ {
+ segmentLength += HaversineMeters(previous.Lon, previous.Lat, coord.Lon, coord.Lat);
+ }
+
+ var isVertex = i == 0
+ || i == nodeIds.Length - 1
+ || degrees.GetValueOrDefault(nodeId) > 1;
+ if (isVertex)
+ {
+ vertexIds.Add(nodeId);
+ ExpandBounds(ref minLon, ref minLat, ref maxLon, ref maxLat, coord.Lon, coord.Lat);
+ if (segmentFrom is long fromId && fromId != nodeId && segmentLength > 0)
+ {
+ var (from, to, onewayFlag) = NormalizeDirection(fromId, nodeId, onewayCode);
+ eId.Value = ++edgeId;
+ eFrom.Value = from;
+ eTo.Value = to;
+ eHighway.Value = highway;
+ eName.Value = name is null ? DBNull.Value : name;
+ eOneway.Value = onewayFlag ? 1 : 0;
+ eLength.Value = segmentLength;
+ await insertEdge.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
+ }
+
+ segmentFrom = nodeId;
+ segmentLength = 0;
+ }
+
+ prevCoord = coord;
+ }
+ }
+ }
+
+ foreach (var vertexId in vertexIds)
+ {
+ if (!coords.TryGetValue(vertexId, out var coord))
+ {
+ continue;
+ }
+
+ nId.Value = vertexId;
+ nLon.Value = coord.Lon;
+ nLat.Value = coord.Lat;
+ await insertNode.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
+ }
+
+ await using (var meta = output.CreateCommand())
+ {
+ meta.Transaction = outTx;
+ meta.CommandText = "INSERT INTO meta (key, value) VALUES ($k, $v);";
+ await WriteMetaAsync(meta, "extract_id", extractId, ct).ConfigureAwait(false);
+ await WriteMetaAsync(meta, "node_count", vertexIds.Count.ToString(CultureInfo.InvariantCulture), ct)
+ .ConfigureAwait(false);
+ await WriteMetaAsync(meta, "edge_count", edgeId.ToString(CultureInfo.InvariantCulture), ct)
+ .ConfigureAwait(false);
+ await WriteMetaAsync(meta, "built_at", DateTimeOffset.UtcNow.ToString("O"), ct).ConfigureAwait(false);
+ if (vertexIds.Count > 0)
+ {
+ var bounds =
+ $"{minLon.ToString(CultureInfo.InvariantCulture)},{minLat.ToString(CultureInfo.InvariantCulture)},{maxLon.ToString(CultureInfo.InvariantCulture)},{maxLat.ToString(CultureInfo.InvariantCulture)}";
+ await WriteMetaAsync(meta, "bounds", bounds, ct).ConfigureAwait(false);
+ }
+ }
+
+ await outTx.CommitAsync(ct).ConfigureAwait(false);
+ }
+
+ private static (long From, long To, bool Oneway) NormalizeDirection(long fromId, long toId, int onewayCode)
+ => onewayCode switch
+ {
+ -1 => (toId, fromId, true),
+ 1 => (fromId, toId, true),
+ _ => (fromId, toId, false)
+ };
+
+ private static async Task WriteMetaAsync(SqliteCommand command, string key, string value, CancellationToken ct)
+ {
+ command.Parameters.Clear();
+ command.Parameters.AddWithValue("$k", key);
+ command.Parameters.AddWithValue("$v", value);
+ await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
+ }
+
+ private static void ExpandBounds(ref double minLon, ref double minLat, ref double maxLon, ref double maxLat, double lon, double lat)
+ {
+ minLon = Math.Min(minLon, lon);
+ minLat = Math.Min(minLat, lat);
+ maxLon = Math.Max(maxLon, lon);
+ maxLat = Math.Max(maxLat, lat);
+ }
+
+ private static int ParseOneway(TagsCollectionBase tags)
+ {
+ if (!TryGetTag(tags, "oneway", out var value))
+ {
+ if (TryGetTag(tags, "junction", out var junction) && junction == "roundabout")
+ {
+ return 1;
+ }
+
+ return 0;
+ }
+
+ return value switch
+ {
+ "yes" or "true" or "1" => 1,
+ "-1" or "reverse" => -1,
+ _ => 0
+ };
+ }
+
+ private static bool TryGetTag(TagsCollectionBase tags, string key, out string value)
+ {
+ if (tags.TryGetValue(key, out var found) && !string.IsNullOrEmpty(found))
+ {
+ value = found;
+ return true;
+ }
+
+ value = string.Empty;
+ return false;
+ }
+
+ private static byte[] PackNodeIds(long[] nodes)
+ {
+ var bytes = new byte[nodes.Length * sizeof(long)];
+ for (var i = 0; i < nodes.Length; i++)
+ {
+ BinaryPrimitives.WriteInt64LittleEndian(bytes.AsSpan(i * sizeof(long)), nodes[i]);
+ }
+
+ return bytes;
+ }
+
+ private static long[] UnpackNodeIds(byte[] bytes)
+ {
+ var count = bytes.Length / sizeof(long);
+ var nodes = new long[count];
+ for (var i = 0; i < count; i++)
+ {
+ nodes[i] = BinaryPrimitives.ReadInt64LittleEndian(bytes.AsSpan(i * sizeof(long)));
+ }
+
+ return nodes;
+ }
+
+ internal static double HaversineMeters(double lon1, double lat1, double lon2, double lat2)
+ {
+ const double r = 6_371_000d;
+ static double Rad(double deg) => deg * Math.PI / 180d;
+ var dLat = Rad(lat2 - lat1);
+ var dLon = Rad(lon2 - lon1);
+ var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2)
+ + Math.Cos(Rad(lat1)) * Math.Cos(Rad(lat2))
+ * Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
+ return 2 * r * Math.Asin(Math.Min(1, Math.Sqrt(a)));
+ }
+}
diff --git a/src/TileServer.Infrastructure/Graph/SqliteRoadGraphStore.cs b/src/TileServer.Infrastructure/Graph/SqliteRoadGraphStore.cs
new file mode 100644
index 0000000..924d574
--- /dev/null
+++ b/src/TileServer.Infrastructure/Graph/SqliteRoadGraphStore.cs
@@ -0,0 +1,204 @@
+using System.Globalization;
+using Microsoft.Data.Sqlite;
+using Microsoft.Extensions.Logging;
+using TileServer.Application;
+using TileServer.Application.Graph;
+using TileServer.Domain.Graph;
+
+namespace TileServer.Infrastructure.Graph;
+
+public sealed class SqliteRoadGraphStore(IDataPaths paths, ILogger logger) : IRoadGraphStore
+{
+ public bool Exists(string extractId) => File.Exists(paths.RoadGraph(extractId));
+
+ public string GetActivePath(string extractId) => paths.RoadGraph(extractId);
+
+ public string GetStagingPath(string extractId) => paths.StagingRoadGraph(extractId);
+
+ public void Activate(string extractId, string stagingPath)
+ {
+ var target = paths.RoadGraph(extractId);
+ Directory.CreateDirectory(Path.GetDirectoryName(target)!);
+ if (File.Exists(target))
+ {
+ File.Delete(target);
+ }
+
+ File.Move(stagingPath, target);
+ var wal = stagingPath + "-wal";
+ var shm = stagingPath + "-shm";
+ if (File.Exists(wal))
+ {
+ File.Delete(wal);
+ }
+
+ if (File.Exists(shm))
+ {
+ File.Delete(shm);
+ }
+
+ logger.LogInformation("Activated road graph for {ExtractId} at {Path}", extractId, target);
+ }
+
+ public RoadGraphMetadata? GetMetadata(string extractId)
+ {
+ var path = paths.RoadGraph(extractId);
+ if (!File.Exists(path))
+ {
+ return null;
+ }
+
+ using var connection = Open(path);
+ var nodeCount = ReadLongMeta(connection, "node_count");
+ var edgeCount = ReadLongMeta(connection, "edge_count");
+ var builtRaw = ReadStringMeta(connection, "built_at");
+ var builtAt = DateTimeOffset.TryParse(builtRaw, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var parsed)
+ ? parsed
+ : File.GetLastWriteTimeUtc(path);
+ var boundsRaw = ReadStringMeta(connection, "bounds");
+ RoadGraphBounds? bounds = null;
+ if (!string.IsNullOrWhiteSpace(boundsRaw))
+ {
+ var parts = boundsRaw.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
+ if (parts.Length == 4
+ && double.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out var minLon)
+ && double.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var minLat)
+ && double.TryParse(parts[2], NumberStyles.Float, CultureInfo.InvariantCulture, out var maxLon)
+ && double.TryParse(parts[3], NumberStyles.Float, CultureInfo.InvariantCulture, out var maxLat))
+ {
+ bounds = new RoadGraphBounds(minLon, minLat, maxLon, maxLat);
+ }
+ }
+
+ return new RoadGraphMetadata(extractId, nodeCount, edgeCount, bounds, builtAt);
+ }
+
+ public async Task> QueryNodesAsync(
+ string extractId,
+ RoadGraphBounds bounds,
+ long afterId,
+ int limit,
+ CancellationToken ct)
+ {
+ await using var connection = Open(paths.RoadGraph(extractId));
+ await using var command = connection.CreateCommand();
+ command.CommandText =
+ """
+ SELECT id, lon, lat
+ FROM nodes
+ WHERE id > $after
+ AND lon BETWEEN $minLon AND $maxLon
+ AND lat BETWEEN $minLat AND $maxLat
+ ORDER BY id
+ LIMIT $limit;
+ """;
+ command.Parameters.AddWithValue("$after", afterId);
+ command.Parameters.AddWithValue("$minLon", bounds.MinLon);
+ command.Parameters.AddWithValue("$maxLon", bounds.MaxLon);
+ command.Parameters.AddWithValue("$minLat", bounds.MinLat);
+ command.Parameters.AddWithValue("$maxLat", bounds.MaxLat);
+ command.Parameters.AddWithValue("$limit", limit + 1);
+
+ var items = new List(limit);
+ long? next = null;
+ await using var reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false);
+ while (await reader.ReadAsync(ct).ConfigureAwait(false))
+ {
+ var id = reader.GetInt64(0);
+ if (items.Count >= limit)
+ {
+ next = id;
+ break;
+ }
+
+ items.Add(new RoadGraphNode(id, reader.GetDouble(1), reader.GetDouble(2)));
+ }
+
+ return new RoadGraphPage(items, next);
+ }
+
+ public async Task> QueryEdgesAsync(
+ string extractId,
+ RoadGraphBounds bounds,
+ long afterId,
+ int limit,
+ CancellationToken ct)
+ {
+ await using var connection = Open(paths.RoadGraph(extractId));
+ await using var command = connection.CreateCommand();
+ // Edge is in bbox if either endpoint is inside (cheap join, good enough for light API).
+ command.CommandText =
+ """
+ SELECT e.id, e.from_id, e.to_id, e.highway, e.name, e.oneway, e.length_m
+ FROM edges e
+ INNER JOIN nodes a ON a.id = e.from_id
+ INNER JOIN nodes b ON b.id = e.to_id
+ WHERE e.id > $after
+ AND (
+ (a.lon BETWEEN $minLon AND $maxLon AND a.lat BETWEEN $minLat AND $maxLat)
+ OR (b.lon BETWEEN $minLon AND $maxLon AND b.lat BETWEEN $minLat AND $maxLat)
+ )
+ ORDER BY e.id
+ LIMIT $limit;
+ """;
+ command.Parameters.AddWithValue("$after", afterId);
+ command.Parameters.AddWithValue("$minLon", bounds.MinLon);
+ command.Parameters.AddWithValue("$maxLon", bounds.MaxLon);
+ command.Parameters.AddWithValue("$minLat", bounds.MinLat);
+ command.Parameters.AddWithValue("$maxLat", bounds.MaxLat);
+ command.Parameters.AddWithValue("$limit", limit + 1);
+
+ var items = new List(limit);
+ long? next = null;
+ await using var reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false);
+ while (await reader.ReadAsync(ct).ConfigureAwait(false))
+ {
+ var id = reader.GetInt64(0);
+ if (items.Count >= limit)
+ {
+ next = id;
+ break;
+ }
+
+ items.Add(new RoadGraphEdge(
+ id,
+ reader.GetInt64(1),
+ reader.GetInt64(2),
+ reader.GetString(3),
+ reader.IsDBNull(4) ? null : reader.GetString(4),
+ reader.GetInt64(5) != 0,
+ reader.GetDouble(6)));
+ }
+
+ return new RoadGraphPage(items, next);
+ }
+
+ private static SqliteConnection Open(string path)
+ {
+ var connection = new SqliteConnection(new SqliteConnectionStringBuilder
+ {
+ DataSource = path,
+ Mode = SqliteOpenMode.ReadOnly,
+ Cache = SqliteCacheMode.Shared
+ }.ToString());
+ connection.Open();
+ return connection;
+ }
+
+ private static long ReadLongMeta(SqliteConnection connection, string key)
+ {
+ using var command = connection.CreateCommand();
+ command.CommandText = "SELECT value FROM meta WHERE key = $key LIMIT 1;";
+ command.Parameters.AddWithValue("$key", key);
+ var value = command.ExecuteScalar()?.ToString();
+ return long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsed) ? parsed : 0;
+ }
+
+ private static string? ReadStringMeta(SqliteConnection connection, string key)
+ {
+ using var command = connection.CreateCommand();
+ command.CommandText = "SELECT value FROM meta WHERE key = $key LIMIT 1;";
+ command.Parameters.AddWithValue("$key", key);
+ return command.ExecuteScalar()?.ToString();
+ }
+}
diff --git a/src/TileServer.Infrastructure/Storage/DataPaths.cs b/src/TileServer.Infrastructure/Storage/DataPaths.cs
index 14b46c7..8b8fd1a 100644
--- a/src/TileServer.Infrastructure/Storage/DataPaths.cs
+++ b/src/TileServer.Infrastructure/Storage/DataPaths.cs
@@ -15,6 +15,7 @@ public sealed class DataPaths : IDataPaths
: Path.Combine(environment.ContentRootPath, configured));
Extracts = Path.Combine(Root, "extracts");
Tiles = Path.Combine(Root, "tiles");
+ Graphs = Path.Combine(Root, "graphs");
Styles = Path.Combine(Root, "styles");
Tools = Path.Combine(Root, "tools");
State = Path.Combine(Root, "state");
@@ -31,6 +32,8 @@ public sealed class DataPaths : IDataPaths
public string Tiles { get; }
+ public string Graphs { get; }
+
public string Styles { get; }
public string Tools { get; }
@@ -52,10 +55,15 @@ public sealed class DataPaths : IDataPaths
// Planetiler infers archive format from the last suffix; keep ".mbtiles".
public string StagingMbtiles(string extractId) => Path.Combine(Tiles, $"{extractId}.building.mbtiles");
+ public string RoadGraph(string extractId) => Path.Combine(Graphs, $"{extractId}.sqlite");
+
+ public string StagingRoadGraph(string extractId) => Path.Combine(Graphs, $"{extractId}.building.sqlite");
+
public void EnsureCreated()
{
Directory.CreateDirectory(Extracts);
Directory.CreateDirectory(Tiles);
+ Directory.CreateDirectory(Graphs);
Directory.CreateDirectory(Styles);
Directory.CreateDirectory(Tools);
Directory.CreateDirectory(State);
diff --git a/src/TileServer.Infrastructure/TileServer.Infrastructure.csproj b/src/TileServer.Infrastructure/TileServer.Infrastructure.csproj
index 6647858..f64d8ba 100644
--- a/src/TileServer.Infrastructure/TileServer.Infrastructure.csproj
+++ b/src/TileServer.Infrastructure/TileServer.Infrastructure.csproj
@@ -15,6 +15,7 @@
+
diff --git a/tests/TileServer.UnitTests/RoadGraphTests.cs b/tests/TileServer.UnitTests/RoadGraphTests.cs
new file mode 100644
index 0000000..4dd1aaf
--- /dev/null
+++ b/tests/TileServer.UnitTests/RoadGraphTests.cs
@@ -0,0 +1,29 @@
+using TileServer.Application.Graph;
+using TileServer.Domain.Exceptions;
+using TileServer.Domain.Graph;
+using TileServer.Infrastructure.Graph;
+
+namespace TileServer.UnitTests;
+
+public sealed class RoadGraphTests
+{
+ [Fact]
+ public void Haversine_MoscowBlock_IsRoughlyHundredMeters()
+ {
+ var meters = OsmSharpRoadGraphBuilder.HaversineMeters(37.6173, 55.7558, 37.6185, 55.7558);
+ Assert.InRange(meters, 60, 120);
+ }
+
+ [Fact]
+ public void ValidateBounds_RejectsWideBbox()
+ {
+ Assert.Throws(() =>
+ RoadGraphQueryService.ValidateBounds(new RoadGraphBounds(37, 55, 40, 56)));
+ }
+
+ [Fact]
+ public void ValidateBounds_AcceptsSmallBbox()
+ {
+ RoadGraphQueryService.ValidateBounds(new RoadGraphBounds(37.5, 55.7, 37.7, 55.8));
+ }
+}
diff --git a/web/src/features/guides/GuidesPage.tsx b/web/src/features/guides/GuidesPage.tsx
index 3127259..06cdc73 100644
--- a/web/src/features/guides/GuidesPage.tsx
+++ b/web/src/features/guides/GuidesPage.tsx
@@ -48,6 +48,8 @@ export function GuidesPage() {
const styleUrl = `${origin}/u/${slug}/styles/osm-bright?source=${source}${token ? `&token=${token}` : "&token=ts_…"}`;
const tilesUrl = `${origin}/u/${slug}/tiles/${source}/{z}/{x}/{y}.pbf?token=${token ?? "ts_…"}`;
+ const graphUrl = `${origin}/u/${slug}/graph/${source}?token=${token ?? "ts_…"}`;
+ const graphEdgesUrl = `${origin}/u/${slug}/graph/${source}/edges?bbox=37.5,55.7,37.7,55.8&token=${token ?? "ts_…"}`;
const html = useMemo(
() => `
@@ -131,6 +133,13 @@ const map = new maplibregl.Map({
скопирует слои. Один стиль — несколько округов на одной карте.
+
+ 5. Граф дорог
+
+ После sync рядом с тайлами лежит SQLite-граф (highway=*, рёбра между перекрёстками). Отдаётся только с
+ токеном. Узлы/рёбра — по bbox (≤ 2°), пагинация after.
+