Files
SocialPub/PrivaPub/Domain/Statistics/SelfLocation.cs
T
thepraandClaude Opus 5.5 0f73f69239
Build / Build (push) Successful in 30s
House rules: primary constructors, a cancellation token on every async call, and the rules fail the build
- Services, controllers and jobs take their dependencies through primary
  constructors and use them directly; where a method already named a local
  after a dependency, the dependency takes its type's name.
- Every async method takes a CancellationToken last and passes it down to
  MongoDB, HTTP and the job queue. The setup claim is still given back when
  a request is cancelled.
- The federation and media options are read through IOptionsMonitor.
- The Mastodon entities keep sending "" for empty strings, and every model
  field where null means something says so.
- The inbox's 503 with Retry-After, which other servers retry, is the one
  server error left, and says why.
- Arasaka.HouseRules.Analyzers checks all of this in every build, here and in
  PrivaPub.ClientModels as decePubClient builds it.

Checked against GoToSocial in the pasture: 64 passed, 0 failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W4YtEJrgxG12Pc39Fai8Bd
2026-11-10 01:24:43 +01:00

100 lines
3.0 KiB
C#

using Microsoft.Extensions.Options;
using PrivaPub.Infrastructure.Geo;
using PrivaPub.Infrastructure.Statistics;
using PrivaPub.Models;
using PrivaPub.Models.Jobs;
using System.Net;
using System.Net.Sockets;
namespace PrivaPub.Domain.Statistics
{
public interface ISelfLocation
{
//where this server is, or default when it cannot tell; Source is "configured" when the owner set it (Statistics:Geo:Self)
Task<InstanceGeo> Get(CancellationToken token);
}
// This server's own place, for the instance API (the client's globe draws every server from it). The owner may set it,
// for a server behind a proxy or a CDN; otherwise the server's own host name is resolved and located like any other
// server's, once a day. Never the address of a request.
public class SelfLocation(
IGeoLocator geo,
IOptionsMonitor<StatisticsOptions> options,
IOptionsMonitor<AppConfiguration> app,
ILogger<SelfLocation> logger,
ICdnRanges cdnRanges = default) : ISelfLocation
{
static readonly TimeSpan Lifetime = TimeSpan.FromDays(1);
readonly SemaphoreSlim _gate = new(1, 1);
InstanceGeo _located;
DateTime _locatedAt = DateTime.MinValue;
public async Task<InstanceGeo> Get(CancellationToken token)
{
if (options.CurrentValue.Geo.Self is { Latitude: { } latitude, Longitude: { } longitude } self)
return new InstanceGeo
{
Country = self.Country,
City = self.City,
Latitude = Math.Round(latitude, 1),
Longitude = Math.Round(longitude, 1),
Source = "configured"
};
if (DateTime.UtcNow - _locatedAt < Lifetime)
return _located;
await _gate.WaitAsync(token);
try
{
if (DateTime.UtcNow - _locatedAt >= Lifetime)
{
_located = await Locate(token);
_locatedAt = DateTime.UtcNow;
}
return _located;
}
finally
{
_gate.Release();
}
}
async Task<InstanceGeo> Locate(CancellationToken token)
{
try
{
if (!Uri.TryCreate(app.CurrentValue.BackendBaseAddress, UriKind.Absolute, out var self))
return default;
var addresses = await Dns.GetHostAddressesAsync(self.Host, token);
var address = addresses.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork) ?? addresses.FirstOrDefault();
var fix = address == default ? default : geo.Locate(address);
var (cdn, cdnSource) = Federation.Objects.InstanceDescriber.Cdn(address, self.Host, fix?.Asn, cdnRanges, default);
return fix == default ? default : new InstanceGeo
{
Country = fix.Country,
City = fix.City,
Latitude = fix.Latitude,
Longitude = fix.Longitude,
Asn = fix.Asn,
AsnOrg = fix.AsnOrg,
Cdn = cdn?.Name,
CdnDomain = cdn?.Domain,
CdnSource = cdnSource,
Ipv6 = address.AddressFamily == AddressFamily.InterNetworkV6,
Source = geo.Source,
LocatedAt = DateTime.UtcNow
};
}
catch (Exception ex) when (ex is SocketException or ArgumentException)
{
logger.LogInformation("{Service}: this server's host does not resolve", nameof(SelfLocation));
return default;
}
}
}
}