Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

perf(api): claim message nonces up front and overlap send steps (#3737)

Hampusc9dec4c51166
diff --git a/fluxer_api/src/api/channel/repositories/MessageRepository.ts b/fluxer_api/src/api/channel/repositories/MessageRepository.ts
index 4fba5e976..da07d1b2a 100644
--- a/fluxer_api/src/api/channel/repositories/MessageRepository.ts
+++ b/fluxer_api/src/api/channel/repositories/MessageRepository.ts
@@ -51,15 +51,16 @@ export class MessageRepository {
}
async upsertMessage(data: MessageRow, oldData?: MessageRow | null, opts?: UpsertMessageOptions): Promise<Message> {
- const message = await this.dataRepo.upsertMessage(data, oldData);
- if (!oldData && !opts?.skipParentLastMessageId) {
- await this.channelDataRepo.updateLastMessageId(
+ if (oldData || opts?.skipParentLastMessageId) {
+ return this.dataRepo.upsertMessage(data, oldData);
+ }
+ return this.dataRepo.upsertMessage(data, oldData, () =>
+ this.channelDataRepo.updateLastMessageId(
data.channel_id,
data.message_id,
opts?.isInsert ? {isInsert: true} : undefined,
- );
- }
- return message;
+ ),
+ );
}
async deleteMessage(
diff --git a/fluxer_api/src/api/channel/repositories/message/MessageDataRepository.ts b/fluxer_api/src/api/channel/repositories/message/MessageDataRepository.ts
index f3973b17b..cbe9d4c90 100644
--- a/fluxer_api/src/api/channel/repositories/message/MessageDataRepository.ts
+++ b/fluxer_api/src/api/channel/repositories/message/MessageDataRepository.ts
@@ -25,6 +25,7 @@ import {
Messages,
MessagesByAuthorV2,
} from '@app/api/Tables';
+import {startEarly} from '@app/api/utils/ConcurrencyUtils';
import {generateSnowflake} from '@fluxer/snowflake/src/Snowflake';
import * as BucketUtils from '@fluxer/snowflake/src/SnowflakeBuckets';
@@ -665,7 +666,11 @@ export class MessageDataRepository {
return repairedMessage;
}
- async upsertMessage(data: MessageRow, oldData?: MessageRow | null): Promise<Message> {
+ async upsertMessage(
+ data: MessageRow,
+ oldData?: MessageRow | null,
+ alongsideChannelState?: () => Promise<void>,
+ ): Promise<Message> {
const expectedBucket = BucketUtils.makeBucket(data.message_id);
if (data.bucket !== expectedBucket) {
throw new Error(
@@ -759,7 +764,12 @@ export class MessageDataRepository {
}),
);
await batch.execute(false);
- await this.recordChannelStateForMessage(data.channel_id, data.message_id, data.bucket);
+ const channelStateTask = startEarly(
+ this.recordChannelStateForMessage(data.channel_id, data.message_id, data.bucket),
+ );
+ const alongsideTask = startEarly(alongsideChannelState ? alongsideChannelState() : Promise.resolve());
+ await channelStateTask;
+ await alongsideTask;
return new Message({...data, version: finalVersion});
}
diff --git a/fluxer_api/src/api/channel/services/BaseChannelAuthService.ts b/fluxer_api/src/api/channel/services/BaseChannelAuthService.ts
index 6aec9f6d9..b5e89803f 100644
--- a/fluxer_api/src/api/channel/services/BaseChannelAuthService.ts
+++ b/fluxer_api/src/api/channel/services/BaseChannelAuthService.ts
@@ -49,6 +49,7 @@ import type {GuildMember} from '@app/api/models/GuildMember';
import type {User} from '@app/api/models/User';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import {canUserAccessNsfwContent} from '@app/api/utils/AgeUtils';
+import {startEarly} from '@app/api/utils/ConcurrencyUtils';
import {ChannelTypes, Permissions} from '@fluxer/constants/src/ChannelConstants';
import {GUILD_VISITOR_PERMISSIONS_MASK} from '@fluxer/constants/src/GuildVisitConstants';
import {
@@ -330,6 +331,13 @@ export abstract class BaseChannelAuthService {
return this.getThreadChannelAuth({channel, userId, skipNsfwValidation});
}
const guildId = channel.guildId!;
+ const channelPermissionsTask = startEarly(
+ this.gatewayService.getUserPermissions({
+ guildId,
+ userId,
+ channelId: channel.id,
+ }),
+ );
const [authContextResult, guildMemberResult] = await Promise.all([
this.fetchGuildAuthContextOrThrow({guildId, userId, channelId: this.parentLookupChannelId(channel)}),
this.fetchGuildMemberOrThrow({guildId, userId}),
@@ -351,11 +359,7 @@ export abstract class BaseChannelAuthService {
guildData: guildDataResult,
userId,
});
- const channelPermissions = await this.gatewayService.getUserPermissions({
- guildId,
- userId,
- channelId: channel.id,
- });
+ const channelPermissions = await channelPermissionsTask;
const hasPermission = async (permission: bigint): Promise<boolean> => {
const allowed = (channelPermissions & permission) === permission;
if (allowed) enforceGuildMfa(permission);
diff --git a/fluxer_api/src/api/channel/services/MessageService.ts b/fluxer_api/src/api/channel/services/MessageService.ts
index ef9da6fb2..7406dcb1f 100644
--- a/fluxer_api/src/api/channel/services/MessageService.ts
+++ b/fluxer_api/src/api/channel/services/MessageService.ts
@@ -73,7 +73,7 @@ export class MessageService {
attachmentUploadTraceRepository: AttachmentUploadTraceRepository,
limitConfigService: LimitConfigService,
) {
- this.validation = new MessageValidationService(cacheService, limitConfigService);
+ this.validation = new MessageValidationService(limitConfigService);
this.writeLock = new MessageWriteLock(cacheService, channelRepository.messages);
this.crosspostPropagation = new CrosspostPropagation({rateLimitService, workerService});
this.mention = new MessageMentionService(
diff --git a/fluxer_api/src/api/channel/services/message/MessageOperationsHelpers.ts b/fluxer_api/src/api/channel/services/message/MessageOperationsHelpers.ts
index a07cae13f..bc4308b32 100644
--- a/fluxer_api/src/api/channel/services/message/MessageOperationsHelpers.ts
+++ b/fluxer_api/src/api/channel/services/message/MessageOperationsHelpers.ts
@@ -1,10 +1,11 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import type {ChannelID, UserID} from '@app/api/BrandedTypes';
+import {createHash} from 'node:crypto';
+import type {ChannelID, MessageID, UserID} from '@app/api/BrandedTypes';
import {createAttachmentID, createChannelID, createMemeID, createMessageID} from '@app/api/BrandedTypes';
import {Config} from '@app/api/Config';
import type {ChannelRepository} from '@app/api/channel/ChannelRepository';
-import {makeAttachmentCdnKey} from '@app/api/channel/services/message/MessageHelpers';
+import {MESSAGE_NONCE_TTL, makeAttachmentCdnKey} from '@app/api/channel/services/message/MessageHelpers';
import type {MessageAttachment} from '@app/api/database/types/MessageTypes';
import type {FavoriteMemeRepository} from '@app/api/favorite_meme/FavoriteMemeRepository';
import type {IMediaService} from '@app/api/infrastructure/IMediaService';
@@ -15,10 +16,12 @@ import type {FavoriteMeme} from '@app/api/models/FavoriteMeme';
import type {Message} from '@app/api/models/Message';
import type {User} from '@app/api/models/User';
import {S3ServiceException} from '@aws-sdk/client-s3';
+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {MessageAttachmentFlags} from '@fluxer/constants/src/ChannelConstants';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {UnknownMessageError} from '@fluxer/errors/src/domains/channel/UnknownMessageError';
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
+import {ThrottledError} from '@fluxer/errors/src/domains/core/ThrottledError';
import type {ICacheService} from '@pkgs/cache/src/ICacheService';
interface MessageOperationsHelpersDeps {
@@ -31,11 +34,24 @@ interface MessageOperationsHelpersDeps {
}
const ANIMATION_PROBE_CONTENT_TYPES = new Set(['image/webp', 'image/apng', 'image/avif', 'image/png']);
+const MESSAGE_NONCE_CLAIM_TTL_SECONDS = 10;
+const MESSAGE_NONCE_WAIT_MS = 30_000;
+const MESSAGE_NONCE_POLL_MS = 100;
+
+function messageNonceKey(userId: UserID, nonce: string): string {
+ return `message-nonce:${userId}:${nonce}`;
+}
+
+function messageNonceClaimKey(userId: UserID, nonce: string): string {
+ return `message-nonce-claim:${userId}:${createHash('sha256').update(nonce).digest('hex')}`;
+}
+
+type RecordMessageNonce = (messageId: MessageID) => Promise<void>;
export class MessageOperationsHelpers {
constructor(private readonly deps: MessageOperationsHelpersDeps) {}
- async findExistingMessage({
+ private async findExistingMessage({
userId,
nonce,
expectedChannelId,
@@ -48,7 +64,7 @@ export class MessageOperationsHelpers {
const existingNonce = await this.deps.cacheService.get<{
channel_id: string;
message_id: string;
- }>(`message-nonce:${userId}:${nonce}`);
+ }>(messageNonceKey(userId, nonce));
if (!existingNonce) return null;
const cachedChannelId = createChannelID(BigInt(existingNonce.channel_id));
if (cachedChannelId !== expectedChannelId) {
@@ -60,6 +76,93 @@ export class MessageOperationsHelpers {
);
}
+ async sendOncePerNonce<T>({
+ userId,
+ nonce,
+ expectedChannelId,
+ existing,
+ send,
+ }: {
+ userId: UserID;
+ nonce?: string;
+ expectedChannelId: ChannelID;
+ existing: (message: Message) => T;
+ send: (recordNonce: RecordMessageNonce) => Promise<T>;
+ }): Promise<T> {
+ if (!nonce) return send(async () => {});
+ const claimKey = messageNonceClaimKey(userId, nonce);
+ const deadline = Date.now() + MESSAGE_NONCE_WAIT_MS;
+ while (true) {
+ const existingMessage = await this.findExistingMessage({userId, nonce, expectedChannelId});
+ if (existingMessage) return existing(existingMessage);
+ const token = await this.deps.cacheService.acquireLock(claimKey, MESSAGE_NONCE_CLAIM_TTL_SECONDS);
+ if (token) {
+ return this.sendWithNonceClaim({userId, nonce, expectedChannelId, claimKey, token, existing, send});
+ }
+ if (Date.now() >= deadline) {
+ throw new ThrottledError({
+ code: APIErrorCodes.RESOURCE_LOCKED,
+ retryAfterSeconds: 1,
+ data: {retry_after: 1},
+ });
+ }
+ await new Promise((resolve) => setTimeout(resolve, MESSAGE_NONCE_POLL_MS));
+ }
+ }
+
+ private async sendWithNonceClaim<T>({
+ userId,
+ nonce,
+ expectedChannelId,
+ claimKey,
+ token,
+ existing,
+ send,
+ }: {
+ userId: UserID;
+ nonce: string;
+ expectedChannelId: ChannelID;
+ claimKey: string;
+ token: string;
+ existing: (message: Message) => T;
+ send: (recordNonce: RecordMessageNonce) => Promise<T>;
+ }): Promise<T> {
+ const keepAlive = setInterval(
+ () => {
+ this.deps.cacheService.extendLock(claimKey, token, MESSAGE_NONCE_CLAIM_TTL_SECONDS).catch(() => {});
+ },
+ (MESSAGE_NONCE_CLAIM_TTL_SECONDS * 1000) / 3,
+ );
+ let keepClaim = false;
+ try {
+ const existingMessage = await this.findExistingMessage({userId, nonce, expectedChannelId});
+ if (existingMessage) return existing(existingMessage);
+ return await send(async (messageId) => {
+ try {
+ await this.deps.cacheService.set(
+ messageNonceKey(userId, nonce),
+ {channel_id: expectedChannelId.toString(), message_id: messageId.toString()},
+ MESSAGE_NONCE_TTL,
+ );
+ } catch (error) {
+ keepClaim = true;
+ Logger.warn(
+ {
+ userId: userId.toString(),
+ channelId: expectedChannelId.toString(),
+ messageId: messageId.toString(),
+ error,
+ },
+ 'Message was persisted but nonce cache failed',
+ );
+ }
+ });
+ } finally {
+ clearInterval(keepAlive);
+ if (!keepClaim) await this.deps.cacheService.releaseLock(claimKey, token).catch(() => {});
+ }
+ }
+
async processFavoriteMeme({
user,
channelId,
diff --git a/fluxer_api/src/api/channel/services/message/MessageSendService.ts b/fluxer_api/src/api/channel/services/message/MessageSendService.ts
index c83a2ea48..98de29e9b 100644
--- a/fluxer_api/src/api/channel/services/message/MessageSendService.ts
+++ b/fluxer_api/src/api/channel/services/message/MessageSendService.ts
@@ -63,6 +63,7 @@ import {assertMayStartConversation} from '@app/api/user/NewConversationLimit';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import {systemDmsHidden} from '@app/api/user/services/SystemDmMessage';
import {isContentHidden, isDirectDeliverySuppressed} from '@app/api/user/UserHelpers';
+import {startEarly} from '@app/api/utils/ConcurrencyUtils';
import {assertGuildMemberCanCommunicate} from '@app/api/utils/GuildCommunicationUtils';
import {checkGuildVerificationWithResponse} from '@app/api/utils/GuildVerificationUtils';
import {
@@ -140,35 +141,6 @@ export class MessageSendService {
}
}
- private async cacheMessageNonceIfPresent(params: {
- userId: UserID;
- nonce?: string;
- channelId: ChannelID;
- messageId: MessageID;
- }): Promise<void> {
- if (!params.nonce) {
- return;
- }
- try {
- await this.deps.validationService.cacheMessageNonce({
- userId: params.userId,
- nonce: params.nonce,
- channelId: params.channelId,
- messageId: params.messageId,
- });
- } catch (error) {
- Logger.warn(
- {
- userId: params.userId.toString(),
- channelId: params.channelId.toString(),
- messageId: params.messageId.toString(),
- error,
- },
- 'Message was persisted but nonce cache failed',
- );
- }
- }
-
private logPostCreateFailure(params: {messageId: MessageID; step: string; error: unknown}): void {
Logger.warn(
{messageId: params.messageId.toString(), step: params.step, error: params.error},
@@ -364,33 +336,44 @@ export class MessageSendService {
guildFeatures: Iterable<string> | null;
}): Promise<void> {
if (!attachments || attachments.length === 0) return;
+ const uploads = attachments.flatMap((attachment, index) =>
+ 'upload_filename' in attachment && attachment.upload_filename
+ ? [
+ {
+ index,
+ filename: attachment.filename,
+ pendingUploadTask: startEarly(
+ this.deps.attachmentUploadTraceRepository.getPendingUpload({
+ uploadKey: attachment.upload_filename,
+ userId: user.id,
+ channelId,
+ }),
+ ),
+ metadataTask: startEarly(
+ this.deps.storageService.getObjectMetadata(Config.s3.buckets.uploads, attachment.upload_filename),
+ ),
+ },
+ ]
+ : [],
+ );
const uploadedAttachmentSizes: Array<{
size: number | bigint;
}> = [];
- for (let index = 0; index < attachments.length; index++) {
- const attachment = attachments[index];
- if (!('upload_filename' in attachment) || !attachment.upload_filename) continue;
- const pendingUpload = await this.deps.attachmentUploadTraceRepository.getPendingUpload({
- uploadKey: attachment.upload_filename,
- userId: user.id,
- channelId,
- });
+ for (const {index, filename, pendingUploadTask, metadataTask} of uploads) {
+ const pendingUpload = await pendingUploadTask;
if (!pendingUpload) {
throw InputValidationError.fromCode(
`attachments.${index}.upload_filename`,
ValidationErrorCodes.UPLOADED_ATTACHMENT_NOT_FOUND,
- {filename: attachment.filename},
+ {filename},
);
}
- const metadata = await this.deps.storageService.getObjectMetadata(
- Config.s3.buckets.uploads,
- attachment.upload_filename,
- );
+ const metadata = await metadataTask;
if (!metadata) {
throw InputValidationError.fromCode(
`attachments.${index}.upload_filename`,
ValidationErrorCodes.UPLOADED_ATTACHMENT_NOT_FOUND,
- {filename: attachment.filename},
+ {filename},
);
}
uploadedAttachmentSizes.push({size: metadata.contentLength});
@@ -680,267 +663,289 @@ export class MessageSendService {
embeds: data.embeds,
attachments: data.attachments,
});
- const existingMessage = await this.deps.operationsHelpers.findExistingMessage({
+ return this.deps.operationsHelpers.sendOncePerNonce({
userId: user.id,
nonce: data.nonce,
expectedChannelId: channelId,
- });
- if (existingMessage) {
- return {message: existingMessage, authChannel};
- }
- const referenceContext = await this.resolveReferenceContext({
- data,
- channelId,
- channelIsThread: channel.isThread(),
- isForwardMessage,
- user,
- viewer,
- });
- const {referencedMessage, referencedChannelGuildId, messageSnapshots} = referenceContext;
- this.assertForwardableReference(isForwardMessage, referencedMessage);
- if (isForwardMessage && messageSnapshots && guild) {
- const snapshotHasEmbeds = messageSnapshots.some((s) => s.embeds.length > 0);
- const snapshotHasAttachments = messageSnapshots.some((s) => s.attachments.length > 0);
- if (snapshotHasEmbeds && !canEmbedLinks) {
- throw new MissingPermissionsError();
- }
- if (snapshotHasAttachments && !canAttachFiles) {
- throw new MissingPermissionsError();
- }
- }
- if (isForwardMessage && messageSnapshots && this.snapshotsContainNsfwContent(messageSnapshots)) {
- const guildNsfw = guild != null && guild.nsfw_level === GuildNSFWLevel.AGE_RESTRICTED;
- const destAllowsNsfw = (authChannel.thread?.parent ?? channel).isNsfw || guildNsfw;
- if (!destAllowsNsfw) {
- throw new NsfwContentRequiresAgeVerificationError();
- }
- }
- if (data.message_reference && guild && !isForwardMessage) {
- const hasReadHistory = await hasPermission(Permissions.READ_MESSAGE_HISTORY);
- if (!hasReadHistory) {
- assertMessageWithinHistoryCutoff({
- message: referencedMessage,
+ existing: (message) => ({message, authChannel}),
+ send: async (recordNonce) => {
+ const referenceContextTask = startEarly(
+ this.resolveReferenceContext({
+ data,
+ channelId,
+ channelIsThread: channel.isThread(),
+ isForwardMessage,
+ user,
+ viewer,
+ }),
+ );
+ const dmRecipientId = this.getOneToOneDmRecipientId(channel, user.id);
+ const conversationTask = startEarly(
+ dmRecipientId !== null
+ ? assertMayStartConversation({
+ user,
+ targetId: dmRecipientId,
+ users: this.deps.userRepository,
+ messages: this.deps.channelRepository.messages,
+ channel,
+ })
+ : Promise.resolve(),
+ );
+ const attachmentsExistTask = startEarly(
+ this.ensureAttachmentsExist({
+ attachments: data.attachments,
+ user,
+ channelId: uploadChannelId,
+ guildFeatures: guild?.features ?? null,
+ }),
+ );
+ const dmNsfwContextTask = startEarly(
+ guild ? Promise.resolve(undefined) : this.deps.persistenceService.resolveDmNsfwContext(channel, user.id),
+ );
+ const messageIdTask = startEarly(
+ forumStarter ? Promise.resolve(channelIdToMessageId(channel.id)) : this.generateMessageId(channel),
+ );
+ const referenceContext = await referenceContextTask;
+ const {referencedMessage, referencedChannelGuildId, messageSnapshots} = referenceContext;
+ this.assertForwardableReference(isForwardMessage, referencedMessage);
+ if (isForwardMessage && messageSnapshots && guild) {
+ const snapshotHasEmbeds = messageSnapshots.some((s) => s.embeds.length > 0);
+ const snapshotHasAttachments = messageSnapshots.some((s) => s.attachments.length > 0);
+ if (snapshotHasEmbeds && !canEmbedLinks) {
+ throw new MissingPermissionsError();
+ }
+ if (snapshotHasAttachments && !canAttachFiles) {
+ throw new MissingPermissionsError();
+ }
+ }
+ if (isForwardMessage && messageSnapshots && this.snapshotsContainNsfwContent(messageSnapshots)) {
+ const guildNsfw = guild != null && guild.nsfw_level === GuildNSFWLevel.AGE_RESTRICTED;
+ const destAllowsNsfw = (authChannel.thread?.parent ?? channel).isNsfw || guildNsfw;
+ if (!destAllowsNsfw) {
+ throw new NsfwContentRequiresAgeVerificationError();
+ }
+ }
+ if (data.message_reference && guild && !isForwardMessage) {
+ const hasReadHistory = await hasPermission(Permissions.READ_MESSAGE_HISTORY);
+ if (!hasReadHistory) {
+ assertMessageWithinHistoryCutoff({
+ message: referencedMessage,
+ guild,
+ });
+ }
+ }
+ if (data.message_reference && referencedMessage && !isForwardMessage) {
+ const replyableTypes: ReadonlySet<Message['type']> = new Set([MessageTypes.DEFAULT, MessageTypes.REPLY]);
+ if (!replyableTypes.has(referencedMessage.type)) {
+ throw InputValidationError.fromCode(
+ 'message_reference',
+ ValidationErrorCodes.CANNOT_REPLY_TO_SYSTEM_MESSAGE,
+ );
+ }
+ }
+ this.ensureForwardGuildMatches({data, referencedChannelGuildId});
+ await conversationTask;
+ await attachmentsExistTask;
+ const {attachmentsToProcess, favoriteMemeAttachment} = await this.prepareMessageAttachments({
+ user,
+ channelId,
+ data,
+ });
+ const dmNsfwContext = await dmNsfwContextTask;
+ const messageId = await messageIdTask;
+ let mentionData: SendMentionData | undefined;
+ const shouldExtractMentions =
+ channel && !isForwardMessage && (data.content !== undefined || data.message_reference != null);
+ if (shouldExtractMentions) {
+ const mentionContent = data.content ?? '';
+ const mentions = await this.deps.mentionService.extractMentions({
+ content: mentionContent,
+ referencedMessage: referencedMessage || null,
+ message: {
+ id: messageId,
+ channelId,
+ authorId: user.id,
+ content: mentionContent,
+ flags: this.deps.validationService.calculateMessageFlags(data),
+ } as Message,
+ channelType: channel.type,
+ allowedMentions: data.allowed_mentions || null,
+ guild,
+ canMentionEveryone,
+ });
+ const {validUserIds, validRoleIds, validChannelMentions} = await this.deps.mentionService.validateMentions({
+ userMentions: mentions.userMentions,
+ roleMentions: mentions.roleMentions,
+ channelMentions: mentions.channelMentions,
+ channel,
+ message: {authorId: user.id, webhookId: null},
+ guild,
+ canMentionRoles: canMentionEveryone,
+ });
+ mentionData = {
+ flags: mentions.flags,
+ mentionUserIds: validUserIds,
+ mentionRoleIds: validRoleIds,
+ mentionChannelIds: validChannelMentions.map((mentionedChannel) =>
+ createChannelID(BigInt(mentionedChannel.id)),
+ ),
+ mentionChannels: validChannelMentions,
+ mentionEveryone: mentions.mentionsEveryone || mentions.mentionsHere,
+ mentionHere: mentions.mentionsHere,
+ };
+ }
+ const messageReference = this.buildMessageReferencePayload({
+ data,
+ referencedMessage,
guild,
+ isForwardMessage,
+ referencedChannelGuildId,
});
- }
- }
- if (data.message_reference && referencedMessage && !isForwardMessage) {
- const replyableTypes: ReadonlySet<Message['type']> = new Set([MessageTypes.DEFAULT, MessageTypes.REPLY]);
- if (!replyableTypes.has(referencedMessage.type)) {
- throw InputValidationError.fromCode('message_reference', ValidationErrorCodes.CANNOT_REPLY_TO_SYSTEM_MESSAGE);
- }
- }
- this.ensureForwardGuildMatches({data, referencedChannelGuildId});
- const dmRecipientId = this.getOneToOneDmRecipientId(channel, user.id);
- if (dmRecipientId !== null) {
- await assertMayStartConversation({
- user,
- targetId: dmRecipientId,
- users: this.deps.userRepository,
- messages: this.deps.channelRepository.messages,
- channel,
- });
- }
- await this.ensureAttachmentsExist({
- attachments: data.attachments,
- user,
- channelId: uploadChannelId,
- guildFeatures: guild?.features ?? null,
- });
- const {attachmentsToProcess, favoriteMemeAttachment} = await this.prepareMessageAttachments({
- user,
- channelId,
- data,
- });
- const dmNsfwContext = guild ? undefined : await this.deps.persistenceService.resolveDmNsfwContext(channel, user.id);
- const messageId = forumStarter ? channelIdToMessageId(channel.id) : await this.generateMessageId(channel);
- let mentionData: SendMentionData | undefined;
- const shouldExtractMentions =
- channel && !isForwardMessage && (data.content !== undefined || data.message_reference != null);
- if (shouldExtractMentions) {
- const mentionContent = data.content ?? '';
- const mentions = await this.deps.mentionService.extractMentions({
- content: mentionContent,
- referencedMessage: referencedMessage || null,
- message: {
- id: messageId,
+ if (slowmodeKey) {
+ const slowmodeResult = await this.deps.rateLimitService.checkLimit({
+ identifier: slowmodeKey,
+ maxAttempts: 1,
+ windowMs: channel.rateLimitPerUser! * 1000,
+ });
+ if (!slowmodeResult.allowed) {
+ throw new SlowmodeRateLimitError({
+ retryAfter: slowmodeResult.retryAfter,
+ retryAfterDecimal: slowmodeResult.retryAfterDecimal,
+ });
+ }
+ }
+ if (authChannel.thread && !forumStarter) {
+ await this.deps.threadActivity.beforeUserSend({
+ channel,
+ parent: authChannel.thread.parent,
+ state: authChannel.thread.state,
+ member: authChannel.thread.member,
+ userId: user.id,
+ isBot: user.isBot,
+ });
+ }
+ const suppressDmRecipientDelivery = dmRecipientId !== null && isDirectDeliverySuppressed(user);
+ const suppressDelivery = suppressDmRecipientDelivery || isContentHidden(user, messageId);
+ const channelHadMessages = channel.lastMessageId !== null;
+ const {message, enqueueDeferredEmbeds} = await this.deps.persistenceService.createMessage({
+ messageId,
channelId,
- authorId: user.id,
- content: mentionContent,
+ user,
+ type: this.getMessageTypeForRequest(data),
+ content: data.content,
flags: this.deps.validationService.calculateMessageFlags(data),
- } as Message,
- channelType: channel.type,
- allowedMentions: data.allowed_mentions || null,
- guild,
- canMentionEveryone,
- });
- const {validUserIds, validRoleIds, validChannelMentions} = await this.deps.mentionService.validateMentions({
- userMentions: mentions.userMentions,
- roleMentions: mentions.roleMentions,
- channelMentions: mentions.channelMentions,
- channel,
- message: {authorId: user.id, webhookId: null},
- guild,
- canMentionRoles: canMentionEveryone,
- });
- mentionData = {
- flags: mentions.flags,
- mentionUserIds: validUserIds,
- mentionRoleIds: validRoleIds,
- mentionChannelIds: validChannelMentions.map((mentionedChannel) => createChannelID(BigInt(mentionedChannel.id))),
- mentionChannels: validChannelMentions,
- mentionEveryone: mentions.mentionsEveryone || mentions.mentionsHere,
- mentionHere: mentions.mentionsHere,
- };
- }
- const messageReference = this.buildMessageReferencePayload({
- data,
- referencedMessage,
- guild,
- isForwardMessage,
- referencedChannelGuildId,
- });
- if (slowmodeKey) {
- const slowmodeResult = await this.deps.rateLimitService.checkLimit({
- identifier: slowmodeKey,
- maxAttempts: 1,
- windowMs: channel.rateLimitPerUser! * 1000,
- });
- if (!slowmodeResult.allowed) {
- throw new SlowmodeRateLimitError({
- retryAfter: slowmodeResult.retryAfter,
- retryAfterDecimal: slowmodeResult.retryAfterDecimal,
+ embeds: data.embeds,
+ attachments: attachmentsToProcess,
+ attachmentUploadUserId: user.id,
+ uploadChannelId,
+ processedAttachments: favoriteMemeAttachment ? [favoriteMemeAttachment] : undefined,
+ stickerIds: data.sticker_ids
+ ? data.sticker_ids.flatMap((stickerId) => createStickerID(stickerId))
+ : undefined,
+ messageReference,
+ messageSnapshots,
+ guildId: guild?.id ? createGuildID(BigInt(guild.id)) : null,
+ channel,
+ referencedMessage,
+ allowedMentions: data.allowed_mentions,
+ guild,
+ member,
+ hasPermission: guild ? hasPermission : undefined,
+ mentionData,
+ allowEmbeds: canEmbedLinks,
+ dmNsfwContext,
+ threadInsert: authChannel.thread !== undefined,
});
- }
- }
- if (authChannel.thread && !forumStarter) {
- await this.deps.threadActivity.beforeUserSend({
- channel,
- parent: authChannel.thread.parent,
- state: authChannel.thread.state,
- member: authChannel.thread.member,
- userId: user.id,
- isBot: user.isBot,
- });
- }
- const suppressDmRecipientDelivery = dmRecipientId !== null && isDirectDeliverySuppressed(user);
- const suppressDelivery = suppressDmRecipientDelivery || isContentHidden(user, messageId);
- const channelHadMessages = channel.lastMessageId !== null;
- const {message, enqueueDeferredEmbeds} = await this.deps.persistenceService.createMessage({
- messageId,
- channelId,
- user,
- type: this.getMessageTypeForRequest(data),
- content: data.content,
- flags: this.deps.validationService.calculateMessageFlags(data),
- embeds: data.embeds,
- attachments: attachmentsToProcess,
- attachmentUploadUserId: user.id,
- uploadChannelId,
- processedAttachments: favoriteMemeAttachment ? [favoriteMemeAttachment] : undefined,
- stickerIds: data.sticker_ids ? data.sticker_ids.flatMap((stickerId) => createStickerID(stickerId)) : undefined,
- messageReference,
- messageSnapshots,
- guildId: guild?.id ? createGuildID(BigInt(guild.id)) : null,
- channel,
- referencedMessage,
- allowedMentions: data.allowed_mentions,
- guild,
- member,
- hasPermission: guild ? hasPermission : undefined,
- mentionData,
- allowEmbeds: canEmbedLinks,
- dmNsfwContext,
- threadInsert: authChannel.thread !== undefined,
- });
- this.cacheMentionChannels({
- requestCache,
- messageId,
- mentionChannels: mentionData?.mentionChannels,
- });
- if (!suppressDelivery) {
- await this.settlePostCreateWork(messageId, [
- {
- step: 'update_dm_recipients',
- promise: this.deps.processingService.updateDMRecipients({channel, channelId, messageId, requestCache}),
- },
- {
- step: 'process_message_after_creation',
- promise: this.deps.processingService.processMessageAfterCreation({
- message,
- channel,
- guild,
- user,
- data,
- referencedMessage,
- mentionHere: mentionData?.mentionHere ?? false,
- }),
- },
- {
- step: 'update_read_states',
- promise: this.deps.processingService.updateReadStates({user, guild, channel, channelId, messageId}),
- },
- ...(authChannel.thread && mentionData && mentionData.mentionUserIds.length > 0
- ? [
- {
- step: 'thread_mention_members',
- promise: this.deps.threadActivity.addMentionedUsers({
+ await recordNonce(messageId);
+ this.cacheMentionChannels({
+ requestCache,
+ messageId,
+ mentionChannels: mentionData?.mentionChannels,
+ });
+ if (!suppressDelivery) {
+ await this.settlePostCreateWork(messageId, [
+ {
+ step: 'update_dm_recipients',
+ promise: this.deps.processingService.updateDMRecipients({channel, channelId, messageId, requestCache}),
+ },
+ {
+ step: 'process_message_after_creation',
+ promise: this.deps.processingService.processMessageAfterCreation({
+ message,
+ channel,
+ guild,
+ user,
+ data,
+ referencedMessage,
+ mentionHere: mentionData?.mentionHere ?? false,
+ }),
+ },
+ {
+ step: 'update_read_states',
+ promise: this.deps.processingService.updateReadStates({user, guild, channel, channelId, messageId}),
+ },
+ ...(authChannel.thread && mentionData && mentionData.mentionUserIds.length > 0
+ ? [
+ {
+ step: 'thread_mention_members',
+ promise: this.deps.threadActivity.addMentionedUsers({
+ channel,
+ parent: authChannel.thread.parent,
+ isModerator: authChannel.thread.isModerator,
+ authorId: user.id,
+ mentionUserIds: mentionData.mentionUserIds,
+ }),
+ },
+ ]
+ : []),
+ ]);
+ }
+ await this.settlePostCreateWork(messageId, [
+ {
+ step: 'dispatch',
+ promise: suppressDelivery
+ ? dispatchMessageCreateToUser({
+ gatewayService: this.deps.gatewayService,
+ channel,
+ message,
+ userId: user.id,
+ currentUserId: user.id,
+ nonce: data.nonce,
+ tts: data.tts,
+ mentionHere: mentionData?.mentionHere ?? false,
+ })
+ : dispatchMessageCreateBroadcast({
+ gatewayService: this.deps.gatewayService,
channel,
- parent: authChannel.thread.parent,
- isModerator: authChannel.thread.isModerator,
- authorId: user.id,
- mentionUserIds: mentionData.mentionUserIds,
+ message,
+ currentUserId: user.id,
+ nonce: data.nonce,
+ tts: data.tts,
+ mentionHere: mentionData?.mentionHere ?? false,
}),
- },
- ]
- : []),
- ]);
- }
- await this.settlePostCreateWork(messageId, [
- {
- step: 'dispatch',
- promise: suppressDelivery
- ? dispatchMessageCreateToUser({
- gatewayService: this.deps.gatewayService,
- channel,
- message,
- userId: user.id,
- currentUserId: user.id,
- nonce: data.nonce,
- tts: data.tts,
- mentionHere: mentionData?.mentionHere ?? false,
- })
- : dispatchMessageCreateBroadcast({
- gatewayService: this.deps.gatewayService,
- channel,
- message,
- currentUserId: user.id,
- nonce: data.nonce,
- tts: data.tts,
- mentionHere: mentionData?.mentionHere ?? false,
- }),
+ },
+ ]);
+ emitMessageCreated({
+ user,
+ message,
+ channel,
+ guildId: guild?.id ? createGuildID(BigInt(guild.id)) : null,
+ guildOwnerId: guild?.owner_id ? createUserID(BigInt(guild.owner_id)) : null,
+ dmRecipientId,
+ channelHadMessages,
+ delivered: !suppressDelivery,
+ userRepository: this.deps.userRepository,
+ });
+ void enqueueDeferredEmbeds().catch((error) => {
+ Logger.warn({error, messageId: messageId.toString()}, 'Failed to enqueue deferred embed extraction');
+ });
+ if (authChannel.thread) enqueueThreadSearchSync(channel.id, {activity: true});
+ if (channel.indexedAt != null && !suppressDmRecipientDelivery) {
+ void this.deps.searchService.indexMessage(message, user.isBot);
+ }
+ return {message, authChannel};
},
- ]);
- await this.cacheMessageNonceIfPresent({userId: user.id, nonce: data.nonce, channelId, messageId});
- emitMessageCreated({
- user,
- message,
- channel,
- guildId: guild?.id ? createGuildID(BigInt(guild.id)) : null,
- guildOwnerId: guild?.owner_id ? createUserID(BigInt(guild.owner_id)) : null,
- dmRecipientId,
- channelHadMessages,
- delivered: !suppressDelivery,
- userRepository: this.deps.userRepository,
});
- void enqueueDeferredEmbeds().catch((error) => {
- Logger.warn({error, messageId: messageId.toString()}, 'Failed to enqueue deferred embed extraction');
- });
- if (authChannel.thread) enqueueThreadSearchSync(channel.id, {activity: true});
- if (channel.indexedAt != null && !suppressDmRecipientDelivery) {
- void this.deps.searchService.indexMessage(message, user.isBot);
- }
- return {message, authChannel};
}
async sendWebhookMessage({
@@ -980,145 +985,158 @@ export class MessageSendService {
attachments: data.attachments,
});
const webhookActorId = createUserID(BigInt(webhook.id));
- const existingMessage = await this.deps.operationsHelpers.findExistingMessage({
+ return this.deps.operationsHelpers.sendOncePerNonce({
userId: webhookActorId,
nonce: data.nonce,
expectedChannelId: channelId,
- });
- if (existingMessage) {
- return existingMessage;
- }
- let referencedMessage: Message | null = null;
- let messageSnapshots: Array<MessageSnapshot> | undefined;
- if (data.message_reference) {
- const referenceChannelId = isForwardMessage ? createChannelID(data.message_reference.channel_id!) : channelId;
- if (referenceChannelId !== channelId) {
- throw new UnknownMessageError();
- }
- referencedMessage = await this.deps.channelRepository.messages.getMessage(
- referenceChannelId,
- createMessageID(data.message_reference.message_id),
- );
- if (!referencedMessage) {
- throw new UnknownMessageError();
- }
- if (isForwardMessage) {
- messageSnapshots = await createMessageSnapshotsForForward(
- referencedMessage,
- null,
- channelId,
- this.deps.storageService,
- this.deps.snowflakeService,
- this.deps.limitConfigService,
- this.getForwardMediaSelection(data),
+ existing: (message) => message,
+ send: async (recordNonce) => {
+ const messageIdTask = startEarly(
+ thread && forumStarter ? Promise.resolve(channelIdToMessageId(thread.id)) : this.generateMessageId(channel),
);
- } else {
- const replyableTypes: ReadonlySet<Message['type']> = new Set([MessageTypes.DEFAULT, MessageTypes.REPLY]);
- if (!replyableTypes.has(referencedMessage.type)) {
- throw InputValidationError.fromCode('message_reference', ValidationErrorCodes.CANNOT_REPLY_TO_SYSTEM_MESSAGE);
+ const attachmentUploadUserIdTask = startEarly(
+ this.resolveWebhookAttachmentUploadUserId(webhook, data.attachments),
+ );
+ let referencedMessage: Message | null = null;
+ let messageSnapshots: Array<MessageSnapshot> | undefined;
+ if (data.message_reference) {
+ const referenceChannelId = isForwardMessage ? createChannelID(data.message_reference.channel_id!) : channelId;
+ if (referenceChannelId !== channelId) {
+ throw new UnknownMessageError();
+ }
+ referencedMessage = await this.deps.channelRepository.messages.getMessage(
+ referenceChannelId,
+ createMessageID(data.message_reference.message_id),
+ );
+ if (!referencedMessage) {
+ throw new UnknownMessageError();
+ }
+ if (isForwardMessage) {
+ messageSnapshots = await createMessageSnapshotsForForward(
+ referencedMessage,
+ null,
+ channelId,
+ this.deps.storageService,
+ this.deps.snowflakeService,
+ this.deps.limitConfigService,
+ this.getForwardMediaSelection(data),
+ );
+ } else {
+ const replyableTypes: ReadonlySet<Message['type']> = new Set([MessageTypes.DEFAULT, MessageTypes.REPLY]);
+ if (!replyableTypes.has(referencedMessage.type)) {
+ throw InputValidationError.fromCode(
+ 'message_reference',
+ ValidationErrorCodes.CANNOT_REPLY_TO_SYSTEM_MESSAGE,
+ );
+ }
+ }
+ this.assertForwardableReference(isForwardMessage, referencedMessage);
}
- }
- this.assertForwardableReference(isForwardMessage, referencedMessage);
- }
- const messageReference = this.buildMessageReferencePayload({
- data,
- referencedMessage,
- guild,
- isForwardMessage,
- referencedChannelGuildId: channel.guildId,
- });
- if (thread && !forumStarter) {
- await this.deps.threadActivity.beforeWebhookSend(thread);
- }
- const messageId = thread && forumStarter ? channelIdToMessageId(thread.id) : await this.generateMessageId(channel);
- let mentionData: SendMentionData | undefined;
- const shouldExtractWebhookMentions =
- channel && !isForwardMessage && (data.content !== undefined || data.message_reference != null);
- if (shouldExtractWebhookMentions) {
- const mentionContent = data.content ?? '';
- const mentions = await this.deps.mentionService.extractMentions({
- content: mentionContent,
- referencedMessage: referencedMessage,
- message: {
- id: messageId,
+ const messageReference = this.buildMessageReferencePayload({
+ data,
+ referencedMessage,
+ guild,
+ isForwardMessage,
+ referencedChannelGuildId: channel.guildId,
+ });
+ if (thread && !forumStarter) {
+ await this.deps.threadActivity.beforeWebhookSend(thread);
+ }
+ const messageId = await messageIdTask;
+ let mentionData: SendMentionData | undefined;
+ const shouldExtractWebhookMentions =
+ channel && !isForwardMessage && (data.content !== undefined || data.message_reference != null);
+ if (shouldExtractWebhookMentions) {
+ const mentionContent = data.content ?? '';
+ const mentions = await this.deps.mentionService.extractMentions({
+ content: mentionContent,
+ referencedMessage: referencedMessage,
+ message: {
+ id: messageId,
+ channelId,
+ webhookId: webhook.id,
+ content: mentionContent,
+ flags: this.deps.validationService.calculateMessageFlags(data),
+ } as Message,
+ channelType: channel.type,
+ allowedMentions: data.allowed_mentions || null,
+ guild,
+ });
+ const {validUserIds, validRoleIds, validChannelMentions} = await this.deps.mentionService.validateMentions({
+ userMentions: mentions.userMentions,
+ roleMentions: mentions.roleMentions,
+ channelMentions: mentions.channelMentions,
+ channel,
+ message: {authorId: null, webhookId: webhook.id},
+ guild,
+ });
+ mentionData = {
+ flags: mentions.flags,
+ mentionUserIds: validUserIds,
+ mentionRoleIds: validRoleIds,
+ mentionChannelIds: validChannelMentions.map((mentionedChannel) =>
+ createChannelID(BigInt(mentionedChannel.id)),
+ ),
+ mentionChannels: validChannelMentions,
+ mentionEveryone: mentions.mentionsEveryone || mentions.mentionsHere,
+ mentionHere: mentions.mentionsHere,
+ };
+ }
+ const {message, enqueueDeferredEmbeds} = await this.deps.persistenceService.createMessage({
+ messageId,
channelId,
webhookId: webhook.id,
- content: mentionContent,
+ webhookName: username ?? webhook.name!,
+ webhookAvatar: avatar ?? webhook.avatarHash,
+ type: this.getMessageTypeForRequest(data),
+ content: data.content,
flags: this.deps.validationService.calculateMessageFlags(data),
- } as Message,
- channelType: channel.type,
- allowedMentions: data.allowed_mentions || null,
- guild,
- });
- const {validUserIds, validRoleIds, validChannelMentions} = await this.deps.mentionService.validateMentions({
- userMentions: mentions.userMentions,
- roleMentions: mentions.roleMentions,
- channelMentions: mentions.channelMentions,
- channel,
- message: {authorId: null, webhookId: webhook.id},
- guild,
- });
- mentionData = {
- flags: mentions.flags,
- mentionUserIds: validUserIds,
- mentionRoleIds: validRoleIds,
- mentionChannelIds: validChannelMentions.map((mentionedChannel) => createChannelID(BigInt(mentionedChannel.id))),
- mentionChannels: validChannelMentions,
- mentionEveryone: mentions.mentionsEveryone || mentions.mentionsHere,
- mentionHere: mentions.mentionsHere,
- };
- }
- const {message, enqueueDeferredEmbeds} = await this.deps.persistenceService.createMessage({
- messageId,
- channelId,
- webhookId: webhook.id,
- webhookName: username ?? webhook.name!,
- webhookAvatar: avatar ?? webhook.avatarHash,
- type: this.getMessageTypeForRequest(data),
- content: data.content,
- flags: this.deps.validationService.calculateMessageFlags(data),
- embeds: data.embeds,
- attachments: this.attachmentsToProcess(data.attachments),
- attachmentUploadUserId: await this.resolveWebhookAttachmentUploadUserId(webhook, data.attachments),
- uploadChannelId: thread ? (webhook.channelId ?? undefined) : undefined,
- stickerIds: data.sticker_ids ? data.sticker_ids.flatMap((stickerId) => createStickerID(stickerId)) : undefined,
- messageReference,
- messageSnapshots,
- guildId: channel.guildId,
- channel,
- guild,
- referencedMessage,
- mentionData,
- allowEmbeds: true,
- threadInsert: thread != null,
- });
- this.cacheMentionChannels({
- requestCache,
- messageId,
- mentionChannels: mentionData?.mentionChannels,
- });
- await this.deps.mentionService.handleMentionTasks({
- guildId: channel.guildId,
- message,
- authorId: webhookActorId,
- mentionHere: mentionData?.mentionHere ?? false,
- });
- await dispatchMessageCreateBroadcast({
- gatewayService: this.deps.gatewayService,
- channel,
- message,
- nonce: data.nonce,
- mentionHere: mentionData?.mentionHere ?? false,
- });
- await this.cacheMessageNonceIfPresent({userId: webhookActorId, nonce: data.nonce, channelId, messageId});
- void enqueueDeferredEmbeds().catch((error) => {
- Logger.warn({error, messageId: messageId.toString()}, 'Failed to enqueue deferred embed extraction');
+ embeds: data.embeds,
+ attachments: this.attachmentsToProcess(data.attachments),
+ attachmentUploadUserId: await attachmentUploadUserIdTask,
+ uploadChannelId: thread ? (webhook.channelId ?? undefined) : undefined,
+ stickerIds: data.sticker_ids
+ ? data.sticker_ids.flatMap((stickerId) => createStickerID(stickerId))
+ : undefined,
+ messageReference,
+ messageSnapshots,
+ guildId: channel.guildId,
+ channel,
+ guild,
+ referencedMessage,
+ mentionData,
+ allowEmbeds: true,
+ threadInsert: thread != null,
+ });
+ await recordNonce(messageId);
+ this.cacheMentionChannels({
+ requestCache,
+ messageId,
+ mentionChannels: mentionData?.mentionChannels,
+ });
+ await this.deps.mentionService.handleMentionTasks({
+ guildId: channel.guildId,
+ message,
+ authorId: webhookActorId,
+ mentionHere: mentionData?.mentionHere ?? false,
+ });
+ await dispatchMessageCreateBroadcast({
+ gatewayService: this.deps.gatewayService,
+ channel,
+ message,
+ nonce: data.nonce,
+ mentionHere: mentionData?.mentionHere ?? false,
+ });
+ void enqueueDeferredEmbeds().catch((error) => {
+ Logger.warn({error, messageId: messageId.toString()}, 'Failed to enqueue deferred embed extraction');
+ });
+ if (thread) enqueueThreadSearchSync(thread.id, {activity: true});
+ if (channel.indexedAt != null) {
+ void this.deps.searchService.indexMessage(message, false);
+ }
+ return message;
+ },
});
- if (thread) enqueueThreadSearchSync(thread.id, {activity: true});
- if (channel.indexedAt != null) {
- void this.deps.searchService.indexMessage(message, false);
- }
- return message;
}
async editWebhookMessage({
@@ -1217,76 +1235,76 @@ export class MessageSendService {
embeds: data.embeds,
attachments: data.attachments,
});
- const existingMessage = await this.deps.operationsHelpers.findExistingMessage({
+ return this.deps.operationsHelpers.sendOncePerNonce({
userId: user.id,
nonce: data.nonce,
expectedChannelId: channelId,
+ existing: (message) => message,
+ send: async (recordNonce) => {
+ const {referencedMessage, referencedChannelGuildId, messageSnapshots} = await this.resolveReferenceContext({
+ data,
+ channelId,
+ channelIsThread: channel.isThread(),
+ isForwardMessage,
+ user,
+ viewer,
+ });
+ this.ensureForwardGuildMatches({data, referencedChannelGuildId});
+ await this.ensureAttachmentsExist({
+ attachments: data.attachments,
+ user,
+ channelId,
+ guildFeatures: null,
+ });
+ const {attachmentsToProcess, favoriteMemeAttachment} = await this.prepareMessageAttachments({
+ user,
+ channelId,
+ data,
+ });
+ const messageId = createMessageID(await this.deps.snowflakeService.generateForChannel(channelId));
+ const messageReference = this.buildMessageReferencePayload({
+ data,
+ referencedMessage,
+ guild: null,
+ isForwardMessage,
+ referencedChannelGuildId,
+ });
+ const {message, enqueueDeferredEmbeds} = await this.deps.persistenceService.createMessage({
+ messageId,
+ channelId,
+ user,
+ type: this.getMessageTypeForRequest(data),
+ content: data.content,
+ flags: data.flags ? data.flags & SENDABLE_MESSAGE_FLAGS : 0,
+ embeds: data.embeds,
+ attachments: attachmentsToProcess,
+ attachmentUploadUserId: user.id,
+ processedAttachments: favoriteMemeAttachment ? [favoriteMemeAttachment] : undefined,
+ stickerIds: data.sticker_ids
+ ? data.sticker_ids.flatMap((stickerId) => createStickerID(stickerId))
+ : undefined,
+ messageReference,
+ messageSnapshots,
+ guildId: null,
+ channel,
+ });
+ await recordNonce(messageId);
+ await dispatchMessageCreateBroadcast({
+ gatewayService: this.deps.gatewayService,
+ channel,
+ message,
+ currentUserId: user.id,
+ nonce: data.nonce,
+ tts: data.tts,
+ });
+ void enqueueDeferredEmbeds().catch((error) => {
+ Logger.warn({error, messageId: messageId.toString()}, 'Failed to enqueue deferred embed extraction');
+ });
+ if (channel.indexedAt != null) {
+ void this.deps.searchService.indexMessage(message, user.isBot);
+ }
+ return message;
+ },
});
- if (existingMessage) {
- return existingMessage;
- }
- const {referencedMessage, referencedChannelGuildId, messageSnapshots} = await this.resolveReferenceContext({
- data,
- channelId,
- channelIsThread: channel.isThread(),
- isForwardMessage,
- user,
- viewer,
- });
- this.ensureForwardGuildMatches({data, referencedChannelGuildId});
- await this.ensureAttachmentsExist({
- attachments: data.attachments,
- user,
- channelId,
- guildFeatures: null,
- });
- const {attachmentsToProcess, favoriteMemeAttachment} = await this.prepareMessageAttachments({
- user,
- channelId,
- data,
- });
- const messageId = createMessageID(await this.deps.snowflakeService.generateForChannel(channelId));
- const messageReference = this.buildMessageReferencePayload({
- data,
- referencedMessage,
- guild: null,
- isForwardMessage,
- referencedChannelGuildId,
- });
- const {message, enqueueDeferredEmbeds} = await this.deps.persistenceService.createMessage({
- messageId,
- channelId,
- user,
- type: this.getMessageTypeForRequest(data),
- content: data.content,
- flags: data.flags ? data.flags & SENDABLE_MESSAGE_FLAGS : 0,
- embeds: data.embeds,
- attachments: attachmentsToProcess,
- attachmentUploadUserId: user.id,
- processedAttachments: favoriteMemeAttachment ? [favoriteMemeAttachment] : undefined,
- stickerIds: data.sticker_ids ? data.sticker_ids.flatMap((stickerId) => createStickerID(stickerId)) : undefined,
- messageReference,
- messageSnapshots,
- guildId: null,
- channel,
- });
- await dispatchMessageCreateBroadcast({
- gatewayService: this.deps.gatewayService,
- channel,
- message,
- currentUserId: user.id,
- nonce: data.nonce,
- tts: data.tts,
- });
- void enqueueDeferredEmbeds().catch((error) => {
- Logger.warn({error, messageId: messageId.toString()}, 'Failed to enqueue deferred embed extraction');
- });
- if (data.nonce) {
- await this.deps.validationService.cacheMessageNonce({userId: user.id, nonce: data.nonce, channelId, messageId});
- }
- if (channel.indexedAt != null) {
- void this.deps.searchService.indexMessage(message, user.isBot);
- }
- return message;
}
}
diff --git a/fluxer_api/src/api/channel/services/message/MessageValidationService.ts b/fluxer_api/src/api/channel/services/message/MessageValidationService.ts
index ba8b8d8a3..486110629 100644
--- a/fluxer_api/src/api/channel/services/message/MessageValidationService.ts
+++ b/fluxer_api/src/api/channel/services/message/MessageValidationService.ts
@@ -1,11 +1,8 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import type {ChannelID, MessageID, UserID} from '@app/api/BrandedTypes';
+import type {UserID} from '@app/api/BrandedTypes';
import type {MessageRequest, MessageUpdateRequest} from '@app/api/channel/MessageTypes';
-import {
- assertAttachmentFileSizesWithinLimit,
- MESSAGE_NONCE_TTL,
-} from '@app/api/channel/services/message/MessageHelpers';
+import {assertAttachmentFileSizesWithinLimit} from '@app/api/channel/services/message/MessageHelpers';
import {contentModerationService} from '@app/api/infrastructure/ContentModerationService';
import type {LimitConfigService} from '@app/api/limits/LimitConfigService';
import {resolveLimitSafe} from '@app/api/limits/LimitConfigUtils';
@@ -33,13 +30,9 @@ import {CannotSendEmptyMessageError} from '@fluxer/errors/src/domains/channel/Ca
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
import {hasVisibleContent} from '@fluxer/schema/src/primitives/MessageValidators';
-import type {ICacheService} from '@pkgs/cache/src/ICacheService';
export class MessageValidationService {
- constructor(
- private cacheService: ICacheService,
- private limitConfigService: LimitConfigService,
- ) {}
+ constructor(private limitConfigService: LimitConfigService) {}
validateMessageContent(
data: MessageRequest | MessageUpdateRequest,
@@ -186,27 +179,6 @@ export class MessageValidationService {
);
}
- async cacheMessageNonce({
- userId,
- nonce,
- channelId,
- messageId,
- }: {
- userId: UserID;
- nonce: string;
- channelId: ChannelID;
- messageId: MessageID;
- }): Promise<void> {
- await this.cacheService.set(
- `message-nonce:${userId}:${nonce}`,
- {
- channel_id: channelId.toString(),
- message_id: messageId.toString(),
- },
- MESSAGE_NONCE_TTL,
- );
- }
-
async canDeleteMessage({
message,
userId,
diff --git a/fluxer_api/src/api/utils/ConcurrencyUtils.ts b/fluxer_api/src/api/utils/ConcurrencyUtils.ts
index 844faf306..e78805943 100644
--- a/fluxer_api/src/api/utils/ConcurrencyUtils.ts
+++ b/fluxer_api/src/api/utils/ConcurrencyUtils.ts
@@ -11,6 +11,11 @@ export async function awaitAll(tasks: ReadonlyArray<Promise<unknown>>, failureMe
throwCompletionErrors(errors, failureMessage);
}
+export function startEarly<T>(task: Promise<T>): Promise<T> {
+ task.catch(() => {});
+ return task;
+}
+
export async function runAllInOrder(
steps: ReadonlyArray<() => Promise<unknown>>,
failureMessage: string,