feat(proj): add graph
This commit is contained in:
@@ -6,7 +6,8 @@ ASP.NET Core сервер векторных тайлов для клиенто
|
|||||||
|
|
||||||
1. Скачивает все настроенные OSM-extract’ы с Geofabrik (и любых других HTTP-ссылок на `.osm.pbf`).
|
1. Скачивает все настроенные OSM-extract’ы с Geofabrik (и любых других HTTP-ссылок на `.osm.pbf`).
|
||||||
2. Собирает из них OpenMapTiles MBTiles через [planetiler-openmaptiles](https://github.com/openmaptiles/planetiler-openmaptiles).
|
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 | Назначение |
|
| Метод | URL | Назначение |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `GET` | `/api/v1/tiles/{source}/{z}/{x}/{y}.pbf` | векторный тайл (MapLibre XYZ) |
|
| `GET` | `/u/{slug}/tiles/{source}/{z}/{x}/{y}.pbf?token=` | персональные тайлы |
|
||||||
| `GET` | `/api/v1/tiles/{source}.json` | TileJSON |
|
| `GET` | `/u/{slug}/styles/{name}?source=&token=` | персональный стиль |
|
||||||
| `GET` | `/api/v1/styles` | список стилей |
|
| `GET` | `/u/{slug}/graph/{source}?token=` | метаданные графа дорог |
|
||||||
| `GET` | `/api/v1/styles/{name}?source={source}` | MapLibre style JSON |
|
| `GET` | `/u/{slug}/graph/{source}/nodes?bbox=&token=` | узлы в bbox (пагинация `after`) |
|
||||||
| `PUT` | `/api/v1/styles/{name}` | добавить/обновить стиль |
|
| `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` | прогнать все extract’ы сейчас |
|
||||||
| `POST` | `/api/v1/sync/{id}` | прогнать один 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`.
|
||||||
|
|
||||||
## Несколько регионов
|
## Несколько регионов
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Вопрос: граф дорог из OSM при sync
|
||||||
|
|
||||||
|
Можно. Источник — тот же `.osm.pbf`, не MBTiles (тайлы режут топологию). Параллельный артефакт на sync: узлы/рёбра `highway=*`. Варианты: свой граф (OsmSharp/Osmium), Valhalla/OSRM/GraphHopper. На ЦФО/СЗФО — отдельный CPU/RAM бюджет, не в том же JVM что Planetiler.
|
||||||
@@ -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.
|
||||||
@@ -61,6 +61,7 @@ services:
|
|||||||
TileServer__JvmMaxHeap: 4g
|
TileServer__JvmMaxHeap: 4g
|
||||||
TileServer__PlanetilerThreads: "8"
|
TileServer__PlanetilerThreads: "8"
|
||||||
TileServer__PlanetilerMmapTemp: "false"
|
TileServer__PlanetilerMmapTemp: "false"
|
||||||
|
TileServer__BuildRoadGraph: "true"
|
||||||
TileServer__Sync__RunOnStartup: "true"
|
TileServer__Sync__RunOnStartup: "true"
|
||||||
TileServer__Sync__Cron: "0 3 * * *"
|
TileServer__Sync__Cron: "0 3 * * *"
|
||||||
TileServer__Sync__TimeZone: UTC
|
TileServer__Sync__TimeZone: UTC
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using System.Globalization;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
@@ -6,9 +7,11 @@ using TileServer.Api.Http;
|
|||||||
using TileServer.Application.Accounts;
|
using TileServer.Application.Accounts;
|
||||||
using TileServer.Application.Configuration;
|
using TileServer.Application.Configuration;
|
||||||
using TileServer.Application.Extracts;
|
using TileServer.Application.Extracts;
|
||||||
|
using TileServer.Application.Graph;
|
||||||
using TileServer.Application.Styles;
|
using TileServer.Application.Styles;
|
||||||
using TileServer.Application.Tiles;
|
using TileServer.Application.Tiles;
|
||||||
using TileServer.Domain.Exceptions;
|
using TileServer.Domain.Exceptions;
|
||||||
|
using TileServer.Domain.Graph;
|
||||||
using TileServer.Domain.Tiles;
|
using TileServer.Domain.Tiles;
|
||||||
|
|
||||||
namespace TileServer.Api.Controllers;
|
namespace TileServer.Api.Controllers;
|
||||||
@@ -20,6 +23,7 @@ public sealed class PersonalDeliveryController(
|
|||||||
IApiTokenService tokens,
|
IApiTokenService tokens,
|
||||||
ITileQueryService tiles,
|
ITileQueryService tiles,
|
||||||
IUserStyleService styles,
|
IUserStyleService styles,
|
||||||
|
IRoadGraphQueryService graphs,
|
||||||
IExtractCatalog extracts,
|
IExtractCatalog extracts,
|
||||||
IUsageRecorder usage,
|
IUsageRecorder usage,
|
||||||
IOptions<TileServerOptions> options) : ControllerBase
|
IOptions<TileServerOptions> options) : ControllerBase
|
||||||
@@ -92,6 +96,86 @@ public sealed class PersonalDeliveryController(
|
|||||||
return new JsonResult(style);
|
return new JsonResult(style);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpGet("graph/{source}")]
|
||||||
|
[Produces("application/json")]
|
||||||
|
public async Task<IActionResult> 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<IActionResult> 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<IActionResult> 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<ResolvedAccess> ResolveAsync(string slug, CancellationToken ct)
|
private Task<ResolvedAccess> ResolveAsync(string slug, CancellationToken ct)
|
||||||
=> tokens.ResolveAsync(slug, AccessToken.Read(Request), bearer: null, 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);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,6 +30,7 @@
|
|||||||
"DefaultMinZoom": 0,
|
"DefaultMinZoom": 0,
|
||||||
"DefaultMaxZoom": 15,
|
"DefaultMaxZoom": 15,
|
||||||
"OverzoomMaxZoom": 18,
|
"OverzoomMaxZoom": 18,
|
||||||
|
"BuildRoadGraph": true,
|
||||||
"GlyphsUrl": "https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf",
|
"GlyphsUrl": "https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf",
|
||||||
"Yandex": {
|
"Yandex": {
|
||||||
"RedirectUri": "https://tile-server.ru"
|
"RedirectUri": "https://tile-server.ru"
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ public interface IUsageRecorder
|
|||||||
|
|
||||||
void RecordStyle(Guid userId, Guid tokenId, long bytes);
|
void RecordStyle(Guid userId, Guid tokenId, long bytes);
|
||||||
|
|
||||||
|
void RecordGraph(Guid userId, Guid tokenId, long bytes);
|
||||||
|
|
||||||
IReadOnlyList<UsageDelta> Drain();
|
IReadOnlyList<UsageDelta> Drain();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,9 @@ public sealed class UsageAccumulator : IUsageRecorder
|
|||||||
public void RecordStyle(Guid userId, Guid tokenId, long bytes)
|
public void RecordStyle(Guid userId, Guid tokenId, long bytes)
|
||||||
=> Record(userId, tokenId, tileRequests: 0, styleRequests: 1, 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)
|
public void Restore(UsageDelta delta)
|
||||||
=> Record(delta.UserId, delta.TokenId, delta.TileRequests, delta.StyleRequests, delta.Bytes);
|
=> Record(delta.UserId, delta.TokenId, delta.TileRequests, delta.StyleRequests, delta.Bytes);
|
||||||
|
|
||||||
|
|||||||
@@ -108,6 +108,9 @@ public sealed class TileServerOptions
|
|||||||
|
|
||||||
public SyncOptions Sync { get; set; } = new();
|
public SyncOptions Sync { get; set; } = new();
|
||||||
|
|
||||||
|
/// <summary>Build a light highway graph (SQLite) from each PBF during sync.</summary>
|
||||||
|
public bool BuildRoadGraph { get; set; } = true;
|
||||||
|
|
||||||
public YandexOAuthOptions Yandex { get; set; } = new();
|
public YandexOAuthOptions Yandex { get; set; } = new();
|
||||||
|
|
||||||
public List<ExtractOptions> Extracts { get; set; } = [];
|
public List<ExtractOptions> Extracts { get; set; } = [];
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using TileServer.Application.Accounts;
|
using TileServer.Application.Accounts;
|
||||||
using TileServer.Application.Extracts;
|
using TileServer.Application.Extracts;
|
||||||
|
using TileServer.Application.Graph;
|
||||||
using TileServer.Application.Styles;
|
using TileServer.Application.Styles;
|
||||||
using TileServer.Application.Sync;
|
using TileServer.Application.Sync;
|
||||||
using TileServer.Application.Tiles;
|
using TileServer.Application.Tiles;
|
||||||
@@ -14,6 +15,7 @@ public static class DependencyInjection
|
|||||||
services.AddSingleton<ITileQueryService, TileQueryService>();
|
services.AddSingleton<ITileQueryService, TileQueryService>();
|
||||||
services.AddSingleton<IStyleService, StyleService>();
|
services.AddSingleton<IStyleService, StyleService>();
|
||||||
services.AddSingleton<IExtractService, ExtractService>();
|
services.AddSingleton<IExtractService, ExtractService>();
|
||||||
|
services.AddSingleton<IRoadGraphQueryService, RoadGraphQueryService>();
|
||||||
services.AddSingleton<IMapSyncService, MapSyncService>();
|
services.AddSingleton<IMapSyncService, MapSyncService>();
|
||||||
services.AddSingleton<UsageAccumulator>();
|
services.AddSingleton<UsageAccumulator>();
|
||||||
services.AddSingleton<IUsageRecorder>(sp => sp.GetRequiredService<UsageAccumulator>());
|
services.AddSingleton<IUsageRecorder>(sp => sp.GetRequiredService<UsageAccumulator>());
|
||||||
|
|||||||
@@ -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<RoadGraphPage<RoadGraphNode>> QueryNodesAsync(
|
||||||
|
string extractId,
|
||||||
|
RoadGraphBounds bounds,
|
||||||
|
long afterId,
|
||||||
|
int limit,
|
||||||
|
CancellationToken ct);
|
||||||
|
|
||||||
|
Task<RoadGraphPage<RoadGraphEdge>> QueryEdgesAsync(
|
||||||
|
string extractId,
|
||||||
|
RoadGraphBounds bounds,
|
||||||
|
long afterId,
|
||||||
|
int limit,
|
||||||
|
CancellationToken ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public interface IRoadGraphQueryService
|
||||||
|
{
|
||||||
|
RoadGraphMetadata GetMetadata(string extractId);
|
||||||
|
|
||||||
|
Task<RoadGraphPage<RoadGraphNode>> GetNodesAsync(
|
||||||
|
string extractId,
|
||||||
|
RoadGraphBounds bounds,
|
||||||
|
long afterId,
|
||||||
|
int limit,
|
||||||
|
CancellationToken ct);
|
||||||
|
|
||||||
|
Task<RoadGraphPage<RoadGraphEdge>> GetEdgesAsync(
|
||||||
|
string extractId,
|
||||||
|
RoadGraphBounds bounds,
|
||||||
|
long afterId,
|
||||||
|
int limit,
|
||||||
|
CancellationToken ct);
|
||||||
|
}
|
||||||
@@ -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<RoadGraphPage<RoadGraphNode>> 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<RoadGraphPage<RoadGraphEdge>> 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=).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -28,5 +28,11 @@ public interface IDataPaths
|
|||||||
|
|
||||||
string StagingMbtiles(string extractId);
|
string StagingMbtiles(string extractId);
|
||||||
|
|
||||||
|
string Graphs { get; }
|
||||||
|
|
||||||
|
string RoadGraph(string extractId);
|
||||||
|
|
||||||
|
string StagingRoadGraph(string extractId);
|
||||||
|
|
||||||
void EnsureCreated();
|
void EnsureCreated();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ using Microsoft.Extensions.Options;
|
|||||||
using TileServer.Application.Configuration;
|
using TileServer.Application.Configuration;
|
||||||
using TileServer.Application;
|
using TileServer.Application;
|
||||||
using TileServer.Application.Extracts;
|
using TileServer.Application.Extracts;
|
||||||
|
using TileServer.Application.Graph;
|
||||||
using TileServer.Application.Tiles;
|
using TileServer.Application.Tiles;
|
||||||
using TileServer.Domain.Exceptions;
|
using TileServer.Domain.Exceptions;
|
||||||
using TileServer.Domain.Extracts;
|
using TileServer.Domain.Extracts;
|
||||||
@@ -15,6 +16,8 @@ public sealed class MapSyncService(
|
|||||||
IExtractStateStore stateStore,
|
IExtractStateStore stateStore,
|
||||||
ITileBuilder tileBuilder,
|
ITileBuilder tileBuilder,
|
||||||
ITileStore tileStore,
|
ITileStore tileStore,
|
||||||
|
IRoadGraphBuilder roadGraphBuilder,
|
||||||
|
IRoadGraphStore roadGraphStore,
|
||||||
IPlanetilerBootstrapper planetiler,
|
IPlanetilerBootstrapper planetiler,
|
||||||
IPlanetilerSourceBootstrapper planetilerSources,
|
IPlanetilerSourceBootstrapper planetilerSources,
|
||||||
IDataPaths dataPaths,
|
IDataPaths dataPaths,
|
||||||
@@ -148,13 +151,17 @@ public sealed class MapSyncService(
|
|||||||
}
|
}
|
||||||
|
|
||||||
var tilesMissing = !tileStore.Exists(extract.Id);
|
var tilesMissing = !tileStore.Exists(extract.Id);
|
||||||
|
var graphMissing = options.Value.BuildRoadGraph && !roadGraphStore.Exists(extract.Id);
|
||||||
var metadata = tileStore.GetMetadata(extract.Id);
|
var metadata = tileStore.GetMetadata(extract.Id);
|
||||||
var zoomRaised = metadata is not null && extract.MaxZoom > metadata.MaxZoom;
|
var zoomRaised = metadata is not null && extract.MaxZoom > metadata.MaxZoom;
|
||||||
var shouldBuild = download.Changed
|
var shouldBuildTiles = download.Changed
|
||||||
|| previousStatus == ExtractSyncState.Failed
|
|| previousStatus == ExtractSyncState.Failed
|
||||||
|| (tilesMissing && options.Value.Sync.RebuildIfTilesMissing)
|
|| (tilesMissing && options.Value.Sync.RebuildIfTilesMissing)
|
||||||
|| zoomRaised;
|
|| zoomRaised;
|
||||||
if (!shouldBuild)
|
var shouldBuildGraph = options.Value.BuildRoadGraph
|
||||||
|
&& (shouldBuildTiles || graphMissing || previousStatus == ExtractSyncState.Failed);
|
||||||
|
|
||||||
|
if (!shouldBuildTiles && !shouldBuildGraph)
|
||||||
{
|
{
|
||||||
state.Status = ExtractSyncState.Ready;
|
state.Status = ExtractSyncState.Ready;
|
||||||
await stateStore.SaveAsync(state, ct).ConfigureAwait(false);
|
await stateStore.SaveAsync(state, ct).ConfigureAwait(false);
|
||||||
@@ -174,27 +181,44 @@ public sealed class MapSyncService(
|
|||||||
{
|
{
|
||||||
logger.LogInformation("Rebuilding {ExtractId}: previous run failed.", extract.Id);
|
logger.LogInformation("Rebuilding {ExtractId}: previous run failed.", extract.Id);
|
||||||
}
|
}
|
||||||
|
else if (graphMissing && !shouldBuildTiles)
|
||||||
if (!planetiler.IsJavaAvailable())
|
|
||||||
{
|
{
|
||||||
throw new InvalidOperationException(
|
logger.LogInformation("Building road graph for {ExtractId}: graph missing.", extract.Id);
|
||||||
"Java 21+ is required to build tiles with planetiler-openmaptiles. Install a JDK and set TileServer:JavaPath.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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 planetiler.EnsureJarAsync(ct).ConfigureAwait(false);
|
||||||
await stateStore.SaveAsync(state, ct).ConfigureAwait(false);
|
|
||||||
logger.LogInformation("Preparing Planetiler sidecar sources for {ExtractId}.", extract.Id);
|
|
||||||
await planetilerSources.EnsureAsync(ct).ConfigureAwait(false);
|
|
||||||
|
|
||||||
state.Status = ExtractSyncState.Building;
|
state.Status = ExtractSyncState.PreparingSources;
|
||||||
await stateStore.SaveAsync(state, ct).ConfigureAwait(false);
|
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);
|
state.Status = ExtractSyncState.Building;
|
||||||
logger.LogInformation("Building vector tiles for {ExtractId} -> {Path}", extract.Id, staging);
|
await stateStore.SaveAsync(state, ct).ConfigureAwait(false);
|
||||||
await tileBuilder.BuildAsync(extract, pbfPath, staging, ct).ConfigureAwait(false);
|
|
||||||
tileStore.Activate(extract.Id, staging);
|
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.BuiltAt = DateTimeOffset.UtcNow;
|
||||||
state.Status = ExtractSyncState.Ready;
|
state.Status = ExtractSyncState.Ready;
|
||||||
|
|||||||
@@ -8,4 +8,7 @@
|
|||||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.2" />
|
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.2" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.2" />
|
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.2" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<InternalsVisibleTo Include="TileServer.UnitTests" />
|
||||||
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -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<T>(IReadOnlyList<T> Items, long? NextAfter);
|
||||||
@@ -5,6 +5,7 @@ using TileServer.Application;
|
|||||||
using TileServer.Application.Accounts;
|
using TileServer.Application.Accounts;
|
||||||
using TileServer.Application.Configuration;
|
using TileServer.Application.Configuration;
|
||||||
using TileServer.Application.Extracts;
|
using TileServer.Application.Extracts;
|
||||||
|
using TileServer.Application.Graph;
|
||||||
using TileServer.Application.Styles;
|
using TileServer.Application.Styles;
|
||||||
using TileServer.Application.Sync;
|
using TileServer.Application.Sync;
|
||||||
using TileServer.Application.Tiles;
|
using TileServer.Application.Tiles;
|
||||||
@@ -13,6 +14,7 @@ using TileServer.Infrastructure.Auth;
|
|||||||
using TileServer.Infrastructure.Data;
|
using TileServer.Infrastructure.Data;
|
||||||
using TileServer.Infrastructure.Downloads;
|
using TileServer.Infrastructure.Downloads;
|
||||||
using TileServer.Infrastructure.Extracts;
|
using TileServer.Infrastructure.Extracts;
|
||||||
|
using TileServer.Infrastructure.Graph;
|
||||||
using TileServer.Infrastructure.Storage;
|
using TileServer.Infrastructure.Storage;
|
||||||
using TileServer.Infrastructure.Styles;
|
using TileServer.Infrastructure.Styles;
|
||||||
using TileServer.Infrastructure.Sync;
|
using TileServer.Infrastructure.Sync;
|
||||||
@@ -74,6 +76,8 @@ public static class DependencyInjection
|
|||||||
services.AddSingleton<IExtractDownloader, HttpExtractDownloader>();
|
services.AddSingleton<IExtractDownloader, HttpExtractDownloader>();
|
||||||
services.AddSingleton<ITileStore, SqliteMbtilesTileStore>();
|
services.AddSingleton<ITileStore, SqliteMbtilesTileStore>();
|
||||||
services.AddSingleton<ITileBuilder, PlanetilerTileBuilder>();
|
services.AddSingleton<ITileBuilder, PlanetilerTileBuilder>();
|
||||||
|
services.AddSingleton<IRoadGraphStore, SqliteRoadGraphStore>();
|
||||||
|
services.AddSingleton<IRoadGraphBuilder, OsmSharpRoadGraphBuilder>();
|
||||||
services.AddSingleton<IPlanetilerBootstrapper, PlanetilerJarBootstrapper>();
|
services.AddSingleton<IPlanetilerBootstrapper, PlanetilerJarBootstrapper>();
|
||||||
services.AddSingleton<IPlanetilerSourceBootstrapper, PlanetilerSourceBootstrapper>();
|
services.AddSingleton<IPlanetilerSourceBootstrapper, PlanetilerSourceBootstrapper>();
|
||||||
services.AddSingleton<IStyleCatalog, FileStyleCatalog>();
|
services.AddSingleton<IStyleCatalog, FileStyleCatalog>();
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Two-pass PBF scan: highway ways → degree map + packed node refs; nodes → coords;
|
||||||
|
/// then collapse chains between intersections into edges with Haversine length.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class OsmSharpRoadGraphBuilder(ILogger<OsmSharpRoadGraphBuilder> logger) : IRoadGraphBuilder
|
||||||
|
{
|
||||||
|
private static readonly HashSet<string> 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<Dictionary<long, int>> CollectWaysAsync(string pbfPath, string waysDbPath, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var degrees = new Dictionary<long, int>();
|
||||||
|
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<Dictionary<long, (double Lon, double Lat)>> CollectCoordsAsync(
|
||||||
|
string pbfPath,
|
||||||
|
Dictionary<long, int> degrees,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
var coords = new Dictionary<long, (double Lon, double Lat)>(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<long, int> degrees,
|
||||||
|
Dictionary<long, (double Lon, double Lat)> 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<long>();
|
||||||
|
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)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<SqliteRoadGraphStore> 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<RoadGraphPage<RoadGraphNode>> 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<RoadGraphNode>(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<RoadGraphNode>(items, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<RoadGraphPage<RoadGraphEdge>> 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<RoadGraphEdge>(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<RoadGraphEdge>(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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,6 +15,7 @@ public sealed class DataPaths : IDataPaths
|
|||||||
: Path.Combine(environment.ContentRootPath, configured));
|
: Path.Combine(environment.ContentRootPath, configured));
|
||||||
Extracts = Path.Combine(Root, "extracts");
|
Extracts = Path.Combine(Root, "extracts");
|
||||||
Tiles = Path.Combine(Root, "tiles");
|
Tiles = Path.Combine(Root, "tiles");
|
||||||
|
Graphs = Path.Combine(Root, "graphs");
|
||||||
Styles = Path.Combine(Root, "styles");
|
Styles = Path.Combine(Root, "styles");
|
||||||
Tools = Path.Combine(Root, "tools");
|
Tools = Path.Combine(Root, "tools");
|
||||||
State = Path.Combine(Root, "state");
|
State = Path.Combine(Root, "state");
|
||||||
@@ -31,6 +32,8 @@ public sealed class DataPaths : IDataPaths
|
|||||||
|
|
||||||
public string Tiles { get; }
|
public string Tiles { get; }
|
||||||
|
|
||||||
|
public string Graphs { get; }
|
||||||
|
|
||||||
public string Styles { get; }
|
public string Styles { get; }
|
||||||
|
|
||||||
public string Tools { get; }
|
public string Tools { get; }
|
||||||
@@ -52,10 +55,15 @@ public sealed class DataPaths : IDataPaths
|
|||||||
// Planetiler infers archive format from the last suffix; keep ".mbtiles".
|
// Planetiler infers archive format from the last suffix; keep ".mbtiles".
|
||||||
public string StagingMbtiles(string extractId) => Path.Combine(Tiles, $"{extractId}.building.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()
|
public void EnsureCreated()
|
||||||
{
|
{
|
||||||
Directory.CreateDirectory(Extracts);
|
Directory.CreateDirectory(Extracts);
|
||||||
Directory.CreateDirectory(Tiles);
|
Directory.CreateDirectory(Tiles);
|
||||||
|
Directory.CreateDirectory(Graphs);
|
||||||
Directory.CreateDirectory(Styles);
|
Directory.CreateDirectory(Styles);
|
||||||
Directory.CreateDirectory(Tools);
|
Directory.CreateDirectory(Tools);
|
||||||
Directory.CreateDirectory(State);
|
Directory.CreateDirectory(State);
|
||||||
|
|||||||
@@ -15,6 +15,7 @@
|
|||||||
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.1" />
|
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.1" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
|
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
|
||||||
<PackageReference Include="NetTopologySuite" Version="2.5.0" />
|
<PackageReference Include="NetTopologySuite" Version="2.5.0" />
|
||||||
|
<PackageReference Include="OsmSharp" Version="7.0.0-pre022" />
|
||||||
<PackageReference Include="protobuf-net" Version="3.2.30" />
|
<PackageReference Include="protobuf-net" Version="3.2.30" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -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<DomainValidationException>(() =>
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -48,6 +48,8 @@ export function GuidesPage() {
|
|||||||
|
|
||||||
const styleUrl = `${origin}/u/${slug}/styles/osm-bright?source=${source}${token ? `&token=${token}` : "&token=ts_…"}`;
|
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 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(
|
const html = useMemo(
|
||||||
() => `<link href="https://unpkg.com/maplibre-gl@5.6.1/dist/maplibre-gl.css" rel="stylesheet" />
|
() => `<link href="https://unpkg.com/maplibre-gl@5.6.1/dist/maplibre-gl.css" rel="stylesheet" />
|
||||||
@@ -131,6 +133,13 @@ const map = new maplibregl.Map({
|
|||||||
скопирует слои. Один стиль — несколько округов на одной карте.
|
скопирует слои. Один стиль — несколько округов на одной карте.
|
||||||
</p>
|
</p>
|
||||||
</li>
|
</li>
|
||||||
|
<li>
|
||||||
|
<strong>5. Граф дорог</strong>
|
||||||
|
<p>
|
||||||
|
После sync рядом с тайлами лежит SQLite-граф (<code>highway=*</code>, рёбра между перекрёстками). Отдаётся только с
|
||||||
|
токеном. Узлы/рёбра — по <code>bbox</code> (≤ 2°), пагинация <code>after</code>.
|
||||||
|
</p>
|
||||||
|
</li>
|
||||||
</ol>
|
</ol>
|
||||||
|
|
||||||
<CopyBlock label="Style JSON" value={styleUrl} />
|
<CopyBlock label="Style JSON" value={styleUrl} />
|
||||||
@@ -139,6 +148,8 @@ const map = new maplibregl.Map({
|
|||||||
value={`${origin}/u/${slug}/styles/osm-bright?source=${sources.map((item) => item.id).join(",") || "central-fed-district,volga-fed-district"}${token ? `&token=${token}` : "&token=ts_…"}`}
|
value={`${origin}/u/${slug}/styles/osm-bright?source=${sources.map((item) => item.id).join(",") || "central-fed-district,volga-fed-district"}${token ? `&token=${token}` : "&token=ts_…"}`}
|
||||||
/>
|
/>
|
||||||
<CopyBlock label="Тайлы MVT" value={tilesUrl} />
|
<CopyBlock label="Тайлы MVT" value={tilesUrl} />
|
||||||
|
<CopyBlock label="Граф (метаданные)" value={graphUrl} />
|
||||||
|
<CopyBlock label="Граф: рёбра в bbox" value={graphEdgesUrl} />
|
||||||
|
|
||||||
<h2 className="guides__h">HTML</h2>
|
<h2 className="guides__h">HTML</h2>
|
||||||
<CopyBlock label="Минимальная страница" value={html} />
|
<CopyBlock label="Минимальная страница" value={html} />
|
||||||
|
|||||||
Reference in New Issue
Block a user