feat(proj): init

This commit is contained in:
vl.arkhangelskii
2026-09-21 03:53:15 +03:00
commit 3e34f391b3
258 changed files with 20968 additions and 0 deletions
@@ -0,0 +1,131 @@
using System.Security.Claims;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using TileServer.Application.Accounts;
using TileServer.Application.Configuration;
using TileServer.Domain.Exceptions;
namespace TileServer.Api.Controllers;
[ApiController]
[Route("api/v1/auth")]
public sealed class AuthController(
IAccountService accounts,
IOptions<TileServerOptions> options) : ControllerBase
{
private const string OAuthStateCookie = "ts_oauth_state";
[HttpGet("providers")]
[AllowAnonymous]
public IActionResult Providers()
{
var yandex = options.Value.Yandex;
var configured = yandex.IsConfigured;
return Ok(new AuthProvidersResponse(
new YandexProviderResponse(
configured,
configured ? yandex.ClientId : null,
configured ? yandex.RedirectUri : null)));
}
[HttpGet("yandex/start")]
[AllowAnonymous]
public IActionResult StartYandex()
{
var yandex = options.Value.Yandex;
if (!yandex.IsConfigured)
{
throw new DomainValidationException("Yandex OAuth is not configured.");
}
var state = Convert.ToHexString(RandomNumberGenerator.GetBytes(16)).ToLowerInvariant();
Response.Cookies.Append(OAuthStateCookie, state, new CookieOptions
{
HttpOnly = true,
Secure = Request.IsHttps,
SameSite = SameSiteMode.Lax,
MaxAge = TimeSpan.FromMinutes(15),
Path = "/"
});
var url =
"https://oauth.yandex.ru/authorize" +
"?response_type=code" +
$"&client_id={Uri.EscapeDataString(yandex.ClientId)}" +
$"&redirect_uri={Uri.EscapeDataString(yandex.RedirectUri)}" +
$"&state={Uri.EscapeDataString(state)}";
return Redirect(url);
}
[HttpPost("yandex")]
[AllowAnonymous]
public async Task<IActionResult> ExchangeYandex([FromBody] YandexCodeRequest request, CancellationToken ct)
{
var yandex = options.Value.Yandex;
if (!yandex.IsConfigured)
{
throw new DomainValidationException("Yandex OAuth is not configured.");
}
var redirectUri = string.IsNullOrWhiteSpace(request.RedirectUri)
? yandex.RedirectUri
: request.RedirectUri.Trim();
if (!IsAllowedRedirect(yandex.RedirectUri, redirectUri))
{
throw new DomainValidationException("Invalid Yandex redirect_uri.");
}
if (Request.Cookies.TryGetValue(OAuthStateCookie, out var expected) &&
!string.IsNullOrEmpty(expected) &&
!string.Equals(expected, request.State, StringComparison.Ordinal))
{
throw new UnauthenticatedException("OAuth state mismatch.");
}
var (me, cabinetToken) = await accounts.SignInFromYandexAsync(request.Code, redirectUri, ct)
.ConfigureAwait(false);
var identity = new ClaimsIdentity(
[
new Claim(ClaimTypes.NameIdentifier, me.Id.ToString()),
new Claim(ClaimTypes.Name, me.Login),
new Claim("slug", me.Slug)
],
CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(identity),
new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTimeOffset.UtcNow.AddDays(30)
}).ConfigureAwait(false);
Response.Cookies.Delete(OAuthStateCookie);
return Ok(new AuthResponse(me, cabinetToken));
}
[HttpPost("logout")]
[Authorize]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme).ConfigureAwait(false);
return NoContent();
}
private static bool IsAllowedRedirect(string configured, string incoming)
{
static string Normalize(string value) => value.Trim().TrimEnd('/');
return string.Equals(Normalize(configured), Normalize(incoming), StringComparison.OrdinalIgnoreCase);
}
}
public sealed record YandexCodeRequest(string Code, string? State, string? RedirectUri);
public sealed record AuthResponse(MeResponse User, string? CabinetToken);
public sealed record YandexProviderResponse(bool Enabled, string? ClientId, string? RedirectUri);
public sealed record AuthProvidersResponse(YandexProviderResponse Yandex);
@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Mvc;
namespace TileServer.Api.Controllers;
[Route("demo")]
[ApiExplorerSettings(IgnoreApi = true)]
public sealed class DemoController : Controller
{
[HttpGet("")]
[HttpGet("index")]
public IActionResult Index() => View();
}
@@ -0,0 +1,88 @@
using System.Text.Json.Nodes;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TileServer.Api.Http;
using TileServer.Application.Accounts;
using TileServer.Domain.Exceptions;
namespace TileServer.Api.Controllers;
[ApiController]
[Authorize]
[Route("api/v1/me")]
public sealed class MeController(
IAccountService accounts,
IApiTokenService tokens,
IUserStyleService styles,
IUsageQuery usage) : ControllerBase
{
[HttpGet]
public async Task<IActionResult> Get(CancellationToken ct)
=> Ok(await accounts.GetMeAsync(SessionUser.GetId(User), ct).ConfigureAwait(false));
[HttpGet("tokens")]
public async Task<IActionResult> ListTokens(CancellationToken ct)
=> Ok(await tokens.ListAsync(SessionUser.GetId(User), ct).ConfigureAwait(false));
[HttpPost("tokens")]
public async Task<IActionResult> CreateToken([FromBody] CreateTokenRequest request, CancellationToken ct)
=> Ok(await tokens.CreateAsync(SessionUser.GetId(User), request.Name ?? "Token", ct).ConfigureAwait(false));
[HttpDelete("tokens/{id:guid}")]
public async Task<IActionResult> RevokeToken(Guid id, CancellationToken ct)
{
await tokens.RevokeAsync(SessionUser.GetId(User), id, ct).ConfigureAwait(false);
return NoContent();
}
[HttpGet("styles")]
public async Task<IActionResult> ListStyles(CancellationToken ct)
=> Ok(await styles.ListMineAsync(SessionUser.GetId(User), ct).ConfigureAwait(false));
[HttpGet("styles/{name}")]
public async Task<IActionResult> GetStyle(string name, CancellationToken ct)
=> new JsonResult(await styles.GetMineAsync(SessionUser.GetId(User), name, ct).ConfigureAwait(false));
[HttpPost("styles")]
public async Task<IActionResult> CloneStyle([FromBody] CloneStyleRequest request, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(request.Name) || string.IsNullOrWhiteSpace(request.From))
{
throw new DomainValidationException("Style name and source preset are required.");
}
return Ok(await styles.CloneAsync(SessionUser.GetId(User), request.Name, request.From, ct)
.ConfigureAwait(false));
}
[HttpPut("styles/{name}")]
public async Task<IActionResult> SaveStyle(string name, [FromBody] JsonObject style, CancellationToken ct)
{
await styles.SaveMineAsync(SessionUser.GetId(User), name, style, ct).ConfigureAwait(false);
return NoContent();
}
[HttpDelete("styles/{name}")]
public async Task<IActionResult> DeleteStyle(string name, CancellationToken ct)
{
await styles.DeleteMineAsync(SessionUser.GetId(User), name, ct).ConfigureAwait(false);
return NoContent();
}
[HttpGet("usage")]
public async Task<IActionResult> GetUsage([FromQuery] DateOnly? from, [FromQuery] DateOnly? to, CancellationToken ct)
{
var end = to ?? DateOnly.FromDateTime(DateTime.UtcNow);
var start = from ?? end.AddDays(-6);
if (start > end)
{
throw new DomainValidationException("'from' must be on or before 'to'.");
}
return Ok(await usage.GetAsync(SessionUser.GetId(User), start, end, ct).ConfigureAwait(false));
}
}
public sealed record CreateTokenRequest(string? Name);
public sealed record CloneStyleRequest(string Name, string From);
@@ -0,0 +1,94 @@
using System.Text;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using TileServer.Api.Http;
using TileServer.Application.Accounts;
using TileServer.Application.Configuration;
using TileServer.Application.Extracts;
using TileServer.Application.Tiles;
using TileServer.Domain.Exceptions;
using TileServer.Domain.Tiles;
namespace TileServer.Api.Controllers;
[ApiController]
[AllowAnonymous]
[Route("u/{slug}")]
public sealed class PersonalDeliveryController(
IApiTokenService tokens,
ITileQueryService tiles,
IUserStyleService styles,
IExtractCatalog extracts,
IUsageRecorder usage,
IOptions<TileServerOptions> options) : ControllerBase
{
[HttpGet("tiles/{source}/{z:int}/{x:int}/{y:int}.pbf")]
public async Task<IActionResult> GetTile(string slug, string source, int z, int x, int y, CancellationToken ct)
{
var access = await ResolveAsync(slug, ct).ConfigureAwait(false);
var result = await tiles.GetTileAsync(source, new TileCoordinate(z, x, y), ct).ConfigureAwait(false);
if (result is null)
{
Response.Headers.CacheControl = "no-store";
usage.RecordTile(access.User.Id, access.Token.Id, 0);
return NoContent();
}
var payload = result.Tile.Uncompressed();
usage.RecordTile(access.User.Id, access.Token.Id, payload.Length);
Response.Headers.CacheControl = "private, max-age=604800, immutable";
return File(payload, "application/vnd.mapbox-vector-tile");
}
[HttpGet("tiles/{source}.json")]
[Produces("application/json")]
public async Task<IActionResult> GetTileJson(string slug, string source, CancellationToken ct)
{
var access = await ResolveAsync(slug, ct).ConfigureAwait(false);
var token = AccessToken.Read(Request) ?? string.Empty;
var tilesUrl =
$"{PublicUrl.GetBase(Request, options)}/u/{access.User.Slug}/tiles/{source}/{{z}}/{{x}}/{{y}}.pbf?v=3&token={Uri.EscapeDataString(token)}";
return Ok(tiles.GetTileJson(source, tilesUrl));
}
[HttpGet("styles")]
public async Task<IActionResult> ListStyles(string slug, CancellationToken ct)
{
var access = await ResolveAsync(slug, ct).ConfigureAwait(false);
var token = AccessToken.Read(Request) ?? string.Empty;
var list = await styles.ListForDeliveryAsync(
access.User.Slug,
PublicUrl.GetBase(Request, options),
token,
ct)
.ConfigureAwait(false);
return Ok(list);
}
[HttpGet("styles/{name}")]
[Produces("application/json")]
public async Task<IActionResult> GetStyle(string slug, string name, [FromQuery] string? source, CancellationToken ct)
{
var access = await ResolveAsync(slug, ct).ConfigureAwait(false);
var token = AccessToken.Read(Request) ?? string.Empty;
var extract = string.IsNullOrWhiteSpace(source)
? extracts.GetAll().FirstOrDefault(e => e.Enabled)
: extracts.Find(source);
if (extract is null)
{
throw new ResourceNotFoundException("Extract", source ?? "(none configured)");
}
var tilesUrl =
$"{PublicUrl.GetBase(Request, options)}/u/{access.User.Slug}/tiles/{extract.Id}/{{z}}/{{x}}/{{y}}.pbf?v=3&token={Uri.EscapeDataString(token)}";
var style = await styles.GetForDeliveryAsync(access.User.Slug, name, extract.Id, tilesUrl, ct)
.ConfigureAwait(false);
var json = style.ToJsonString();
usage.RecordStyle(access.User.Id, access.Token.Id, Encoding.UTF8.GetByteCount(json));
return new JsonResult(style);
}
private Task<ResolvedAccess> ResolveAsync(string slug, CancellationToken ct)
=> tokens.ResolveAsync(slug, AccessToken.Read(Request), bearer: null, ct);
}
@@ -0,0 +1,38 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using TileServer.Api.Http;
using TileServer.Application.Configuration;
using TileServer.Application.Extracts;
namespace TileServer.Api.Controllers;
[ApiController]
[Route("api/v1/sources")]
public sealed class SourcesController(IExtractService extracts, IOptions<TileServerOptions> options) : ControllerBase
{
[HttpGet]
[ProducesResponseType(typeof(IReadOnlyList<ExtractResponse>), StatusCodes.Status200OK)]
public async Task<IActionResult> List(CancellationToken ct)
=> Ok(await extracts.ListAsync(PublicUrl.GetBase(Request, options), ct).ConfigureAwait(false));
[HttpGet("{id}")]
[ProducesResponseType(typeof(ExtractResponse), StatusCodes.Status200OK)]
public async Task<IActionResult> Get(string id, CancellationToken ct)
=> Ok(await extracts.GetAsync(id, PublicUrl.GetBase(Request, options), ct).ConfigureAwait(false));
[HttpPut("{id}")]
[ProducesResponseType(typeof(ExtractResponse), StatusCodes.Status200OK)]
public async Task<IActionResult> Upsert(string id, [FromBody] CreateExtractRequest request, CancellationToken ct)
{
var payload = request with { Id = string.IsNullOrWhiteSpace(request.Id) ? id : request.Id };
return Ok(await extracts.AddOrUpdateAsync(payload, PublicUrl.GetBase(Request, options), ct).ConfigureAwait(false));
}
[HttpDelete("{id}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> Delete(string id, CancellationToken ct)
{
await extracts.RemoveAsync(id, ct).ConfigureAwait(false);
return NoContent();
}
}
@@ -0,0 +1,22 @@
using System.Text.Json.Nodes;
using Microsoft.AspNetCore.Mvc;
using TileServer.Api.Http;
namespace TileServer.Api.Controllers;
[ApiController]
[Route("api/v1/styles")]
public sealed class StylesController : ControllerBase
{
[HttpGet]
public IActionResult List() => Closed();
[HttpGet("{name}")]
public IActionResult Get(string name, [FromQuery] string? source) => Closed();
[HttpPut("{name}")]
public IActionResult Put(string name, [FromBody] JsonObject style) => Closed();
private static IActionResult Closed()
=> PublicDelivery.Closed("Public styles are disabled. Use /u/{slug}/styles/{name}?token= or POST /api/v1/me/styles while signed in.");
}
@@ -0,0 +1,53 @@
using Microsoft.AspNetCore.Mvc;
using TileServer.Application.Sync;
using TileServer.Domain.Exceptions;
namespace TileServer.Api.Controllers;
[ApiController]
[Route("api/v1/sync")]
public sealed class SyncController(IMapSyncService sync, ILogger<SyncController> logger) : ControllerBase
{
[HttpGet("status")]
[ProducesResponseType(typeof(SyncJobStatus), StatusCodes.Status200OK)]
public IActionResult Status() => Ok(sync.GetStatus());
[HttpPost]
[ProducesResponseType(StatusCodes.Status202Accepted)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
public IActionResult RunAll()
=> Start(() => sync.RunAllAsync(CancellationToken.None), "Synchronization started for all extracts.");
[HttpPost("{extractId}")]
[ProducesResponseType(StatusCodes.Status202Accepted)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
public IActionResult RunOne(string extractId)
=> Start(() => sync.RunOneAsync(extractId, CancellationToken.None), $"Synchronization started for '{extractId}'.");
private IActionResult Start(Func<Task> work, string message)
{
if (sync.GetStatus().IsRunning)
{
return Conflict(new { message = "A synchronization job is already running." });
}
_ = RunInBackground(work);
return Accepted(new { message });
}
private async Task RunInBackground(Func<Task> work)
{
try
{
await work().ConfigureAwait(false);
}
catch (ResourceConflictException)
{
logger.LogInformation("Sync request ignored because another job is running.");
}
catch (Exception ex)
{
logger.LogError(ex, "Background synchronization failed.");
}
}
}
@@ -0,0 +1,22 @@
using Microsoft.AspNetCore.Mvc;
using TileServer.Api.Http;
namespace TileServer.Api.Controllers;
[ApiController]
[Route("api/v1/tiles")]
public sealed class TilesController : ControllerBase
{
[HttpGet("{extractId}/{z:int}/{x:int}/{y:int}.pbf")]
[HttpGet("/tiles/{extractId}/{z:int}/{x:int}/{y:int}.pbf")]
public IActionResult GetTile(string extractId, int z, int x, int y)
=> Closed();
[HttpGet("{extractId}.json")]
[HttpGet("/tiles/{extractId}.json")]
public IActionResult GetTileJson(string extractId)
=> Closed();
private static IActionResult Closed()
=> PublicDelivery.Closed("Public tiles are disabled. Use /u/{slug}/tiles/{source}/{z}/{x}/{y}.pbf?token=");
}
+18
View File
@@ -0,0 +1,18 @@
namespace TileServer.Api.Http;
public static class AccessToken
{
public static string? Read(HttpRequest request)
{
if (request.Query.TryGetValue("token", out var query) && !string.IsNullOrWhiteSpace(query))
{
return query.ToString();
}
var header = request.Headers.Authorization.ToString();
const string bearer = "Bearer ";
return header.StartsWith(bearer, StringComparison.OrdinalIgnoreCase)
? header[bearer.Length..].Trim()
: null;
}
}
+17
View File
@@ -0,0 +1,17 @@
using Microsoft.AspNetCore.Mvc;
namespace TileServer.Api.Http;
internal static class PublicDelivery
{
public static IActionResult Closed(string detail)
=> new ObjectResult(new ProblemDetails
{
Status = StatusCodes.Status401Unauthorized,
Title = "Unauthorized",
Detail = detail
})
{
StatusCode = StatusCodes.Status401Unauthorized
};
}
+37
View File
@@ -0,0 +1,37 @@
using Microsoft.Extensions.Options;
using TileServer.Application.Configuration;
namespace TileServer.Api.Http;
public static class PublicUrl
{
public static string GetBase(HttpRequest request, IOptions<TileServerOptions> options)
=> GetBase(request, options.Value.PublicBaseUrl);
public static string GetBase(HttpRequest request, string? publicBaseUrl)
{
if (!string.IsNullOrWhiteSpace(publicBaseUrl))
{
return publicBaseUrl.TrimEnd('/');
}
var scheme = FirstForwarded(request.Headers["X-Forwarded-Proto"]) ?? request.Scheme;
var host = FirstForwarded(request.Headers["X-Forwarded-Host"]) ?? request.Host.Value;
var pathBase = request.PathBase.HasValue
? request.PathBase.Value!.TrimEnd('/')
: string.Empty;
return $"{scheme}://{host}{pathBase}";
}
private static string? FirstForwarded(string? header)
{
if (string.IsNullOrWhiteSpace(header))
{
return null;
}
var value = header.Split(',')[0].Trim();
return string.IsNullOrWhiteSpace(value) ? null : value;
}
}
+17
View File
@@ -0,0 +1,17 @@
using System.Security.Claims;
namespace TileServer.Api.Http;
public static class SessionUser
{
public static Guid GetId(ClaimsPrincipal user)
{
var raw = user.FindFirstValue(ClaimTypes.NameIdentifier);
if (!Guid.TryParse(raw, out var id))
{
throw new InvalidOperationException("Authenticated user id is missing.");
}
return id;
}
}
@@ -0,0 +1,47 @@
using System.Net;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using TileServer.Domain.Exceptions;
namespace TileServer.Api.Middleware;
public sealed class DomainExceptionHandler(ILogger<DomainExceptionHandler> logger) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
var (status, title) = exception switch
{
ResourceNotFoundException => (HttpStatusCode.NotFound, "Resource not found"),
DomainValidationException => (HttpStatusCode.BadRequest, "Validation failed"),
ResourceConflictException => (HttpStatusCode.Conflict, "Conflict"),
UnauthenticatedException => (HttpStatusCode.Unauthorized, "Unauthorized"),
_ => (HttpStatusCode.InternalServerError, "Unexpected error")
};
if (status == HttpStatusCode.InternalServerError)
{
logger.LogError(exception, "Unhandled exception");
}
else
{
logger.LogInformation(exception, "Domain exception mapped to {Status}", (int)status);
}
var problem = new ProblemDetails
{
Status = (int)status,
Title = title,
Detail = status == HttpStatusCode.InternalServerError ? "An unexpected error occurred." : exception.Message,
Instance = httpContext.Request.Path
};
httpContext.Response.StatusCode = (int)status;
if (status == HttpStatusCode.Unauthorized)
{
httpContext.Response.Headers.CacheControl = "no-store";
}
await httpContext.Response.WriteAsJsonAsync(problem, cancellationToken).ConfigureAwait(false);
return true;
}
}
+133
View File
@@ -0,0 +1,133 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.FileProviders;
using TileServer.Api.Middleware;
using TileServer.Application;
using TileServer.Infrastructure;
using TileServer.Infrastructure.Data;
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddApplication()
.AddInfrastructure(builder.Configuration);
var dataDirectory = builder.Configuration["TileServer:DataDirectory"] ?? "data";
var keyPath = Path.Combine(dataDirectory, "aspnet-keys");
Directory.CreateDirectory(keyPath);
builder.Services
.AddDataProtection()
.SetApplicationName("TileServer")
.PersistKeysToFileSystem(new DirectoryInfo(keyPath));
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor
| ForwardedHeaders.XForwardedProto
| ForwardedHeaders.XForwardedHost;
// Docker / nginx source IPs are not in the default known-proxy list.
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
});
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<DomainExceptionHandler>();
builder.Services.AddResponseCaching();
builder.Services.AddHealthChecks();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new()
{
Title = "Tile Server API",
Version = "v1",
Description = "Vector tiles, MapLibre styles and OSM extract synchronization."
});
});
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
policy.AllowAnyOrigin()
.AllowAnyHeader()
.WithMethods("GET", "HEAD", "PUT", "POST", "DELETE"));
});
builder.Services
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "ts_session";
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = SameSiteMode.Lax;
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
options.SlidingExpiration = true;
options.ExpireTimeSpan = TimeSpan.FromDays(30);
options.Events.OnRedirectToLogin = context =>
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.CompletedTask;
};
options.Events.OnRedirectToAccessDenied = context =>
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return Task.CompletedTask;
};
});
builder.Services.AddAuthorization();
builder.Services
.AddControllersWithViews()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
db.Database.Migrate();
}
app.UseForwardedHeaders();
app.UseExceptionHandler();
app.UseSwagger();
app.UseSwaggerUI();
var spaRoot = Path.Combine(app.Environment.WebRootPath, "app");
if (Directory.Exists(spaRoot))
{
var spaFiles = new PhysicalFileProvider(spaRoot);
app.UseDefaultFiles(new DefaultFilesOptions { FileProvider = spaFiles });
app.UseStaticFiles(new StaticFileOptions { FileProvider = spaFiles });
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseResponseCaching();
app.UseCors();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapHealthChecks("/health/live");
app.MapHealthChecks("/health/ready");
if (File.Exists(Path.Combine(spaRoot, "index.html")))
{
app.MapFallbackToFile("app/index.html");
}
else
{
app.MapGet("/", () => Results.Redirect("/demo"));
}
app.Run();
@@ -0,0 +1,15 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "",
"applicationUrl": "http://localhost:5088",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
+16
View File
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.11">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TileServer.Application\TileServer.Application.csproj" />
<ProjectReference Include="..\TileServer.Infrastructure\TileServer.Infrastructure.csproj" />
</ItemGroup>
<ItemGroup>
<Content Include="..\TileServer.Infrastructure\Seed\styles\*.json" Link="Seed\styles\%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
</Project>
+6
View File
@@ -0,0 +1,6 @@
@TileServer.Api_HostAddress = http://localhost:5005
GET {{TileServer.Api_HostAddress}}/weatherforecast/
Accept: application/json
###
@@ -0,0 +1,96 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Tile Server</title>
<link rel="stylesheet" href="https://unpkg.com/maplibre-gl@5.6.1/dist/maplibre-gl.css" />
<link rel="stylesheet" href="~/css/demo.css" asp-append-version="true" />
</head>
<body>
<div id="map" role="application" aria-label="Карта"></div>
<header class="hud hud--top">
<div class="brand">
<span class="brand__mark" aria-hidden="true">
<svg viewBox="0 0 24 24" width="22" height="22">
<rect x="2" y="2" width="9" height="9" rx="1.6" fill="currentColor" opacity="0.95"/>
<rect x="13" y="2" width="9" height="9" rx="1.6" fill="currentColor" opacity="0.55"/>
<rect x="2" y="13" width="9" height="9" rx="1.6" fill="currentColor" opacity="0.55"/>
<rect x="13" y="13" width="9" height="9" rx="1.6" fill="currentColor" opacity="0.28"/>
</svg>
</span>
<span class="brand__text">
<strong>Tile Server</strong>
<span>OSM · MapLibre · Geofabrik</span>
</span>
</div>
<div class="toolbar">
<label class="field field--inline">
<span>Источник</span>
<select id="source-select"></select>
</label>
<label class="field field--inline">
<span>Стиль</span>
<select id="style-select"></select>
</label>
<span class="pill" id="status-pill">—</span>
<button type="button" class="btn btn--accent" id="sync-button">Синхронизировать</button>
<a class="link" href="/swagger" target="_blank" rel="noreferrer">OpenAPI</a>
</div>
</header>
<form class="hud hud--goto" id="goto-form">
<div class="goto__head">
<div>
<h1>Камера</h1>
<p class="coords" id="live-coords">—</p>
</div>
</div>
<div class="presets" role="group" aria-label="Быстрый переход">
<button type="button" class="preset" data-lat="55.7558" data-lon="37.6173" data-zoom="14">Москва</button>
<button type="button" class="preset" data-lat="54.2255" data-lon="38.4692" data-zoom="6">ЦФО</button>
<button type="button" class="preset preset--ghost" id="fit-bounds">По выгрузке</button>
</div>
<div class="goto__row">
<label class="field">
<span>Широта</span>
<input id="goto-lat" name="lat" inputmode="decimal" autocomplete="off" spellcheck="false" placeholder="55.7558" required />
</label>
<label class="field">
<span>Долгота</span>
<input id="goto-lon" name="lon" inputmode="decimal" autocomplete="off" spellcheck="false" placeholder="37.6173" required />
</label>
<label class="field field--zoom">
<span>Зум</span>
<input id="goto-zoom" name="zoom" inputmode="decimal" autocomplete="off" spellcheck="false" placeholder="14" required />
</label>
</div>
<button type="submit" class="btn btn--accent btn--block">Перейти</button>
<p class="error" id="goto-error" hidden></p>
</form>
<aside class="hud hud--status" id="worker-panel">
<details>
<summary>
<span class="worker__pulse" aria-hidden="true"></span>
Воркер
</summary>
<dl>
<div><dt>Задача</dt><dd id="sync-running">—</dd></div>
<div><dt>Источник</dt><dd id="source-state">—</dd></div>
<div><dt>Скачан</dt><dd id="source-downloaded">—</dd></div>
<div><dt>Собран</dt><dd id="source-built">—</dd></div>
<div><dt>Следующий запуск</dt><dd id="sync-next">—</dd></div>
</dl>
<p class="error" id="sync-error" hidden></p>
</details>
</aside>
<div id="banner" class="banner" hidden></div>
<script src="https://unpkg.com/maplibre-gl@5.6.1/dist/maplibre-gl.js"></script>
<script src="~/js/demo.js" asp-append-version="true"></script>
</body>
</html>
@@ -0,0 +1 @@
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft.AspNetCore": "Information"
}
}
}
+64
View File
@@ -0,0 +1,64 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"Accounts": "Host=127.0.0.1;Port=5433;Database=tile_server;Username=tiles;Password=tiles"
},
"TileServer": {
"DataDirectory": "../../data",
"JavaPath": "java",
"JvmMaxHeap": "8g",
"PlanetilerJarUrl": "https://github.com/openmaptiles/planetiler-openmaptiles/releases/download/v3.16/planetiler-openmaptiles.jar",
"PlanetilerHttpTimeout": "15m",
"DownloadStallTimeoutSeconds": 45,
"NaturalEarthUrls": [
"https://naciscdn.org/naturalearth/packages/natural_earth_vector.sqlite.zip",
"https://naturalearth.s3.amazonaws.com/packages/natural_earth_vector.sqlite.zip"
],
"LakeCenterlinesUrls": [
"https://github.com/acalcutt/osm-lakelines/releases/download/latest/lake_centerline.shp.zip",
"https://acalcutt.github.io/osm-lakelines/lake_centerline.shp.zip"
],
"WaterPolygonsUrls": [
"https://osmdata.openstreetmap.de/download/water-polygons-split-3857.zip"
],
"DefaultMinZoom": 0,
"DefaultMaxZoom": 15,
"OverzoomMaxZoom": 18,
"GlyphsUrl": "https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf",
"Yandex": {
"RedirectUri": "https://tile-server.ru"
},
"Sync": {
"Cron": "0 3 * * *",
"TimeZone": "UTC",
"RunOnStartup": true,
"RebuildIfTilesMissing": true
},
"Extracts": [
{
"Id": "central-fed-district",
"Name": "Центральный федеральный округ",
"Url": "https://download.geofabrik.de/russia/central-fed-district-latest.osm.pbf",
"Center": [ 37.6173, 55.7558 ],
"MinZoom": 0,
"MaxZoom": 15,
"Enabled": true
},
{
"Id": "volga-fed-district",
"Name": "Волго-Вятский федеральный округ",
"Url": "https://download.geofabrik.de/russia/volga-fed-district-latest.osm.pbf",
"Center": [ 45.0000, 57.0000 ],
"MinZoom": 0,
"MaxZoom": 15,
"Enabled": true
}
]
}
}
+469
View File
@@ -0,0 +1,469 @@
:root {
--bg: #0b0f14;
--panel: rgba(14, 18, 26, 0.78);
--panel-strong: rgba(10, 13, 18, 0.92);
--text: #f4f1ea;
--muted: #9aa6b4;
--line: rgba(244, 241, 234, 0.1);
--line-strong: rgba(244, 241, 234, 0.16);
--accent: #e8923d;
--accent-press: #f3a85a;
--accent-ink: #1a1208;
--danger: #ff8a7a;
--ok: #7dcea0;
--warn: #f5c16c;
--radius: 16px;
--radius-sm: 10px;
--font: "Segoe UI Variable Display", "Segoe UI", "SF Pro Display", ui-sans-serif, system-ui, sans-serif;
--hud-z: 3;
--shadow: 0 18px 50px rgba(0, 0, 0, 0.38), 0 1px 0 rgba(255, 255, 255, 0.04) inset;
--space: 12px;
}
* { box-sizing: border-box; }
html {
color-scheme: dark;
}
html, body, #map {
margin: 0;
width: 100%;
height: 100%;
}
body {
font-family: var(--font);
color: var(--text);
background: var(--bg);
overflow: hidden;
letter-spacing: 0.01em;
}
.hud {
position: absolute;
z-index: var(--hud-z);
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.045), transparent 42%),
var(--panel);
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: var(--shadow);
backdrop-filter: blur(22px) saturate(1.35);
-webkit-backdrop-filter: blur(22px) saturate(1.35);
}
.hud--top {
top: var(--space);
left: var(--space);
max-width: min(70rem, calc(100vw - 4.5rem));
display: flex;
flex-wrap: nowrap;
align-items: flex-end;
gap: 0.85rem 1rem;
padding: 0.7rem 0.8rem 0.75rem;
}
.brand {
display: flex;
align-items: center;
gap: 0.7rem;
padding: 0 0.2rem 0.15rem;
flex: 0 0 auto;
}
.brand__mark {
display: grid;
place-items: center;
width: 2.25rem;
height: 2.25rem;
border-radius: 11px;
color: var(--accent);
background: rgba(232, 146, 61, 0.12);
border: 1px solid rgba(232, 146, 61, 0.28);
}
.brand__text {
display: flex;
flex-direction: column;
gap: 0.08rem;
}
.brand strong {
font-size: 0.92rem;
font-weight: 650;
letter-spacing: 0.01em;
}
.brand__text span {
color: var(--muted);
font-size: 0.68rem;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.toolbar {
display: flex;
flex-wrap: wrap;
align-items: end;
gap: 0.55rem 0.65rem;
padding-left: 0.85rem;
border-left: 1px solid var(--line);
}
.field {
display: flex;
flex-direction: column;
gap: 0.28rem;
font-size: 0.68rem;
color: var(--muted);
letter-spacing: 0.06em;
text-transform: uppercase;
}
.field--inline { min-width: 10.5rem; }
.field--zoom { min-width: 0; }
select, button, input {
font: inherit;
letter-spacing: 0;
text-transform: none;
border-radius: var(--radius-sm);
border: 1px solid var(--line-strong);
background: rgba(8, 11, 16, 0.72);
color: var(--text);
padding: 0.48rem 0.7rem;
min-height: 2.75rem;
}
select, input {
font-variant-numeric: tabular-nums;
}
select {
appearance: none;
background-image:
linear-gradient(45deg, transparent 50%, var(--muted) 50%),
linear-gradient(135deg, var(--muted) 50%, transparent 50%);
background-position:
calc(100% - 16px) calc(50% - 3px),
calc(100% - 11px) calc(50% - 3px);
background-size: 5px 5px, 5px 5px;
background-repeat: no-repeat;
padding-right: 1.7rem;
}
.btn,
button {
cursor: pointer;
border: 0;
font-weight: 650;
}
.btn--accent,
#sync-button,
.hud--goto button[type="submit"] {
background: var(--accent);
color: var(--accent-ink);
box-shadow: 0 8px 20px rgba(232, 146, 61, 0.22);
}
.btn--accent:hover,
#sync-button:hover,
.hud--goto button[type="submit"]:hover {
background: var(--accent-press);
}
.btn--block {
width: 100%;
}
button:disabled { opacity: 0.55; cursor: wait; }
.preset,
.hud--status summary,
.preset--ghost {
background: rgba(8, 11, 16, 0.55);
color: var(--text);
font-weight: 550;
border: 1px solid var(--line);
box-shadow: none;
}
.preset:hover,
.preset--ghost:hover,
.hud--status summary:hover {
border-color: rgba(232, 146, 61, 0.45);
color: #fff;
}
.link {
color: var(--muted);
font-size: 0.78rem;
align-self: center;
padding: 0.45rem 0.35rem;
text-decoration: none;
}
.link:hover { color: var(--accent); }
.pill {
align-self: end;
font-size: 0.72rem;
padding: 0.42rem 0.75rem 0.42rem 0.65rem;
min-height: 2.75rem;
display: inline-flex;
align-items: center;
gap: 0.45rem;
border-radius: 999px;
border: 1px solid var(--line);
background: rgba(8, 11, 16, 0.72);
letter-spacing: 0.04em;
text-transform: uppercase;
}
.pill::before {
content: "";
width: 0.48rem;
height: 0.48rem;
border-radius: 50%;
background: var(--muted);
box-shadow: 0 0 0 4px rgba(154, 166, 180, 0.12);
}
.pill--ok { color: var(--ok); border-color: rgba(125, 206, 160, 0.32); }
.pill--ok::before { background: var(--ok); box-shadow: 0 0 0 4px rgba(125, 206, 160, 0.16); }
.pill--work { color: var(--warn); border-color: rgba(245, 193, 108, 0.32); }
.pill--work::before { background: var(--warn); box-shadow: 0 0 0 4px rgba(245, 193, 108, 0.16); }
.pill--fail { color: var(--danger); border-color: rgba(255, 138, 122, 0.4); }
.pill--fail::before { background: var(--danger); box-shadow: 0 0 0 4px rgba(255, 138, 122, 0.16); }
.hud--goto {
left: var(--space);
bottom: 1.75rem;
width: min(22.75rem, calc(100vw - 24px));
padding: 0.95rem;
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.goto__head h1 {
margin: 0;
font-size: 0.68rem;
font-weight: 650;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.08em;
}
.coords {
margin: 0.28rem 0 0;
font-variant-numeric: tabular-nums;
font-size: 0.98rem;
font-weight: 560;
letter-spacing: 0.01em;
}
.coords__sep {
color: var(--muted);
margin: 0 0.35rem;
font-weight: 400;
}
.presets {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
}
.presets button {
min-height: 2.5rem;
padding: 0.4rem 0.75rem;
font-size: 0.8rem;
}
.goto__row {
display: grid;
grid-template-columns: 1fr 1fr 4.8rem;
gap: 0.45rem;
padding: 0.45rem;
border-radius: 12px;
background: rgba(8, 11, 16, 0.45);
border: 1px solid var(--line);
}
.goto__row input {
min-height: 2.5rem;
background: transparent;
border-color: transparent;
padding-inline: 0.35rem;
}
.goto__row input:focus {
border-color: rgba(232, 146, 61, 0.45);
background: rgba(232, 146, 61, 0.06);
}
.hud--status {
right: var(--space);
bottom: 3.4rem;
top: auto;
width: min(19.5rem, calc(100vw - 24px));
padding: 0;
overflow: hidden;
}
.hud--status summary {
cursor: pointer;
list-style: none;
display: flex;
align-items: center;
gap: 0.55rem;
padding: 0.7rem 0.9rem;
font-size: 0.78rem;
letter-spacing: 0.06em;
text-transform: uppercase;
border: 0;
border-radius: 0;
min-height: 2.75rem;
background: transparent;
}
.hud--status summary::-webkit-details-marker { display: none; }
.worker__pulse {
width: 0.5rem;
height: 0.5rem;
border-radius: 50%;
background: var(--muted);
}
.hud--status.is-running .worker__pulse {
background: var(--warn);
box-shadow: 0 0 0 0 rgba(245, 193, 108, 0.7);
animation: pulse 1.6s ease-out infinite;
}
.hud--status.is-ready .worker__pulse {
background: var(--ok);
}
.hud--status dl,
.hud--status .error {
padding: 0 0.9rem 0.85rem;
}
dl {
margin: 0;
display: grid;
gap: 0.45rem;
}
dl div {
display: flex;
justify-content: space-between;
gap: 0.75rem;
font-size: 0.78rem;
letter-spacing: 0;
text-transform: none;
}
dt { color: var(--muted); }
dd {
margin: 0;
text-align: right;
font-variant-numeric: tabular-nums;
}
.error {
margin: 0;
font-size: 0.78rem;
color: var(--danger);
letter-spacing: 0;
text-transform: none;
}
.banner {
position: absolute;
z-index: var(--hud-z);
left: var(--space);
top: 5.4rem;
max-width: min(34rem, calc(100vw - 24px));
background: rgba(42, 31, 18, 0.92);
color: #ffe0c2;
border: 1px solid #6a4a22;
border-radius: var(--radius);
padding: 0.75rem 1rem;
box-shadow: var(--shadow);
}
button:focus-visible,
select:focus-visible,
input:focus-visible,
a:focus-visible,
summary:focus-visible {
outline: 2px solid #fff;
outline-offset: 2px;
}
.maplibregl-ctrl-top-right { top: var(--space); right: var(--space); }
.maplibregl-ctrl-bottom-right { right: var(--space); bottom: var(--space); }
.maplibregl-ctrl-group {
background: var(--panel-strong);
border: 1px solid var(--line);
border-radius: 12px;
box-shadow: var(--shadow);
overflow: hidden;
}
.maplibregl-ctrl-group button {
background: transparent;
min-height: 2.25rem;
}
.maplibregl-ctrl-attrib {
background: rgba(10, 13, 18, 0.62) !important; /* MapLibre default is opaque white */
color: var(--muted);
border-radius: 8px;
}
.maplibregl-ctrl-scale {
background: rgba(10, 13, 18, 0.62);
color: var(--text);
border-color: var(--muted);
}
@keyframes pulse {
0% { box-shadow: 0 0 0 0 rgba(245, 193, 108, 0.55); }
100% { box-shadow: 0 0 0 10px rgba(245, 193, 108, 0); }
}
@media (max-width: 860px) {
.hud--top {
right: 3.6rem;
max-width: none;
flex-wrap: wrap;
align-items: center;
}
.toolbar {
padding-left: 0;
border-left: 0;
width: 100%;
}
.field--inline { min-width: 8.5rem; flex: 1; }
.hud--status { display: none; }
.banner { top: auto; bottom: 13.5rem; }
}
@media (prefers-reduced-motion: reduce) {
* {
scroll-behavior: auto;
animation: none !important; /* third-party MapLibre fade + our pulse */
transition: none !important;
}
}
+323
View File
@@ -0,0 +1,323 @@
const sourceSelect = document.getElementById("source-select");
const styleSelect = document.getElementById("style-select");
const syncButton = document.getElementById("sync-button");
const gotoForm = document.getElementById("goto-form");
const gotoError = document.getElementById("goto-error");
const latInput = document.getElementById("goto-lat");
const lonInput = document.getElementById("goto-lon");
const zoomInput = document.getElementById("goto-zoom");
const liveCoords = document.getElementById("live-coords");
const banner = document.getElementById("banner");
const statusPill = document.getElementById("status-pill");
let map;
let sources = [];
let styles = [];
let activeStyleKey = null;
let suppressGotoSync = false;
function formatStatus(value) {
const labels = {
Pending: "ожидание",
Downloading: "скачивание PBF",
PreparingSources: "данные Planetiler",
Building: "сборка тайлов",
Ready: "готово",
Failed: "ошибка"
};
return labels[value] ?? value ?? "—";
}
function formatDate(value) {
if (!value) {
return "нет";
}
return new Date(value).toLocaleString("ru-RU");
}
function showBanner(text, visible) {
banner.hidden = !visible;
banner.textContent = text ?? "";
}
function showGotoError(text) {
gotoError.hidden = !text;
gotoError.textContent = text ?? "";
}
function parseNumber(value) {
const parsed = Number(String(value).trim().replace(",", "."));
return Number.isFinite(parsed) ? parsed : null;
}
function cameraFromHash() {
const match = location.hash.match(/^#([\d.]+)\/(-?[\d.]+)\/(-?[\d.]+)/);
if (!match) {
return null;
}
const zoom = Number(match[1]);
const lat = Number(match[2]);
const lon = Number(match[3]);
if (![zoom, lat, lon].every(Number.isFinite)) {
return null;
}
return { zoom, lat, lon };
}
function isGotoInputFocused() {
const el = document.activeElement;
return el === latInput || el === lonInput || el === zoomInput;
}
function isUninitializedCamera(center, zoom) {
return zoom < 2 && Math.abs(center.lat) < 1 && Math.abs(center.lng) < 1;
}
async function fetchJson(url, options) {
const response = await fetch(url, options);
if (!response.ok) {
const body = await response.text();
throw new Error(body || `${response.status} ${response.statusText}`);
}
if (response.status === 204) {
return null;
}
return response.json();
}
function currentSource() {
return sources.find((item) => item.id === sourceSelect.value) ?? sources[0];
}
function updateHud() {
if (!map) {
return;
}
const center = map.getCenter();
const zoom = map.getZoom();
liveCoords.innerHTML = `${center.lat.toFixed(5)}°<span class="coords__sep">·</span>${center.lng.toFixed(5)}°<span class="coords__sep">z</span>${zoom.toFixed(2)}`;
}
function syncGotoFromMap() {
if (!map || suppressGotoSync || isGotoInputFocused()) {
return;
}
const center = map.getCenter();
const zoom = map.getZoom();
if (isUninitializedCamera(center, zoom)) {
return;
}
latInput.value = center.lat.toFixed(5);
lonInput.value = center.lng.toFixed(5);
zoomInput.value = zoom.toFixed(2);
}
function flyTo(lat, lon, zoom) {
showGotoError("");
suppressGotoSync = true;
map.flyTo({ center: [lon, lat], zoom });
map.once("moveend", () => {
suppressGotoSync = false;
updateHud();
syncGotoFromMap();
});
}
function readGoto() {
const lat = parseNumber(latInput.value);
const lon = parseNumber(lonInput.value);
const zoom = parseNumber(zoomInput.value);
const maxZoom = map.getMaxZoom();
if (lat === null || lat < -90 || lat > 90) {
return { error: "Широта: число от -90 до 90." };
}
if (lon === null || lon < -180 || lon > 180) {
return { error: "Долгота: число от -180 до 180." };
}
if (zoom === null || zoom < 0 || zoom > maxZoom) {
return { error: `Зум: число от 0 до ${maxZoom}.` };
}
return { lat, lon, zoom };
}
function bindMapEvents() {
map.on("move", updateHud);
map.on("moveend", syncGotoFromMap);
map.on("load", () => {
map.resize();
updateHud();
syncGotoFromMap();
});
map.on("error", (event) => {
const message = event?.error?.message;
if (message) {
showBanner(message, true);
}
});
}
async function loadStyle() {
const source = currentSource();
const styleName = styleSelect.value;
if (!source || !styleName) {
return;
}
const styleKey = `${source.id}|${styleName}|${source.status}|${source.builtAt ?? ""}`;
if (map && activeStyleKey === styleKey) {
return;
}
const style = await fetchJson(`/api/v1/styles/${encodeURIComponent(styleName)}?source=${encodeURIComponent(source.id)}`);
const hashed = cameraFromHash();
const center = hashed
? [hashed.lon, hashed.lat]
: (source.center ?? [37.6173, 55.7558]);
const zoom = hashed ? hashed.zoom : 6;
if (!map) {
map = new maplibregl.Map({
container: "map",
style,
center,
zoom,
maxZoom: 18,
hash: true,
attributionControl: true,
transformRequest: (url) => ({
url: new URL(url, window.location.origin).href
})
});
map.addControl(new maplibregl.NavigationControl(), "top-right");
map.addControl(new maplibregl.ScaleControl(), "bottom-right");
bindMapEvents();
} else {
map.setStyle(style, { diff: false });
}
activeStyleKey = styleKey;
const ready = source.status === "Ready";
showBanner(
ready
? ""
: `Тайлы источника «${source.name}» ещё не готовы (${formatStatus(source.status)}). Первый прогон может занять часы.`,
!ready
);
}
function renderStatus() {
const source = currentSource();
const status = source?.status;
document.getElementById("source-state").textContent = formatStatus(status);
document.getElementById("source-downloaded").textContent = formatDate(source?.downloadedAt);
document.getElementById("source-built").textContent = formatDate(source?.builtAt);
statusPill.textContent = formatStatus(status);
statusPill.className = "pill";
if (status === "Ready") {
statusPill.classList.add("pill--ok");
} else if (status === "Failed") {
statusPill.classList.add("pill--fail");
} else {
statusPill.classList.add("pill--work");
}
}
async function refresh() {
const [sourceList, styleList, sync] = await Promise.all([
fetchJson("/api/v1/sources"),
fetchJson("/api/v1/styles"),
fetchJson("/api/v1/sync/status")
]);
sources = sourceList;
styles = styleList;
const selectedSource = sourceSelect.value;
const selectedStyle = styleSelect.value;
sourceSelect.innerHTML = sources.map((item) => `<option value="${item.id}">${item.name}</option>`).join("");
styleSelect.innerHTML = styles.map((item) => `<option value="${item.name}">${item.name}</option>`).join("");
if (sources.some((item) => item.id === selectedSource)) {
sourceSelect.value = selectedSource;
}
if (styles.some((item) => item.name === selectedStyle)) {
styleSelect.value = selectedStyle;
} else if (styles.some((item) => item.name === "osm-bright")) {
styleSelect.value = "osm-bright";
}
document.getElementById("sync-running").textContent = sync.isRunning ? "идёт синхронизация" : "ожидание";
document.getElementById("sync-next").textContent = formatDate(sync.nextScheduledAt);
const error = document.getElementById("sync-error");
error.hidden = !sync.lastError;
error.textContent = sync.lastError ?? "";
const workerPanel = document.getElementById("worker-panel");
workerPanel.classList.toggle("is-running", Boolean(sync.isRunning));
workerPanel.classList.toggle("is-ready", !sync.isRunning && currentSource()?.status === "Ready");
renderStatus();
await loadStyle();
}
sourceSelect.addEventListener("change", async () => {
renderStatus();
await loadStyle();
const source = currentSource();
if (map && source?.center) {
flyTo(source.center[1], source.center[0], Math.max(map.getZoom(), 6));
}
});
styleSelect.addEventListener("change", () => loadStyle());
gotoForm.addEventListener("submit", (event) => {
event.preventDefault();
if (!map) {
showGotoError("Карта ещё не загружена.");
return;
}
const result = readGoto();
if (result.error) {
showGotoError(result.error);
return;
}
flyTo(result.lat, result.lon, result.zoom);
});
document.querySelectorAll(".preset").forEach((button) => {
button.addEventListener("click", () => {
if (!map) {
return;
}
flyTo(Number(button.dataset.lat), Number(button.dataset.lon), Number(button.dataset.zoom));
});
});
document.getElementById("fit-bounds").addEventListener("click", () => {
const bounds = currentSource()?.bounds;
if (!map || !bounds) {
showGotoError("У источника ещё нет bounds.");
return;
}
map.fitBounds(
[
[bounds.minLon, bounds.minLat],
[bounds.maxLon, bounds.maxLat]
],
{ padding: 48, maxZoom: 10 }
);
});
syncButton.addEventListener("click", async () => {
const source = currentSource();
syncButton.disabled = true;
try {
const url = source ? `/api/v1/sync/${encodeURIComponent(source.id)}` : "/api/v1/sync";
await fetchJson(url, { method: "POST" });
await refresh();
} catch (error) {
showBanner(error.message, true);
} finally {
syncButton.disabled = false;
}
});
refresh().catch((error) => showBanner(error.message, true));
setInterval(() => {
refresh().catch(() => undefined);
}, 15000);
@@ -0,0 +1,48 @@
using TileServer.Domain.Accounts;
namespace TileServer.Application.Accounts;
public sealed record YandexProfile(string Id, string Login, string DisplayName);
public sealed record MeResponse(
Guid Id,
string Login,
string DisplayName,
string Slug,
string YandexId);
public sealed record TokenListItem(
Guid Id,
string Name,
string Prefix,
DateTimeOffset CreatedAt,
DateTimeOffset? RevokedAt);
public sealed record CreatedToken(
Guid Id,
string Name,
string Prefix,
string Token,
DateTimeOffset CreatedAt);
public sealed record UsageDayDto(
DateOnly Date,
long TileRequests,
long StyleRequests,
long Bytes);
public sealed record UserStyleListItem(
string Name,
string? CreatedFrom,
DateTimeOffset UpdatedAt,
bool IsPreset);
public sealed record ResolvedAccess(User User, ApiToken Token);
public sealed record UsageDelta(
Guid UserId,
Guid TokenId,
DateOnly Day,
long TileRequests,
long StyleRequests,
long Bytes);
@@ -0,0 +1,104 @@
using TileServer.Domain.Accounts;
using TileServer.Domain.Exceptions;
namespace TileServer.Application.Accounts;
public sealed class AccountService(
IYandexOAuthClient yandex,
IUserRepository users,
IApiTokenRepository tokens) : IAccountService
{
public const string CabinetTokenName = "Кабинет";
public async Task<(MeResponse Me, string? CabinetToken)> SignInFromYandexAsync(
string code,
string redirectUri,
CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(code))
{
throw new DomainValidationException("OAuth code is required.");
}
var profile = await yandex.ExchangeAsync(code.Trim(), redirectUri, ct).ConfigureAwait(false);
var now = DateTimeOffset.UtcNow;
var user = await users.FindByYandexIdAsync(profile.Id, ct).ConfigureAwait(false);
if (user is null)
{
user = new User
{
Id = Guid.NewGuid(),
YandexId = profile.Id,
Login = profile.Login,
DisplayName = string.IsNullOrWhiteSpace(profile.DisplayName) ? profile.Login : profile.DisplayName,
Slug = await AllocateSlugAsync(profile.Login, exceptUserId: null, ct).ConfigureAwait(false),
CreatedAt = now,
LastLoginAt = now
};
await users.AddAsync(user, ct).ConfigureAwait(false);
}
else
{
user.Login = profile.Login;
user.DisplayName = string.IsNullOrWhiteSpace(profile.DisplayName) ? profile.Login : profile.DisplayName;
user.LastLoginAt = now;
}
await users.SaveChangesAsync(ct).ConfigureAwait(false);
string? cabinetToken = null;
if (await tokens.CountActiveAsync(user.Id, ct).ConfigureAwait(false) == 0)
{
cabinetToken = await CreateCabinetTokenAsync(user.Id, ct).ConfigureAwait(false);
}
return (Map(user), cabinetToken);
}
public async Task<MeResponse> GetMeAsync(Guid userId, CancellationToken ct)
{
var user = await users.FindByIdAsync(userId, ct).ConfigureAwait(false)
?? throw new ResourceNotFoundException("User", userId.ToString());
return Map(user);
}
private async Task<string> AllocateSlugAsync(string login, Guid? exceptUserId, CancellationToken ct)
{
var baseSlug = AccountSlug.FromLogin(login);
if (!await users.SlugExistsAsync(baseSlug, exceptUserId, ct).ConfigureAwait(false))
{
return baseSlug;
}
for (var i = 2; i < 1000; i++)
{
var candidate = AccountSlug.WithSuffix(baseSlug, i);
if (!await users.SlugExistsAsync(candidate, exceptUserId, ct).ConfigureAwait(false))
{
return candidate;
}
}
throw new ResourceConflictException("Could not allocate a unique account slug.");
}
private async Task<string> CreateCabinetTokenAsync(Guid userId, CancellationToken ct)
{
var plaintext = ApiTokenHash.CreatePlaintext();
var token = new ApiToken
{
Id = Guid.NewGuid(),
UserId = userId,
Name = CabinetTokenName,
Hash = ApiTokenHash.Compute(plaintext),
Prefix = ApiTokenHash.DisplayPrefix(plaintext),
CreatedAt = DateTimeOffset.UtcNow
};
await tokens.AddAsync(token, ct).ConfigureAwait(false);
await tokens.SaveChangesAsync(ct).ConfigureAwait(false);
return plaintext;
}
private static MeResponse Map(User user)
=> new(user.Id, user.Login, user.DisplayName, user.Slug, user.YandexId);
}
@@ -0,0 +1,89 @@
using TileServer.Domain.Accounts;
using TileServer.Domain.Exceptions;
namespace TileServer.Application.Accounts;
public sealed class ApiTokenService(
IUserRepository users,
IApiTokenRepository tokens) : IApiTokenService
{
public async Task<IReadOnlyList<TokenListItem>> ListAsync(Guid userId, CancellationToken ct)
{
var items = await tokens.ListByUserAsync(userId, ct).ConfigureAwait(false);
return items
.Select(t => new TokenListItem(t.Id, t.Name, t.Prefix, t.CreatedAt, t.RevokedAt))
.ToArray();
}
public async Task<CreatedToken> CreateAsync(Guid userId, string name, CancellationToken ct)
{
if (await users.FindByIdAsync(userId, ct).ConfigureAwait(false) is null)
{
throw new ResourceNotFoundException("User", userId.ToString());
}
var trimmed = string.IsNullOrWhiteSpace(name) ? "Token" : name.Trim();
if (trimmed.Length > 64)
{
throw new DomainValidationException("Token name must be at most 64 characters.");
}
var plaintext = ApiTokenHash.CreatePlaintext();
var token = new ApiToken
{
Id = Guid.NewGuid(),
UserId = userId,
Name = trimmed,
Hash = ApiTokenHash.Compute(plaintext),
Prefix = ApiTokenHash.DisplayPrefix(plaintext),
CreatedAt = DateTimeOffset.UtcNow
};
await tokens.AddAsync(token, ct).ConfigureAwait(false);
await tokens.SaveChangesAsync(ct).ConfigureAwait(false);
return new CreatedToken(token.Id, token.Name, token.Prefix, plaintext, token.CreatedAt);
}
public async Task RevokeAsync(Guid userId, Guid tokenId, CancellationToken ct)
{
var token = await tokens.FindByIdAsync(userId, tokenId, ct).ConfigureAwait(false)
?? throw new ResourceNotFoundException("Token", tokenId.ToString());
if (token.IsRevoked)
{
return;
}
token.RevokedAt = DateTimeOffset.UtcNow;
await tokens.SaveChangesAsync(ct).ConfigureAwait(false);
}
public async Task<ResolvedAccess> ResolveAsync(string slug, string? queryToken, string? bearer, CancellationToken ct)
{
var plaintext = !string.IsNullOrWhiteSpace(queryToken)
? queryToken.Trim()
: bearer?.Trim();
if (string.IsNullOrWhiteSpace(plaintext))
{
throw new UnauthenticatedException("API token is required.");
}
if (!plaintext.StartsWith(ApiTokenHash.Prefix, StringComparison.Ordinal))
{
throw new UnauthenticatedException("API token is invalid.");
}
var user = await users.FindBySlugAsync(slug, ct).ConfigureAwait(false)
?? throw new UnauthenticatedException("API token is invalid.");
var token = await tokens.FindByHashAsync(ApiTokenHash.Compute(plaintext), ct).ConfigureAwait(false);
if (token is null || token.UserId != user.Id || !ApiTokenHash.Verify(plaintext, token.Hash))
{
throw new UnauthenticatedException("API token is invalid.");
}
if (token.IsRevoked)
{
throw new UnauthenticatedException("API token has been revoked.");
}
return new ResolvedAccess(user, token);
}
}
@@ -0,0 +1,11 @@
namespace TileServer.Application.Accounts;
public interface IAccountService
{
Task<(MeResponse Me, string? CabinetToken)> SignInFromYandexAsync(
string code,
string redirectUri,
CancellationToken ct);
Task<MeResponse> GetMeAsync(Guid userId, CancellationToken ct);
}
@@ -0,0 +1,18 @@
using TileServer.Domain.Accounts;
namespace TileServer.Application.Accounts;
public interface IApiTokenRepository
{
Task<IReadOnlyList<ApiToken>> ListByUserAsync(Guid userId, CancellationToken ct);
Task<ApiToken?> FindByIdAsync(Guid userId, Guid tokenId, CancellationToken ct);
Task<ApiToken?> FindByHashAsync(string hash, CancellationToken ct);
Task<int> CountActiveAsync(Guid userId, CancellationToken ct);
Task AddAsync(ApiToken token, CancellationToken ct);
Task SaveChangesAsync(CancellationToken ct);
}
@@ -0,0 +1,12 @@
namespace TileServer.Application.Accounts;
public interface IApiTokenService
{
Task<IReadOnlyList<TokenListItem>> ListAsync(Guid userId, CancellationToken ct);
Task<CreatedToken> CreateAsync(Guid userId, string name, CancellationToken ct);
Task RevokeAsync(Guid userId, Guid tokenId, CancellationToken ct);
Task<ResolvedAccess> ResolveAsync(string slug, string? queryToken, string? bearer, CancellationToken ct);
}
@@ -0,0 +1,15 @@
namespace TileServer.Application.Accounts;
public interface IUsageRecorder
{
void RecordTile(Guid userId, Guid tokenId, long bytes);
void RecordStyle(Guid userId, Guid tokenId, long bytes);
IReadOnlyList<UsageDelta> Drain();
}
public interface IUsageQuery
{
Task<IReadOnlyList<UsageDayDto>> GetAsync(Guid userId, DateOnly from, DateOnly to, CancellationToken ct);
}
@@ -0,0 +1,8 @@
namespace TileServer.Application.Accounts;
public interface IUsageRepository
{
Task ApplyAsync(IReadOnlyList<UsageDelta> deltas, CancellationToken ct);
Task<IReadOnlyList<UsageDayDto>> GetAsync(Guid userId, DateOnly from, DateOnly to, CancellationToken ct);
}
@@ -0,0 +1,18 @@
using TileServer.Domain.Accounts;
namespace TileServer.Application.Accounts;
public interface IUserRepository
{
Task<User?> FindByIdAsync(Guid id, CancellationToken ct);
Task<User?> FindByYandexIdAsync(string yandexId, CancellationToken ct);
Task<User?> FindBySlugAsync(string slug, CancellationToken ct);
Task<bool> SlugExistsAsync(string slug, Guid? exceptUserId, CancellationToken ct);
Task AddAsync(User user, CancellationToken ct);
Task SaveChangesAsync(CancellationToken ct);
}
@@ -0,0 +1,16 @@
using TileServer.Domain.Accounts;
namespace TileServer.Application.Accounts;
public interface IUserStyleRepository
{
Task<IReadOnlyList<UserStyle>> ListByUserAsync(Guid userId, CancellationToken ct);
Task<UserStyle?> FindAsync(Guid userId, string name, CancellationToken ct);
Task AddAsync(UserStyle style, CancellationToken ct);
Task RemoveAsync(UserStyle style, CancellationToken ct);
Task SaveChangesAsync(CancellationToken ct);
}
@@ -0,0 +1,21 @@
using System.Text.Json.Nodes;
using TileServer.Application.Styles;
namespace TileServer.Application.Accounts;
public interface IUserStyleService
{
Task<IReadOnlyList<UserStyleListItem>> ListMineAsync(Guid userId, CancellationToken ct);
Task<JsonObject> GetMineAsync(Guid userId, string name, CancellationToken ct);
Task<UserStyleListItem> CloneAsync(Guid userId, string name, string from, CancellationToken ct);
Task SaveMineAsync(Guid userId, string name, JsonObject style, CancellationToken ct);
Task DeleteMineAsync(Guid userId, string name, CancellationToken ct);
Task<IReadOnlyList<StyleListItem>> ListForDeliveryAsync(string slug, string baseUrl, string token, CancellationToken ct);
Task<JsonObject> GetForDeliveryAsync(string slug, string name, string extractId, string tilesUrl, CancellationToken ct);
}
@@ -0,0 +1,6 @@
namespace TileServer.Application.Accounts;
public interface IYandexOAuthClient
{
Task<YandexProfile> ExchangeAsync(string code, string redirectUri, CancellationToken ct);
}
@@ -0,0 +1,66 @@
using System.Collections.Concurrent;
namespace TileServer.Application.Accounts;
public sealed class UsageAccumulator : IUsageRecorder
{
private readonly ConcurrentDictionary<(Guid UserId, Guid TokenId, DateOnly Day), Counters> _map = new();
public void RecordTile(Guid userId, Guid tokenId, long bytes)
=> Record(userId, tokenId, tileRequests: 1, styleRequests: 0, bytes);
public void RecordStyle(Guid userId, Guid tokenId, long bytes)
=> Record(userId, tokenId, tileRequests: 0, styleRequests: 1, bytes);
public void Restore(UsageDelta delta)
=> Record(delta.UserId, delta.TokenId, delta.TileRequests, delta.StyleRequests, delta.Bytes);
public IReadOnlyList<UsageDelta> Drain()
{
var drained = new List<UsageDelta>();
foreach (var key in _map.Keys)
{
if (!_map.TryRemove(key, out var counters))
{
continue;
}
drained.Add(new UsageDelta(
key.UserId,
key.TokenId,
key.Day,
counters.TileRequests,
counters.StyleRequests,
counters.Bytes));
}
return drained;
}
private void Record(Guid userId, Guid tokenId, long tileRequests, long styleRequests, long bytes)
{
var key = (userId, tokenId, DateOnly.FromDateTime(DateTime.UtcNow));
var counters = _map.GetOrAdd(key, static _ => new Counters());
if (tileRequests != 0)
{
Interlocked.Add(ref counters.TileRequests, tileRequests);
}
if (styleRequests != 0)
{
Interlocked.Add(ref counters.StyleRequests, styleRequests);
}
if (bytes > 0)
{
Interlocked.Add(ref counters.Bytes, bytes);
}
}
private sealed class Counters
{
public long TileRequests;
public long StyleRequests;
public long Bytes;
}
}
@@ -0,0 +1,154 @@
using System.Text.Json.Nodes;
using TileServer.Application.Styles;
using TileServer.Domain;
using TileServer.Domain.Accounts;
using TileServer.Domain.Exceptions;
namespace TileServer.Application.Accounts;
public sealed class UserStyleService(
IUserRepository users,
IUserStyleRepository styles,
IStyleCatalog catalog,
IStyleService styleService) : IUserStyleService
{
public async Task<IReadOnlyList<UserStyleListItem>> ListMineAsync(Guid userId, CancellationToken ct)
{
var own = await styles.ListByUserAsync(userId, ct).ConfigureAwait(false);
var ownNames = own.Select(s => s.Name).ToHashSet(StringComparer.Ordinal);
var items = own
.Select(s => new UserStyleListItem(s.Name, s.CreatedFrom, s.UpdatedAt, IsPreset: false))
.ToList();
items.AddRange(catalog.List()
.Where(p => !ownNames.Contains(p.Name))
.Select(p => new UserStyleListItem(p.Name, null, p.UpdatedAt, IsPreset: true)));
return items
.OrderBy(s => s.IsPreset)
.ThenBy(s => s.Name, StringComparer.Ordinal)
.ToArray();
}
public async Task<JsonObject> GetMineAsync(Guid userId, string name, CancellationToken ct)
{
var styleName = ResourceName.Require(name, nameof(name));
var own = await styles.FindAsync(userId, styleName, ct).ConfigureAwait(false);
if (own is not null)
{
return Parse(own.Json, styleName);
}
return catalog.GetRequired(styleName);
}
public async Task<UserStyleListItem> CloneAsync(Guid userId, string name, string from, CancellationToken ct)
{
var styleName = ResourceName.Require(name, nameof(name));
var sourceName = ResourceName.Require(from, nameof(from));
if (await styles.FindAsync(userId, styleName, ct).ConfigureAwait(false) is not null)
{
throw new ResourceConflictException($"Style '{styleName}' already exists.");
}
var source = catalog.GetRequired(sourceName);
var now = DateTimeOffset.UtcNow;
var row = new UserStyle
{
Id = Guid.NewGuid(),
UserId = userId,
Name = styleName,
Json = source.ToJsonString(),
CreatedFrom = sourceName,
CreatedAt = now,
UpdatedAt = now
};
await styles.AddAsync(row, ct).ConfigureAwait(false);
await styles.SaveChangesAsync(ct).ConfigureAwait(false);
return new UserStyleListItem(row.Name, row.CreatedFrom, row.UpdatedAt, IsPreset: false);
}
public async Task SaveMineAsync(Guid userId, string name, JsonObject style, CancellationToken ct)
{
var styleName = ResourceName.Require(name, nameof(name));
if (style["version"] is null)
{
style["version"] = 8;
}
var now = DateTimeOffset.UtcNow;
var existing = await styles.FindAsync(userId, styleName, ct).ConfigureAwait(false);
if (existing is null)
{
await styles.AddAsync(new UserStyle
{
Id = Guid.NewGuid(),
UserId = userId,
Name = styleName,
Json = style.ToJsonString(),
CreatedAt = now,
UpdatedAt = now
}, ct).ConfigureAwait(false);
}
else
{
existing.Json = style.ToJsonString();
existing.UpdatedAt = now;
}
await styles.SaveChangesAsync(ct).ConfigureAwait(false);
}
public async Task DeleteMineAsync(Guid userId, string name, CancellationToken ct)
{
var styleName = ResourceName.Require(name, nameof(name));
var existing = await styles.FindAsync(userId, styleName, ct).ConfigureAwait(false)
?? throw new ResourceNotFoundException("Style", styleName);
await styles.RemoveAsync(existing, ct).ConfigureAwait(false);
await styles.SaveChangesAsync(ct).ConfigureAwait(false);
}
public async Task<IReadOnlyList<StyleListItem>> ListForDeliveryAsync(
string slug,
string baseUrl,
string token,
CancellationToken ct)
{
var user = await users.FindBySlugAsync(slug, ct).ConfigureAwait(false)
?? throw new ResourceNotFoundException("User", slug);
var own = await styles.ListByUserAsync(user.Id, ct).ConfigureAwait(false);
var ownNames = own.Select(s => s.Name).ToHashSet(StringComparer.Ordinal);
var items = own
.Select(s => new StyleListItem(s.Name, DeliveryUrl(baseUrl, slug, s.Name, token)))
.ToList();
items.AddRange(catalog.List()
.Where(p => !ownNames.Contains(p.Name))
.Select(p => new StyleListItem(p.Name, DeliveryUrl(baseUrl, slug, p.Name, token))));
return items
.OrderBy(s => s.Name, StringComparer.Ordinal)
.ToArray();
}
public async Task<JsonObject> GetForDeliveryAsync(
string slug,
string name,
string extractId,
string tilesUrl,
CancellationToken ct)
{
var styleName = ResourceName.Require(name, nameof(name));
var user = await users.FindBySlugAsync(slug, ct).ConfigureAwait(false)
?? throw new ResourceNotFoundException("User", slug);
var own = await styles.FindAsync(user.Id, styleName, ct).ConfigureAwait(false);
var raw = own is null ? catalog.GetRequired(styleName) : Parse(own.Json, styleName);
return styleService.Bind(raw, extractId, tilesUrl);
}
private static JsonObject Parse(string json, string name)
=> JsonNode.Parse(json)?.AsObject()
?? throw new DomainValidationException($"Style '{name}' is not a JSON object.");
private static string DeliveryUrl(string baseUrl, string slug, string name, string token)
{
var root = string.IsNullOrEmpty(baseUrl) ? string.Empty : baseUrl.TrimEnd('/');
return $"{root}/u/{slug}/styles/{name}?token={Uri.EscapeDataString(token)}";
}
}
@@ -0,0 +1,155 @@
namespace TileServer.Application.Configuration;
public sealed class TileServerOptions
{
public const string SectionName = "TileServer";
public string DataDirectory { get; set; } = "data";
public string JavaPath { get; set; } = "java";
public string JvmMaxHeap { get; set; } = "8g";
public string PlanetilerJarUrl { get; set; } =
"https://github.com/openmaptiles/planetiler-openmaptiles/releases/download/v3.16/planetiler-openmaptiles.jar";
public string PlanetilerJarFileName { get; set; } = "planetiler-openmaptiles.jar";
public int DefaultMinZoom { get; set; } = 0;
public int DefaultMaxZoom { get; set; } = 15;
public string GlyphsUrl { get; set; } = "https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf";
/// <summary>
/// Public origin for absolute URLs in styles/TileJSON, e.g. https://tile-server.ru.
/// Empty = root-relative paths (safe behind HTTPS reverse proxy).
/// </summary>
public string? PublicBaseUrl { get; set; }
public int TileCacheSize { get; set; } = 512;
/// <summary>
/// Highest zoom generated on the fly from stored tiles when a client asks past
/// the MBTiles pyramid. Not advertised in TileJSON/style: MapLibre must see the
/// stored maxzoom so it overzooms z14/z15 instead of requesting sparse children.
/// </summary>
public int OverzoomMaxZoom { get; set; } = 18;
public string PlanetilerHttpTimeout { get; set; } = "15m";
public int DownloadStallTimeoutSeconds { get; set; } = 45;
public List<string> NaturalEarthUrls { get; set; } =
[
"https://naciscdn.org/naturalearth/packages/natural_earth_vector.sqlite.zip",
"https://naturalearth.s3.amazonaws.com/packages/natural_earth_vector.sqlite.zip"
];
public List<string> LakeCenterlinesUrls { get; set; } =
[
"https://github.com/acalcutt/osm-lakelines/releases/download/latest/lake_centerline.shp.zip",
"https://acalcutt.github.io/osm-lakelines/lake_centerline.shp.zip"
];
public List<string> WaterPolygonsUrls { get; set; } =
[
"https://osmdata.openstreetmap.de/download/water-polygons-split-3857.zip"
];
public string NaturalEarthUrl
{
get => NaturalEarthUrls.Count > 0 ? NaturalEarthUrls[0] : string.Empty;
set
{
if (!string.IsNullOrWhiteSpace(value))
{
NaturalEarthUrls = PrependUnique(NaturalEarthUrls, value);
}
}
}
public string LakeCenterlinesUrl
{
get => LakeCenterlinesUrls.Count > 0 ? LakeCenterlinesUrls[0] : string.Empty;
set
{
if (!string.IsNullOrWhiteSpace(value))
{
LakeCenterlinesUrls = PrependUnique(LakeCenterlinesUrls, value);
}
}
}
public string WaterPolygonsUrl
{
get => WaterPolygonsUrls.Count > 0 ? WaterPolygonsUrls[0] : string.Empty;
set
{
if (!string.IsNullOrWhiteSpace(value))
{
WaterPolygonsUrls = PrependUnique(WaterPolygonsUrls, value);
}
}
}
public SyncOptions Sync { get; set; } = new();
public YandexOAuthOptions Yandex { get; set; } = new();
public List<ExtractOptions> Extracts { get; set; } = [];
private static List<string> PrependUnique(List<string> existing, string value)
{
var result = new List<string> { value };
foreach (var item in existing)
{
if (!string.Equals(item, value, StringComparison.OrdinalIgnoreCase))
{
result.Add(item);
}
}
return result;
}
}
public sealed class SyncOptions
{
public string Cron { get; set; } = "0 3 * * *";
public string TimeZone { get; set; } = "UTC";
public bool RunOnStartup { get; set; } = true;
public bool RebuildIfTilesMissing { get; set; } = true;
}
public sealed class YandexOAuthOptions
{
public string ClientId { get; set; } = string.Empty;
public string ClientSecret { get; set; } = string.Empty;
public string RedirectUri { get; set; } = "https://tile-server.ru";
public bool IsConfigured =>
!string.IsNullOrWhiteSpace(ClientId) && !string.IsNullOrWhiteSpace(ClientSecret);
}
public sealed class ExtractOptions
{
public string Id { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public string Url { get; set; } = string.Empty;
public double[] Center { get; set; } = [37.6173, 55.7558];
public int MinZoom { get; set; } = 0;
public int MaxZoom { get; set; } = 15;
public bool Enabled { get; set; } = true;
}
@@ -0,0 +1,25 @@
using Microsoft.Extensions.DependencyInjection;
using TileServer.Application.Accounts;
using TileServer.Application.Extracts;
using TileServer.Application.Styles;
using TileServer.Application.Sync;
using TileServer.Application.Tiles;
namespace TileServer.Application;
public static class DependencyInjection
{
public static IServiceCollection AddApplication(this IServiceCollection services)
{
services.AddSingleton<ITileQueryService, TileQueryService>();
services.AddSingleton<IStyleService, StyleService>();
services.AddSingleton<IExtractService, ExtractService>();
services.AddSingleton<IMapSyncService, MapSyncService>();
services.AddSingleton<UsageAccumulator>();
services.AddSingleton<IUsageRecorder>(sp => sp.GetRequiredService<UsageAccumulator>());
services.AddScoped<IAccountService, AccountService>();
services.AddScoped<IApiTokenService, ApiTokenService>();
services.AddScoped<IUserStyleService, UserStyleService>();
return services;
}
}
@@ -0,0 +1,93 @@
using Microsoft.Extensions.Options;
using TileServer.Application.Configuration;
using TileServer.Application.Tiles;
using TileServer.Domain;
using TileServer.Domain.Exceptions;
using TileServer.Domain.Extracts;
using TileServer.Domain.Tiles;
namespace TileServer.Application.Extracts;
public sealed class ExtractService(
IExtractCatalog catalog,
IExtractStateStore stateStore,
ITileStore tileStore,
IOptions<TileServerOptions> options) : IExtractService
{
public async Task<IReadOnlyList<ExtractResponse>> ListAsync(string baseUrl, CancellationToken ct)
{
var result = new List<ExtractResponse>();
foreach (var extract in catalog.GetAll())
{
result.Add(await MapAsync(extract, baseUrl, ct).ConfigureAwait(false));
}
return result;
}
public async Task<ExtractResponse> GetAsync(string id, string baseUrl, CancellationToken ct)
=> await MapAsync(catalog.GetRequired(id), baseUrl, ct).ConfigureAwait(false);
public async Task<ExtractResponse> AddOrUpdateAsync(CreateExtractRequest request, string baseUrl, CancellationToken ct)
{
var id = ResourceName.Require(request.Id, nameof(request.Id));
if (string.IsNullOrWhiteSpace(request.Name))
{
throw new DomainValidationException("Extract name is required.");
}
if (!Uri.TryCreate(request.Url, UriKind.Absolute, out var url) ||
(url.Scheme != Uri.UriSchemeHttp && url.Scheme != Uri.UriSchemeHttps))
{
throw new DomainValidationException("Extract URL must be an absolute http(s) URI.");
}
var defaults = options.Value;
var center = request.Center is { Length: >= 2 } ? request.Center : [37.6173, 55.7558];
var extract = new Extract
{
Id = id,
Name = request.Name.Trim(),
Url = url,
CenterLon = center[0],
CenterLat = center[1],
MinZoom = request.MinZoom ?? defaults.DefaultMinZoom,
MaxZoom = PlanetilerLimits.ClampMaxZoom(request.MaxZoom ?? defaults.DefaultMaxZoom),
Enabled = request.Enabled
};
await catalog.AddOrUpdateAsync(extract, ct).ConfigureAwait(false);
return await MapAsync(extract, baseUrl, ct).ConfigureAwait(false);
}
public Task RemoveAsync(string id, CancellationToken ct)
=> catalog.RemoveAsync(ResourceName.Require(id, nameof(id)), ct);
private async Task<ExtractResponse> MapAsync(Extract extract, string baseUrl, CancellationToken ct)
{
var state = await stateStore.GetAsync(extract.Id, ct).ConfigureAwait(false);
var metadata = tileStore.GetMetadata(extract.Id);
var bounds = metadata is null
? null
: new TilesetBounds(metadata.MinLon, metadata.MinLat, metadata.MaxLon, metadata.MaxLat);
return new ExtractResponse(
extract.Id,
extract.Name,
extract.Url.ToString(),
extract.Enabled,
[extract.CenterLon, extract.CenterLat],
extract.MinZoom,
extract.MaxZoom,
string.Empty,
string.Empty,
tileStore.Exists(extract.Id) && state.Status == ExtractSyncState.Pending
? ExtractSyncState.Ready
: state.Status,
state.DownloadedAt,
state.BuiltAt,
state.PbfBytes,
state.LastError,
bounds);
}
}
@@ -0,0 +1,16 @@
using TileServer.Domain.Extracts;
namespace TileServer.Application.Extracts;
public interface IExtractCatalog
{
IReadOnlyList<Extract> GetAll();
Extract? Find(string id);
Extract GetRequired(string id);
Task AddOrUpdateAsync(Extract extract, CancellationToken ct);
Task RemoveAsync(string id, CancellationToken ct);
}
@@ -0,0 +1,14 @@
using TileServer.Domain.Extracts;
namespace TileServer.Application.Extracts;
public sealed record DownloadResult(
bool Changed,
long Bytes,
string? ETag,
DateTimeOffset? LastModified);
public interface IExtractDownloader
{
Task<DownloadResult> DownloadAsync(Extract extract, string destinationPath, ExtractRuntimeState state, CancellationToken ct);
}
@@ -0,0 +1,42 @@
using TileServer.Domain.Extracts;
namespace TileServer.Application.Extracts;
public sealed record ExtractResponse(
string Id,
string Name,
string Url,
bool Enabled,
double[] Center,
int MinZoom,
int MaxZoom,
string TileUrlTemplate,
string TileJsonUrl,
ExtractSyncState Status,
DateTimeOffset? DownloadedAt,
DateTimeOffset? BuiltAt,
long? PbfBytes,
string? LastError,
TilesetBounds? Bounds);
public sealed record TilesetBounds(double MinLon, double MinLat, double MaxLon, double MaxLat);
public sealed record CreateExtractRequest(
string Id,
string Name,
string Url,
double[]? Center,
int? MinZoom,
int? MaxZoom,
bool Enabled = true);
public interface IExtractService
{
Task<IReadOnlyList<ExtractResponse>> ListAsync(string baseUrl, CancellationToken ct);
Task<ExtractResponse> GetAsync(string id, string baseUrl, CancellationToken ct);
Task<ExtractResponse> AddOrUpdateAsync(CreateExtractRequest request, string baseUrl, CancellationToken ct);
Task RemoveAsync(string id, CancellationToken ct);
}
@@ -0,0 +1,10 @@
using TileServer.Domain.Extracts;
namespace TileServer.Application.Extracts;
public interface IExtractStateStore
{
Task<ExtractRuntimeState> GetAsync(string extractId, CancellationToken ct);
Task SaveAsync(ExtractRuntimeState state, CancellationToken ct);
}
+32
View File
@@ -0,0 +1,32 @@
namespace TileServer.Application;
public interface IDataPaths
{
string Root { get; }
string Extracts { get; }
string Tiles { get; }
string Styles { get; }
string Tools { get; }
string State { get; }
string PlanetilerSources { get; }
string Tmp { get; }
string OverlayExtractsFile { get; }
string AppDatabase { get; }
string OsmPbf(string extractId);
string Mbtiles(string extractId);
string StagingMbtiles(string extractId);
void EnsureCreated();
}
@@ -0,0 +1,16 @@
using System.Text.Json.Nodes;
namespace TileServer.Application.Styles;
public sealed record MapStyleInfo(string Name, DateTimeOffset UpdatedAt);
public interface IStyleCatalog
{
IReadOnlyList<MapStyleInfo> List();
JsonObject GetRequired(string name);
Task SaveAsync(string name, JsonObject style, CancellationToken ct);
Task SeedDefaultsAsync(CancellationToken ct);
}
@@ -0,0 +1,16 @@
using System.Text.Json.Nodes;
namespace TileServer.Application.Styles;
public sealed record StyleListItem(string Name, string Url);
public interface IStyleService
{
IReadOnlyList<StyleListItem> List(string baseUrl);
JsonObject Get(string name, string extractId, string baseUrl);
JsonObject Bind(JsonObject style, string extractId, string tilesUrl);
Task SaveAsync(string name, JsonObject style, CancellationToken ct);
}
@@ -0,0 +1,147 @@
using System.Text.Json.Nodes;
using Microsoft.Extensions.Options;
using TileServer.Application.Configuration;
using TileServer.Application.Extracts;
using TileServer.Application.Tiles;
using TileServer.Domain;
using TileServer.Domain.Exceptions;
using TileServer.Domain.Extracts;
namespace TileServer.Application.Styles;
public sealed class StyleService(
IStyleCatalog catalog,
IExtractCatalog extracts,
ITileStore tileStore,
IOptions<TileServerOptions> options) : IStyleService
{
public IReadOnlyList<StyleListItem> List(string baseUrl)
=> catalog.List()
.Select(s => new StyleListItem(s.Name, Combine(baseUrl, $"/api/v1/styles/{s.Name}")))
.ToArray();
public JsonObject Get(string name, string extractId, string baseUrl)
{
var styleName = ResourceName.Require(name, nameof(name));
var extract = ResolveExtract(extractId);
var style = catalog.GetRequired(styleName);
var tilesUrl = Combine(baseUrl, $"/api/v1/tiles/{extract.Id}/{{z}}/{{x}}/{{y}}.pbf?v=3");
BindRuntimeUrls(style, extract, tilesUrl);
return style;
}
public JsonObject Bind(JsonObject style, string extractId, string tilesUrl)
{
var extract = ResolveExtract(extractId);
var clone = JsonNode.Parse(style.ToJsonString())?.AsObject()
?? throw new DomainValidationException("Style must be a JSON object.");
BindRuntimeUrls(clone, extract, tilesUrl);
return clone;
}
private Extract ResolveExtract(string extractId)
=> string.IsNullOrWhiteSpace(extractId)
? extracts.GetAll().FirstOrDefault(e => e.Enabled)
?? throw new ResourceNotFoundException("Extract", "(none configured)")
: extracts.GetRequired(extractId);
public Task SaveAsync(string name, JsonObject style, CancellationToken ct)
{
var styleName = ResourceName.Require(name, nameof(name));
if (style["version"] is null)
{
style["version"] = 8;
}
return catalog.SaveAsync(styleName, style, ct);
}
private void BindRuntimeUrls(JsonObject style, Extract extract, string tilesUrl)
{
var glyphs = options.Value.GlyphsUrl;
var metadata = tileStore.GetMetadata(extract.Id);
var minZoom = metadata?.MinZoom ?? extract.MinZoom;
var maxZoom = metadata?.MaxZoom ?? extract.MaxZoom;
style["glyphs"] = glyphs;
ReplaceOpenSansFonts(style);
style["sources"] ??= new JsonObject();
if (style["sources"] is not JsonObject sources)
{
throw new DomainValidationException("Style 'sources' must be a JSON object.");
}
if (sources.Count == 0)
{
sources["openmaptiles"] = CreateVectorSource(tilesUrl, minZoom, maxZoom);
return;
}
foreach (var property in sources.ToList())
{
if (property.Value is JsonObject source &&
string.Equals(source["type"]?.GetValue<string>(), "vector", StringComparison.OrdinalIgnoreCase))
{
ApplyVectorSource(source, tilesUrl, minZoom, maxZoom);
}
}
}
private static JsonObject CreateVectorSource(string tilesUrl, int minZoom, int maxZoom)
{
var source = new JsonObject
{
["type"] = "vector"
};
ApplyVectorSource(source, tilesUrl, minZoom, maxZoom);
return source;
}
private static void ApplyVectorSource(JsonObject source, string tilesUrl, int minZoom, int maxZoom)
{
source["type"] = "vector";
source["tiles"] = new JsonArray(tilesUrl);
source["minzoom"] = minZoom;
source["maxzoom"] = maxZoom;
source["scheme"] = "xyz";
source["attribution"] = "© OpenStreetMap contributors";
source.Remove("url");
source.Remove("bounds");
}
private static void ReplaceOpenSansFonts(JsonObject style)
{
if (style["layers"] is not JsonArray layers)
{
return;
}
foreach (var node in layers)
{
if (node is not JsonObject layer || layer["layout"] is not JsonObject layout || layout["text-font"] is not JsonArray fonts)
{
continue;
}
for (var i = 0; i < fonts.Count; i++)
{
var name = fonts[i]?.GetValue<string>();
if (name == "Open Sans Regular")
{
fonts[i] = "Noto Sans Regular";
}
else if (name == "Open Sans Bold")
{
fonts[i] = "Noto Sans Bold";
}
else if (name == "Open Sans Italic")
{
fonts[i] = "Noto Sans Italic";
}
}
}
}
private static string Combine(string baseUrl, string path)
=> string.IsNullOrEmpty(baseUrl) ? path : $"{baseUrl.TrimEnd('/')}{path}";
}
@@ -0,0 +1,24 @@
namespace TileServer.Application.Sync;
public sealed record SyncJobStatus(
bool IsRunning,
DateTimeOffset? LastStartedAt,
DateTimeOffset? LastFinishedAt,
DateTimeOffset? NextScheduledAt,
string? LastError);
public interface IMapSyncService
{
Task RunAllAsync(CancellationToken ct);
Task RunOneAsync(string extractId, CancellationToken ct);
SyncJobStatus GetStatus();
void SetNextScheduledAt(DateTimeOffset? next);
}
public interface ISyncSchedulerClock
{
DateTimeOffset? GetNextOccurrence(DateTimeOffset fromUtc);
}
@@ -0,0 +1,231 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using TileServer.Application.Configuration;
using TileServer.Application;
using TileServer.Application.Extracts;
using TileServer.Application.Tiles;
using TileServer.Domain.Exceptions;
using TileServer.Domain.Extracts;
namespace TileServer.Application.Sync;
public sealed class MapSyncService(
IExtractCatalog catalog,
IExtractDownloader downloader,
IExtractStateStore stateStore,
ITileBuilder tileBuilder,
ITileStore tileStore,
IPlanetilerBootstrapper planetiler,
IPlanetilerSourceBootstrapper planetilerSources,
IDataPaths dataPaths,
IOptions<TileServerOptions> options,
ILogger<MapSyncService> logger) : IMapSyncService
{
private readonly SemaphoreSlim _gate = new(1, 1);
private readonly object _statusLock = new();
private DateTimeOffset? _lastStartedAt;
private DateTimeOffset? _lastFinishedAt;
private DateTimeOffset? _nextScheduledAt;
private string? _lastError;
private int _running;
public SyncJobStatus GetStatus()
{
lock (_statusLock)
{
return new SyncJobStatus(
Volatile.Read(ref _running) == 1,
_lastStartedAt,
_lastFinishedAt,
_nextScheduledAt,
_lastError);
}
}
public void SetNextScheduledAt(DateTimeOffset? next)
{
lock (_statusLock)
{
_nextScheduledAt = next;
}
}
public async Task RunAllAsync(CancellationToken ct)
{
if (!await _gate.WaitAsync(0, ct).ConfigureAwait(false))
{
throw new ResourceConflictException("A synchronization job is already running.");
}
try
{
Begin();
var extracts = catalog.GetAll().Where(e => e.Enabled).ToArray();
if (extracts.Length == 0)
{
logger.LogWarning("No enabled OSM extracts configured.");
Finish(null);
return;
}
logger.LogInformation("Starting sync for {Count} OSM extract(s).", extracts.Length);
foreach (var extract in extracts)
{
ct.ThrowIfCancellationRequested();
await SyncExtractAsync(extract, ct).ConfigureAwait(false);
}
Finish(null);
}
catch (OperationCanceledException)
{
Finish("Cancelled");
throw;
}
catch (Exception ex)
{
logger.LogError(ex, "Map sync failed.");
Finish(ex.Message);
throw;
}
finally
{
_gate.Release();
}
}
public async Task RunOneAsync(string extractId, CancellationToken ct)
{
var extract = catalog.GetRequired(extractId);
if (!await _gate.WaitAsync(0, ct).ConfigureAwait(false))
{
throw new ResourceConflictException("A synchronization job is already running.");
}
try
{
Begin();
await SyncExtractAsync(extract, ct).ConfigureAwait(false);
Finish(null);
}
catch (OperationCanceledException)
{
Finish("Cancelled");
throw;
}
catch (Exception ex)
{
logger.LogError(ex, "Map sync failed for {ExtractId}.", extractId);
Finish(ex.Message);
throw;
}
finally
{
_gate.Release();
}
}
private async Task SyncExtractAsync(Extract extract, CancellationToken ct)
{
var state = await stateStore.GetAsync(extract.Id, ct).ConfigureAwait(false);
var pbfPath = dataPaths.OsmPbf(extract.Id);
try
{
state.Status = ExtractSyncState.Downloading;
state.LastError = null;
await stateStore.SaveAsync(state, ct).ConfigureAwait(false);
logger.LogInformation("Downloading {ExtractId} from {Url}", extract.Id, extract.Url);
var download = await downloader.DownloadAsync(extract, pbfPath, state, ct).ConfigureAwait(false);
state.ETag = download.ETag;
state.RemoteLastModified = download.LastModified;
state.PbfBytes = download.Bytes;
if (download.Changed)
{
state.DownloadedAt = DateTimeOffset.UtcNow;
}
var tilesMissing = !tileStore.Exists(extract.Id);
var metadata = tileStore.GetMetadata(extract.Id);
var zoomRaised = metadata is not null && extract.MaxZoom > metadata.MaxZoom;
var shouldBuild = download.Changed
|| (tilesMissing && options.Value.Sync.RebuildIfTilesMissing)
|| zoomRaised;
if (!shouldBuild)
{
state.Status = ExtractSyncState.Ready;
await stateStore.SaveAsync(state, ct).ConfigureAwait(false);
logger.LogInformation("Extract {ExtractId} is up to date, skip rebuild.", extract.Id);
return;
}
if (zoomRaised)
{
logger.LogInformation(
"Rebuilding {ExtractId}: configured maxzoom {Wanted} > tileset maxzoom {Have}.",
extract.Id,
extract.MaxZoom,
metadata!.MaxZoom);
}
if (!planetiler.IsJavaAvailable())
{
throw new InvalidOperationException(
"Java 21+ is required to build tiles with planetiler-openmaptiles. Install a JDK and set TileServer:JavaPath.");
}
await planetiler.EnsureJarAsync(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);
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);
state.BuiltAt = DateTimeOffset.UtcNow;
state.Status = ExtractSyncState.Ready;
state.LastError = null;
await stateStore.SaveAsync(state, ct).ConfigureAwait(false);
logger.LogInformation("Extract {ExtractId} is ready.", extract.Id);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to sync extract {ExtractId}", extract.Id);
state.Status = ExtractSyncState.Failed;
state.LastError = ex.Message;
await stateStore.SaveAsync(state, CancellationToken.None).ConfigureAwait(false);
}
}
private void Begin()
{
Volatile.Write(ref _running, 1);
lock (_statusLock)
{
_lastStartedAt = DateTimeOffset.UtcNow;
_lastError = null;
}
}
private void Finish(string? error)
{
Volatile.Write(ref _running, 0);
lock (_statusLock)
{
_lastFinishedAt = DateTimeOffset.UtcNow;
_lastError = error;
}
}
}
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\TileServer.Domain\TileServer.Domain.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.2" />
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.2" />
</ItemGroup>
</Project>
@@ -0,0 +1,20 @@
using TileServer.Domain.Extracts;
namespace TileServer.Application.Tiles;
public interface ITileBuilder
{
Task BuildAsync(Extract extract, string osmPbfPath, string outputMbtilesPath, CancellationToken ct);
}
public interface IPlanetilerBootstrapper
{
Task<string> EnsureJarAsync(CancellationToken ct);
bool IsJavaAvailable();
}
public interface IPlanetilerSourceBootstrapper
{
Task EnsureAsync(CancellationToken ct);
}
@@ -0,0 +1,32 @@
using System.Text.Json.Serialization;
using TileServer.Domain.Tiles;
namespace TileServer.Application.Tiles;
public sealed record TileQueryResult(TileData Tile, string ExtractId, DateTimeOffset? BuiltAt);
public interface ITileQueryService
{
Task<TileQueryResult?> GetTileAsync(string extractId, TileCoordinate tile, CancellationToken ct);
TileJsonResponse GetTileJson(string extractId, string tilesUrl);
}
public sealed record TileJsonResponse(
string Tilejson,
string Name,
string[] Tiles,
double[] Bounds,
double[] Center,
int Minzoom,
int Maxzoom,
string Format,
string Attribution,
[property: JsonPropertyName("vector_layers")] IReadOnlyList<VectorLayerJson> VectorLayers);
public sealed record VectorLayerJson(
string Id,
string Description,
int Minzoom,
int Maxzoom,
IReadOnlyDictionary<string, string> Fields);
@@ -0,0 +1,19 @@
using TileServer.Domain.Extracts;
using TileServer.Domain.Tiles;
namespace TileServer.Application.Tiles;
public interface ITileStore
{
bool Exists(string extractId);
Task<TileData?> GetTileAsync(string extractId, TileCoordinate tile, CancellationToken ct);
TilesetMetadata? GetMetadata(string extractId);
string GetActivePath(string extractId);
string GetStagingPath(string extractId);
void Activate(string extractId, string stagingPath);
}
@@ -0,0 +1,8 @@
using TileServer.Domain.Tiles;
namespace TileServer.Application.Tiles;
public interface IVectorTileOverzoomer
{
TileData Overzoom(TileData parent, TileCoordinate parentTile, TileCoordinate childTile);
}
@@ -0,0 +1,131 @@
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using TileServer.Application.Configuration;
using TileServer.Application.Extracts;
using TileServer.Domain.Exceptions;
using TileServer.Domain.Tiles;
namespace TileServer.Application.Tiles;
public sealed class TileQueryService(
ITileStore tileStore,
IExtractCatalog extracts,
IVectorTileOverzoomer overzoomer,
IMemoryCache cache,
IOptions<TileServerOptions> options,
ILogger<TileQueryService> logger) : ITileQueryService
{
private const string Attribution = "© OpenStreetMap contributors";
public async Task<TileQueryResult?> GetTileAsync(string extractId, TileCoordinate tile, CancellationToken ct)
{
var extract = extracts.GetRequired(extractId);
if (!tile.IsValid)
{
throw new DomainValidationException($"Invalid XYZ tile {tile.Z}/{tile.X}/{tile.Y}.");
}
var metadata = tileStore.GetMetadata(extractId);
var dataMaxZoom = metadata?.MaxZoom ?? extract.MaxZoom;
var servedMaxZoom = TileZoomPolicy.ServedMaxZoom(dataMaxZoom, options.Value.OverzoomMaxZoom);
if (tile.Z > servedMaxZoom)
{
return null;
}
var stored = await tileStore.GetTileAsync(extractId, tile, ct).ConfigureAwait(false);
if (stored is not null)
{
return new TileQueryResult(stored, extractId, GuessBuiltAt(extractId, metadata));
}
if (tile.Z <= dataMaxZoom)
{
return null;
}
var cacheKey = $"overzoom:{extractId}/{tile.Z}/{tile.X}/{tile.Y}";
if (cache.TryGetValue(cacheKey, out TileData? cached) && cached is not null)
{
return new TileQueryResult(cached, extractId, GuessBuiltAt(extractId, metadata));
}
var parent = tile.Ancestor(dataMaxZoom);
var parentTile = await tileStore.GetTileAsync(extractId, parent, ct).ConfigureAwait(false);
if (parentTile is null)
{
return null;
}
var overzoomed = overzoomer.Overzoom(parentTile, parent, tile);
cache.Set(cacheKey, overzoomed, new MemoryCacheEntryOptions
{
Size = 1,
SlidingExpiration = TimeSpan.FromMinutes(15)
});
return new TileQueryResult(overzoomed, extractId, GuessBuiltAt(extractId, metadata));
}
public TileJsonResponse GetTileJson(string extractId, string tilesUrl)
{
var extract = extracts.GetRequired(extractId);
var metadata = tileStore.GetMetadata(extractId);
var minZoom = metadata?.MinZoom ?? extract.MinZoom;
var maxZoom = metadata?.MaxZoom ?? extract.MaxZoom;
var bounds = metadata?.Bounds ?? [-180, -85.0511, 180, 85.0511];
var center = metadata is null
? new[] { extract.CenterLon, extract.CenterLat, Math.Clamp(extract.MinZoom + 6, extract.MinZoom, extract.MaxZoom) }
: metadata.Center;
var layers = metadata?.VectorLayers
.Select(l => new VectorLayerJson(l.Id, l.Id, l.MinZoom, l.MaxZoom, l.Fields))
.ToArray()
?? DefaultOpenMapTilesLayers(minZoom, maxZoom);
return new TileJsonResponse(
Tilejson: "3.0.0",
Name: extract.Name,
Tiles: [tilesUrl],
Bounds: bounds,
Center: center,
Minzoom: minZoom,
Maxzoom: maxZoom,
Format: "pbf",
Attribution: Attribution,
VectorLayers: layers);
}
private DateTimeOffset? GuessBuiltAt(string extractId, TilesetMetadata? metadata)
{
if (metadata is null)
{
return null;
}
try
{
var path = tileStore.GetActivePath(extractId);
return File.Exists(path) ? new DateTimeOffset(File.GetLastWriteTimeUtc(path), TimeSpan.Zero) : null;
}
catch (Exception ex)
{
logger.LogDebug(ex, "Could not read mtime for extract {ExtractId}", extractId);
return null;
}
}
private static IReadOnlyList<VectorLayerJson> DefaultOpenMapTilesLayers(int minZoom, int maxZoom)
{
string[] ids =
[
"water", "waterway", "landcover", "landuse", "park", "boundary", "aeroway",
"transportation", "building", "water_name", "transportation_name", "place",
"housenumber", "poi", "mountain_peak", "aerodrome_label"
];
return ids
.Select(id => new VectorLayerJson(id, id, minZoom, maxZoom, new Dictionary<string, string>()))
.ToArray();
}
}
@@ -0,0 +1,9 @@
namespace TileServer.Application.Tiles;
public static class TileZoomPolicy
{
public const int ClientMaxZoom = 22;
public static int ServedMaxZoom(int dataMaxZoom, int overzoomMaxZoom)
=> Math.Clamp(Math.Max(dataMaxZoom, overzoomMaxZoom), 0, ClientMaxZoom);
}
@@ -0,0 +1,60 @@
using System.Globalization;
using System.Text;
namespace TileServer.Domain.Accounts;
public static class AccountSlug
{
public static string FromLogin(string login)
{
ArgumentException.ThrowIfNullOrWhiteSpace(login);
var normalized = login.Trim().ToLowerInvariant();
var buffer = new StringBuilder(normalized.Length);
foreach (var ch in normalized)
{
if (ch is >= 'a' and <= 'z' || ch is >= '0' and <= '9')
{
buffer.Append(ch);
}
else if (ch is '-' or '_' or '.')
{
if (buffer.Length > 0 && buffer[^1] != '-')
{
buffer.Append('-');
}
}
}
var slug = buffer.ToString().Trim('-');
if (slug.Length == 0)
{
slug = "user";
}
if (char.IsDigit(slug[0]))
{
slug = "u-" + slug;
}
if (slug.Length > ResourceName.MaxLength)
{
slug = slug[..ResourceName.MaxLength].TrimEnd('-');
}
return ResourceName.Require(slug, nameof(login));
}
public static string WithSuffix(string slug, int suffix)
{
var tail = suffix.ToString(CultureInfo.InvariantCulture);
var maxBase = ResourceName.MaxLength - tail.Length - 1;
var head = slug.Length > maxBase ? slug[..maxBase].TrimEnd('-') : slug;
if (head.Length == 0 || !char.IsLetter(head[0]))
{
head = "user";
}
return ResourceName.Require($"{head}-{tail}", nameof(slug));
}
}
@@ -0,0 +1,22 @@
namespace TileServer.Domain.Accounts;
public sealed class ApiToken
{
public Guid Id { get; set; }
public Guid UserId { get; set; }
public User? User { get; set; }
public required string Name { get; set; }
public required string Hash { get; set; }
public required string Prefix { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset? RevokedAt { get; set; }
public bool IsRevoked => RevokedAt is not null;
}
@@ -0,0 +1,47 @@
using System.Security.Cryptography;
using System.Text;
namespace TileServer.Domain.Accounts;
public static class ApiTokenHash
{
public const string Prefix = "ts_";
public static string CreatePlaintext()
{
Span<byte> bytes = stackalloc byte[24];
RandomNumberGenerator.Fill(bytes);
return Prefix + Convert.ToHexString(bytes).ToLowerInvariant();
}
public static string Compute(string plaintext)
{
ArgumentException.ThrowIfNullOrWhiteSpace(plaintext);
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(plaintext));
return Convert.ToHexString(hash).ToLowerInvariant();
}
public static bool Verify(string plaintext, string expectedHash)
{
if (string.IsNullOrWhiteSpace(plaintext) || string.IsNullOrWhiteSpace(expectedHash))
{
return false;
}
var actual = Compute(plaintext);
var actualBytes = Encoding.UTF8.GetBytes(actual);
var expectedBytes = Encoding.UTF8.GetBytes(expectedHash.Trim().ToLowerInvariant());
return actualBytes.Length == expectedBytes.Length
&& CryptographicOperations.FixedTimeEquals(actualBytes, expectedBytes);
}
public static string DisplayPrefix(string plaintext)
{
if (string.IsNullOrEmpty(plaintext) || plaintext.Length < 11)
{
return Prefix;
}
return plaintext[..11];
}
}
@@ -0,0 +1,18 @@
namespace TileServer.Domain.Accounts;
public sealed class UsageDaily
{
public Guid Id { get; set; }
public Guid UserId { get; set; }
public Guid TokenId { get; set; }
public DateOnly Date { get; set; }
public long TileRequests { get; set; }
public long StyleRequests { get; set; }
public long Bytes { get; set; }
}
+22
View File
@@ -0,0 +1,22 @@
namespace TileServer.Domain.Accounts;
public sealed class User
{
public Guid Id { get; set; }
public required string YandexId { get; set; }
public required string Login { get; set; }
public required string DisplayName { get; set; }
public required string Slug { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset LastLoginAt { get; set; }
public List<ApiToken> Tokens { get; set; } = [];
public List<UserStyle> Styles { get; set; } = [];
}
@@ -0,0 +1,20 @@
namespace TileServer.Domain.Accounts;
public sealed class UserStyle
{
public Guid Id { get; set; }
public Guid UserId { get; set; }
public User? User { get; set; }
public required string Name { get; set; }
public required string Json { get; set; }
public string? CreatedFrom { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset UpdatedAt { get; set; }
}
@@ -0,0 +1,43 @@
namespace TileServer.Domain.Exceptions;
public abstract class DomainException : Exception
{
protected DomainException(string message) : base(message)
{
}
}
public sealed class ResourceNotFoundException : DomainException
{
public ResourceNotFoundException(string resource, string key)
: base($"{resource} '{key}' was not found.")
{
Resource = resource;
Key = key;
}
public string Resource { get; }
public string Key { get; }
}
public sealed class ResourceConflictException : DomainException
{
public ResourceConflictException(string message) : base(message)
{
}
}
public sealed class DomainValidationException : DomainException
{
public DomainValidationException(string message) : base(message)
{
}
}
public sealed class UnauthenticatedException : DomainException
{
public UnauthenticatedException(string message) : base(message)
{
}
}
+22
View File
@@ -0,0 +1,22 @@
using TileServer.Domain.Tiles;
namespace TileServer.Domain.Extracts;
public sealed class Extract
{
public required string Id { get; init; }
public required string Name { get; init; }
public required Uri Url { get; init; }
public double CenterLon { get; init; }
public double CenterLat { get; init; }
public int MinZoom { get; init; } = 0;
public int MaxZoom { get; init; } = PlanetilerLimits.MaxZoom;
public bool Enabled { get; init; } = true;
}
@@ -0,0 +1,32 @@
namespace TileServer.Domain.Extracts;
public enum ExtractSyncState
{
Pending = 0,
Downloading = 1,
Building = 2,
Ready = 3,
Failed = 4,
PreparingSources = 5
}
public sealed class ExtractRuntimeState
{
public required string ExtractId { get; init; }
public ExtractSyncState Status { get; set; } = ExtractSyncState.Pending;
public string? ETag { get; set; }
public DateTimeOffset? RemoteLastModified { get; set; }
public long? PbfBytes { get; set; }
public DateTimeOffset? DownloadedAt { get; set; }
public DateTimeOffset? BuiltAt { get; set; }
public string? LastError { get; set; }
public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow;
}
+26
View File
@@ -0,0 +1,26 @@
using System.Text.RegularExpressions;
namespace TileServer.Domain;
public static partial class ResourceName
{
public const int MaxLength = 64;
public static bool IsValid(string? value)
=> !string.IsNullOrWhiteSpace(value) && value.Length <= MaxLength && Pattern().IsMatch(value);
public static string Require(string? value, string paramName)
{
if (!IsValid(value))
{
throw new ArgumentException(
"Name must be lowercase latin, digits and hyphens, start with a letter, max 64 chars.",
paramName);
}
return value!;
}
[GeneratedRegex("^[a-z][a-z0-9-]{0,63}$", RegexOptions.CultureInvariant)]
private static partial Regex Pattern();
}
@@ -0,0 +1,3 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup />
</Project>
@@ -0,0 +1,15 @@
namespace TileServer.Domain.Tiles;
/// <summary>
/// OpenMapTiles schema targets z0–z14. Planetiler 0.9.x (planetiler-openmaptiles 3.16)
/// can emit one extra zoom; z16+ is a hard addressing limit in that release.
/// </summary>
public static class PlanetilerLimits
{
public const int DefaultMaxZoom = 14;
public const int MaxZoom = 15;
public static int ClampMaxZoom(int maxZoom)
=> Math.Clamp(maxZoom, 0, MaxZoom);
}
@@ -0,0 +1,39 @@
namespace TileServer.Domain.Tiles;
public readonly record struct TileCoordinate(int Z, int X, int Y)
{
public bool IsValid
{
get
{
if (Z is < 0 or > 30)
{
return false;
}
var size = 1 << Z;
return X >= 0 && Y >= 0 && X < size && Y < size;
}
}
/// <summary>
/// MBTiles stores TMS (origin south-west). MapLibre/XYZ origin is north-west.
/// </summary>
public int ToTmsY() => (1 << Z) - 1 - Y;
public TileCoordinate Ancestor(int zoom)
{
if (zoom == Z)
{
return this;
}
if (zoom < 0 || zoom > Z)
{
throw new ArgumentOutOfRangeException(nameof(zoom), zoom, "Ancestor zoom must be between 0 and Z.");
}
var shift = Z - zoom;
return new TileCoordinate(zoom, X >> shift, Y >> shift);
}
}
+23
View File
@@ -0,0 +1,23 @@
using System.IO.Compression;
namespace TileServer.Domain.Tiles;
public sealed record TileData(byte[] Bytes, bool IsGzipped)
{
public static bool IsGzip(ReadOnlySpan<byte> payload)
=> payload.Length >= 2 && payload[0] == 0x1F && payload[1] == 0x8B;
public byte[] Uncompressed()
{
if (!IsGzipped)
{
return Bytes;
}
using var input = new MemoryStream(Bytes, writable: false);
using var gzip = new GZipStream(input, CompressionMode.Decompress);
using var output = new MemoryStream();
gzip.CopyTo(output);
return output.ToArray();
}
}
@@ -0,0 +1,23 @@
namespace TileServer.Domain.Tiles;
public sealed record VectorLayerInfo(string Id, int MinZoom, int MaxZoom, IReadOnlyDictionary<string, string> Fields);
public sealed record TilesetMetadata(
string ExtractId,
string Name,
string Format,
double MinLon,
double MinLat,
double MaxLon,
double MaxLat,
double CenterLon,
double CenterLat,
int CenterZoom,
int MinZoom,
int MaxZoom,
IReadOnlyList<VectorLayerInfo> VectorLayers)
{
public double[] Bounds => [MinLon, MinLat, MaxLon, MaxLat];
public double[] Center => [CenterLon, CenterLat, CenterZoom];
}
@@ -0,0 +1,31 @@
using Microsoft.EntityFrameworkCore;
using TileServer.Application.Accounts;
using TileServer.Domain.Accounts;
using TileServer.Infrastructure.Data;
namespace TileServer.Infrastructure.Accounts;
public sealed class ApiTokenRepository(AppDbContext db) : IApiTokenRepository
{
public async Task<IReadOnlyList<ApiToken>> ListByUserAsync(Guid userId, CancellationToken ct)
=> await db.ApiTokens
.Where(x => x.UserId == userId)
.OrderByDescending(x => x.CreatedAt)
.ToListAsync(ct)
.ConfigureAwait(false);
public Task<ApiToken?> FindByIdAsync(Guid userId, Guid tokenId, CancellationToken ct)
=> db.ApiTokens.FirstOrDefaultAsync(x => x.UserId == userId && x.Id == tokenId, ct);
public Task<ApiToken?> FindByHashAsync(string hash, CancellationToken ct)
=> db.ApiTokens.FirstOrDefaultAsync(x => x.Hash == hash, ct);
public Task<int> CountActiveAsync(Guid userId, CancellationToken ct)
=> db.ApiTokens.CountAsync(x => x.UserId == userId && x.RevokedAt == null, ct);
public async Task AddAsync(ApiToken token, CancellationToken ct)
=> await db.ApiTokens.AddAsync(token, ct).ConfigureAwait(false);
public Task SaveChangesAsync(CancellationToken ct)
=> db.SaveChangesAsync(ct);
}
@@ -0,0 +1,53 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using TileServer.Application.Accounts;
namespace TileServer.Infrastructure.Accounts;
public sealed class UsageFlushHostedService(
UsageAccumulator accumulator,
IServiceScopeFactory scopes,
ILogger<UsageFlushHostedService> logger) : BackgroundService
{
private static readonly TimeSpan Interval = TimeSpan.FromSeconds(5);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(Interval);
while (await timer.WaitForNextTickAsync(stoppingToken).ConfigureAwait(false))
{
await FlushAsync(stoppingToken).ConfigureAwait(false);
}
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
await FlushAsync(cancellationToken).ConfigureAwait(false);
await base.StopAsync(cancellationToken).ConfigureAwait(false);
}
private async Task FlushAsync(CancellationToken ct)
{
var deltas = accumulator.Drain();
if (deltas.Count == 0)
{
return;
}
try
{
await using var scope = scopes.CreateAsyncScope();
var usage = scope.ServiceProvider.GetRequiredService<IUsageRepository>();
await usage.ApplyAsync(deltas, ct).ConfigureAwait(false);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to flush {Count} usage aggregates", deltas.Count);
foreach (var delta in deltas)
{
accumulator.Restore(delta);
}
}
}
}
@@ -0,0 +1,66 @@
using Microsoft.EntityFrameworkCore;
using TileServer.Application.Accounts;
using TileServer.Domain.Accounts;
using TileServer.Infrastructure.Data;
namespace TileServer.Infrastructure.Accounts;
public sealed class UsageRepository(AppDbContext db) : IUsageRepository, IUsageQuery
{
public async Task ApplyAsync(IReadOnlyList<UsageDelta> deltas, CancellationToken ct)
{
if (deltas.Count == 0)
{
return;
}
foreach (var delta in deltas)
{
var row = await db.UsageDaily.FirstOrDefaultAsync(
x => x.UserId == delta.UserId && x.TokenId == delta.TokenId && x.Date == delta.Day,
ct)
.ConfigureAwait(false);
if (row is null)
{
db.UsageDaily.Add(new UsageDaily
{
Id = Guid.NewGuid(),
UserId = delta.UserId,
TokenId = delta.TokenId,
Date = delta.Day,
TileRequests = delta.TileRequests,
StyleRequests = delta.StyleRequests,
Bytes = delta.Bytes
});
}
else
{
row.TileRequests += delta.TileRequests;
row.StyleRequests += delta.StyleRequests;
row.Bytes += delta.Bytes;
}
}
await db.SaveChangesAsync(ct).ConfigureAwait(false);
}
public async Task<IReadOnlyList<UsageDayDto>> GetAsync(Guid userId, DateOnly from, DateOnly to, CancellationToken ct)
{
var rows = await db.UsageDaily
.AsNoTracking()
.Where(x => x.UserId == userId && x.Date >= from && x.Date <= to)
.Select(x => new { x.Date, x.TileRequests, x.StyleRequests, x.Bytes })
.ToListAsync(ct)
.ConfigureAwait(false);
return rows
.GroupBy(x => x.Date)
.Select(g => new UsageDayDto(
g.Key,
g.Sum(x => x.TileRequests),
g.Sum(x => x.StyleRequests),
g.Sum(x => x.Bytes)))
.OrderBy(x => x.Date)
.ToArray();
}
}
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore;
using TileServer.Application.Accounts;
using TileServer.Domain.Accounts;
using TileServer.Infrastructure.Data;
namespace TileServer.Infrastructure.Accounts;
public sealed class UserRepository(AppDbContext db) : IUserRepository
{
public Task<User?> FindByIdAsync(Guid id, CancellationToken ct)
=> db.Users.FirstOrDefaultAsync(x => x.Id == id, ct);
public Task<User?> FindByYandexIdAsync(string yandexId, CancellationToken ct)
=> db.Users.FirstOrDefaultAsync(x => x.YandexId == yandexId, ct);
public Task<User?> FindBySlugAsync(string slug, CancellationToken ct)
=> db.Users.FirstOrDefaultAsync(x => x.Slug == slug, ct);
public Task<bool> SlugExistsAsync(string slug, Guid? exceptUserId, CancellationToken ct)
=> exceptUserId is null
? db.Users.AnyAsync(x => x.Slug == slug, ct)
: db.Users.AnyAsync(x => x.Slug == slug && x.Id != exceptUserId, ct);
public async Task AddAsync(User user, CancellationToken ct)
=> await db.Users.AddAsync(user, ct).ConfigureAwait(false);
public Task SaveChangesAsync(CancellationToken ct)
=> db.SaveChangesAsync(ct);
}
@@ -0,0 +1,31 @@
using Microsoft.EntityFrameworkCore;
using TileServer.Application.Accounts;
using TileServer.Domain.Accounts;
using TileServer.Infrastructure.Data;
namespace TileServer.Infrastructure.Accounts;
public sealed class UserStyleRepository(AppDbContext db) : IUserStyleRepository
{
public async Task<IReadOnlyList<UserStyle>> ListByUserAsync(Guid userId, CancellationToken ct)
=> await db.UserStyles
.Where(x => x.UserId == userId)
.OrderBy(x => x.Name)
.ToListAsync(ct)
.ConfigureAwait(false);
public Task<UserStyle?> FindAsync(Guid userId, string name, CancellationToken ct)
=> db.UserStyles.FirstOrDefaultAsync(x => x.UserId == userId && x.Name == name, ct);
public async Task AddAsync(UserStyle style, CancellationToken ct)
=> await db.UserStyles.AddAsync(style, ct).ConfigureAwait(false);
public Task RemoveAsync(UserStyle style, CancellationToken ct)
{
db.UserStyles.Remove(style);
return Task.CompletedTask;
}
public Task SaveChangesAsync(CancellationToken ct)
=> db.SaveChangesAsync(ct);
}
@@ -0,0 +1,86 @@
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Options;
using TileServer.Application.Accounts;
using TileServer.Application.Configuration;
using TileServer.Domain.Exceptions;
namespace TileServer.Infrastructure.Auth;
public sealed class YandexOAuthClient(
IHttpClientFactory httpClientFactory,
IOptions<TileServerOptions> options) : IYandexOAuthClient
{
public async Task<YandexProfile> ExchangeAsync(string code, string redirectUri, CancellationToken ct)
{
var yandex = options.Value.Yandex;
if (!yandex.IsConfigured)
{
throw new DomainValidationException("Yandex OAuth is not configured.");
}
var callback = string.IsNullOrWhiteSpace(redirectUri) ? yandex.RedirectUri : redirectUri.Trim();
var client = httpClientFactory.CreateClient("Yandex");
using var tokenRequest = new FormUrlEncodedContent(new Dictionary<string, string>
{
["grant_type"] = "authorization_code",
["code"] = code,
["client_id"] = yandex.ClientId,
["client_secret"] = yandex.ClientSecret,
["redirect_uri"] = callback
});
using var tokenResponse = await client.PostAsync("https://oauth.yandex.ru/token", tokenRequest, ct)
.ConfigureAwait(false);
if (!tokenResponse.IsSuccessStatusCode)
{
throw new UnauthenticatedException("Yandex rejected the authorization code.");
}
var token = await tokenResponse.Content.ReadFromJsonAsync<YandexTokenResponse>(ct).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(token?.AccessToken))
{
throw new UnauthenticatedException("Yandex did not return an access token.");
}
using var infoRequest = new HttpRequestMessage(HttpMethod.Get, "https://login.yandex.ru/info?format=json");
infoRequest.Headers.Authorization = new AuthenticationHeaderValue("OAuth", token.AccessToken);
using var infoResponse = await client.SendAsync(infoRequest, ct).ConfigureAwait(false);
if (!infoResponse.IsSuccessStatusCode)
{
throw new UnauthenticatedException("Could not load the Yandex profile.");
}
var profile = await infoResponse.Content.ReadFromJsonAsync<YandexInfoResponse>(ct).ConfigureAwait(false);
if (profile is null || string.IsNullOrWhiteSpace(profile.Id) || string.IsNullOrWhiteSpace(profile.Login))
{
throw new UnauthenticatedException("Yandex profile is incomplete.");
}
var display = string.IsNullOrWhiteSpace(profile.DisplayName)
? profile.RealName
: profile.DisplayName;
return new YandexProfile(profile.Id, profile.Login, display ?? profile.Login);
}
private sealed class YandexTokenResponse
{
[JsonPropertyName("access_token")]
public string? AccessToken { get; set; }
}
private sealed class YandexInfoResponse
{
[JsonPropertyName("id")]
public string? Id { get; set; }
[JsonPropertyName("login")]
public string? Login { get; set; }
[JsonPropertyName("display_name")]
public string? DisplayName { get; set; }
[JsonPropertyName("real_name")]
public string? RealName { get; set; }
}
}
@@ -0,0 +1,62 @@
using Microsoft.EntityFrameworkCore;
using TileServer.Domain.Accounts;
namespace TileServer.Infrastructure.Data;
public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<User> Users => Set<User>();
public DbSet<ApiToken> ApiTokens => Set<ApiToken>();
public DbSet<UserStyle> UserStyles => Set<UserStyle>();
public DbSet<UsageDaily> UsageDaily => Set<UsageDaily>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>(entity =>
{
entity.ToTable("Users");
entity.HasKey(x => x.Id);
entity.Property(x => x.YandexId).HasMaxLength(64).IsRequired();
entity.Property(x => x.Login).HasMaxLength(128).IsRequired();
entity.Property(x => x.DisplayName).HasMaxLength(256).IsRequired();
entity.Property(x => x.Slug).HasMaxLength(64).IsRequired();
entity.HasIndex(x => x.YandexId).IsUnique();
entity.HasIndex(x => x.Slug).IsUnique();
entity.HasMany(x => x.Tokens).WithOne(x => x.User).HasForeignKey(x => x.UserId).OnDelete(DeleteBehavior.Cascade);
entity.HasMany(x => x.Styles).WithOne(x => x.User).HasForeignKey(x => x.UserId).OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity<ApiToken>(entity =>
{
entity.ToTable("ApiTokens");
entity.HasKey(x => x.Id);
entity.Property(x => x.Name).HasMaxLength(64).IsRequired();
entity.Property(x => x.Hash).HasMaxLength(64).IsRequired();
entity.Property(x => x.Prefix).HasMaxLength(16).IsRequired();
entity.HasIndex(x => x.Hash).IsUnique();
entity.HasIndex(x => x.UserId);
entity.Ignore(x => x.IsRevoked);
});
modelBuilder.Entity<UserStyle>(entity =>
{
entity.ToTable("UserStyles");
entity.HasKey(x => x.Id);
entity.Property(x => x.Name).HasMaxLength(64).IsRequired();
entity.Property(x => x.Json).HasColumnType("text").IsRequired();
entity.Property(x => x.CreatedFrom).HasMaxLength(64);
entity.HasIndex(x => new { x.UserId, x.Name }).IsUnique();
});
modelBuilder.Entity<UsageDaily>(entity =>
{
entity.ToTable("UsageDaily");
entity.HasKey(x => x.Id);
entity.HasIndex(x => new { x.UserId, x.TokenId, x.Date }).IsUnique();
entity.HasIndex(x => new { x.UserId, x.Date });
});
}
}
@@ -0,0 +1,17 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
namespace TileServer.Infrastructure.Data;
public sealed class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
public AppDbContext CreateDbContext(string[] args)
{
var connection = Environment.GetEnvironmentVariable("ConnectionStrings__Accounts")
?? "Host=127.0.0.1;Port=5433;Database=tile_server;Username=tiles;Password=tiles";
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseNpgsql(connection)
.Options;
return new AppDbContext(options);
}
}
@@ -0,0 +1,212 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using TileServer.Infrastructure.Data;
#nullable disable
namespace TileServer.Infrastructure.Data.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260920225316_InitialAccounts")]
partial class InitialAccounts
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.11")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("TileServer.Domain.Accounts.ApiToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Hash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<string>("Prefix")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("character varying(16)");
b.Property<DateTimeOffset?>("RevokedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("Hash")
.IsUnique();
b.HasIndex("UserId");
b.ToTable("ApiTokens", (string)null);
});
modelBuilder.Entity("TileServer.Domain.Accounts.UsageDaily", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<long>("Bytes")
.HasColumnType("bigint");
b.Property<DateOnly>("Date")
.HasColumnType("date");
b.Property<long>("StyleRequests")
.HasColumnType("bigint");
b.Property<long>("TileRequests")
.HasColumnType("bigint");
b.Property<Guid>("TokenId")
.HasColumnType("uuid");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId", "Date");
b.HasIndex("UserId", "TokenId", "Date")
.IsUnique();
b.ToTable("UsageDaily", (string)null);
});
modelBuilder.Entity("TileServer.Domain.Accounts.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<DateTimeOffset>("LastLoginAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Login")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("Slug")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<string>("YandexId")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.HasKey("Id");
b.HasIndex("Slug")
.IsUnique();
b.HasIndex("YandexId")
.IsUnique();
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("TileServer.Domain.Accounts.UserStyle", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("CreatedFrom")
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<string>("Json")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId", "Name")
.IsUnique();
b.ToTable("UserStyles", (string)null);
});
modelBuilder.Entity("TileServer.Domain.Accounts.ApiToken", b =>
{
b.HasOne("TileServer.Domain.Accounts.User", "User")
.WithMany("Tokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("TileServer.Domain.Accounts.UserStyle", b =>
{
b.HasOne("TileServer.Domain.Accounts.User", "User")
.WithMany("Styles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("TileServer.Domain.Accounts.User", b =>
{
b.Navigation("Styles");
b.Navigation("Tokens");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,151 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace TileServer.Infrastructure.Data.Migrations
{
/// <inheritdoc />
public partial class InitialAccounts : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "UsageDaily",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
UserId = table.Column<Guid>(type: "uuid", nullable: false),
TokenId = table.Column<Guid>(type: "uuid", nullable: false),
Date = table.Column<DateOnly>(type: "date", nullable: false),
TileRequests = table.Column<long>(type: "bigint", nullable: false),
StyleRequests = table.Column<long>(type: "bigint", nullable: false),
Bytes = table.Column<long>(type: "bigint", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UsageDaily", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
YandexId = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
Login = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: false),
DisplayName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: false),
Slug = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
LastLoginAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ApiTokens",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
UserId = table.Column<Guid>(type: "uuid", nullable: false),
Name = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
Hash = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
Prefix = table.Column<string>(type: "character varying(16)", maxLength: 16, nullable: false),
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
RevokedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ApiTokens", x => x.Id);
table.ForeignKey(
name: "FK_ApiTokens_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "UserStyles",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
UserId = table.Column<Guid>(type: "uuid", nullable: false),
Name = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
Json = table.Column<string>(type: "text", nullable: false),
CreatedFrom = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
UpdatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserStyles", x => x.Id);
table.ForeignKey(
name: "FK_UserStyles_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_ApiTokens_Hash",
table: "ApiTokens",
column: "Hash",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_ApiTokens_UserId",
table: "ApiTokens",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_UsageDaily_UserId_Date",
table: "UsageDaily",
columns: new[] { "UserId", "Date" });
migrationBuilder.CreateIndex(
name: "IX_UsageDaily_UserId_TokenId_Date",
table: "UsageDaily",
columns: new[] { "UserId", "TokenId", "Date" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Users_Slug",
table: "Users",
column: "Slug",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Users_YandexId",
table: "Users",
column: "YandexId",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_UserStyles_UserId_Name",
table: "UserStyles",
columns: new[] { "UserId", "Name" },
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ApiTokens");
migrationBuilder.DropTable(
name: "UsageDaily");
migrationBuilder.DropTable(
name: "UserStyles");
migrationBuilder.DropTable(
name: "Users");
}
}
}
@@ -0,0 +1,209 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using TileServer.Infrastructure.Data;
#nullable disable
namespace TileServer.Infrastructure.Data.Migrations
{
[DbContext(typeof(AppDbContext))]
partial class AppDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.11")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("TileServer.Domain.Accounts.ApiToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Hash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<string>("Prefix")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("character varying(16)");
b.Property<DateTimeOffset?>("RevokedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("Hash")
.IsUnique();
b.HasIndex("UserId");
b.ToTable("ApiTokens", (string)null);
});
modelBuilder.Entity("TileServer.Domain.Accounts.UsageDaily", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<long>("Bytes")
.HasColumnType("bigint");
b.Property<DateOnly>("Date")
.HasColumnType("date");
b.Property<long>("StyleRequests")
.HasColumnType("bigint");
b.Property<long>("TileRequests")
.HasColumnType("bigint");
b.Property<Guid>("TokenId")
.HasColumnType("uuid");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId", "Date");
b.HasIndex("UserId", "TokenId", "Date")
.IsUnique();
b.ToTable("UsageDaily", (string)null);
});
modelBuilder.Entity("TileServer.Domain.Accounts.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<DateTimeOffset>("LastLoginAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Login")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("Slug")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<string>("YandexId")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.HasKey("Id");
b.HasIndex("Slug")
.IsUnique();
b.HasIndex("YandexId")
.IsUnique();
b.ToTable("Users", (string)null);
});
modelBuilder.Entity("TileServer.Domain.Accounts.UserStyle", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("CreatedFrom")
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<string>("Json")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId", "Name")
.IsUnique();
b.ToTable("UserStyles", (string)null);
});
modelBuilder.Entity("TileServer.Domain.Accounts.ApiToken", b =>
{
b.HasOne("TileServer.Domain.Accounts.User", "User")
.WithMany("Tokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("TileServer.Domain.Accounts.UserStyle", b =>
{
b.HasOne("TileServer.Domain.Accounts.User", "User")
.WithMany("Styles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("TileServer.Domain.Accounts.User", b =>
{
b.Navigation("Styles");
b.Navigation("Tokens");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,103 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using TileServer.Application;
using TileServer.Application.Accounts;
using TileServer.Application.Configuration;
using TileServer.Application.Extracts;
using TileServer.Application.Styles;
using TileServer.Application.Sync;
using TileServer.Application.Tiles;
using TileServer.Infrastructure.Accounts;
using TileServer.Infrastructure.Auth;
using TileServer.Infrastructure.Data;
using TileServer.Infrastructure.Downloads;
using TileServer.Infrastructure.Extracts;
using TileServer.Infrastructure.Storage;
using TileServer.Infrastructure.Styles;
using TileServer.Infrastructure.Sync;
using TileServer.Infrastructure.Tiles;
namespace TileServer.Infrastructure;
public static class DependencyInjection
{
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
{
services.AddOptions<TileServerOptions>()
.Bind(configuration.GetSection(TileServerOptions.SectionName))
.PostConfigure(options =>
{
// Same flat names as please_pay_me_bot: YANDEX_CLIENT_ID / SECRET / REDIRECT_URI.
var id = configuration["YANDEX_CLIENT_ID"];
if (!string.IsNullOrWhiteSpace(id))
{
options.Yandex.ClientId = id.Trim();
}
var secret = configuration["YANDEX_CLIENT_SECRET"];
if (!string.IsNullOrWhiteSpace(secret))
{
options.Yandex.ClientSecret = secret.Trim();
}
var redirect = configuration["YANDEX_REDIRECT_URI"];
if (!string.IsNullOrWhiteSpace(redirect))
{
options.Yandex.RedirectUri = redirect.Trim();
}
});
services.AddSingleton<IDataPaths, DataPaths>();
services.AddDbContext<AppDbContext>(options =>
{
var connection = configuration.GetConnectionString("Accounts")
?? throw new InvalidOperationException("Connection string 'Accounts' is not configured.");
options.UseNpgsql(connection);
});
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<IApiTokenRepository, ApiTokenRepository>();
services.AddScoped<IUserStyleRepository, UserStyleRepository>();
services.AddScoped<IUsageRepository, UsageRepository>();
services.AddScoped<IUsageQuery, UsageRepository>();
services.AddScoped<IYandexOAuthClient, YandexOAuthClient>();
services.AddHostedService<UsageFlushHostedService>();
services.AddMemoryCache(cache =>
{
var size = configuration.GetSection(TileServerOptions.SectionName)
.GetValue(nameof(TileServerOptions.TileCacheSize), 512);
cache.SizeLimit = Math.Max(64, size);
});
services.AddSingleton<IVectorTileOverzoomer, VectorTileOverzoomer>();
services.AddSingleton<IExtractCatalog, FileExtractCatalog>();
services.AddSingleton<IExtractStateStore, JsonExtractStateStore>();
services.AddSingleton<IExtractDownloader, HttpExtractDownloader>();
services.AddSingleton<ITileStore, SqliteMbtilesTileStore>();
services.AddSingleton<ITileBuilder, PlanetilerTileBuilder>();
services.AddSingleton<IPlanetilerBootstrapper, PlanetilerJarBootstrapper>();
services.AddSingleton<IPlanetilerSourceBootstrapper, PlanetilerSourceBootstrapper>();
services.AddSingleton<IStyleCatalog, FileStyleCatalog>();
services.AddSingleton<ISyncSchedulerClock, CronSyncSchedulerClock>();
services.AddHostedService<MapSyncHostedService>();
services.AddHttpClient("Extracts", client =>
{
client.Timeout = Timeout.InfiniteTimeSpan;
client.DefaultRequestHeaders.UserAgent.ParseAdd("TileServer/1.0 (+https://openstreetmap.org/copyright)");
});
services.AddHttpClient("Tools", client =>
{
client.Timeout = TimeSpan.FromMinutes(15);
client.DefaultRequestHeaders.UserAgent.ParseAdd("TileServer/1.0");
});
services.AddHttpClient("Yandex", client =>
{
client.Timeout = TimeSpan.FromSeconds(20);
client.DefaultRequestHeaders.UserAgent.ParseAdd("TileServer/1.0");
});
return services;
}
}
@@ -0,0 +1,90 @@
using System.Net;
using System.Net.Http.Headers;
using Microsoft.Extensions.Logging;
using TileServer.Application.Extracts;
using TileServer.Domain.Extracts;
namespace TileServer.Infrastructure.Downloads;
public sealed class HttpExtractDownloader(IHttpClientFactory httpClientFactory, ILogger<HttpExtractDownloader> logger)
: IExtractDownloader
{
public async Task<DownloadResult> DownloadAsync(
Extract extract,
string destinationPath,
ExtractRuntimeState state,
CancellationToken ct)
{
Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!);
var client = httpClientFactory.CreateClient("Extracts");
using var request = new HttpRequestMessage(HttpMethod.Get, extract.Url);
if (!string.IsNullOrWhiteSpace(state.ETag))
{
request.Headers.IfNoneMatch.Add(new EntityTagHeaderValue(Quote(state.ETag)));
}
if (state.RemoteLastModified is { } lastModified)
{
request.Headers.IfModifiedSince = lastModified.UtcDateTime;
}
using var response = await client
.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct)
.ConfigureAwait(false);
if (response.StatusCode == HttpStatusCode.NotModified && File.Exists(destinationPath))
{
logger.LogInformation("Extract {ExtractId} was not modified remotely.", extract.Id);
return new DownloadResult(false, new FileInfo(destinationPath).Length, state.ETag, state.RemoteLastModified);
}
response.EnsureSuccessStatusCode();
var etag = response.Headers.ETag?.Tag?.Trim('"');
var remoteModified = response.Content.Headers.LastModified;
var total = response.Content.Headers.ContentLength;
if (File.Exists(destinationPath) &&
total is { } expected &&
new FileInfo(destinationPath).Length == expected)
{
logger.LogInformation(
"Extract {ExtractId} already on disk ({Bytes} bytes), skip re-download.",
extract.Id,
expected);
return new DownloadResult(false, expected, etag ?? state.ETag, remoteModified ?? state.RemoteLastModified);
}
var partialPath = destinationPath + ".partial";
logger.LogInformation(
"Extract {ExtractId}: headers OK (HTTP {Status}, {TotalMb} MB).",
extract.Id,
(int)response.StatusCode,
total is null ? "?" : (total.Value / 1_000_000d).ToString("F1"));
await using (var input = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false))
await using (var output = new FileStream(partialPath, FileMode.Create, FileAccess.Write, FileShare.None, 1024 * 1024, FileOptions.Asynchronous))
{
await StreamCopy.CopyWithStallTimeoutAsync(
input,
output,
TimeSpan.FromSeconds(60),
TimeSpan.FromSeconds(15),
(copied, expectedSize) => logger.LogInformation(
"Downloading {ExtractId}: {CopiedMb:F1} / {TotalMb} MB",
extract.Id,
copied / 1_000_000d,
expectedSize is null ? "?" : (expectedSize.Value / 1_000_000d).ToString("F1")),
total,
ct)
.ConfigureAwait(false);
}
File.Move(partialPath, destinationPath, overwrite: true);
var bytes = new FileInfo(destinationPath).Length;
logger.LogInformation("Downloaded {ExtractId}: {Bytes} bytes.", extract.Id, bytes);
return new DownloadResult(true, bytes, etag, remoteModified);
}
private static string Quote(string etag)
=> etag.StartsWith('"') ? etag : $"\"{etag}\"";
}
@@ -0,0 +1,62 @@
using System.Diagnostics;
namespace TileServer.Infrastructure.Downloads;
public static class StreamCopy
{
public static async Task<long> CopyWithStallTimeoutAsync(
Stream input,
Stream output,
TimeSpan stallTimeout,
TimeSpan logInterval,
Action<long, long?> onProgress,
long? totalBytes,
CancellationToken ct)
{
var buffer = new byte[1024 * 1024];
long copied = 0;
var firstByteLogged = false;
var lastLog = TimeSpan.Zero;
var clock = Stopwatch.StartNew();
while (true)
{
int read;
using (var stallCts = CancellationTokenSource.CreateLinkedTokenSource(ct))
{
stallCts.CancelAfter(stallTimeout);
try
{
read = await input.ReadAsync(buffer.AsMemory(0, buffer.Length), stallCts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
throw new TimeoutException(
$"No data received for {stallTimeout.TotalSeconds:0}s after {copied} bytes (stall).");
}
}
if (read == 0)
{
break;
}
await output.WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false);
copied += read;
if (!firstByteLogged)
{
firstByteLogged = true;
onProgress(copied, totalBytes);
lastLog = clock.Elapsed;
}
else if (clock.Elapsed - lastLog >= logInterval)
{
onProgress(copied, totalBytes);
lastLog = clock.Elapsed;
}
}
return copied;
}
}
@@ -0,0 +1,188 @@
using System.Text.Json;
using Microsoft.Extensions.Options;
using TileServer.Application;
using TileServer.Application.Configuration;
using TileServer.Application.Extracts;
using TileServer.Domain;
using TileServer.Domain.Exceptions;
using TileServer.Domain.Extracts;
using TileServer.Domain.Tiles;
namespace TileServer.Infrastructure.Extracts;
public sealed class FileExtractCatalog : IExtractCatalog
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true,
PropertyNameCaseInsensitive = true
};
private readonly IOptionsMonitor<TileServerOptions> _options;
private readonly IDataPaths _paths;
private readonly object _gate = new();
public FileExtractCatalog(IOptionsMonitor<TileServerOptions> options, IDataPaths paths)
{
_options = options;
_paths = paths;
}
public IReadOnlyList<Extract> GetAll()
{
lock (_gate)
{
return MergeUnlocked().Values.OrderBy(e => e.Id, StringComparer.Ordinal).ToArray();
}
}
public Extract? Find(string id)
{
lock (_gate)
{
return MergeUnlocked().GetValueOrDefault(id);
}
}
public Extract GetRequired(string id)
=> Find(id) ?? throw new ResourceNotFoundException("Extract", id);
public async Task AddOrUpdateAsync(Extract extract, CancellationToken ct)
{
ResourceName.Require(extract.Id, nameof(extract.Id));
List<ExtractOptions> overlay;
lock (_gate)
{
overlay = ReadOverlayUnlocked();
var existing = overlay.FindIndex(x => string.Equals(x.Id, extract.Id, StringComparison.OrdinalIgnoreCase));
var mapped = ToOptions(extract);
if (existing >= 0)
{
overlay[existing] = mapped;
}
else
{
overlay.Add(mapped);
}
}
await WriteOverlayAsync(overlay, ct).ConfigureAwait(false);
}
public async Task RemoveAsync(string id, CancellationToken ct)
{
List<ExtractOptions> overlay;
lock (_gate)
{
overlay = ReadOverlayUnlocked();
var removed = overlay.RemoveAll(x => string.Equals(x.Id, id, StringComparison.OrdinalIgnoreCase));
if (removed == 0 && _options.CurrentValue.Extracts.Any(x => x.Id == id))
{
throw new DomainValidationException(
$"Extract '{id}' comes from appsettings and cannot be removed via API. Disable it in configuration instead.");
}
}
await WriteOverlayAsync(overlay, ct).ConfigureAwait(false);
}
private Dictionary<string, Extract> MergeUnlocked()
{
var map = new Dictionary<string, Extract>(StringComparer.OrdinalIgnoreCase);
foreach (var item in _options.CurrentValue.Extracts)
{
var extract = ToDomain(item);
if (extract is not null)
{
map[extract.Id] = extract;
}
}
foreach (var item in ReadOverlayUnlocked())
{
var extract = ToDomain(item);
if (extract is null)
{
continue;
}
if (map.TryGetValue(extract.Id, out var configured))
{
extract = new Extract
{
Id = extract.Id,
Name = extract.Name,
Url = extract.Url,
CenterLon = extract.CenterLon,
CenterLat = extract.CenterLat,
MinZoom = extract.MinZoom,
MaxZoom = Math.Max(extract.MaxZoom, configured.MaxZoom),
Enabled = extract.Enabled
};
}
map[extract.Id] = extract;
}
return map;
}
private List<ExtractOptions> ReadOverlayUnlocked()
{
if (!File.Exists(_paths.OverlayExtractsFile))
{
return [];
}
var json = File.ReadAllText(_paths.OverlayExtractsFile);
return JsonSerializer.Deserialize<List<ExtractOptions>>(json, JsonOptions) ?? [];
}
private async Task WriteOverlayAsync(List<ExtractOptions> overlay, CancellationToken ct)
{
var json = JsonSerializer.Serialize(overlay, JsonOptions);
var temp = _paths.OverlayExtractsFile + ".tmp";
await File.WriteAllTextAsync(temp, json, ct).ConfigureAwait(false);
File.Move(temp, _paths.OverlayExtractsFile, overwrite: true);
}
private static Extract? ToDomain(ExtractOptions options)
{
if (!ResourceName.IsValid(options.Id) || string.IsNullOrWhiteSpace(options.Url))
{
return null;
}
if (!Uri.TryCreate(options.Url, UriKind.Absolute, out var uri))
{
return null;
}
var centerLon = options.Center is { Length: >= 1 } ? options.Center[0] : 37.6173;
var centerLat = options.Center is { Length: >= 2 } ? options.Center[1] : 55.7558;
return new Extract
{
Id = options.Id,
Name = string.IsNullOrWhiteSpace(options.Name) ? options.Id : options.Name,
Url = uri,
CenterLon = centerLon,
CenterLat = centerLat,
MinZoom = options.MinZoom,
MaxZoom = PlanetilerLimits.ClampMaxZoom(options.MaxZoom),
Enabled = options.Enabled
};
}
private static ExtractOptions ToOptions(Extract extract) => new()
{
Id = extract.Id,
Name = extract.Name,
Url = extract.Url.ToString(),
Center = [extract.CenterLon, extract.CenterLat],
MinZoom = extract.MinZoom,
MaxZoom = extract.MaxZoom,
Enabled = extract.Enabled
};
}
@@ -0,0 +1,58 @@
using System.Text.Json;
using TileServer.Application;
using TileServer.Application.Extracts;
using TileServer.Domain.Extracts;
namespace TileServer.Infrastructure.Extracts;
public sealed class JsonExtractStateStore : IExtractStateStore
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true,
PropertyNameCaseInsensitive = true
};
private readonly IDataPaths _paths;
private readonly object _gate = new();
public JsonExtractStateStore(IDataPaths paths)
{
_paths = paths;
}
public Task<ExtractRuntimeState> GetAsync(string extractId, CancellationToken ct)
{
var path = PathFor(extractId);
lock (_gate)
{
if (!File.Exists(path))
{
return Task.FromResult(new ExtractRuntimeState { ExtractId = extractId });
}
var json = File.ReadAllText(path);
var state = JsonSerializer.Deserialize<ExtractRuntimeState>(json, JsonOptions)
?? new ExtractRuntimeState { ExtractId = extractId };
return Task.FromResult(state);
}
}
public Task SaveAsync(ExtractRuntimeState state, CancellationToken ct)
{
state.UpdatedAt = DateTimeOffset.UtcNow;
var path = PathFor(state.ExtractId);
var json = JsonSerializer.Serialize(state, JsonOptions);
lock (_gate)
{
var temp = path + ".tmp";
File.WriteAllText(temp, json);
File.Move(temp, path, overwrite: true);
}
return Task.CompletedTask;
}
private string PathFor(string extractId) => Path.Combine(_paths.State, $"{extractId}.json");
}
@@ -0,0 +1,118 @@
{
"version": 8,
"name": "Dark",
"metadata": { "tile-server:kind": "openmaptiles" },
"sources": {
"openmaptiles": { "type": "vector", "url": "{{tilejson}}" }
},
"glyphs": "https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf",
"layers": [
{ "id": "background", "type": "background", "paint": { "background-color": "#1b1f24" } },
{
"id": "landcover-wood",
"type": "fill",
"source": "openmaptiles",
"source-layer": "landcover",
"filter": ["==", "class", "wood"],
"paint": { "fill-color": "#243026", "fill-opacity": 0.9 }
},
{
"id": "park",
"type": "fill",
"source": "openmaptiles",
"source-layer": "park",
"paint": { "fill-color": "#2a382c", "fill-opacity": 0.7 }
},
{
"id": "water",
"type": "fill",
"source": "openmaptiles",
"source-layer": "water",
"filter": ["==", "$type", "Polygon"],
"paint": { "fill-color": "#1a3347" }
},
{
"id": "waterway",
"type": "line",
"source": "openmaptiles",
"source-layer": "waterway",
"paint": { "line-color": "#1a3347", "line-width": { "base": 1.3, "stops": [[8, 0.5], [16, 4]] } }
},
{
"id": "building",
"type": "fill",
"source": "openmaptiles",
"source-layer": "building",
"minzoom": 13,
"paint": { "fill-color": "#2b3138", "fill-outline-color": "#3a414a" }
},
{
"id": "road-minor",
"type": "line",
"source": "openmaptiles",
"source-layer": "transportation",
"minzoom": 12,
"filter": ["in", "class", "minor", "service", "track"],
"paint": { "line-color": "#3d4450", "line-width": { "base": 1.2, "stops": [[12, 0.8], [18, 8]] } }
},
{
"id": "road-secondary",
"type": "line",
"source": "openmaptiles",
"source-layer": "transportation",
"filter": ["in", "class", "primary", "secondary", "tertiary"],
"paint": { "line-color": "#5a6270", "line-width": { "base": 1.2, "stops": [[6, 0.8], [18, 14]] } }
},
{
"id": "road-motorway",
"type": "line",
"source": "openmaptiles",
"source-layer": "transportation",
"filter": ["in", "class", "motorway", "trunk"],
"paint": { "line-color": "#c47a3a", "line-width": { "base": 1.2, "stops": [[5, 0.8], [18, 18]] } }
},
{
"id": "road-rail",
"type": "line",
"source": "openmaptiles",
"source-layer": "transportation",
"filter": ["==", "class", "rail"],
"paint": { "line-color": "#4a4450", "line-width": 0.8 }
},
{
"id": "boundary",
"type": "line",
"source": "openmaptiles",
"source-layer": "boundary",
"filter": ["in", "admin_level", 2, 4],
"paint": { "line-color": "#6a7380", "line-dasharray": [3, 2], "line-width": 1, "line-opacity": 0.6 }
},
{
"id": "road-name",
"type": "symbol",
"source": "openmaptiles",
"source-layer": "transportation_name",
"minzoom": 12,
"layout": {
"text-field": ["coalesce", ["get", "name"], ["get", "name:latin"]],
"text-font": ["Noto Sans Regular"],
"text-size": 11,
"symbol-placement": "line"
},
"paint": { "text-color": "#d7dde6", "text-halo-color": "#1b1f24", "text-halo-width": 1.2 }
},
{
"id": "place-city",
"type": "symbol",
"source": "openmaptiles",
"source-layer": "place",
"filter": ["in", "class", "city", "town"],
"layout": {
"text-field": ["coalesce", ["get", "name"], ["get", "name:latin"]],
"text-font": ["Noto Sans Bold"],
"text-size": { "stops": [[4, 12], [10, 18]] }
},
"paint": { "text-color": "#f2f5f8", "text-halo-color": "#1b1f24", "text-halo-width": 1.6 }
}
]
}
@@ -0,0 +1,305 @@
{
"version": 8,
"name": "OSM Bright",
"metadata": {
"tile-server:kind": "openmaptiles"
},
"sources": {
"openmaptiles": {
"type": "vector",
"url": "{{tilejson}}"
}
},
"glyphs": "https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf",
"layers": [
{
"id": "background",
"type": "background",
"paint": { "background-color": "#f4f1ea" }
},
{
"id": "landcover-wood",
"type": "fill",
"source": "openmaptiles",
"source-layer": "landcover",
"filter": ["==", "class", "wood"],
"paint": { "fill-color": "#c6ddb4", "fill-opacity": 0.8 }
},
{
"id": "landcover-grass",
"type": "fill",
"source": "openmaptiles",
"source-layer": "landcover",
"filter": ["==", "class", "grass"],
"paint": { "fill-color": "#d8e8c8", "fill-opacity": 0.7 }
},
{
"id": "landcover-farmland",
"type": "fill",
"source": "openmaptiles",
"source-layer": "landcover",
"filter": ["==", "class", "farmland"],
"paint": { "fill-color": "#e8e4c8", "fill-opacity": 0.6 }
},
{
"id": "landuse-residential",
"type": "fill",
"source": "openmaptiles",
"source-layer": "landuse",
"filter": ["==", "class", "residential"],
"paint": { "fill-color": "#e8e0d8", "fill-opacity": 0.5 }
},
{
"id": "park",
"type": "fill",
"source": "openmaptiles",
"source-layer": "park",
"paint": { "fill-color": "#cdebb0", "fill-opacity": 0.7 }
},
{
"id": "water",
"type": "fill",
"source": "openmaptiles",
"source-layer": "water",
"filter": ["==", "$type", "Polygon"],
"paint": { "fill-color": "#7eb6d9" }
},
{
"id": "waterway",
"type": "line",
"source": "openmaptiles",
"source-layer": "waterway",
"paint": {
"line-color": "#7eb6d9",
"line-width": { "base": 1.3, "stops": [[8, 0.5], [16, 4]] }
}
},
{
"id": "building",
"type": "fill",
"source": "openmaptiles",
"source-layer": "building",
"minzoom": 13,
"paint": {
"fill-color": "#d9d0c7",
"fill-outline-color": "#c4bbb2",
"fill-opacity": { "base": 1, "stops": [[13, 0], [14, 1]] }
}
},
{
"id": "transportation-tunnel",
"type": "line",
"source": "openmaptiles",
"source-layer": "transportation",
"filter": ["==", "brunnel", "tunnel"],
"paint": {
"line-color": "#d0d0d0",
"line-dasharray": [1, 1],
"line-width": { "base": 1.4, "stops": [[6, 0.5], [14, 4], [18, 16]] }
}
},
{
"id": "road-minor-casing",
"type": "line",
"source": "openmaptiles",
"source-layer": "transportation",
"minzoom": 12,
"filter": ["all", ["in", "class", "minor", "service", "track"], ["!=", "brunnel", "tunnel"]],
"paint": {
"line-color": "#cfcdca",
"line-width": { "base": 1.2, "stops": [[12, 1.2], [18, 10]] }
}
},
{
"id": "road-minor",
"type": "line",
"source": "openmaptiles",
"source-layer": "transportation",
"minzoom": 12,
"filter": ["all", ["in", "class", "minor", "service", "track"], ["!=", "brunnel", "tunnel"]],
"paint": {
"line-color": "#ffffff",
"line-width": { "base": 1.2, "stops": [[12, 0.8], [18, 8]] }
}
},
{
"id": "road-tertiary-casing",
"type": "line",
"source": "openmaptiles",
"source-layer": "transportation",
"minzoom": 8,
"filter": ["all", ["==", "class", "tertiary"], ["!=", "brunnel", "tunnel"]],
"paint": {
"line-color": "#c4b9a6",
"line-width": { "base": 1.2, "stops": [[8, 1.5], [18, 14]] }
}
},
{
"id": "road-tertiary",
"type": "line",
"source": "openmaptiles",
"source-layer": "transportation",
"minzoom": 8,
"filter": ["all", ["==", "class", "tertiary"], ["!=", "brunnel", "tunnel"]],
"paint": {
"line-color": "#ffffff",
"line-width": { "base": 1.2, "stops": [[8, 0.8], [18, 12]] }
}
},
{
"id": "road-secondary-casing",
"type": "line",
"source": "openmaptiles",
"source-layer": "transportation",
"filter": ["all", ["in", "class", "primary", "secondary"], ["!=", "brunnel", "tunnel"]],
"paint": {
"line-color": "#d4b98a",
"line-width": { "base": 1.2, "stops": [[6, 1.4], [18, 18]] }
}
},
{
"id": "road-secondary",
"type": "line",
"source": "openmaptiles",
"source-layer": "transportation",
"filter": ["all", ["in", "class", "primary", "secondary"], ["!=", "brunnel", "tunnel"]],
"paint": {
"line-color": "#feeaa2",
"line-width": { "base": 1.2, "stops": [[6, 0.8], [18, 14]] }
}
},
{
"id": "road-motorway-casing",
"type": "line",
"source": "openmaptiles",
"source-layer": "transportation",
"filter": ["all", ["in", "class", "motorway", "trunk"], ["!=", "brunnel", "tunnel"]],
"paint": {
"line-color": "#d05a3a",
"line-width": { "base": 1.2, "stops": [[5, 1.6], [18, 22]] }
}
},
{
"id": "road-motorway",
"type": "line",
"source": "openmaptiles",
"source-layer": "transportation",
"filter": ["all", ["in", "class", "motorway", "trunk"], ["!=", "brunnel", "tunnel"]],
"paint": {
"line-color": "#e8923d",
"line-width": { "base": 1.2, "stops": [[5, 0.8], [18, 18]] }
}
},
{
"id": "road-rail",
"type": "line",
"source": "openmaptiles",
"source-layer": "transportation",
"filter": ["==", "class", "rail"],
"paint": {
"line-color": "#9a8f86",
"line-width": { "base": 1.2, "stops": [[8, 0.4], [16, 2]] }
}
},
{
"id": "boundary",
"type": "line",
"source": "openmaptiles",
"source-layer": "boundary",
"filter": ["in", "admin_level", 2, 4],
"paint": {
"line-color": "#9e8f80",
"line-dasharray": [3, 2],
"line-width": { "base": 1, "stops": [[2, 0.6], [10, 1.8]] },
"line-opacity": 0.7
}
},
{
"id": "road-name",
"type": "symbol",
"source": "openmaptiles",
"source-layer": "transportation_name",
"minzoom": 12,
"layout": {
"text-field": ["coalesce", ["get", "name"], ["get", "name:latin"]],
"text-font": ["Noto Sans Regular"],
"text-size": 11,
"symbol-placement": "line"
},
"paint": {
"text-color": "#4a433c",
"text-halo-color": "#ffffff",
"text-halo-width": 1.2
}
},
{
"id": "water-name",
"type": "symbol",
"source": "openmaptiles",
"source-layer": "water_name",
"layout": {
"text-field": ["coalesce", ["get", "name"], ["get", "name:latin"]],
"text-font": ["Noto Sans Regular"],
"text-size": { "stops": [[10, 11], [14, 16]] }
},
"paint": {
"text-color": "#3d6e8c",
"text-halo-color": "#d6ecf7",
"text-halo-width": 1.2
}
},
{
"id": "place-village",
"type": "symbol",
"source": "openmaptiles",
"source-layer": "place",
"minzoom": 9,
"filter": ["==", "class", "village"],
"layout": {
"text-field": ["coalesce", ["get", "name"], ["get", "name:latin"]],
"text-font": ["Noto Sans Regular"],
"text-size": 11
},
"paint": {
"text-color": "#333333",
"text-halo-color": "#ffffff",
"text-halo-width": 1.4
}
},
{
"id": "place-town",
"type": "symbol",
"source": "openmaptiles",
"source-layer": "place",
"minzoom": 7,
"filter": ["==", "class", "town"],
"layout": {
"text-field": ["coalesce", ["get", "name"], ["get", "name:latin"]],
"text-font": ["Noto Sans Regular"],
"text-size": { "stops": [[7, 12], [12, 16]] }
},
"paint": {
"text-color": "#222222",
"text-halo-color": "#ffffff",
"text-halo-width": 1.5
}
},
{
"id": "place-city",
"type": "symbol",
"source": "openmaptiles",
"source-layer": "place",
"filter": ["==", "class", "city"],
"layout": {
"text-field": ["coalesce", ["get", "name"], ["get", "name:latin"]],
"text-font": ["Noto Sans Bold"],
"text-size": { "stops": [[4, 12], [10, 20]] }
},
"paint": {
"text-color": "#111111",
"text-halo-color": "#ffffff",
"text-halo-width": 1.6
}
}
]
}
@@ -0,0 +1,110 @@
{
"version": 8,
"name": "Positron",
"metadata": { "tile-server:kind": "openmaptiles" },
"sources": {
"openmaptiles": { "type": "vector", "url": "{{tilejson}}" }
},
"glyphs": "https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf",
"layers": [
{ "id": "background", "type": "background", "paint": { "background-color": "#f2f4f7" } },
{
"id": "landcover-wood",
"type": "fill",
"source": "openmaptiles",
"source-layer": "landcover",
"filter": ["in", "class", "wood", "grass"],
"paint": { "fill-color": "#e4eadc", "fill-opacity": 0.8 }
},
{
"id": "park",
"type": "fill",
"source": "openmaptiles",
"source-layer": "park",
"paint": { "fill-color": "#e6eedd" }
},
{
"id": "water",
"type": "fill",
"source": "openmaptiles",
"source-layer": "water",
"filter": ["==", "$type", "Polygon"],
"paint": { "fill-color": "#cddceb" }
},
{
"id": "waterway",
"type": "line",
"source": "openmaptiles",
"source-layer": "waterway",
"paint": { "line-color": "#cddceb", "line-width": { "stops": [[8, 0.5], [16, 3]] } }
},
{
"id": "building",
"type": "fill",
"source": "openmaptiles",
"source-layer": "building",
"minzoom": 13,
"paint": { "fill-color": "#e6e8ec", "fill-outline-color": "#d5d8de" }
},
{
"id": "road-minor",
"type": "line",
"source": "openmaptiles",
"source-layer": "transportation",
"minzoom": 12,
"filter": ["in", "class", "minor", "service"],
"paint": { "line-color": "#ffffff", "line-width": { "stops": [[12, 0.6], [18, 7]] } }
},
{
"id": "road-secondary",
"type": "line",
"source": "openmaptiles",
"source-layer": "transportation",
"filter": ["in", "class", "primary", "secondary", "tertiary"],
"paint": { "line-color": "#ffffff", "line-width": { "stops": [[7, 0.8], [18, 12]] } }
},
{
"id": "road-motorway",
"type": "line",
"source": "openmaptiles",
"source-layer": "transportation",
"filter": ["in", "class", "motorway", "trunk"],
"paint": { "line-color": "#e6cfc0", "line-width": { "stops": [[5, 1], [18, 16]] } }
},
{
"id": "boundary",
"type": "line",
"source": "openmaptiles",
"source-layer": "boundary",
"filter": ["in", "admin_level", 2, 4],
"paint": { "line-color": "#b7bec8", "line-dasharray": [4, 2], "line-width": 1 }
},
{
"id": "road-name",
"type": "symbol",
"source": "openmaptiles",
"source-layer": "transportation_name",
"minzoom": 13,
"layout": {
"text-field": ["coalesce", ["get", "name"], ["get", "name:latin"]],
"text-font": ["Noto Sans Regular"],
"text-size": 11,
"symbol-placement": "line"
},
"paint": { "text-color": "#6b7380", "text-halo-color": "#ffffff", "text-halo-width": 1.2 }
},
{
"id": "place-city",
"type": "symbol",
"source": "openmaptiles",
"source-layer": "place",
"filter": ["in", "class", "city", "town"],
"layout": {
"text-field": ["coalesce", ["get", "name"], ["get", "name:latin"]],
"text-font": ["Noto Sans Bold"],
"text-size": { "stops": [[4, 11], [10, 16]] }
},
"paint": { "text-color": "#4a5160", "text-halo-color": "#ffffff", "text-halo-width": 1.6 }
}
]
}
@@ -0,0 +1,65 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using TileServer.Application;
using TileServer.Application.Configuration;
namespace TileServer.Infrastructure.Storage;
public sealed class DataPaths : IDataPaths
{
public DataPaths(IOptions<TileServerOptions> options, IHostEnvironment environment)
{
var configured = options.Value.DataDirectory;
Root = Path.GetFullPath(Path.IsPathRooted(configured)
? configured
: Path.Combine(environment.ContentRootPath, configured));
Extracts = Path.Combine(Root, "extracts");
Tiles = Path.Combine(Root, "tiles");
Styles = Path.Combine(Root, "styles");
Tools = Path.Combine(Root, "tools");
State = Path.Combine(Root, "state");
PlanetilerSources = Path.Combine(Root, "planetiler-sources");
Tmp = Path.Combine(Root, "tmp");
OverlayExtractsFile = Path.Combine(Root, "extracts.json");
AppDatabase = Path.Combine(Root, "app.db");
EnsureCreated();
}
public string Root { get; }
public string Extracts { get; }
public string Tiles { get; }
public string Styles { get; }
public string Tools { get; }
public string State { get; }
public string PlanetilerSources { get; }
public string Tmp { get; }
public string OverlayExtractsFile { get; }
public string AppDatabase { get; }
public string OsmPbf(string extractId) => Path.Combine(Extracts, $"{extractId}.osm.pbf");
public string Mbtiles(string extractId) => Path.Combine(Tiles, $"{extractId}.mbtiles");
// Planetiler infers archive format from the last suffix; keep ".mbtiles".
public string StagingMbtiles(string extractId) => Path.Combine(Tiles, $"{extractId}.building.mbtiles");
public void EnsureCreated()
{
Directory.CreateDirectory(Extracts);
Directory.CreateDirectory(Tiles);
Directory.CreateDirectory(Styles);
Directory.CreateDirectory(Tools);
Directory.CreateDirectory(State);
Directory.CreateDirectory(PlanetilerSources);
Directory.CreateDirectory(Tmp);
}
}
@@ -0,0 +1,90 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using TileServer.Application;
using TileServer.Application.Styles;
using TileServer.Domain;
using TileServer.Domain.Exceptions;
namespace TileServer.Infrastructure.Styles;
public sealed class FileStyleCatalog : IStyleCatalog
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true,
PropertyNameCaseInsensitive = true
};
private readonly IDataPaths _paths;
public FileStyleCatalog(IDataPaths paths)
{
_paths = paths;
}
public IReadOnlyList<MapStyleInfo> List()
{
if (!Directory.Exists(_paths.Styles))
{
return [];
}
return Directory.GetFiles(_paths.Styles, "*.json", SearchOption.TopDirectoryOnly)
.Select(path => new MapStyleInfo(
Path.GetFileNameWithoutExtension(path),
new DateTimeOffset(File.GetLastWriteTimeUtc(path), TimeSpan.Zero)))
.OrderBy(x => x.Name, StringComparer.Ordinal)
.ToArray();
}
public JsonObject GetRequired(string name)
{
var path = PathFor(name);
if (!File.Exists(path))
{
throw new ResourceNotFoundException("Style", name);
}
var json = File.ReadAllText(path);
var node = JsonNode.Parse(json) as JsonObject
?? throw new DomainValidationException($"Style '{name}' is not a JSON object.");
return node;
}
public async Task SaveAsync(string name, JsonObject style, CancellationToken ct)
{
ResourceName.Require(name, nameof(name));
Directory.CreateDirectory(_paths.Styles);
var path = PathFor(name);
var temp = path + ".tmp";
await File.WriteAllTextAsync(temp, style.ToJsonString(JsonOptions), ct).ConfigureAwait(false);
File.Move(temp, path, overwrite: true);
}
public async Task SeedDefaultsAsync(CancellationToken ct)
{
Directory.CreateDirectory(_paths.Styles);
var seedDir = Path.Combine(AppContext.BaseDirectory, "Seed", "styles");
if (!Directory.Exists(seedDir))
{
return;
}
foreach (var source in Directory.GetFiles(seedDir, "*.json", SearchOption.TopDirectoryOnly))
{
ct.ThrowIfCancellationRequested();
var destination = Path.Combine(_paths.Styles, Path.GetFileName(source));
if (File.Exists(destination))
{
continue;
}
File.Copy(source, destination);
}
await Task.CompletedTask.ConfigureAwait(false);
}
private string PathFor(string name) => Path.Combine(_paths.Styles, $"{name}.json");
}
@@ -0,0 +1,37 @@
using Cronos;
using Microsoft.Extensions.Options;
using TileServer.Application.Configuration;
using TileServer.Application.Sync;
namespace TileServer.Infrastructure.Sync;
public sealed class CronSyncSchedulerClock : ISyncSchedulerClock
{
private readonly CronExpression _cron;
private readonly TimeZoneInfo _timeZone;
public CronSyncSchedulerClock(IOptions<TileServerOptions> options)
{
_cron = CronExpression.Parse(options.Value.Sync.Cron);
_timeZone = ResolveTimeZone(options.Value.Sync.TimeZone);
}
public DateTimeOffset? GetNextOccurrence(DateTimeOffset fromUtc)
=> _cron.GetNextOccurrence(fromUtc, _timeZone);
private static TimeZoneInfo ResolveTimeZone(string id)
{
try
{
return TimeZoneInfo.FindSystemTimeZoneById(id);
}
catch (TimeZoneNotFoundException)
{
return TimeZoneInfo.Utc;
}
catch (InvalidTimeZoneException)
{
return TimeZoneInfo.Utc;
}
}
}
@@ -0,0 +1,86 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using TileServer.Application.Configuration;
using TileServer.Application.Styles;
using TileServer.Application.Sync;
using TileServer.Domain.Exceptions;
namespace TileServer.Infrastructure.Sync;
public sealed class MapSyncHostedService(
IMapSyncService sync,
ISyncSchedulerClock clock,
IStyleCatalog styles,
IOptions<TileServerOptions> options,
ILogger<MapSyncHostedService> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
await styles.SeedDefaultsAsync(stoppingToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogWarning(ex, "Failed to seed default map styles.");
}
sync.SetNextScheduledAt(clock.GetNextOccurrence(DateTimeOffset.UtcNow));
if (options.Value.Sync.RunOnStartup)
{
logger.LogInformation("Running initial OSM extract synchronization.");
await RunSafelyAsync(stoppingToken).ConfigureAwait(false);
}
while (!stoppingToken.IsCancellationRequested)
{
var now = DateTimeOffset.UtcNow;
var next = clock.GetNextOccurrence(now);
sync.SetNextScheduledAt(next);
if (next is null)
{
logger.LogWarning("Sync cron '{Cron}' has no future occurrence.", options.Value.Sync.Cron);
break;
}
var delay = next.Value - now;
if (delay < TimeSpan.Zero)
{
delay = TimeSpan.Zero;
}
logger.LogInformation("Next OSM extract sync at {Next}.", next);
try
{
await Task.Delay(delay, stoppingToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
await RunSafelyAsync(stoppingToken).ConfigureAwait(false);
}
}
private async Task RunSafelyAsync(CancellationToken ct)
{
try
{
await sync.RunAllAsync(ct).ConfigureAwait(false);
}
catch (ResourceConflictException)
{
logger.LogInformation("Sync already in progress, skip scheduled run.");
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
}
catch (Exception ex)
{
logger.LogError(ex, "Scheduled map synchronization failed.");
}
}
}
@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\TileServer.Application\TileServer.Application.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Cronos" Version="0.13.0" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.11" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.11">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Hosting" 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="NetTopologySuite" Version="2.5.0" />
<PackageReference Include="protobuf-net" Version="3.2.30" />
</ItemGroup>
<ItemGroup>
<Content Include="Seed\styles\*.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="TileServer.UnitTests" />
</ItemGroup>
</Project>
@@ -0,0 +1,141 @@
using System.IO.Compression;
using ProtoBuf;
using TileServer.Domain.Tiles;
namespace TileServer.Infrastructure.Tiles.Mvt;
internal static class MvtCodec
{
public const int MoveTo = 1;
public const int LineTo = 2;
public const int ClosePath = 7;
public const int Point = 1;
public const int LineString = 2;
public const int Polygon = 3;
public static MvtTile Decode(TileData tile)
{
var payload = tile.IsGzipped ? Gunzip(tile.Bytes) : tile.Bytes;
using var stream = new MemoryStream(payload, writable: false);
return Serializer.Deserialize<MvtTile>(stream) ?? new MvtTile();
}
public static TileData EncodeGzip(MvtTile tile)
{
using var raw = new MemoryStream();
Serializer.Serialize(raw, tile);
using var gzipped = new MemoryStream();
using (var gzip = new GZipStream(gzipped, CompressionLevel.Fastest, leaveOpen: true))
{
gzip.Write(raw.GetBuffer(), 0, (int)raw.Length);
}
return new TileData(gzipped.ToArray(), true);
}
public static List<List<(int X, int Y)>> DecodeGeometry(IReadOnlyList<uint> commands)
{
var paths = new List<List<(int X, int Y)>>();
var current = new List<(int X, int Y)>();
var x = 0;
var y = 0;
var i = 0;
while (i < commands.Count)
{
var cmdInt = commands[i++];
var cmd = (int)(cmdInt & 0x7);
var count = (int)(cmdInt >> 3);
if (cmd is MoveTo or LineTo)
{
if (cmd == MoveTo && current.Count > 0)
{
paths.Add(current);
current = [];
}
for (var n = 0; n < count && i + 1 < commands.Count; n++)
{
x += ZigZagDecode(commands[i++]);
y += ZigZagDecode(commands[i++]);
current.Add((x, y));
}
}
else if (cmd == ClosePath)
{
if (current.Count > 0)
{
paths.Add(current);
current = [];
}
}
}
if (current.Count > 0)
{
paths.Add(current);
}
return paths;
}
public static List<uint> EncodeGeometry(IReadOnlyList<IReadOnlyList<(int X, int Y)>> paths, bool close)
{
var commands = new List<uint>();
var cx = 0;
var cy = 0;
foreach (var path in paths)
{
if (path.Count == 0)
{
continue;
}
var (x0, y0) = path[0];
commands.Add(Command(MoveTo, 1));
commands.Add(ZigZagEncode(x0 - cx));
commands.Add(ZigZagEncode(y0 - cy));
cx = x0;
cy = y0;
if (path.Count > 1)
{
commands.Add(Command(LineTo, (uint)(path.Count - 1)));
for (var i = 1; i < path.Count; i++)
{
var (x, y) = path[i];
commands.Add(ZigZagEncode(x - cx));
commands.Add(ZigZagEncode(y - cy));
cx = x;
cy = y;
}
}
if (close)
{
commands.Add(Command(ClosePath, 1));
}
}
return commands;
}
public static uint Command(int id, uint count) => (uint)((count << 3) | (uint)id);
public static int ZigZagDecode(uint value)
{
var n = (int)value;
return (n >> 1) ^ -(n & 1);
}
public static uint ZigZagEncode(int value)
=> (uint)((value << 1) ^ (value >> 31));
private static byte[] Gunzip(byte[] bytes)
{
using var input = new MemoryStream(bytes, writable: false);
using var gzip = new GZipStream(input, CompressionMode.Decompress);
using var output = new MemoryStream();
gzip.CopyTo(output);
return output.ToArray();
}
}
@@ -0,0 +1,73 @@
using ProtoBuf;
namespace TileServer.Infrastructure.Tiles.Mvt;
[ProtoContract]
internal sealed class MvtTile
{
[ProtoMember(3)]
public List<MvtLayer> Layers { get; set; } = [];
}
[ProtoContract]
internal sealed class MvtLayer
{
[ProtoMember(15)]
public uint Version { get; set; } = 2;
[ProtoMember(1)]
public string Name { get; set; } = string.Empty;
[ProtoMember(2)]
public List<MvtFeature> Features { get; set; } = [];
[ProtoMember(3)]
public List<string> Keys { get; set; } = [];
[ProtoMember(4)]
public List<MvtValue> Values { get; set; } = [];
[ProtoMember(5)]
public uint Extent { get; set; } = 4096;
}
[ProtoContract]
internal sealed class MvtFeature
{
[ProtoMember(1)]
public ulong Id { get; set; }
[ProtoMember(2, IsPacked = true)]
public List<uint> Tags { get; set; } = [];
[ProtoMember(3)]
public int Type { get; set; }
[ProtoMember(4, IsPacked = true)]
public List<uint> Geometry { get; set; } = [];
}
[ProtoContract]
internal sealed class MvtValue
{
[ProtoMember(1)]
public string? StringValue { get; set; }
[ProtoMember(2)]
public float? FloatValue { get; set; }
[ProtoMember(3)]
public double? DoubleValue { get; set; }
[ProtoMember(4)]
public long? IntValue { get; set; }
[ProtoMember(5)]
public ulong? UIntValue { get; set; }
[ProtoMember(6)]
public long? SintValue { get; set; }
[ProtoMember(7)]
public bool? BoolValue { get; set; }
}
@@ -0,0 +1,67 @@
using System.Diagnostics;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using TileServer.Application;
using TileServer.Application.Configuration;
using TileServer.Application.Tiles;
namespace TileServer.Infrastructure.Tiles;
public sealed class PlanetilerJarBootstrapper(
IHttpClientFactory httpClientFactory,
IDataPaths dataPaths,
IOptions<TileServerOptions> options,
ILogger<PlanetilerJarBootstrapper> logger) : IPlanetilerBootstrapper
{
public bool IsJavaAvailable()
{
try
{
var psi = new ProcessStartInfo
{
FileName = options.Value.JavaPath,
ArgumentList = { "-version" },
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
using var process = Process.Start(psi);
if (process is null)
{
return false;
}
process.WaitForExit(TimeSpan.FromSeconds(10));
return process.HasExited && process.ExitCode == 0;
}
catch (Exception ex)
{
logger.LogWarning(ex, "Java is not available at '{JavaPath}'.", options.Value.JavaPath);
return false;
}
}
public async Task<string> EnsureJarAsync(CancellationToken ct)
{
var jarPath = Path.Combine(dataPaths.Tools, options.Value.PlanetilerJarFileName);
if (File.Exists(jarPath) && new FileInfo(jarPath).Length > 1_000_000)
{
return jarPath;
}
logger.LogInformation("Downloading Planetiler JAR from {Url}", options.Value.PlanetilerJarUrl);
Directory.CreateDirectory(dataPaths.Tools);
var client = httpClientFactory.CreateClient("Tools");
var temp = jarPath + ".partial";
await using (var input = await client.GetStreamAsync(options.Value.PlanetilerJarUrl, ct).ConfigureAwait(false))
await using (var output = File.Create(temp))
{
await input.CopyToAsync(output, ct).ConfigureAwait(false);
}
File.Move(temp, jarPath, overwrite: true);
logger.LogInformation("Planetiler JAR saved to {Path}", jarPath);
return jarPath;
}
}
@@ -0,0 +1,134 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using TileServer.Application;
using TileServer.Application.Configuration;
using TileServer.Application.Tiles;
using TileServer.Infrastructure.Downloads;
namespace TileServer.Infrastructure.Tiles;
public sealed class PlanetilerSourceBootstrapper(
IHttpClientFactory httpClientFactory,
IDataPaths dataPaths,
IOptions<TileServerOptions> options,
ILogger<PlanetilerSourceBootstrapper> logger) : IPlanetilerSourceBootstrapper
{
public async Task EnsureAsync(CancellationToken ct)
{
Directory.CreateDirectory(dataPaths.PlanetilerSources);
var cfg = options.Value;
await EnsureFileAsync("natural_earth_vector.sqlite.zip", cfg.NaturalEarthUrls, 10_000_000, ct)
.ConfigureAwait(false);
await EnsureFileAsync("lake_centerline.shp.zip", cfg.LakeCenterlinesUrls, 50_000, ct)
.ConfigureAwait(false);
await EnsureFileAsync("water-polygons-split-3857.zip", cfg.WaterPolygonsUrls, 50_000_000, ct)
.ConfigureAwait(false);
}
private async Task EnsureFileAsync(string fileName, IReadOnlyList<string> urls, long minBytes, CancellationToken ct)
{
var path = Path.Combine(dataPaths.PlanetilerSources, fileName);
if (File.Exists(path) && new FileInfo(path).Length >= minBytes)
{
logger.LogInformation("Planetiler source {File} already present ({Bytes} bytes).", fileName, new FileInfo(path).Length);
return;
}
if (File.Exists(path))
{
logger.LogWarning("Removing incomplete Planetiler source {File} ({Bytes} bytes).", fileName, new FileInfo(path).Length);
File.Delete(path);
}
var candidates = urls.Where(u => !string.IsNullOrWhiteSpace(u)).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
if (candidates.Length == 0)
{
throw new InvalidOperationException($"No download URLs configured for '{fileName}'.");
}
Exception? last = null;
foreach (var url in candidates)
{
try
{
await DownloadAsync(url, path, fileName, ct).ConfigureAwait(false);
var size = new FileInfo(path).Length;
if (size < minBytes)
{
throw new IOException($"Downloaded {fileName} is too small ({size} bytes).");
}
return;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
last = ex;
logger.LogWarning(ex, "Could not download {File} from {Url}, trying next mirror.", fileName, url);
TryDelete(path);
TryDelete(path + ".partial");
}
}
throw new InvalidOperationException(
$"Failed to download Planetiler source '{fileName}'. Tried: {string.Join(", ", candidates)}",
last);
}
private async Task DownloadAsync(string url, string destinationPath, string label, CancellationToken ct)
{
logger.LogInformation("Downloading Planetiler source {File} from {Url}", label, url);
var client = httpClientFactory.CreateClient("Extracts");
using var response = await client
.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct)
.ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var total = response.Content.Headers.ContentLength;
logger.LogInformation(
"{File}: headers OK (HTTP {Status}, {TotalMb} MB). Waiting for body...",
label,
(int)response.StatusCode,
total is null ? "?" : (total.Value / 1_000_000d).ToString("F1"));
var stall = TimeSpan.FromSeconds(Math.Max(15, options.Value.DownloadStallTimeoutSeconds));
var partialPath = destinationPath + ".partial";
await using (var input = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false))
await using (var output = new FileStream(partialPath, FileMode.Create, FileAccess.Write, FileShare.None, 1024 * 1024, FileOptions.Asynchronous))
{
await StreamCopy.CopyWithStallTimeoutAsync(
input,
output,
stall,
TimeSpan.FromSeconds(5),
(copied, expected) => logger.LogInformation(
"Downloading {File}: {CopiedMb:F1} / {TotalMb} MB",
label,
copied / 1_000_000d,
expected is null ? "?" : (expected.Value / 1_000_000d).ToString("F1")),
total,
ct)
.ConfigureAwait(false);
}
File.Move(partialPath, destinationPath, overwrite: true);
logger.LogInformation("Saved Planetiler source {File} ({Bytes} bytes).", label, new FileInfo(destinationPath).Length);
}
private static void TryDelete(string path)
{
try
{
if (File.Exists(path))
{
File.Delete(path);
}
}
catch (IOException)
{
}
}
}

Some files were not shown because too many files have changed in this diff Show More