[backend/services] Allow generating snowflake identifiers with timestamps other than DateTime.UtcNow

This commit is contained in:
Laura Hausmann 2024-02-15 21:05:36 +01:00
parent 3da162e302
commit 4985194d64
No known key found for this signature in database
GPG key ID: D044E84C5BE01605
2 changed files with 16 additions and 9 deletions

View file

@ -6,9 +6,14 @@ namespace Iceshrimp.Backend.Core.Helpers;
public static class IdHelpers {
private const long Time2000 = 946684800000;
public static string GenerateSlowflakeId() {
public static string GenerateSlowflakeId(DateTime? createdAt = null) {
if (createdAt?.Kind is not null and not DateTimeKind.Utc)
createdAt = createdAt.Value.ToUniversalTime();
createdAt ??= DateTime.UtcNow;
var cuid = new Cuid2(8);
var now = (long)DateTime.UtcNow.Subtract(DateTime.UnixEpoch).TotalMilliseconds;
var now = (long)createdAt.Value.Subtract(DateTime.UnixEpoch).TotalMilliseconds;
var time = Math.Max(now - Time2000, 0);
var timestamp = time.ToBase36().PadLeft(8, '0');
return timestamp + cuid;

View file

@ -170,14 +170,16 @@ public class NoteService(
var (mentionedUserIds, mentionedLocalUserIds, mentions, remoteMentions, splitDomainMapping) =
await ResolveNoteMentionsAsync(note);
var createdAt = note.PublishedAt?.ToUniversalTime() ??
throw GracefulException.UnprocessableEntity("Missing or invalid PublishedAt field");
var dbNote = new Note {
Id = IdHelpers.GenerateSlowflakeId(),
Id = IdHelpers.GenerateSlowflakeId(createdAt),
Uri = note.Id,
Url = note.Url?.Id, //FIXME: this doesn't seem to work yet
Text = note.MkContent ?? await mfmConverter.FromHtmlAsync(note.Content, mentions),
UserId = user.Id,
CreatedAt = note.PublishedAt?.ToUniversalTime() ??
throw GracefulException.UnprocessableEntity("Missing or invalid PublishedAt field"),
CreatedAt = createdAt,
UserHost = user.Host,
Visibility = note.GetVisibility(actor),
Reply = note.InReplyTo?.Id != null ? await ResolveNoteAsync(note.InReplyTo.Id) : null