feat(proj): add graph
This commit is contained in:
@@ -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<TileServerOptions> options) : ControllerBase
|
||||
@@ -92,6 +96,86 @@ public sealed class PersonalDeliveryController(
|
||||
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)
|
||||
=> 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,
|
||||
"DefaultMaxZoom": 15,
|
||||
"OverzoomMaxZoom": 18,
|
||||
"BuildRoadGraph": true,
|
||||
"GlyphsUrl": "https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf",
|
||||
"Yandex": {
|
||||
"RedirectUri": "https://tile-server.ru"
|
||||
|
||||
@@ -6,6 +6,8 @@ public interface IUsageRecorder
|
||||
|
||||
void RecordStyle(Guid userId, Guid tokenId, long bytes);
|
||||
|
||||
void RecordGraph(Guid userId, Guid tokenId, long bytes);
|
||||
|
||||
IReadOnlyList<UsageDelta> Drain();
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -108,6 +108,9 @@ public sealed class TileServerOptions
|
||||
|
||||
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 List<ExtractOptions> Extracts { get; set; } = [];
|
||||
|
||||
@@ -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<ITileQueryService, TileQueryService>();
|
||||
services.AddSingleton<IStyleService, StyleService>();
|
||||
services.AddSingleton<IExtractService, ExtractService>();
|
||||
services.AddSingleton<IRoadGraphQueryService, RoadGraphQueryService>();
|
||||
services.AddSingleton<IMapSyncService, MapSyncService>();
|
||||
services.AddSingleton<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 Graphs { get; }
|
||||
|
||||
string RoadGraph(string extractId);
|
||||
|
||||
string StagingRoadGraph(string extractId);
|
||||
|
||||
void EnsureCreated();
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -8,4 +8,7 @@
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.2" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.2" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="TileServer.UnitTests" />
|
||||
</ItemGroup>
|
||||
</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.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<IExtractDownloader, HttpExtractDownloader>();
|
||||
services.AddSingleton<ITileStore, SqliteMbtilesTileStore>();
|
||||
services.AddSingleton<ITileBuilder, PlanetilerTileBuilder>();
|
||||
services.AddSingleton<IRoadGraphStore, SqliteRoadGraphStore>();
|
||||
services.AddSingleton<IRoadGraphBuilder, OsmSharpRoadGraphBuilder>();
|
||||
services.AddSingleton<IPlanetilerBootstrapper, PlanetilerJarBootstrapper>();
|
||||
services.AddSingleton<IPlanetilerSourceBootstrapper, PlanetilerSourceBootstrapper>();
|
||||
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));
|
||||
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);
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
|
||||
<PackageReference Include="NetTopologySuite" Version="2.5.0" />
|
||||
<PackageReference Include="OsmSharp" Version="7.0.0-pre022" />
|
||||
<PackageReference Include="protobuf-net" Version="3.2.30" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
|
||||
Reference in New Issue
Block a user