House rules: primary constructors, a cancellation token on every async call, and the rules fail the build
Build / Build (push) Successful in 30s
Build / Build (push) Successful in 30s
- 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
This commit is contained in:
1 parent
f0a14c737f
commit
0f73f69239
176 files changed
+2789
-3974
No files matched your search
@@ -42,7 +42,15 @@ namespace PrivaPub.Infrastructure.Push
|
||||
// safe handler, with the pasture's exceptions where Federation says so).
|
||||
// A 404 or 410 means the subscription is gone: it is deleted. 408, 429, a 5xx, a timeout or a broken connection retry on
|
||||
// the jobs' backoff; any other answer drops the push (logged by the push service's host alone).
|
||||
public class WebPushJob : IJobHandler
|
||||
public class WebPushJob(
|
||||
IHttpClientFactory http,
|
||||
IVapid vapid,
|
||||
IServiceScopeFactory scopes,
|
||||
IInstanceSettings settings,
|
||||
ILocalActorService localActors,
|
||||
IOptionsMonitor<FederationOptions> federation,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
ILogger<WebPushJob> logger) : IJobHandler
|
||||
{
|
||||
public const string ClientName = "push";
|
||||
public static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(15);
|
||||
@@ -52,27 +60,6 @@ namespace PrivaPub.Infrastructure.Push
|
||||
const string Urgency = "normal";
|
||||
const int BodyLength = 140;
|
||||
|
||||
readonly IHttpClientFactory _http;
|
||||
readonly IVapid _vapid;
|
||||
readonly IServiceScopeFactory _scopes;
|
||||
readonly IInstanceSettings _settings;
|
||||
readonly ILocalActorService _localActors;
|
||||
readonly IOptionsMonitor<FederationOptions> _federation;
|
||||
readonly IStringLocalizer<GenericRes> _localizer;
|
||||
readonly ILogger<WebPushJob> _logger;
|
||||
|
||||
public WebPushJob(IHttpClientFactory http, IVapid vapid, IServiceScopeFactory scopes, IInstanceSettings settings, ILocalActorService localActors,
|
||||
IOptionsMonitor<FederationOptions> federation, IStringLocalizer<GenericRes> localizer, ILogger<WebPushJob> logger)
|
||||
{
|
||||
_http = http;
|
||||
_vapid = vapid;
|
||||
_scopes = scopes;
|
||||
_settings = settings;
|
||||
_localActors = localActors;
|
||||
_federation = federation;
|
||||
_localizer = localizer;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public JobKind Kind => JobKind.SendPush;
|
||||
public int Concurrency => 4;
|
||||
@@ -96,22 +83,22 @@ namespace PrivaPub.Infrastructure.Push
|
||||
var notification = await DB.Default.Find<Notification>().Match(n => n.ID == notificationId && n.AvatarId == avatarId).ExecuteFirstAsync(token);
|
||||
if (notification == default || !await WebPush.Pushable(subscription, notification, token))
|
||||
return JobOutcome.Done;
|
||||
if (!Uri.TryCreate(subscription.Endpoint, UriKind.Absolute, out var endpoint) || !IsAllowed(endpoint, _federation.CurrentValue))
|
||||
if (!Uri.TryCreate(subscription.Endpoint, UriKind.Absolute, out var endpoint) || !IsAllowed(endpoint, federation.CurrentValue))
|
||||
return JobOutcome.Dead("endpoint");
|
||||
|
||||
byte[] json;
|
||||
using (var scope = _scopes.CreateScope())
|
||||
var json = default(byte[]);
|
||||
using (var scope = scopes.CreateScope())
|
||||
{
|
||||
// the token the subscription was made with must still be valid, and the persona's: it goes into the payload
|
||||
if (!await TokenHolds(scope.ServiceProvider.GetRequiredService<IOpenIddictTokenManager>(), subscription, token))
|
||||
{
|
||||
await WebPush.ForgetToken(subscription.TokenId);
|
||||
await WebPush.ForgetToken(subscription.TokenId, token);
|
||||
return JobOutcome.Done;
|
||||
}
|
||||
var avatar = await DB.Default.Find<Avatar>().Match(a => a.ID == avatarId && a.DeletionAt == null).ExecuteFirstAsync(token);
|
||||
if (avatar == default)
|
||||
{
|
||||
await WebPush.Forget(new[] { avatarId });
|
||||
await WebPush.Forget(new[] { avatarId }, token);
|
||||
return JobOutcome.Done;
|
||||
}
|
||||
var mapped = (await scope.ServiceProvider.GetRequiredService<MastodonMapper>().Notifications(new List<Notification> { notification }, avatarId, token))
|
||||
@@ -130,7 +117,7 @@ namespace PrivaPub.Infrastructure.Push
|
||||
});
|
||||
}
|
||||
|
||||
var key = await _vapid.Key(token);
|
||||
var key = await vapid.Key(token);
|
||||
var p256dh = WebPushCrypto.FromBase64Url(subscription.P256dh);
|
||||
var auth = WebPushCrypto.FromBase64Url(subscription.Auth);
|
||||
if (!WebPushCrypto.AreUsable(p256dh, auth))
|
||||
@@ -154,24 +141,24 @@ namespace PrivaPub.Infrastructure.Push
|
||||
|
||||
try
|
||||
{
|
||||
using var response = await _http.CreateClient(ClientName).SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token);
|
||||
using var response = await http.CreateClient(ClientName).SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token);
|
||||
var status = (int)response.StatusCode;
|
||||
if (status is >= 200 and < 300)
|
||||
return JobOutcome.Done;
|
||||
if (response.StatusCode is HttpStatusCode.NotFound or HttpStatusCode.Gone)
|
||||
{
|
||||
await DB.Default.DeleteAsync<PushSubscription>(subscription.ID);
|
||||
_logger.LogInformation("{Kind}: {Host} answered {Status}, the subscription is gone", Kind, endpoint.Host, status);
|
||||
logger.LogInformation("{Kind}: {Host} answered {Status}, the subscription is gone", Kind, endpoint.Host, status);
|
||||
return JobOutcome.Done;
|
||||
}
|
||||
if (response.StatusCode is HttpStatusCode.RequestTimeout or HttpStatusCode.TooManyRequests || status >= 500)
|
||||
return JobOutcome.Retry($"status {status}");
|
||||
_logger.LogWarning("{Kind}: {Host} refused a push with {Status}; it is dropped", Kind, endpoint.Host, status);
|
||||
logger.LogWarning("{Kind}: {Host} refused a push with {Status}; it is dropped", Kind, endpoint.Host, status);
|
||||
return JobOutcome.Dead($"status {status}");
|
||||
}
|
||||
catch (BlockedDestinationException)
|
||||
{
|
||||
_logger.LogWarning("{Kind}: {Host} does not resolve to a public address; the push is dropped", Kind, endpoint.Host);
|
||||
logger.LogWarning("{Kind}: {Host} does not resolve to a public address; the push is dropped", Kind, endpoint.Host);
|
||||
return JobOutcome.Dead("blocked destination");
|
||||
}
|
||||
catch (TaskCanceledException) when (!token.IsCancellationRequested)
|
||||
@@ -180,7 +167,7 @@ namespace PrivaPub.Infrastructure.Push
|
||||
}
|
||||
catch (HttpRequestException ex) when (ex.InnerException is BlockedDestinationException)
|
||||
{
|
||||
_logger.LogWarning("{Kind}: {Host} does not resolve to a public address; the push is dropped", Kind, endpoint.Host);
|
||||
logger.LogWarning("{Kind}: {Host} does not resolve to a public address; the push is dropped", Kind, endpoint.Host);
|
||||
return JobOutcome.Dead("blocked destination");
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or IOException or SocketException)
|
||||
@@ -212,10 +199,10 @@ namespace PrivaPub.Infrastructure.Push
|
||||
// so it names a mailbox at its host: RFC 8292 takes only mailto: and https:.)
|
||||
string Subject()
|
||||
{
|
||||
var email = _settings.Current.ContactEmail?.Trim();
|
||||
var email = settings.Current.ContactEmail?.Trim();
|
||||
if (!string.IsNullOrEmpty(email) && !email.Any(char.IsWhiteSpace) && email.Contains('@'))
|
||||
return "mailto:" + email;
|
||||
var address = _localActors.BaseAddress;
|
||||
var address = localActors.BaseAddress;
|
||||
return Uri.TryCreate(address, UriKind.Absolute, out var base_) && base_.Scheme != Uri.UriSchemeHttps
|
||||
? "mailto:privapub@" + base_.Host
|
||||
: address;
|
||||
@@ -234,17 +221,17 @@ namespace PrivaPub.Infrastructure.Push
|
||||
var name = string.IsNullOrWhiteSpace(mapped.Account?.DisplayName) ? mapped.Account?.Username ?? string.Empty : mapped.Account.DisplayName;
|
||||
return notification.Type switch
|
||||
{
|
||||
NotificationType.Mention => string.Format(_localizer["You were mentioned by {0}"], name),
|
||||
NotificationType.Status => string.Format(_localizer["{0} just posted"], name),
|
||||
NotificationType.Reblog => string.Format(_localizer["{0} boosted your post"], name),
|
||||
NotificationType.Follow => string.Format(_localizer["{0} is now following you"], name),
|
||||
NotificationType.FollowRequest => string.Format(_localizer["Pending follower: {0}"], name),
|
||||
NotificationType.Favourite => string.Format(_localizer["{0} favorited your post"], name),
|
||||
NotificationType.Poll => string.Format(_localizer["A poll by {0} has ended"], name),
|
||||
NotificationType.Update => string.Format(_localizer["{0} edited a post"], name),
|
||||
NotificationType.Quote => string.Format(_localizer["{0} quoted your post"], name),
|
||||
NotificationType.Reaction => string.Format(_localizer["{0} reacted to your post with {1}"], name, notification.Emoji),
|
||||
NotificationType.ModerationWarning => _localizer["You have received a moderation warning"],
|
||||
NotificationType.Mention => string.Format(localizer["You were mentioned by {0}"], name),
|
||||
NotificationType.Status => string.Format(localizer["{0} just posted"], name),
|
||||
NotificationType.Reblog => string.Format(localizer["{0} boosted your post"], name),
|
||||
NotificationType.Follow => string.Format(localizer["{0} is now following you"], name),
|
||||
NotificationType.FollowRequest => string.Format(localizer["Pending follower: {0}"], name),
|
||||
NotificationType.Favourite => string.Format(localizer["{0} favorited your post"], name),
|
||||
NotificationType.Poll => string.Format(localizer["A poll by {0} has ended"], name),
|
||||
NotificationType.Update => string.Format(localizer["{0} edited a post"], name),
|
||||
NotificationType.Quote => string.Format(localizer["{0} quoted your post"], name),
|
||||
NotificationType.Reaction => string.Format(localizer["{0} reacted to your post with {1}"], name, notification.Emoji),
|
||||
NotificationType.ModerationWarning => localizer["You have received a moderation warning"],
|
||||
_ => name
|
||||
};
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user