Files
SocialPub/PrivaPub/Domain/Statuses/ScheduledStatuses.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

126 lines
5.9 KiB
C#

using MongoDB.Entities;
using PrivaPub.Federation.Actors;
using PrivaPub.Infrastructure.Jobs;
using PrivaPub.Models.Federation;
using PrivaPub.Models.Jobs;
using PrivaPub.Models.Media;
using PrivaPub.Models.Post;
using PrivaPub.Models.Social;
using PrivaPub.Models.User;
using PrivaPub.Domain.Media;
namespace PrivaPub.Domain.Statuses
{
// Scheduled posts (Mastodon's scheduled_statuses): kept as asked, their media kept from the janitor, and published at
// their time by a PublishScheduled job as if the persona posted then. Mastodon's limits hold: at least five minutes
// ahead, 300 waiting, 25 on one day.
public static class ScheduledStatuses
{
public static readonly TimeSpan Lead = TimeSpan.FromMinutes(5);
public const int MaxWaiting = 300;
public const int MaxPerDay = 25;
public static StatusDraft Draft(ScheduledParams p, string scheduledId = default) => new()
{
ScheduledStatusId = scheduledId,
Text = p.Text,
PlainText = true,
SpoilerText = p.SpoilerText,
Sensitive = p.Sensitive,
Visibility = Visibility(p.Visibility),
InReplyTo = p.InReplyToId,
Language = p.Language,
MediaIds = p.MediaIds,
QuotedStatusId = p.QuotedStatusId,
QuotePolicy = p.QuotePolicy,
Poll = p.Poll == default ? default : new PollDraft(p.Poll.Options, p.Poll.ExpiresIn, p.Poll.Multiple, p.Poll.HideTotals)
};
public static PostVisibility Visibility(string value) => value?.ToLowerInvariant() switch
{
"unlisted" => PostVisibility.Unlisted,
"private" => PostVisibility.FollowersOnly,
"direct" => PostVisibility.Direct,
_ => PostVisibility.Public
};
// why the persona cannot schedule at this time, or default
public static async Task<string> Refusal(string avatarId, DateTime at, string except, CancellationToken token)
{
if (at < DateTime.UtcNow + Lead)
return "Scheduled at The scheduled date must be at least 5 minutes in the future";
if (await DB.Default.CountAsync<ScheduledStatus>(s => s.AvatarId == avatarId && s.ID != except, token) >= MaxWaiting)
return $"Scheduled at You have exceeded the limit of {MaxWaiting} scheduled statuses";
var day = at.Date;
var next = day.AddDays(1);
if (await DB.Default.CountAsync<ScheduledStatus>(s => s.AvatarId == avatarId && s.ID != except && s.ScheduledAt >= day && s.ScheduledAt < next, token) >= MaxPerDay)
return $"Scheduled at You have exceeded the limit of {MaxPerDay} scheduled statuses on that day";
return default;
}
// a job per scheduled time: a rescheduled post has a job for its new time, and the old one finds it not due
public static Job JobFor(ScheduledStatus scheduled, string host) => new()
{
Kind = JobKind.PublishScheduled,
Payload = scheduled.ID,
Host = host,
DedupeKey = $"scheduled|{scheduled.ID}|{scheduled.ScheduledAt.Ticks}",
RunAt = scheduled.ScheduledAt
};
// whether a persona may still publish: neither deleted nor its root deleted or banned
public static async Task<bool> MayPublish(string avatarId, CancellationToken token)
{
if (!await DB.Default.Find<Avatar>().Match(a => a.ID == avatarId && !a.DeletionAt.HasValue).ExecuteAnyAsync(token))
return false;
var rootIds = (await DB.Default.Find<RootToAvatar>().Match(r => r.AvatarId == avatarId).ExecuteAsync(token)).Select(r => r.RootId).ToList();
return await DB.Default.Find<RootUser>().Match(u => rootIds.Contains(u.ID) && u.DeletedAt == null && !u.IsBanned).ExecuteAnyAsync(token);
}
// the post's media go back to being plain uploads (the janitor's after a day), or are attached to the post by now
public static Task Release(string scheduledId, CancellationToken token) =>
DB.Default.Update<MediaAttachment>().Match(m => m.ScheduledStatusId == scheduledId).Modify(m => m.ScheduledStatusId, null).ExecuteAsync(token);
}
public class PublishScheduledJob(
IServiceScopeFactory scopes,
ILogger<PublishScheduledJob> logger) : IJobHandler
{
public JobKind Kind => JobKind.PublishScheduled;
public int Concurrency => 2;
public int MaxAttempts => 3;
public int PerHostLimit => 2;
public async Task<JobOutcome> Handle(Job job, CancellationToken token)
{
var scheduled = await DB.Default.Find<ScheduledStatus>().MatchID(job.Payload).ExecuteFirstAsync(token);
if (scheduled == default || scheduled.ScheduledAt > DateTime.UtcNow.AddSeconds(30))
return JobOutcome.Done;//dropped, or moved to a later time that has its own job
using var scope = scopes.CreateScope();
// a persona suspended since, or whose login was banned, waits: lifting it publishes what came due meanwhile
// (R6), unless that was a month ago
if (Moderation.Restrictions.IsSuspended(scheduled.AvatarId) && scheduled.ScheduledAt > DateTime.UtcNow.AddDays(-30)
&& await DB.Default.Find<Avatar>().Match(a => a.ID == scheduled.AvatarId && !a.DeletionAt.HasValue).ExecuteAnyAsync(token))
return JobOutcome.Defer(DateTime.UtcNow.AddHours(1), "its author is suspended");
// a persona deleted or banned since it was scheduled publishes nothing, and what it held is trashed
if (!await ScheduledStatuses.MayPublish(scheduled.AvatarId, token))
{
await scope.ServiceProvider.GetRequiredService<IMediaService>().Trash(m => m.ScheduledStatusId == scheduled.ID, "its author is gone", token);
await DB.Default.DeleteAsync<ScheduledStatus>(scheduled.ID);
return JobOutcome.Done;
}
var author = await scope.ServiceProvider.GetRequiredService<ILocalActorService>().FindById(LocalActorKind.Person, scheduled.AvatarId, token);
if (author != default)
{
var outcome = await scope.ServiceProvider.GetRequiredService<IStatusService>().Publish(author, ScheduledStatuses.Draft(scheduled.Params, scheduled.ID), token);
if (!outcome.Ok)
logger.LogWarning("Scheduled status {Id} of {Avatar} could not be published: {Error}", scheduled.ID, scheduled.AvatarId, outcome.Error);
}
await ScheduledStatuses.Release(scheduled.ID, token);
await DB.Default.DeleteAsync<ScheduledStatus>(scheduled.ID);
return JobOutcome.Done;
}
}
}