Skip to content

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

TypeScript fluxerfluxerapp

refactor(api): merge duplicated helpers and drop dead code

Hampusb2d6a9d9f61b
diff --git a/fluxer_api/pkgs/elasticsearch_search/src/adapters/ElasticsearchMessageAdapter.ts b/fluxer_api/pkgs/elasticsearch_search/src/adapters/ElasticsearchMessageAdapter.ts
index f6586a13e..47a6a41ac 100644
--- a/fluxer_api/pkgs/elasticsearch_search/src/adapters/ElasticsearchMessageAdapter.ts
+++ b/fluxer_api/pkgs/elasticsearch_search/src/adapters/ElasticsearchMessageAdapter.ts
@@ -39,79 +39,45 @@ function buildMessageFilters(filters: MessageSearchFilters): Array<Elasticsearch
if (filters.channelIds && filters.channelIds.length > 0) {
clauses.push(esTermsFilter('channelId', filters.channelIds));
}
- if (filters.excludeChannelIds && filters.excludeChannelIds.length > 0) {
- clauses.push(...esExcludeAny('channelId', filters.excludeChannelIds));
- }
+ clauses.push(...esExcludeAny('channelId', filters.excludeChannelIds ?? []));
if (filters.authorId && filters.authorId.length > 0) {
clauses.push(esTermsFilter('authorId', filters.authorId));
}
- if (filters.excludeAuthorIds && filters.excludeAuthorIds.length > 0) {
- clauses.push(...esExcludeAny('authorId', filters.excludeAuthorIds));
- }
+ clauses.push(...esExcludeAny('authorId', filters.excludeAuthorIds ?? []));
if (filters.authorType && filters.authorType.length > 0) {
clauses.push(esTermsFilter('authorType', filters.authorType));
}
- if (filters.excludeAuthorType && filters.excludeAuthorType.length > 0) {
- clauses.push(...esExcludeAny('authorType', filters.excludeAuthorType));
- }
- if (filters.mentions && filters.mentions.length > 0) {
- clauses.push(...esAndTerms('mentionedUserIds', filters.mentions));
- }
- if (filters.excludeMentions && filters.excludeMentions.length > 0) {
- clauses.push(...esExcludeAny('mentionedUserIds', filters.excludeMentions));
- }
+ clauses.push(...esExcludeAny('authorType', filters.excludeAuthorType ?? []));
+ clauses.push(...esAndTerms('mentionedUserIds', filters.mentions ?? []));
+ clauses.push(...esExcludeAny('mentionedUserIds', filters.excludeMentions ?? []));
if (filters.mentionEveryone !== undefined) {
clauses.push(esTermFilter('mentionEveryone', filters.mentionEveryone));
}
if (filters.pinned !== undefined) {
clauses.push(esTermFilter('isPinned', filters.pinned));
}
- if (filters.has && filters.has.length > 0) {
- for (const hasType of filters.has) {
- const field = HAS_FIELD_MAP[hasType];
- if (field) {
- clauses.push(esTermFilter(field, true));
- }
+ for (const hasType of filters.has ?? []) {
+ const field = HAS_FIELD_MAP[hasType];
+ if (field) {
+ clauses.push(esTermFilter(field, true));
}
}
- if (filters.excludeHas && filters.excludeHas.length > 0) {
- for (const hasType of filters.excludeHas) {
- const field = HAS_FIELD_MAP[hasType];
- if (field) {
- clauses.push(esTermFilter(field, false));
- }
+ for (const hasType of filters.excludeHas ?? []) {
+ const field = HAS_FIELD_MAP[hasType];
+ if (field) {
+ clauses.push(esTermFilter(field, false));
}
}
- if (filters.embedType && filters.embedType.length > 0) {
- clauses.push(...esAndTerms('embedTypes', filters.embedType));
- }
- if (filters.excludeEmbedTypes && filters.excludeEmbedTypes.length > 0) {
- clauses.push(...esExcludeAny('embedTypes', filters.excludeEmbedTypes));
- }
- if (filters.embedProvider && filters.embedProvider.length > 0) {
- clauses.push(...esAndTerms('embedProviders', filters.embedProvider));
- }
- if (filters.excludeEmbedProviders && filters.excludeEmbedProviders.length > 0) {
- clauses.push(...esExcludeAny('embedProviders', filters.excludeEmbedProviders));
- }
- if (filters.linkHostname && filters.linkHostname.length > 0) {
- clauses.push(...esAndTerms('linkHostnames', filters.linkHostname));
- }
- if (filters.excludeLinkHostnames && filters.excludeLinkHostnames.length > 0) {
- clauses.push(...esExcludeAny('linkHostnames', filters.excludeLinkHostnames));
- }
- if (filters.attachmentFilename && filters.attachmentFilename.length > 0) {
- clauses.push(...esAndTerms('attachmentFilenames', filters.attachmentFilename));
- }
- if (filters.excludeAttachmentFilenames && filters.excludeAttachmentFilenames.length > 0) {
- clauses.push(...esExcludeAny('attachmentFilenames', filters.excludeAttachmentFilenames));
- }
- if (filters.attachmentExtension && filters.attachmentExtension.length > 0) {
- clauses.push(...esAndTerms('attachmentExtensions', filters.attachmentExtension));
- }
- if (filters.excludeAttachmentExtensions && filters.excludeAttachmentExtensions.length > 0) {
- clauses.push(...esExcludeAny('attachmentExtensions', filters.excludeAttachmentExtensions));
- }
+ clauses.push(...esAndTerms('embedTypes', filters.embedType ?? []));
+ clauses.push(...esExcludeAny('embedTypes', filters.excludeEmbedTypes ?? []));
+ clauses.push(...esAndTerms('embedProviders', filters.embedProvider ?? []));
+ clauses.push(...esExcludeAny('embedProviders', filters.excludeEmbedProviders ?? []));
+ clauses.push(...esAndTerms('linkHostnames', filters.linkHostname ?? []));
+ clauses.push(...esExcludeAny('linkHostnames', filters.excludeLinkHostnames ?? []));
+ clauses.push(...esAndTerms('attachmentFilenames', filters.attachmentFilename ?? []));
+ clauses.push(...esExcludeAny('attachmentFilenames', filters.excludeAttachmentFilenames ?? []));
+ clauses.push(...esAndTerms('attachmentExtensions', filters.attachmentExtension ?? []));
+ clauses.push(...esExcludeAny('attachmentExtensions', filters.excludeAttachmentExtensions ?? []));
if (filters.maxId != null) {
clauses.push({range: {id: {lt: filters.maxId}}});
}
@@ -154,18 +120,11 @@ export class ElasticsearchMessageAdapter extends ElasticsearchIndexAdapter<Messa
): Promise<SearchResult<SearchableMessage>> {
const exactPhrases = filters.exactPhrases ?? [];
const contents = filters.contents ?? [];
- const cleanFilters: MessageSearchFilters = {
- ...filters,
- contents: undefined,
- exactPhrases: undefined,
- maxId: undefined,
- minId: undefined,
- };
if (contents.length > 0) {
- return this.searchMultipleContents(contents, exactPhrases, cleanFilters, filters, options);
+ return this.searchMultipleContents(contents, exactPhrases, filters, options);
}
if (exactPhrases.length > 0) {
- return this.searchWithPhrases(query, exactPhrases, cleanFilters, filters, options);
+ return this.searchWithPhrases(query, exactPhrases, filters, options);
}
return super.search(query, filters, options);
}
@@ -173,14 +132,12 @@ export class ElasticsearchMessageAdapter extends ElasticsearchIndexAdapter<Messa
private async searchMultipleContents(
contents: Array<string>,
exactPhrases: Array<string>,
- _cleanFilters: MessageSearchFilters,
originalFilters: MessageSearchFilters,
options?: SearchOptions,
): Promise<SearchResult<SearchableMessage>> {
const filterClauses = compactFilters(
buildMessageFilters({...originalFilters, contents: undefined, exactPhrases: undefined}),
);
- const sort = buildMessageSort(originalFilters);
const should: Array<Record<string, unknown>> = contents.map((term) => ({
multi_match: {query: term, fields: ['content', 'embedContent'], type: 'best_fields'},
}));
@@ -193,45 +150,16 @@ export class ElasticsearchMessageAdapter extends ElasticsearchIndexAdapter<Messa
},
});
}
- const limit = options?.limit ?? options?.hitsPerPage ?? 25;
- const usesCursor = options?.cursor != null && options.cursor.length > 0;
- const searchParams: Record<string, unknown> = {
- index: this.indexDefinition.indexName,
- query: {
- bool: {
- must,
- filter: filterClauses.length > 0 ? filterClauses : undefined,
- },
- },
- size: limit,
- track_total_hits: true,
- };
- if (usesCursor) {
- searchParams.search_after = options!.cursor;
- } else {
- const offset = options?.offset ?? (options?.page ? (options.page - 1) * (options.hitsPerPage ?? 25) : 0);
- searchParams.from = offset;
- }
- const effectiveSort = sort && sort.length > 0 ? [...sort, {id: {order: 'desc'}}] : [{id: {order: 'desc'}}];
- searchParams.sort = effectiveSort;
- const result = await this.client.search<SearchableMessage>(searchParams);
- const totalValue = result.hits.total;
- const total = typeof totalValue === 'number' ? totalValue : (totalValue?.value ?? 0);
- const hits = result.hits.hits.map((hit) => ({...hit._source!, id: hit._id!}));
- const lastHit = result.hits.hits.at(-1);
- const cursor = lastHit?.sort?.map((v) => String(v));
- return {hits, total, cursor};
+ return this.runBoolSearch(must, filterClauses, buildMessageSort(originalFilters), options);
}
private async searchWithPhrases(
query: string,
exactPhrases: Array<string>,
- _cleanFilters: MessageSearchFilters,
originalFilters: MessageSearchFilters,
options?: SearchOptions,
): Promise<SearchResult<SearchableMessage>> {
const filterClauses = compactFilters(buildMessageFilters({...originalFilters, exactPhrases: undefined}));
- const sort = buildMessageSort(originalFilters);
const must: Array<Record<string, unknown>> = [];
if (query) {
must.push({multi_match: {query, fields: ['content'], type: 'best_fields'}});
@@ -247,10 +175,19 @@ export class ElasticsearchMessageAdapter extends ElasticsearchIndexAdapter<Messa
if (must.length === 0) {
must.push({match_all: {}});
}
+ return this.runBoolSearch(must, filterClauses, buildMessageSort(originalFilters), options);
+ }
+
+ private async runBoolSearch(
+ must: Array<Record<string, unknown>>,
+ filterClauses: Array<ElasticsearchFilter>,
+ sort: Array<SortCombinations> | undefined,
+ options?: SearchOptions,
+ ): Promise<SearchResult<SearchableMessage>> {
const limit = options?.limit ?? options?.hitsPerPage ?? 25;
const usesCursor = options?.cursor != null && options.cursor.length > 0;
const searchParams: Record<string, unknown> = {
- index: 'messages',
+ index: this.indexDefinition.indexName,
query: {
bool: {
must,
diff --git a/fluxer_api/src/api/admin/controllers/AuditLogAdminController.ts b/fluxer_api/src/api/admin/controllers/AuditLogAdminController.ts
index 29b080fd3..650740812 100644
--- a/fluxer_api/src/api/admin/controllers/AuditLogAdminController.ts
+++ b/fluxer_api/src/api/admin/controllers/AuditLogAdminController.ts
@@ -40,27 +40,17 @@ export function AuditLogAdminController(app: HonoApp) {
const adminService = ctx.get('adminService');
const {q, admin_user_id, target_type, target_id, access, sort_by, sort_order, limit, offset} =
ctx.req.valid('query');
- const response =
- q === undefined
- ? await adminService.auditService.listAuditLogs({
- admin_user_id,
- target_type,
- target_id,
- access,
- limit,
- offset,
- })
- : await adminService.auditService.searchAuditLogs({
- query: q,
- admin_user_id,
- target_type,
- target_id,
- access,
- sort_by,
- sort_order,
- limit,
- offset,
- });
+ const response = await adminService.auditService.searchAuditLogs({
+ query: q,
+ admin_user_id,
+ target_type,
+ target_id,
+ access,
+ sort_by: q === undefined ? undefined : sort_by,
+ sort_order: q === undefined ? undefined : sort_order,
+ limit,
+ offset,
+ });
await recordAdminRead(ctx, {
targetType: 'audit_log',
targetId: 0n,
diff --git a/fluxer_api/src/api/admin/controllers/InstanceConfigAdminController.ts b/fluxer_api/src/api/admin/controllers/InstanceConfigAdminController.ts
index 1a58dcad1..636e4fbba 100644
--- a/fluxer_api/src/api/admin/controllers/InstanceConfigAdminController.ts
+++ b/fluxer_api/src/api/admin/controllers/InstanceConfigAdminController.ts
@@ -168,6 +168,12 @@ function omitUndefinedFields<T extends object>(value: T): Partial<T> {
return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined)) as Partial<T>;
}
+function nonEmptyPatch<T extends object>(value: T | null | undefined): Partial<T> | undefined {
+ if (!value) return undefined;
+ const patch = omitUndefinedFields(value);
+ return Object.keys(patch).length > 0 ? patch : undefined;
+}
+
async function buildInstanceConfigResponse(): Promise<InstanceConfigResponse> {
const instanceConfigRepository = getInstanceConfigRepository();
const [
@@ -568,11 +574,7 @@ const INSTANCE_CONFIG_SECTION_APPLIERS = {
},
),
push_relay: createInstanceConfigSectionApplier(
- ({data}) => {
- if (!data.push_relay) return undefined;
- const patch = omitUndefinedFields(data.push_relay);
- return Object.keys(patch).length > 0 ? patch : undefined;
- },
+ ({data}) => nonEmptyPatch(data.push_relay),
async (patch, {ctx, instanceConfigRepository}) => {
const adminUserId = ctx.get('adminUserId').toString();
const landed = await instanceConfigRepository.updatePushRelayConfig((current) => ({
@@ -584,11 +586,7 @@ const INSTANCE_CONFIG_SECTION_APPLIERS = {
},
),
domain_migration: createInstanceConfigSectionApplier(
- ({data}) => {
- if (!data.domain_migration) return undefined;
- const patch = omitUndefinedFields(data.domain_migration);
- return Object.keys(patch).length > 0 ? patch : undefined;
- },
+ ({data}) => nonEmptyPatch(data.domain_migration),
async (patch, {instanceConfigRepository}) => {
await instanceConfigRepository.updateDomainMigrationConfig((current) =>
DomainMigrationConfigSchema.parse({
@@ -600,11 +598,7 @@ const INSTANCE_CONFIG_SECTION_APPLIERS = {
},
),
voice_p2p: createInstanceConfigSectionApplier(
- ({data}) => {
- if (!data.voice_p2p) return undefined;
- const patch = omitUndefinedFields(data.voice_p2p);
- return Object.keys(patch).length > 0 ? patch : undefined;
- },
+ ({data}) => nonEmptyPatch(data.voice_p2p),
async (patch, {instanceConfigRepository}) => {
await instanceConfigRepository.updateVoiceP2pConfig((current) => {
const next = VoiceP2pConfigSchema.parse({...current, ...patch});
@@ -613,11 +607,7 @@ const INSTANCE_CONFIG_SECTION_APPLIERS = {
},
),
captcha: createInstanceConfigSectionApplier(
- ({data}) => {
- if (!data.captcha) return undefined;
- const patch = omitUndefinedFields(data.captcha);
- return Object.keys(patch).length > 0 ? patch : undefined;
- },
+ ({data}) => nonEmptyPatch(data.captcha),
async (patch, {instanceConfigRepository}) => {
await instanceConfigRepository.updateCaptchaConfig(patch);
},
diff --git a/fluxer_api/src/api/admin/controllers/OperatorPassAdminController.ts b/fluxer_api/src/api/admin/controllers/OperatorPassAdminController.ts
index 239978cb8..73c187b84 100644
--- a/fluxer_api/src/api/admin/controllers/OperatorPassAdminController.ts
+++ b/fluxer_api/src/api/admin/controllers/OperatorPassAdminController.ts
@@ -85,6 +85,20 @@ function requireFulfilment(ctx: Context<HonoEnv>): OperatorPassFulfilmentService
return fulfilment;
}
+async function wallStateResponse() {
+ const service = getOperatorPassWallService();
+ const state = await service.publication.loadState();
+ const snapshot = await service.publication.snapshot();
+ return {
+ version: Number(state.wall_version),
+ frozen: state.frozen,
+ frozen_at: state.frozen_at?.toISOString() ?? null,
+ frozen_by: state.frozen_by?.toString() ?? null,
+ published_at: state.published_at?.toISOString() ?? null,
+ entry_count: snapshot.entries.length,
+ };
+}
+
async function sendWallStatement(
ctx: Context<HonoEnv>,
user: User,
@@ -160,7 +174,7 @@ export function OperatorPassAdminController(app: HonoApp) {
}),
async (ctx) => {
const userId = createUserID(ctx.req.valid('param').user_id);
- const user = await requireUser(ctx, userId);
+ const user = await ctx.get('userRepository').findUniqueAssert(userId);
const repository = getOperatorPassRepository();
const [pass, removal, removalHistory, purchases, wallEntry, wallHistory, heldUnits, offers] = await Promise.all([
repository.findOperatorPass(userId),
@@ -238,7 +252,7 @@ export function OperatorPassAdminController(app: HonoApp) {
}),
async (ctx) => {
const userId = createUserID(ctx.req.valid('param').user_id);
- const user = await requireUser(ctx, userId);
+ const user = await ctx.get('userRepository').findUniqueAssert(userId);
const body = ctx.req.valid('json');
const {removal, notified} = await requireFulfilment(ctx).removalService.sendNotice({
user,
@@ -274,7 +288,7 @@ export function OperatorPassAdminController(app: HonoApp) {
}),
async (ctx) => {
const userId = createUserID(ctx.req.valid('param').user_id);
- const user = await requireUser(ctx, userId);
+ const user = await ctx.get('userRepository').findUniqueAssert(userId);
const body = ctx.req.valid('json');
const {removal, notified} = await requireFulfilment(ctx).removalService.remove({
user,
@@ -319,7 +333,7 @@ export function OperatorPassAdminController(app: HonoApp) {
}),
async (ctx) => {
const userId = createUserID(ctx.req.valid('param').user_id);
- await requireUser(ctx, userId);
+ await ctx.get('userRepository').findUniqueAssert(userId);
const restored = await requireFulfilment(ctx).removalService.restore(userId);
await recordAdminWrite(ctx, {
targetType: 'user',
@@ -355,7 +369,7 @@ export function OperatorPassAdminController(app: HonoApp) {
if (!found) {
throw new UnknownOperatorPassPurchaseError();
}
- const purchaser = await requireUser(ctx, found.purchaser_id);
+ const purchaser = await ctx.get('userRepository').findUniqueAssert(found.purchaser_id);
const receivedAt = new Date(body.received_at);
const purchase = await fulfilment.withdraw({
purchaser,
@@ -487,7 +501,7 @@ export function OperatorPassAdminController(app: HonoApp) {
}),
async (ctx) => {
const userId = createUserID(BigInt(ctx.req.valid('param').user_id));
- const user = await requireUser(ctx, userId);
+ const user = await ctx.get('userRepository').findUniqueAssert(userId);
const result = await getOperatorPassWallService().moderation.approve(
userId,
ctx.get('adminUserId'),
@@ -525,7 +539,7 @@ export function OperatorPassAdminController(app: HonoApp) {
}),
async (ctx) => {
const userId = createUserID(BigInt(ctx.req.valid('param').user_id));
- const user = await requireUser(ctx, userId);
+ const user = await ctx.get('userRepository').findUniqueAssert(userId);
const before = await getOperatorPassWallService().getEntry(userId);
const body = ctx.req.valid('json');
if (before?.pending_revision_id?.toString() !== ctx.req.valid('param').revision_id) {
@@ -570,7 +584,7 @@ export function OperatorPassAdminController(app: HonoApp) {
}),
async (ctx) => {
const userId = createUserID(BigInt(ctx.req.valid('param').user_id));
- const user = await requireUser(ctx, userId);
+ const user = await ctx.get('userRepository').findUniqueAssert(userId);
const result = await getOperatorPassWallService().moderation.revert(
userId,
ctx.get('adminUserId'),
@@ -608,7 +622,7 @@ export function OperatorPassAdminController(app: HonoApp) {
}),
async (ctx) => {
const userId = createUserID(ctx.req.valid('param').user_id);
- const user = await requireUser(ctx, userId);
+ const user = await ctx.get('userRepository').findUniqueAssert(userId);
const before = await getOperatorPassWallService().getEntry(userId);
const body = ctx.req.valid('json');
const result = await getOperatorPassWallService().moderation.forceFallback(userId, ctx.get('adminUserId'), {
@@ -651,7 +665,7 @@ export function OperatorPassAdminController(app: HonoApp) {
}),
async (ctx) => {
const userId = createUserID(ctx.req.valid('param').user_id);
- const user = await requireUser(ctx, userId);
+ const user = await ctx.get('userRepository').findUniqueAssert(userId);
const stripe = ctx.get('stripeService').getStripe();
if (!stripe) {
throw new StripePaymentNotAvailableError();
@@ -698,7 +712,7 @@ export function OperatorPassAdminController(app: HonoApp) {
}),
async (ctx) => {
const userId = createUserID(ctx.req.valid('param').user_id);
- const user = await requireUser(ctx, userId);
+ const user = await ctx.get('userRepository').findUniqueAssert(userId);
const body = ctx.req.valid('json');
if (body.hidden && (!body.reason || !body.note)) {
throw new InputValidationError([
@@ -951,17 +965,7 @@ export function OperatorPassAdminController(app: HonoApp) {
action: AdminAuditReadActions.GET_OPERATOR_PASS_WALL_STATE,
metadata: {},
});
- const service = getOperatorPassWallService();
- const state = await service.publication.loadState();
- const snapshot = await service.publication.snapshot();
- return ctx.json({
- version: Number(state.wall_version),
- frozen: state.frozen,
- frozen_at: state.frozen_at?.toISOString() ?? null,
- frozen_by: state.frozen_by?.toString() ?? null,
- published_at: state.published_at?.toISOString() ?? null,
- entry_count: snapshot.entries.length,
- });
+ return ctx.json(await wallStateResponse());
},
);
app.post(
@@ -989,17 +993,7 @@ export function OperatorPassAdminController(app: HonoApp) {
action: frozen ? 'freeze_operator_pass_wall' : 'unfreeze_operator_pass_wall',
metadata: {frozen},
});
- const service = getOperatorPassWallService();
- const state = await service.publication.loadState();
- const snapshot = await service.publication.snapshot();
- return ctx.json({
- version: Number(state.wall_version),
- frozen: state.frozen,
- frozen_at: state.frozen_at?.toISOString() ?? null,
- frozen_by: state.frozen_by?.toString() ?? null,
- published_at: state.published_at?.toISOString() ?? null,
- entry_count: snapshot.entries.length,
- });
+ return ctx.json(await wallStateResponse());
},
);
app.post(
@@ -1025,17 +1019,7 @@ export function OperatorPassAdminController(app: HonoApp) {
action: 'republish_operator_pass_wall',
metadata: {version},
});
- const service = getOperatorPassWallService();
- const state = await service.publication.loadState();
- const snapshot = await service.publication.snapshot();
- return ctx.json({
- version: Number(state.wall_version),
- frozen: state.frozen,
- frozen_at: state.frozen_at?.toISOString() ?? null,
- frozen_by: state.frozen_by?.toString() ?? null,
- published_at: state.published_at?.toISOString() ?? null,
- entry_count: snapshot.entries.length,
- });
+ return ctx.json(await wallStateResponse());
},
);
app.post(
@@ -1057,7 +1041,7 @@ export function OperatorPassAdminController(app: HonoApp) {
}),
async (ctx) => {
const userId = createUserID(ctx.req.valid('param').user_id);
- const user = await requireUser(ctx, userId);
+ const user = await ctx.get('userRepository').findUniqueAssert(userId);
const {held} = ctx.req.valid('json');
const entry = await getOperatorPassWallService().retention.setLegalHold(userId, ctx.get('adminUserId'), held);
await indexWallAudit(
diff --git a/fluxer_api/src/api/admin/controllers/SsoIdentityAdminController.ts b/fluxer_api/src/api/admin/controllers/SsoIdentityAdminController.ts
index 81260b1fc..2c15ebe3a 100644
--- a/fluxer_api/src/api/admin/controllers/SsoIdentityAdminController.ts
+++ b/fluxer_api/src/api/admin/controllers/SsoIdentityAdminController.ts
@@ -59,10 +59,7 @@ export function SsoIdentityAdminController(app: HonoApp) {
}),
async (ctx) => {
const userId = createUserID(ctx.req.valid('param').user_id);
- const user = await ctx.get('userRepository').findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ await ctx.get('userRepository').findUniqueAssert(userId);
const identities = await ssoIdentityRepository.listForUser(userId);
await recordAdminRead(ctx, {
targetType: 'user',
@@ -118,10 +115,7 @@ export function SsoIdentityAdminController(app: HonoApp) {
}),
async (ctx) => {
const userId = createUserID(ctx.req.valid('param').user_id);
- const user = await ctx.get('userRepository').findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await ctx.get('userRepository').findUniqueAssert(userId);
const providerId = await currentProviderId();
const identities = await new SsoIdentityLinkService(ctx.get('userRepository')).link(
user,
@@ -156,10 +150,7 @@ export function SsoIdentityAdminController(app: HonoApp) {
}),
async (ctx) => {
const userId = createUserID(ctx.req.valid('param').user_id);
- const user = await ctx.get('userRepository').findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await ctx.get('userRepository').findUniqueAssert(userId);
const before = await ssoIdentityRepository.listForUser(userId);
const identities = await new SsoIdentityLinkService(ctx.get('userRepository')).unlink(
user,
diff --git a/fluxer_api/src/api/admin/controllers/StoreBillingAdminController.ts b/fluxer_api/src/api/admin/controllers/StoreBillingAdminController.ts
index d16c6aec3..ded6c5eec 100644
--- a/fluxer_api/src/api/admin/controllers/StoreBillingAdminController.ts
+++ b/fluxer_api/src/api/admin/controllers/StoreBillingAdminController.ts
@@ -2,26 +2,18 @@
import {AdminAuditReadActions} from '@app/api/admin/AdminAuditActions';
import {recordAdminRead, recordAdminWrite} from '@app/api/admin/AdminAuditRecorder';
-import {createUserID, type UserID} from '@app/api/BrandedTypes';
+import {createUserID} from '@app/api/BrandedTypes';
import {requireAdminACL} from '@app/api/middleware/AdminMiddleware';
import {HostedOnlyRoute} from '@app/api/middleware/BillingRouteAvailability';
import {RateLimitMiddleware} from '@app/api/middleware/RateLimitMiddleware';
import {OpenAPI} from '@app/api/middleware/ResponseTypeMiddleware';
import {RateLimitConfigs} from '@app/api/RateLimitConfig';
import {mapStorePurchaseToAdminResponse} from '@app/api/store_billing/StoreBillingMappers';
-import type {HonoApp, HonoEnv} from '@app/api/types/HonoEnv';
+import type {HonoApp} from '@app/api/types/HonoEnv';
import {Validator} from '@app/api/Validator';
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
-import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';
import {AdminStorePurchaseListResponse} from '@fluxer/schema/src/domains/admin/AdminStoreBillingSchemas';
import {UserIdParam} from '@fluxer/schema/src/domains/common/CommonParamSchemas';
-import type {Context} from 'hono';
-
-async function requireUser(ctx: Context<HonoEnv>, userId: UserID): Promise<void> {
- if (!(await ctx.get('userRepository').findUnique(userId))) {
- throw new UnknownUserError();
- }
-}
export function StoreBillingAdminController(app: HonoApp) {
app.get(
@@ -42,7 +34,7 @@ export function StoreBillingAdminController(app: HonoApp) {
}),
async (ctx) => {
const userId = createUserID(ctx.req.valid('param').user_id);
- await requireUser(ctx, userId);
+ await ctx.get('userRepository').findUniqueAssert(userId);
const rows = await ctx.get('storeEntitlementService').listStorePurchases(userId);
await recordAdminRead(ctx, {
targetType: 'user',
@@ -71,7 +63,7 @@ export function StoreBillingAdminController(app: HonoApp) {
}),
async (ctx) => {
const userId = createUserID(ctx.req.valid('param').user_id);
- await requireUser(ctx, userId);
+ await ctx.get('userRepository').findUniqueAssert(userId);
const storeEntitlementService = ctx.get('storeEntitlementService');
const rows = await storeEntitlementService.listStorePurchases(userId);
for (const row of rows) {
diff --git a/fluxer_api/src/api/admin/services/AdminApplicationService.ts b/fluxer_api/src/api/admin/services/AdminApplicationService.ts
index 61e6800d4..c094081d0 100644
--- a/fluxer_api/src/api/admin/services/AdminApplicationService.ts
+++ b/fluxer_api/src/api/admin/services/AdminApplicationService.ts
@@ -8,7 +8,6 @@ import type {Application} from '@app/api/models/Application';
import type {ApplicationRepository} from '@app/api/oauth/repositories/ApplicationRepository';
import {UnknownGuildError} from '@fluxer/errors/src/domains/guild/UnknownGuildError';
import {UnknownApplicationError} from '@fluxer/errors/src/domains/oauth/UnknownApplicationError';
-import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';
import type {
ApplicationAdminResponse,
ListApplicationsResponse,
@@ -47,10 +46,7 @@ export class AdminApplicationService {
async listUserApplications(ownerUserId: UserID): Promise<ListApplicationsResponse> {
const {applicationRepository} = this.deps;
const {users: userRepository} = this.deps.apiContext.services;
- const owner = await userRepository.findUnique(ownerUserId);
- if (!owner) {
- throw new UnknownUserError();
- }
+ const owner = await userRepository.findUniqueAssert(ownerUserId);
const applications = await applicationRepository.listApplicationsByOwner(ownerUserId);
const ownerDisplay: UserDisplay = {
username: owner.username,
@@ -105,10 +101,7 @@ export class AdminApplicationService {
throw new UnknownApplicationError();
}
const newOwnerId = createUserID(data.new_owner_id);
- const newOwner = await userRepository.findUnique(newOwnerId);
- if (!newOwner) {
- throw new UnknownUserError();
- }
+ await userRepository.findUniqueAssert(newOwnerId);
const oldOwnerId = application.ownerUserId;
const oldRow = application.toRow();
const updatedApplication = await applicationRepository.upsertApplication(
diff --git a/fluxer_api/src/api/admin/services/AdminArchiveService.ts b/fluxer_api/src/api/admin/services/AdminArchiveService.ts
index b17d06930..382997cd0 100644
--- a/fluxer_api/src/api/admin/services/AdminArchiveService.ts
+++ b/fluxer_api/src/api/admin/services/AdminArchiveService.ts
@@ -45,19 +45,15 @@ export class AdminArchiveService {
return new Date(Date.now() + ARCHIVE_RETENTION_DAYS * ms('1 day'));
}
- async triggerUserArchive(
- targetUserId: UserID,
+ private async createQueuedArchive(
+ subjectType: ArchiveSubjectType,
+ subjectId: bigint,
requestedBy: UserID,
- includeAttachments: boolean,
- ): Promise<AdminArchiveResponse> {
- const user = await this.userRepository.findUnique(targetUserId);
- if (!user) {
- throw new UnknownUserError();
- }
+ ): Promise<AdminArchive> {
const archiveId = await this.snowflakeService.generate();
const archive = new AdminArchive({
- subject_type: 'user',
- subject_id: targetUserId,
+ subject_type: subjectType,
+ subject_id: subjectId,
archive_id: archiveId,
requested_by: requestedBy,
requested_at: new Date(),
@@ -73,6 +69,16 @@ export class AdminArchiveService {
expires_at: this.computeExpiry(),
});
await this.adminArchiveRepository.create(archive);
+ return archive;
+ }
+
+ async triggerUserArchive(
+ targetUserId: UserID,
+ requestedBy: UserID,
+ includeAttachments: boolean,
+ ): Promise<AdminArchiveResponse> {
+ await this.userRepository.findUniqueAssert(targetUserId);
+ const archive = await this.createQueuedArchive('user', targetUserId, requestedBy);
await this.workerService.addJob('harvestUserData', {
userId: targetUserId.toString(),
harvestId: archive.archiveId.toString(),
@@ -91,25 +97,7 @@ export class AdminArchiveService {
if (!guild) {
throw new UnknownGuildError();
}
- const archiveId = await this.snowflakeService.generate();
- const archive = new AdminArchive({
- subject_type: 'guild',
- subject_id: targetGuildId,
- archive_id: archiveId,
- requested_by: requestedBy,
- requested_at: new Date(),
- started_at: null,
- completed_at: null,
- failed_at: null,
- storage_key: null,
- file_size: null,
- progress_percent: 0,
- progress_step: 'Queued',
- error_message: null,
- download_url_expires_at: null,
- expires_at: this.computeExpiry(),
- });
- await this.adminArchiveRepository.create(archive);
+ const archive = await this.createQueuedArchive('guild', targetGuildId, requestedBy);
await this.workerService.addJob('harvestGuildData', {
guildId: targetGuildId.toString(),
archiveId: archive.archiveId.toString(),
diff --git a/fluxer_api/src/api/admin/services/AdminBanManagementService.ts b/fluxer_api/src/api/admin/services/AdminBanManagementService.ts
index 1d57ebcae..15c7450a9 100644
--- a/fluxer_api/src/api/admin/services/AdminBanManagementService.ts
+++ b/fluxer_api/src/api/admin/services/AdminBanManagementService.ts
@@ -651,8 +651,7 @@ export class AdminBanManagementService {
}> {
const {users: userRepository} = this.deps.apiContext.services;
const userId = createUserID(BigInt(data.user_id));
- const user = await userRepository.findUnique(userId);
- if (!user) throw new UnknownUserError();
+ const user = await userRepository.findUniqueAssert(userId);
const avatar = user.avatarHash;
if (!avatar) {
throw new NotFoundError({code: APIErrorCodes.NOT_FOUND});
diff --git a/fluxer_api/src/api/admin/services/AdminMessageDeletionService.ts b/fluxer_api/src/api/admin/services/AdminMessageDeletionService.ts
index 2d64711ac..7e9e12005 100644
--- a/fluxer_api/src/api/admin/services/AdminMessageDeletionService.ts
+++ b/fluxer_api/src/api/admin/services/AdminMessageDeletionService.ts
@@ -8,10 +8,8 @@ import type {ChannelRepository} from '@app/api/channel/ChannelRepository';
import type {EnforcementDecisionRow} from '@app/api/database/types/EnforcementTypes';
import type {EnforcementActor} from '@app/api/enforcement/EnforcementActor';
import {decisionAuditMetadata, type EnforcementDecisionService} from '@app/api/enforcement/EnforcementDecisionService';
-import type {User} from '@app/api/models/User';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
-import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';
import type {DeleteAllUserMessagesResponse} from '@fluxer/schema/src/domains/admin/AdminMessageSchemas';
import type {ModerationBasis} from '@fluxer/schema/src/domains/admin/EnforcementSchemas';
@@ -55,7 +53,7 @@ export class AdminMessageDeletionService {
if (basis.type === 'enforcement') {
({decision} = await this.deps.enforcement.record(
{
- subject: {type: 'user', user: await this.requireUser(userId)},
+ subject: {type: 'user', user: await this.deps.apiContext.services.users.findUniqueAssert(userId)},
kind: 'content_removal',
input: basis.decision,
removal: {type: 'all_messages'},
@@ -87,14 +85,6 @@ export class AdminMessageDeletionService {
return response;
}
- private async requireUser(userId: UserID): Promise<User> {
- const user = await this.deps.apiContext.services.users.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
- return user;
- }
-
private async collectMessageRefs(authorId: UserID, includeEntries: boolean) {
let lastMessageId: MessageID | undefined;
const entries: Array<{
diff --git a/fluxer_api/src/api/admin/services/AdminMessageShredService.ts b/fluxer_api/src/api/admin/services/AdminMessageShredService.ts
index b2d5660ed..85b07b7ba 100644
--- a/fluxer_api/src/api/admin/services/AdminMessageShredService.ts
+++ b/fluxer_api/src/api/admin/services/AdminMessageShredService.ts
@@ -7,7 +7,6 @@ import type {EnforcementDecisionRow} from '@app/api/database/types/EnforcementTy
import type {EnforcementActor} from '@app/api/enforcement/EnforcementActor';
import {decisionAuditMetadata, type EnforcementDecisionService} from '@app/api/enforcement/EnforcementDecisionService';
import {Logger} from '@app/api/Logger';
-import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';
import type {
AdminUserMessageShredRequest,
MessageShredResponse,
@@ -87,10 +86,7 @@ export class AdminMessageShredService {
};
let decision: EnforcementDecisionRow | null = null;
if (basis.type === 'enforcement') {
- const user = await apiContext.services.users.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await apiContext.services.users.findUniqueAssert(userId);
({decision} = await enforcement.record(
{
subject: {type: 'user', user},
diff --git a/fluxer_api/src/api/admin/services/AdminUserBanService.ts b/fluxer_api/src/api/admin/services/AdminUserBanService.ts
index 86c1acc38..0fc229a6e 100644
--- a/fluxer_api/src/api/admin/services/AdminUserBanService.ts
+++ b/fluxer_api/src/api/admin/services/AdminUserBanService.ts
@@ -15,13 +15,11 @@ import {setFeatureLimit} from '@app/api/enforcement/FeatureLimitState';
import {permanentSuspensionEnd} from '@app/api/enforcement/NoticeDates';
import {applySuspension, liftSuspension} from '@app/api/enforcement/SuspensionState';
import {emitAdminAction} from '@app/api/infrastructure/activity/AccountChangeEvents';
-import type {User} from '@app/api/models/User';
import {isAccountClosed, isTemporarilyBanned} from '@app/api/user/UserHelpers';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
import {EnforcementAccountClosedError} from '@fluxer/errors/src/domains/moderation/EnforcementAccountClosedError';
import {EnforcementDecisionOwnsStateError} from '@fluxer/errors/src/domains/moderation/EnforcementDecisionOwnsStateError';
-import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';
import type {
AdminUserBanRequest,
AdminUserFeatureLimitRequest,
@@ -57,17 +55,9 @@ function featureLimitEnd(data: AdminUserFeatureLimitRequest, now: Date): Date |
export class AdminUserBanService {
constructor(private readonly deps: AdminUserBanServiceDeps) {}
- private async requireUser(userId: UserID): Promise<User> {
- const user = await this.deps.apiContext.services.users.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
- return user;
- }
-
async tempBanUser(userId: UserID, data: AdminUserBanRequest, actor: EnforcementActor) {
const {auditService, enforcement} = this.deps;
- const user = await this.requireUser(userId);
+ const user = await this.deps.apiContext.services.users.findUniqueAssert(userId);
if (isAccountClosed(user)) {
throw new EnforcementAccountClosedError();
}
@@ -112,7 +102,7 @@ export class AdminUserBanService {
}
async warnUser(userId: UserID, data: AdminUserWarningRequest, actor: EnforcementActor) {
- const user = await this.requireUser(userId);
+ const user = await this.deps.apiContext.services.users.findUniqueAssert(userId);
const {decision} = await this.deps.enforcement.record(
{subject: {type: 'user', user}, kind: 'warning', input: data.decision, actor},
async () => {},
@@ -129,7 +119,7 @@ export class AdminUserBanService {
}
async limitFeatures(userId: UserID, data: AdminUserFeatureLimitRequest, actor: EnforcementActor) {
- const user = await this.requireUser(userId);
+ const user = await this.deps.apiContext.services.users.findUniqueAssert(userId);
const endsAt = featureLimitEnd(data, new Date());
let limited = user;
const {decision} = await this.deps.enforcement.record(
@@ -155,7 +145,7 @@ export class AdminUserBanService {
async unbanUser(userId: UserID, actor: EnforcementActor) {
const {auditService, delivery} = this.deps;
- const user = await this.requireUser(userId);
+ const user = await this.deps.apiContext.services.users.findUniqueAssert(userId);
if (user.enforcementDecisionId !== null) {
throw new EnforcementDecisionOwnsStateError(user.enforcementDecisionId);
}
diff --git a/fluxer_api/src/api/admin/services/AdminUserDeletionService.ts b/fluxer_api/src/api/admin/services/AdminUserDeletionService.ts
index f3dcbc965..b362ec00f 100644
--- a/fluxer_api/src/api/admin/services/AdminUserDeletionService.ts
+++ b/fluxer_api/src/api/admin/services/AdminUserDeletionService.ts
@@ -153,7 +153,7 @@ export class AdminUserDeletionService {
actor: EnforcementActor,
): Promise<{user: User; skippedNetworks: Array<SkippedNetwork>}> {
const {basis} = request;
- const user = await this.requireUser(userId);
+ const user = await this.deps.apiContext.services.users.findUniqueAssert(userId);
if (
user.pendingDeletionAt &&
(!request.replace_pending_deletion_at ||
@@ -266,7 +266,7 @@ export class AdminUserDeletionService {
async cancelAccountDeletion(userId: UserID, data: AdminUserDeletionCancelRequest, actor: EnforcementActor) {
const {cache} = this.deps.apiContext.services;
- const user = await this.requireUser(userId);
+ const user = await this.deps.apiContext.services.users.findUniqueAssert(userId);
if (!user.pendingDeletionAt) {
throw new NoPendingDeletionError();
}
diff --git a/fluxer_api/src/api/admin/services/AdminUserProfileService.ts b/fluxer_api/src/api/admin/services/AdminUserProfileService.ts
index 428aa760c..9585c62fe 100644
--- a/fluxer_api/src/api/admin/services/AdminUserProfileService.ts
+++ b/fluxer_api/src/api/admin/services/AdminUserProfileService.ts
@@ -83,10 +83,7 @@ export class AdminUserProfileService {
async clearUserFields(userId: UserID, {fields, basis}: AdminUserClearFieldsRequest, actor: EnforcementActor) {
const {users: userRepository, cache: cacheService} = this.deps.apiContext.services;
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await userRepository.findUniqueAssert(userId);
const resetFields = [...new Set(fields)];
let updatedUser = user;
const clear = async () => {
@@ -159,10 +156,7 @@ export class AdminUserProfileService {
const {users: userRepository, cache: cacheService} = this.deps.apiContext.services;
const {auditService, userUpdateDeps} = this.deps;
const userId = createUserID(data.user_id);
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await userRepository.findUniqueAssert(userId);
if (data.bot && user.acls.size > 0) {
throw new AccessDeniedError();
}
@@ -194,10 +188,7 @@ export class AdminUserProfileService {
const {users: userRepository, cache: cacheService} = this.deps.apiContext.services;
const {auditService, userUpdateDeps} = this.deps;
const userId = createUserID(data.user_id);
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await userRepository.findUniqueAssert(userId);
if (data.system && !user.isBot) {
throw InputValidationError.fromCode(
'system',
@@ -228,10 +219,7 @@ export class AdminUserProfileService {
const {users: userRepository, cache: cacheService} = this.deps.apiContext.services;
const {auditService, userUpdateDeps} = this.deps;
const userId = createUserID(data.user_id);
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await userRepository.findUniqueAssert(userId);
const updatedUser = await confirmEmailOwnership(this.deps.apiContext, user);
await propagateUserUpdate(userUpdateDeps, user, updatedUser);
await enqueueStripeCustomerEmailSync(this.deps.apiContext.services.worker, user, updatedUser);
@@ -261,10 +249,7 @@ export class AdminUserProfileService {
} = this.deps.apiContext.services;
const {discriminatorService, auditService, userUpdateDeps} = this.deps;
const userId = createUserID(data.user_id);
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await userRepository.findUniqueAssert(userId);
const uniqueUsernames = !user.isBot && (await getInstanceConfigRepository().usesUniqueUsernames());
if (uniqueUsernames) {
assertNoDiscriminatorChange(data.discriminator, user.discriminator);
@@ -335,10 +320,7 @@ export class AdminUserProfileService {
} = this.deps.apiContext.services;
const {auditService, userUpdateDeps} = this.deps;
const userId = createUserID(data.user_id);
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await userRepository.findUniqueAssert(userId);
const updatedUser = await userRepository.patchUpsert(
userId,
{
@@ -394,10 +376,7 @@ export class AdminUserProfileService {
const {users: userRepository, cache: cacheService} = this.deps.apiContext.services;
const {auditService, userUpdateDeps} = this.deps;
const userId = createUserID(data.user_id);
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await userRepository.findUniqueAssert(userId);
const traits = user.traits;
traits.delete(DOB_DEFERRED_TRAIT);
const clearedBelowMinimumAge = traits.delete(BELOW_MINIMUM_AGE_TRAIT);
diff --git a/fluxer_api/src/api/admin/services/AdminUserRelationshipService.ts b/fluxer_api/src/api/admin/services/AdminUserRelationshipService.ts
index 6ac059cdd..dbe95407f 100644
--- a/fluxer_api/src/api/admin/services/AdminUserRelationshipService.ts
+++ b/fluxer_api/src/api/admin/services/AdminUserRelationshipService.ts
@@ -43,10 +43,7 @@ export class AdminUserRelationshipService {
async listRelationships(data: ListUserRelationshipsRequest): Promise<ListUserRelationshipsResponse> {
const {users: userRepository} = this.deps.apiContext.services;
const userId = createUserID(data.user_id);
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ await userRepository.findUniqueAssert(userId);
const relationships = await userRepository.listRelationships(userId);
const targetUserIds = new Set<UserID>();
for (const rel of relationships) {
@@ -99,10 +96,7 @@ export class AdminUserRelationshipService {
const {users: userRepository} = this.deps.apiContext.services;
const userId = createUserID(data.user_id);
const targetUserId = createUserID(data.target_user_id);
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ await userRepository.findUniqueAssert(userId);
const type = CATEGORY_TO_TYPE[data.category];
const relationship = await userRepository.getRelationship(userId, targetUserId, type);
if (!relationship) {
@@ -130,10 +124,7 @@ export class AdminUserRelationshipService {
const {auditService} = this.deps;
const {users: userRepository} = this.deps.apiContext.services;
const userId = createUserID(data.user_id);
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ await userRepository.findUniqueAssert(userId);
const type = CATEGORY_TO_TYPE[data.category];
const allRelationships = await userRepository.listRelationships(userId);
const matching: Array<Relationship> = allRelationships.filter((rel) => rel.type === type);
@@ -165,59 +156,32 @@ export class AdminUserRelationshipService {
}): Promise<void> {
const {users: userRepository, gateway: gatewayService} = this.deps.apiContext.services;
switch (category) {
- case 'friend': {
+ case 'friend':
await this.deps.userRelationshipService.endFriendship(userId, targetUserId);
- await gatewayService.dispatchPresence({
- userId,
- event: 'RELATIONSHIP_REMOVE',
- data: {id: targetUserId.toString()},
- });
- await gatewayService.dispatchPresence({
- userId: targetUserId,
- event: 'RELATIONSHIP_REMOVE',
- data: {id: userId.toString()},
- });
- return;
- }
- case 'outgoing_request': {
+ break;
+ case 'outgoing_request':
await userRepository.deleteRelationship(userId, targetUserId, RelationshipTypes.OUTGOING_REQUEST);
await userRepository.deleteRelationship(targetUserId, userId, RelationshipTypes.INCOMING_REQUEST);
- await gatewayService.dispatchPresence({
- userId,
- event: 'RELATIONSHIP_REMOVE',
- data: {id: targetUserId.toString()},
- });
- await gatewayService.dispatchPresence({
- userId: targetUserId,
- event: 'RELATIONSHIP_REMOVE',
- data: {id: userId.toString()},
- });
- return;
- }
- case 'incoming_request': {
+ break;
+ case 'incoming_request':
await userRepository.deleteRelationship(userId, targetUserId, RelationshipTypes.INCOMING_REQUEST);
await userRepository.deleteRelationship(targetUserId, userId, RelationshipTypes.OUTGOING_REQUEST);
- await gatewayService.dispatchPresence({
- userId,
- event: 'RELATIONSHIP_REMOVE',
- data: {id: targetUserId.toString()},
- });
- await gatewayService.dispatchPresence({
- userId: targetUserId,
- event: 'RELATIONSHIP_REMOVE',
- data: {id: userId.toString()},
- });
- return;
- }
- case 'blocked': {
+ break;
+ case 'blocked':
await userRepository.deleteRelationship(userId, targetUserId, RelationshipTypes.BLOCKED);
- await gatewayService.dispatchPresence({
- userId,
- event: 'RELATIONSHIP_REMOVE',
- data: {id: targetUserId.toString()},
- });
- return;
- }
+ break;
+ }
+ await gatewayService.dispatchPresence({
+ userId,
+ event: 'RELATIONSHIP_REMOVE',
+ data: {id: targetUserId.toString()},
+ });
+ if (category !== 'blocked') {
+ await gatewayService.dispatchPresence({
+ userId: targetUserId,
+ event: 'RELATIONSHIP_REMOVE',
+ data: {id: userId.toString()},
+ });
}
}
}
diff --git a/fluxer_api/src/api/admin/services/AdminUserSecurityService.ts b/fluxer_api/src/api/admin/services/AdminUserSecurityService.ts
index 4d1ffda56..649fcee3f 100644
--- a/fluxer_api/src/api/admin/services/AdminUserSecurityService.ts
+++ b/fluxer_api/src/api/admin/services/AdminUserSecurityService.ts
@@ -201,10 +201,7 @@ export class AdminUserSecurityService {
}) {
const {users: userRepository, cache: cacheService} = this.deps.apiContext.services;
const {auditService, userUpdateDeps} = this.deps;
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await userRepository.findUniqueAssert(userId);
await assertUserFlagUpdateAllowed(user, data.addFlags, data.removeFlags);
let previousFlags = 0n;
const updatedUser = await userRepository.updateFlags(userId, (flags) => {
@@ -257,10 +254,7 @@ export class AdminUserSecurityService {
}) {
const {users: userRepository, cache: cacheService} = this.deps.apiContext.services;
const {auditService, userUpdateDeps} = this.deps;
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await userRepository.findUniqueAssert(userId);
await assertPremiumFlagUpdateAllowed(user, data.addFlags, data.removeFlags);
const newPremiumFlags = applyNumberFlagUpdates(user.premiumFlags, data.addFlags, data.removeFlags);
const updatedUser = await userRepository.patchUpsert(
@@ -292,10 +286,7 @@ export class AdminUserSecurityService {
const {users: userRepository, botMfaMirror: botMfaMirrorService} = this.deps.apiContext.services;
const {auditService, userUpdateDeps} = this.deps;
const userId = createUserID(data.user_id);
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await userRepository.findUniqueAssert(userId);
const updatedUser = await userRepository.patchUpsert(
userId,
{
@@ -323,10 +314,7 @@ export class AdminUserSecurityService {
const {users: userRepository, email: emailService} = this.deps.apiContext.services;
const {auditService} = this.deps;
const userId = createUserID(data.user_id);
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await userRepository.findUniqueAssert(userId);
if (!user.email) {
throw InputValidationError.fromCode('email', ValidationErrorCodes.USER_DOES_NOT_HAVE_AN_EMAIL_ADDRESS);
}
@@ -356,10 +344,7 @@ export class AdminUserSecurityService {
const {users: userRepository} = this.deps.apiContext.services;
const {apiContext, auditService} = this.deps;
const userId = createUserID(data.user_id);
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await userRepository.findUniqueAssert(userId);
AuthUtility.assertNonBotUser(apiContext, user);
requireGrantedAdminACLs(acls, user.acls);
const token = createPasswordResetToken(await RandomUtils.randomString(64));
@@ -393,10 +378,7 @@ export class AdminUserSecurityService {
): Promise<void> {
const {users: userRepository} = this.deps.apiContext.services;
const userId = createUserID(data.user_id);
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await userRepository.findUniqueAssert(userId);
requireGrantedAdminACLs(acls, user.acls);
await new RecoveryKitRepository().delete(userId);
await this.deps.auditService.createAuditLog({
@@ -417,10 +399,7 @@ export class AdminUserSecurityService {
const {users: userRepository} = this.deps.apiContext.services;
const {apiContext, auditService} = this.deps;
const userId = createUserID(data.user_id);
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await userRepository.findUniqueAssert(userId);
if (!user.email) {
throw InputValidationError.fromCode('email', ValidationErrorCodes.USER_DOES_NOT_HAVE_AN_EMAIL_ADDRESS);
}
@@ -439,10 +418,7 @@ export class AdminUserSecurityService {
const {users: userRepository} = this.deps.apiContext.services;
const {auditService} = this.deps;
const userId = createUserID(data.user_id);
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ await userRepository.findUniqueAssert(userId);
const terminatedCount = await revokeAllAuthSessions(this.deps.apiContext.services, userId);
await auditService.createAuditLog({
adminUserId,
@@ -467,10 +443,7 @@ export class AdminUserSecurityService {
if (userId === adminUserId) {
throw new AccessDeniedError();
}
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await userRepository.findUniqueAssert(userId);
requireGrantedAdminACLs(acls, data.acls);
const updatedUser = await userRepository.patchUpsert(
userId,
@@ -502,10 +475,7 @@ export class AdminUserSecurityService {
const {users: userRepository, cache: cacheService} = this.deps.apiContext.services;
const {auditService, userUpdateDeps} = this.deps;
const userId = createUserID(data.user_id);
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await userRepository.findUniqueAssert(userId);
const assigned = resolveAssignedTraits(user.traits ?? [], data.traits);
const traitSet = assigned.size > 0 ? assigned : null;
const updatedUser = await userRepository.patchUpsert(
@@ -537,10 +507,7 @@ export class AdminUserSecurityService {
const {users: userRepository} = this.deps.apiContext.services;
const {auditService} = this.deps;
const userId = createUserID(data.user_id);
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ await userRepository.findUniqueAssert(userId);
const credentials = visibleWebAuthnCredentials(await userRepository.listWebAuthnCredentials(userId));
await auditService.createAuditLog({
adminUserId,
@@ -563,10 +530,7 @@ export class AdminUserSecurityService {
const {users: userRepository} = this.deps.apiContext.services;
const {apiContext, auditService} = this.deps;
const userId = createUserID(data.user_id);
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ await userRepository.findUniqueAssert(userId);
const credential = await userRepository.getWebAuthnCredential(userId, data.credential_id);
if (!credential) {
throw new UnknownUserError();
@@ -591,10 +555,7 @@ export class AdminUserSecurityService {
const {users: userRepository, cache: cacheService} = this.deps.apiContext.services;
const {auditService} = this.deps;
const userIdTyped = createUserID(userId);
- const user = await userRepository.findUnique(userIdTyped);
- if (!user) {
- throw new UnknownUserError();
- }
+ await userRepository.findUniqueAssert(userIdTyped);
const [activeSessions, tombstones] = await Promise.all([
userRepository.listAuthSessions(userIdTyped),
userRepository.listAuthSessionTombstones(userIdTyped),
diff --git a/fluxer_api/src/api/admin/services/AdminUserService.ts b/fluxer_api/src/api/admin/services/AdminUserService.ts
index 7f44e392c..cebb7e669 100644
--- a/fluxer_api/src/api/admin/services/AdminUserService.ts
+++ b/fluxer_api/src/api/admin/services/AdminUserService.ts
@@ -128,10 +128,7 @@ export class AdminUserService {
async listUserDmChannels(data: ListUserDmChannelsRequest) {
const userId = createUserID(data.user_id);
- const user = await this.userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ await this.userRepository.findUniqueAssert(userId);
const channels = await this.userRepository.listHistoricalDmChannelsPaginated(userId, {
limit: data.limit,
beforeChannelId: data.before ? createChannelID(data.before) : undefined,
@@ -194,10 +191,7 @@ export class AdminUserService {
async listUserGroupDmChannels(data: ListUserGroupDmChannelsRequest) {
const userId = createUserID(data.user_id);
- const user = await this.userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ await this.userRepository.findUniqueAssert(userId);
const summaries = await this.userRepository.listPrivateChannelSummaries(userId);
const groupDmSummaries = summaries.filter((s) => s.isGroupDm);
if (groupDmSummaries.length === 0) {
@@ -278,10 +272,7 @@ export class AdminUserService {
acls: ReadonlySet<string>,
) {
const userId = createUserID(data.user_id);
- const user = await this.userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await this.userRepository.findUniqueAssert(userId);
const updatedUser = await this.userRepository.patchUpsert(
userId,
{
diff --git a/fluxer_api/src/api/admin/services/guild/AdminGuildLookupService.ts b/fluxer_api/src/api/admin/services/guild/AdminGuildLookupService.ts
index d4b8ee779..e9b026f20 100644
--- a/fluxer_api/src/api/admin/services/guild/AdminGuildLookupService.ts
+++ b/fluxer_api/src/api/admin/services/guild/AdminGuildLookupService.ts
@@ -11,7 +11,6 @@ import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import {MEDIA_PROXY_ICON_SIZE_DEFAULT} from '@fluxer/constants/src/MediaProxyAssetSizes';
import type {MediaProxyImageSize} from '@fluxer/constants/src/MediaProxyImageSizes';
-import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';
import type {
ListGuildMembersRequest,
ListUserGuildsRequest,
@@ -98,10 +97,7 @@ export class AdminGuildLookupService {
async listUserGuilds(data: ListUserGuildsRequest) {
const {userRepository, guildRepository, gatewayService} = this.deps;
const userId = createUserID(data.user_id);
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ await userRepository.findUniqueAssert(userId);
let guildIds = await userRepository.getUserGuildIds(userId);
guildIds.sort((a, b) => {
if (a < b) return -1;
diff --git a/fluxer_api/src/api/admin/services/guild/AdminGuildMembershipService.ts b/fluxer_api/src/api/admin/services/guild/AdminGuildMembershipService.ts
index 5e0ea5e65..7d9711e79 100644
--- a/fluxer_api/src/api/admin/services/guild/AdminGuildMembershipService.ts
+++ b/fluxer_api/src/api/admin/services/guild/AdminGuildMembershipService.ts
@@ -7,7 +7,6 @@ import type {RequestCache} from '@app/api/middleware/RequestCacheMiddleware';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
import {JoinSourceTypes} from '@fluxer/constants/src/GuildConstants';
-import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';
import type {
BanGuildMemberRequest,
ForceAddUserToGuildRequest,
@@ -41,10 +40,7 @@ export class AdminGuildMembershipService {
const {userRepository, guildService, auditService} = this.deps;
const userId = createUserID(data.user_id);
const guildId = createGuildID(data.guild_id);
- const user = await userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ await userRepository.findUniqueAssert(userId);
await guildService.members.addUserToGuild({
userId,
guildId,
diff --git a/fluxer_api/src/api/auth/AuthLogin.ts b/fluxer_api/src/api/auth/AuthLogin.ts
index bd1d3943b..d6c70821b 100644
--- a/fluxer_api/src/api/auth/AuthLogin.ts
+++ b/fluxer_api/src/api/auth/AuthLogin.ts
@@ -209,10 +209,7 @@ export async function completeIpAuthorization(
if (!payload) {
throw InputValidationError.fromCode('token', ValidationErrorCodes.INVALID_OR_EXPIRED_AUTHORIZATION_TOKEN);
}
- const user = await users.findUnique(createUserID(BigInt(payload.userId)));
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await users.findUniqueAssert(createUserID(BigInt(payload.userId)));
if (user.passwordLastChangedAt !== null && payload.createdAt < user.passwordLastChangedAt.getTime()) {
await cache.delete(cacheKey);
await cache.delete(getTokenCacheKey(token));
diff --git a/fluxer_api/src/api/auth/AuthRequestService.ts b/fluxer_api/src/api/auth/AuthRequestService.ts
index cbf661c2b..9b2e441e1 100644
--- a/fluxer_api/src/api/auth/AuthRequestService.ts
+++ b/fluxer_api/src/api/auth/AuthRequestService.ts
@@ -509,10 +509,7 @@ export class AuthRequestService {
}
private async getUserPartial(userId: string): Promise<UserPartialResponse> {
- const user = await this.apiContext.services.users.findUnique(createUserID(BigInt(userId)));
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await this.apiContext.services.users.findUniqueAssert(createUserID(BigInt(userId)));
return mapUserToPartialResponse(user);
}
diff --git a/fluxer_api/src/api/auth/AuthSession.ts b/fluxer_api/src/api/auth/AuthSession.ts
index e84ae2398..c00c6542a 100644
--- a/fluxer_api/src/api/auth/AuthSession.ts
+++ b/fluxer_api/src/api/auth/AuthSession.ts
@@ -120,10 +120,7 @@ export async function createAdditionalAuthSessionFromToken(
throw new InvalidTokenError();
}
const {users} = ctx.services;
- const user = await users.findUnique(existingSession.userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await users.findUniqueAssert(existingSession.userId);
if (expectedUserId && user.id.toString() !== expectedUserId) {
throw new SessionTokenMismatchError();
}
diff --git a/fluxer_api/src/api/auth/SignInLinks.ts b/fluxer_api/src/api/auth/SignInLinks.ts
index 7f57066c7..843a58890 100644
--- a/fluxer_api/src/api/auth/SignInLinks.ts
+++ b/fluxer_api/src/api/auth/SignInLinks.ts
@@ -42,10 +42,7 @@ export async function createSignInLink(
auditService: AdminAuditService,
args: {userId: UserID; adminUserId: UserID; auditLogReason: string | null},
): Promise<AdminSignInLinkResponse> {
- const user = await ctx.services.users.findUnique(args.userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await ctx.services.users.findUniqueAssert(args.userId);
AuthUtility.assertNonBotUser(ctx, user);
if (!isAdmin(user.acls)) {
throw new MissingACLError(AdminACLs.WILDCARD);
diff --git a/fluxer_api/src/api/channel/controllers/MessageInteractionController.ts b/fluxer_api/src/api/channel/controllers/MessageInteractionController.ts
index dbd5cc624..6208b8bde 100644
--- a/fluxer_api/src/api/channel/controllers/MessageInteractionController.ts
+++ b/fluxer_api/src/api/channel/controllers/MessageInteractionController.ts
@@ -9,7 +9,7 @@ import {RateLimitMiddleware} from '@app/api/middleware/RateLimitMiddleware';
import {OpenAPI} from '@app/api/middleware/ResponseTypeMiddleware';
import {RateLimitConfigs} from '@app/api/RateLimitConfig';
import {readStateCapable} from '@app/api/read_state/ReadStateChannelMeta';
-import type {HonoApp} from '@app/api/types/HonoEnv';
+import type {HonoApp, HonoEnv} from '@app/api/types/HonoEnv';
import {assertTierAllows, NO_TIER_CONTEXT} from '@app/api/user/AccountTier';
import {Validator} from '@app/api/Validator';
import {TierGatedActions} from '@fluxer/constants/src/AccountTierConstants';
@@ -33,6 +33,23 @@ import {
ReactionUsersListResponse,
ReactionUsersPageResponse,
} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
+import type {Context} from 'hono';
+
+function fetchReactionUsers(
+ ctx: Context<HonoEnv>,
+ {channel_id, message_id, emoji}: ChannelIdMessageIdEmojiParam,
+ {limit, after}: ReactionUsersQuerySchema,
+) {
+ return ctx.get('channelService').interactions.getUsersForReaction({
+ viewer: viewerFromCtx(ctx),
+ userId: ctx.get('user').id,
+ channelId: createChannelID(channel_id),
+ messageId: createMessageID(message_id),
+ emoji,
+ limit,
+ after: after ? createUserID(after) : undefined,
+ });
+}
export function MessageInteractionController(app: HonoApp) {
app.get(
@@ -195,21 +212,7 @@ export function MessageInteractionController(app: HonoApp) {
tags: 'Channels',
}),
async (ctx) => {
- const {channel_id, message_id, emoji} = ctx.req.valid('param');
- const {limit, after} = ctx.req.valid('query');
- const userId = ctx.get('user').id;
- const channelId = createChannelID(channel_id);
- const messageId = createMessageID(message_id);
- const afterUserId = after ? createUserID(after) : undefined;
- const result = await ctx.get('channelService').interactions.getUsersForReaction({
- viewer: viewerFromCtx(ctx),
- userId,
- channelId,
- messageId,
- emoji,
- limit,
- after: afterUserId,
- });
+ const result = await fetchReactionUsers(ctx, ctx.req.valid('param'), ctx.req.valid('query'));
ctx.header('X-Has-More', result.has_more ? 'true' : 'false');
if (result.next_after !== null) {
ctx.header('X-Next-After', result.next_after);
@@ -234,21 +237,7 @@ export function MessageInteractionController(app: HonoApp) {
tags: 'Channels',
}),
async (ctx) => {
- const {channel_id, message_id, emoji} = ctx.req.valid('param');
- const {limit, after} = ctx.req.valid('query');
- const userId = ctx.get('user').id;
- const channelId = createChannelID(channel_id);
- const messageId = createMessageID(message_id);
- const afterUserId = after ? createUserID(after) : undefined;
- const result = await ctx.get('channelService').interactions.getUsersForReaction({
- viewer: viewerFromCtx(ctx),
- userId,
- channelId,
- messageId,
- emoji,
- limit,
- after: afterUserId,
- });
+ const result = await fetchReactionUsers(ctx, ctx.req.valid('param'), ctx.req.valid('query'));
return ctx.json(
{
items: result.users,
diff --git a/fluxer_api/src/api/channel/services/CallService.ts b/fluxer_api/src/api/channel/services/CallService.ts
index 404c63e3e..e89381996 100644
--- a/fluxer_api/src/api/channel/services/CallService.ts
+++ b/fluxer_api/src/api/channel/services/CallService.ts
@@ -155,22 +155,7 @@ export class CallService {
});
const recipientIds = Array.from(channel.recipientIds);
const channelRecipients = recipientIds.length > 0 ? await this.userRepository.listUsers(recipientIds) : [];
- if (channel.type === ChannelTypes.DM) {
- const dmRecipientIds = recipientIds.filter((id) => id !== userId);
- if (dmRecipientIds.length === 1) {
- await this.dmPermissionValidator.validate({senderId: userId, recipientId: dmRecipientIds[0]});
- const caller = await this.userRepository.findUnique(userId);
- if (caller) {
- await assertMayStartConversation({
- user: caller,
- targetId: dmRecipientIds[0]!,
- users: this.userRepository,
- messages: this.channelRepository.messages,
- channel,
- });
- }
- }
- }
+ await this.assertMayRingDm(channel, userId);
const existingCall = await this.gatewayService.getCall(channelId);
if (existingCall) {
throw new CallAlreadyExistsError();
@@ -306,22 +291,7 @@ export class CallService {
recipients,
});
}
- if (channel.type === ChannelTypes.DM) {
- const dmRecipientIds = Array.from(channel.recipientIds).filter((id) => id !== userId);
- if (dmRecipientIds.length === 1) {
- await this.dmPermissionValidator.validate({senderId: userId, recipientId: dmRecipientIds[0]});
- const caller = await this.userRepository.findUnique(userId);
- if (caller) {
- await assertMayStartConversation({
- user: caller,
- targetId: dmRecipientIds[0]!,
- users: this.userRepository,
- messages: this.channelRepository.messages,
- channel,
- });
- }
- }
- }
+ await this.assertMayRingDm(channel, userId);
const callerRequestedNoRing = recipients !== undefined && recipients.length === 0;
const recipientsToNotify = (
callerRequestedNoRing ? Array.from(channel.recipientIds) : recipients || Array.from(channel.recipientIds)
@@ -402,6 +372,27 @@ export class CallService {
}
}
+ private async assertMayRingDm(channel: Channel, userId: UserID): Promise<void> {
+ if (channel.type !== ChannelTypes.DM) {
+ return;
+ }
+ const dmRecipientIds = Array.from(channel.recipientIds).filter((id) => id !== userId);
+ if (dmRecipientIds.length !== 1) {
+ return;
+ }
+ await this.dmPermissionValidator.validate({senderId: userId, recipientId: dmRecipientIds[0]});
+ const caller = await this.userRepository.findUnique(userId);
+ if (caller) {
+ await assertMayStartConversation({
+ user: caller,
+ targetId: dmRecipientIds[0]!,
+ users: this.userRepository,
+ messages: this.channelRepository.messages,
+ channel,
+ });
+ }
+ }
+
private resolveCallerName({
channel,
userId,
diff --git a/fluxer_api/src/api/channel/services/ChannelFollowers.ts b/fluxer_api/src/api/channel/services/ChannelFollowers.ts
index a29c05930..5eec748a4 100644
--- a/fluxer_api/src/api/channel/services/ChannelFollowers.ts
+++ b/fluxer_api/src/api/channel/services/ChannelFollowers.ts
@@ -2,18 +2,13 @@
import type {ChannelID} from '@app/api/BrandedTypes';
import type {CrosspostedMessageRepository} from '@app/api/channel/repositories/CrosspostedMessageRepository';
+import {withRetryingLock} from '@app/api/channel/utils/RetryingLock';
import {Logger} from '@app/api/Logger';
import {getSnowflakeService, getWorkerService} from '@app/api/middleware/ServiceRegistry';
import type {Channel} from '@app/api/models/Channel';
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
-import {ThrottledError} from '@fluxer/errors/src/domains/core/ThrottledError';
import type {ICacheService} from '@pkgs/cache/src/ICacheService';
-const CHANNEL_FOLLOW_LOCK_TTL_SECONDS = 5;
-const CHANNEL_FOLLOW_LOCK_ACQUIRE_ATTEMPTS = 6;
-const CHANNEL_FOLLOW_LOCK_RETRY_DELAY_MS = 50;
-
type ChannelFollowerRemovalReason = 'deleted' | 'converted';
export type ChannelFollowerRemovalCopyMode = 'source_deleted' | 'purge';
@@ -23,37 +18,7 @@ export async function withChannelFollowLock<T>(
fn: () => Promise<T>,
keepAliveTtlSeconds?: number,
): Promise<T> {
- const ttlSeconds = keepAliveTtlSeconds ?? CHANNEL_FOLLOW_LOCK_TTL_SECONDS;
- const lockKey = `channel-follow:${channelId}`;
- let lockToken: string | null = null;
- for (let attempt = 0; attempt < CHANNEL_FOLLOW_LOCK_ACQUIRE_ATTEMPTS; attempt++) {
- lockToken = await cacheService.acquireLock(lockKey, ttlSeconds);
- if (lockToken) break;
- await new Promise((resolve) => setTimeout(resolve, CHANNEL_FOLLOW_LOCK_RETRY_DELAY_MS * (attempt + 1)));
- }
- if (!lockToken) {
- throw new ThrottledError({
- code: APIErrorCodes.RESOURCE_LOCKED,
- retryAfterSeconds: 1,
- data: {retry_after: 1},
- });
- }
- const token = lockToken;
- const keepAlive =
- keepAliveTtlSeconds === undefined
- ? null
- : setInterval(
- () => {
- cacheService.extendLock(lockKey, token, keepAliveTtlSeconds).catch(() => {});
- },
- (keepAliveTtlSeconds * 1000) / 3,
- );
- try {
- return await fn();
- } finally {
- if (keepAlive) clearInterval(keepAlive);
- await cacheService.releaseLock(lockKey, token).catch(() => {});
- }
+ return withRetryingLock(cacheService, `channel-follow:${channelId}`, fn, keepAliveTtlSeconds);
}
interface ChannelFollowerRemovalParams {
diff --git a/fluxer_api/src/api/channel/services/ChannelRequestService.ts b/fluxer_api/src/api/channel/services/ChannelRequestService.ts
index 5a0981580..8226cec96 100644
--- a/fluxer_api/src/api/channel/services/ChannelRequestService.ts
+++ b/fluxer_api/src/api/channel/services/ChannelRequestService.ts
@@ -8,6 +8,7 @@ import {applyForumTagEdit, type ForumTagEdit} from '@app/api/channel/services/th
import {mapThreadToResponse} from '@app/api/channel/services/thread/ThreadMappers';
import {withThreadParentFields} from '@app/api/channel/services/thread/ThreadParentSettings';
import {loadThreadViews} from '@app/api/channel/services/thread/ThreadViews';
+import {withRetryingLock} from '@app/api/channel/utils/RetryingLock';
import type {ThreadViewer} from '@app/api/experiment/ChannelThreadsGate';
import {maskChannelResponseThreadBits} from '@app/api/guild/services/ThreadPermissionBits';
import type {UserCacheService} from '@app/api/infrastructure/UserCacheService';
@@ -186,25 +187,7 @@ export class ChannelRequestService {
}
private async withForumTagsLock<T>(channelId: ChannelID, fn: () => Promise<T>): Promise<T> {
- const lockKey = `channel:${channelId}:forum-tags`;
- let lockToken: string | null = null;
- for (let attempt = 0; attempt < FORUM_TAGS_LOCK_ACQUIRE_ATTEMPTS; attempt++) {
- lockToken = await this.cacheService.acquireLock(lockKey, FORUM_TAGS_LOCK_TTL_SECONDS);
- if (lockToken) break;
- await new Promise((resolve) => setTimeout(resolve, FORUM_TAGS_LOCK_RETRY_DELAY_MS * (attempt + 1)));
- }
- if (!lockToken) {
- throw new ThrottledError({
- code: APIErrorCodes.RESOURCE_LOCKED,
- retryAfterSeconds: 1,
- data: {retry_after: 1},
- });
- }
- try {
- return await fn();
- } finally {
- await this.cacheService.releaseLock(lockKey, lockToken).catch(() => {});
- }
+ return withRetryingLock(this.cacheService, `channel:${channelId}:forum-tags`, fn);
}
async deleteChannel(params: {
diff --git a/fluxer_api/src/api/channel/services/MessageInteractionService.ts b/fluxer_api/src/api/channel/services/MessageInteractionService.ts
index 9e7e27adc..419d6de37 100644
--- a/fluxer_api/src/api/channel/services/MessageInteractionService.ts
+++ b/fluxer_api/src/api/channel/services/MessageInteractionService.ts
@@ -122,7 +122,7 @@ export class MessageInteractionService {
viewer,
access: 'visitor_read',
});
- const pins = await this.pinService.getChannelPins({authChannel, userId, requestCache, beforeTimestamp, limit});
+ const pins = await this.pinService.getChannelPins({authChannel, userId, beforeTimestamp, limit});
const original = pins.items.map((item) => item.message as MessageResponse);
const messages = maskThreadArtifactsFor(viewer, authChannel.channel.guildId, original);
if (messages === original) return pins;
@@ -176,7 +176,7 @@ export class MessageInteractionService {
if (!authChannel.guild && authChannel.channel.type !== ChannelTypes.DM_PERSONAL_NOTES) {
await this.authService.validateDMSendPermissions({channel: authChannel.channel, userId});
}
- await this.pinService.unpinMessage({authChannel, messageId, userId, requestCache, auditLogReason});
+ await this.pinService.unpinMessage({authChannel, messageId, userId, auditLogReason});
}
async getUsersForReaction({
@@ -287,7 +287,7 @@ export class MessageInteractionService {
messageId: MessageID;
emoji: string;
}): Promise<void> {
- await this.removeReaction({userId, viewer, sessionId, channelId, messageId, emoji, targetId: userId, requestCache});
+ await this.removeReaction({userId, viewer, sessionId, channelId, messageId, emoji, targetId: userId});
}
async removeAllReactionsForEmoji({
diff --git a/fluxer_api/src/api/channel/services/interaction/MessagePinService.ts b/fluxer_api/src/api/channel/services/interaction/MessagePinService.ts
index 3944293da..7c476ebb8 100644
--- a/fluxer_api/src/api/channel/services/interaction/MessagePinService.ts
+++ b/fluxer_api/src/api/channel/services/interaction/MessagePinService.ts
@@ -49,7 +49,6 @@ export class MessagePinService {
}: {
authChannel: AuthenticatedChannel;
userId: UserID;
- requestCache: RequestCache;
beforeTimestamp?: Date;
limit?: number;
}): Promise<{
@@ -133,18 +132,8 @@ export class MessagePinService {
requestCache: RequestCache;
auditLogReason?: string | null;
}): Promise<void> {
- const {channel, guild, checkPermission} = authChannel;
- if (guild) {
- await checkPermission(Permissions.PIN_MESSAGES);
- if (isOperationDisabled(guild, GuildOperations.SEND_MESSAGE)) {
- throw new FeatureTemporarilyDisabledError();
- }
- }
- ensureTextChannel(channel);
- assertThreadInteractionAllowed(authChannel, 'pin');
- const message = await this.channelRepository.messages.getMessage(channel.id, messageId);
- if (!message) throw new UnknownMessageError();
- this.validateMessagePinnable(message);
+ const {channel} = authChannel;
+ const message = await this.loadPinnableMessage(authChannel, messageId);
if (message.pinnedTimestamp) return;
const now = new Date();
const updatedMessageData = {...message.toRow(), pinned_timestamp: now};
@@ -159,18 +148,7 @@ export class MessagePinService {
channel,
message: updatedMessage,
});
- if (channel.guildId) {
- await this.guildAuditLogService
- .createBuilder(channel.guildId, userId)
- .withAction(AuditLogActionType.MESSAGE_PIN, messageId.toString())
- .withMetadata({
- channel_id: channel.id.toString(),
- message_id: messageId.toString(),
- })
- .withThreadScope(channel.isThread())
- .withReason(auditLogReason ?? null)
- .commit();
- }
+ await this.recordPinAudit(AuditLogActionType.MESSAGE_PIN, channel, messageId, userId, auditLogReason);
}
async unpinMessage({
@@ -182,9 +160,24 @@ export class MessagePinService {
authChannel: AuthenticatedChannel;
messageId: MessageID;
userId: UserID;
- requestCache: RequestCache;
auditLogReason?: string | null;
}): Promise<void> {
+ const {channel} = authChannel;
+ const message = await this.loadPinnableMessage(authChannel, messageId);
+ if (!message.pinnedTimestamp) return;
+ const updatedMessageData = {...message.toRow(), pinned_timestamp: null};
+ const updatedMessage = await this.channelRepository.messages.upsertMessage(updatedMessageData, message.toRow());
+ await this.channelRepository.messageInteractions.removeChannelPin(channel.id, messageId);
+ await this.dispatchChannelPinsUpdate(channel);
+ await dispatchMessageUpdateBroadcast({
+ gatewayService: this.gatewayService,
+ channel,
+ message: updatedMessage,
+ });
+ await this.recordPinAudit(AuditLogActionType.MESSAGE_UNPIN, channel, messageId, userId, auditLogReason);
+ }
+
+ private async loadPinnableMessage(authChannel: AuthenticatedChannel, messageId: MessageID): Promise<Message> {
const {channel, guild, checkPermission} = authChannel;
if (guild) {
await checkPermission(Permissions.PIN_MESSAGES);
@@ -197,28 +190,27 @@ export class MessagePinService {
const message = await this.channelRepository.messages.getMessage(channel.id, messageId);
if (!message) throw new UnknownMessageError();
this.validateMessagePinnable(message);
- if (!message.pinnedTimestamp) return;
- const updatedMessageData = {...message.toRow(), pinned_timestamp: null};
- const updatedMessage = await this.channelRepository.messages.upsertMessage(updatedMessageData, message.toRow());
- await this.channelRepository.messageInteractions.removeChannelPin(channel.id, messageId);
- await this.dispatchChannelPinsUpdate(channel);
- await dispatchMessageUpdateBroadcast({
- gatewayService: this.gatewayService,
- channel,
- message: updatedMessage,
- });
- if (channel.guildId) {
- await this.guildAuditLogService
- .createBuilder(channel.guildId, userId)
- .withAction(AuditLogActionType.MESSAGE_UNPIN, messageId.toString())
- .withMetadata({
- channel_id: channel.id.toString(),
- message_id: messageId.toString(),
- })
- .withThreadScope(channel.isThread())
- .withReason(auditLogReason ?? null)
- .commit();
- }
+ return message;
+ }
+
+ private async recordPinAudit(
+ action: AuditLogActionType,
+ channel: Channel,
+ messageId: MessageID,
+ userId: UserID,
+ auditLogReason?: string | null,
+ ): Promise<void> {
+ if (!channel.guildId) return;
+ await this.guildAuditLogService
+ .createBuilder(channel.guildId, userId)
+ .withAction(action, messageId.toString())
+ .withMetadata({
+ channel_id: channel.id.toString(),
+ message_id: messageId.toString(),
+ })
+ .withThreadScope(channel.isThread())
+ .withReason(auditLogReason ?? null)
+ .commit();
}
private validateMessagePinnable(message: Message): void {
diff --git a/fluxer_api/src/api/channel/services/message/AttachmentProcessingService.ts b/fluxer_api/src/api/channel/services/message/AttachmentProcessingService.ts
index d13c6b8a6..33df9fc80 100644
--- a/fluxer_api/src/api/channel/services/message/AttachmentProcessingService.ts
+++ b/fluxer_api/src/api/channel/services/message/AttachmentProcessingService.ts
@@ -60,7 +60,6 @@ interface ProcessedAttachment {
copyOperation: AttachmentCopyOperation;
hasVirusDetected: boolean;
applyFinalObjectMetadata: boolean;
- sourceLocalPath: string | null;
sniffedContentType: string | null;
}
@@ -293,40 +292,37 @@ export class AttachmentProcessingService {
});
}
const scanResult = await this.scanMalware(sourceLocalPath);
+ const processedAttachment = {
+ attachment_id: attachmentId,
+ filename: attachment.filename,
+ size,
+ title: attachment.title ?? null,
+ description: attachment.description ?? null,
+ height,
+ width,
+ content_type: contentType,
+ content_hash: contentHash,
+ placeholder,
+ flags,
+ duration: duration ?? clientDuration,
+ nsfw,
+ waveform,
+ };
+ const copyOperation = {
+ sourceBucket: Config.s3.buckets.uploads,
+ sourceKey: attachment.upload_filename,
+ destinationBucket: Config.s3.buckets.cdn,
+ destinationKey: cdnKey,
+ newContentType: contentType,
+ };
if (scanResult.isVirusDetected) {
hasVirusDetected = true;
await this.storageService.deleteObject(Config.s3.buckets.uploads, attachment.upload_filename);
- if (sourceLocalPath) {
- await fs.promises.unlink(sourceLocalPath).catch(() => undefined);
- sourceLocalPath = null;
- }
return {
- attachment: {
- attachment_id: attachmentId,
- filename: attachment.filename,
- size,
- title: attachment.title ?? null,
- description: attachment.description ?? null,
- height,
- width,
- content_type: contentType,
- content_hash: contentHash,
- placeholder,
- flags,
- duration: duration ?? clientDuration,
- nsfw,
- waveform,
- },
- copyOperation: {
- sourceBucket: Config.s3.buckets.uploads,
- sourceKey: attachment.upload_filename,
- destinationBucket: Config.s3.buckets.cdn,
- destinationKey: cdnKey,
- newContentType: contentType,
- },
+ attachment: processedAttachment,
+ copyOperation,
hasVirusDetected,
applyFinalObjectMetadata,
- sourceLocalPath: null,
sniffedContentType,
};
}
@@ -337,35 +333,11 @@ export class AttachmentProcessingService {
ValidationErrorCodes.VOICE_MESSAGES_ATTACHMENT_MUST_BE_AUDIO,
);
}
- const retainedLocalPath = sourceLocalPath;
- sourceLocalPath = null;
return {
- attachment: {
- attachment_id: attachmentId,
- filename: attachment.filename,
- size,
- title: attachment.title ?? null,
- description: attachment.description ?? null,
- height,
- width,
- content_type: contentType,
- content_hash: contentHash,
- placeholder,
- flags,
- duration: duration ?? clientDuration,
- nsfw,
- waveform,
- },
- copyOperation: {
- sourceBucket: Config.s3.buckets.uploads,
- sourceKey: attachment.upload_filename,
- destinationBucket: Config.s3.buckets.cdn,
- destinationKey: cdnKey,
- newContentType: contentType,
- },
+ attachment: processedAttachment,
+ copyOperation,
hasVirusDetected,
applyFinalObjectMetadata,
- sourceLocalPath: retainedLocalPath,
sniffedContentType,
};
} catch (error) {
diff --git a/fluxer_api/src/api/channel/services/message/MessagePersistenceService.ts b/fluxer_api/src/api/channel/services/message/MessagePersistenceService.ts
index d901d32d6..3f7e40788 100644
--- a/fluxer_api/src/api/channel/services/message/MessagePersistenceService.ts
+++ b/fluxer_api/src/api/channel/services/message/MessagePersistenceService.ts
@@ -465,20 +465,8 @@ export class MessagePersistenceService {
if ('upload_filename' in att && att.upload_filename) {
newAttachments.push(att as AttachmentToProcess);
} else {
- const existingAtt = att as EditExistingAttachment;
- const refId = createAttachmentID(existingAtt.id);
- let found = message.attachments.find((existing) => existing.id === refId);
- if (!found && refId < BigInt(message.attachments.length)) {
- found = message.attachments[Number(refId)];
- }
- if (found) {
- const updated = found.toMessageAttachment();
- if ('title' in existingAtt && existingAtt.title !== undefined) {
- updated.title = existingAtt.title;
- }
- if ('description' in existingAtt && existingAtt.description !== undefined) {
- updated.description = existingAtt.description;
- }
+ const updated = this.resolveExistingAttachment(message, att as EditExistingAttachment);
+ if (updated) {
existingAttachments.push(updated);
}
}
@@ -644,20 +632,8 @@ export class MessagePersistenceService {
const processedAttachments: Array<MessageAttachment> = [];
for (const att of data.attachments as Array<EditAttachment>) {
if (!('upload_filename' in att)) {
- const existingAtt = att as EditExistingAttachment;
- const refId = createAttachmentID(existingAtt.id);
- let found = message.attachments.find((existing) => existing.id === refId);
- if (!found && refId < BigInt(message.attachments.length)) {
- found = message.attachments[Number(refId)];
- }
- if (found) {
- const updated = found.toMessageAttachment();
- if ('title' in existingAtt && existingAtt.title !== undefined) {
- updated.title = existingAtt.title;
- }
- if ('description' in existingAtt && existingAtt.description !== undefined) {
- updated.description = existingAtt.description;
- }
+ const updated = this.resolveExistingAttachment(message, att as EditExistingAttachment);
+ if (updated) {
processedAttachments.push(updated);
}
}
@@ -667,6 +643,28 @@ export class MessagePersistenceService {
return {canEdit: true, updatedFlags, updatedAttachments};
}
+ private resolveExistingAttachment(
+ message: Message,
+ existingAtt: {id: bigint; title?: string | null; description?: string | null},
+ ): MessageAttachment | null {
+ const refId = createAttachmentID(existingAtt.id);
+ let found = message.attachments.find((existing) => existing.id === refId);
+ if (!found && refId < BigInt(message.attachments.length)) {
+ found = message.attachments[Number(refId)];
+ }
+ if (!found) {
+ return null;
+ }
+ const updated = found.toMessageAttachment();
+ if ('title' in existingAtt && existingAtt.title !== undefined) {
+ updated.title = existingAtt.title;
+ }
+ if ('description' in existingAtt && existingAtt.description !== undefined) {
+ updated.description = existingAtt.description;
+ }
+ return updated;
+ }
+
async createSystemMessage(params: {
messageId: MessageID;
channelId: ChannelID;
diff --git a/fluxer_api/src/api/channel/services/message/MessageResponseDataService.ts b/fluxer_api/src/api/channel/services/message/MessageResponseDataService.ts
index 5d6f78e7f..017a01aab 100644
--- a/fluxer_api/src/api/channel/services/message/MessageResponseDataService.ts
+++ b/fluxer_api/src/api/channel/services/message/MessageResponseDataService.ts
@@ -222,7 +222,7 @@ export class MessageResponseDataService {
messages: batch,
viewer_user_id: params.userId.toString(),
...(await this.accessEnvelope(params.access)),
- include_reactions: params.includeReactions ?? true,
+ include_reactions: true,
});
if (typeof response !== 'object' || !('FoundApiMany' in response)) {
throw new Error(`[message-response-service] unexpected BuildResponses response: ${JSON.stringify(response)}`);
diff --git a/fluxer_api/src/api/channel/services/message/MessageSystemService.ts b/fluxer_api/src/api/channel/services/message/MessageSystemService.ts
index 311bd0006..bbab93172 100644
--- a/fluxer_api/src/api/channel/services/message/MessageSystemService.ts
+++ b/fluxer_api/src/api/channel/services/message/MessageSystemService.ts
@@ -8,7 +8,6 @@ import type {MessagePersistenceService} from '@app/api/channel/services/message/
import type {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
import type {ISnowflakeService} from '@app/api/infrastructure/ISnowflakeService';
-import type {RequestCache} from '@app/api/middleware/RequestCacheMiddleware';
import {MessageTypes} from '@fluxer/constants/src/ChannelConstants';
export class MessageSystemService {
@@ -20,14 +19,7 @@ export class MessageSystemService {
private gatewayService: IGatewayService,
) {}
- async sendJoinSystemMessage({
- guildId,
- userId,
- }: {
- guildId: GuildID;
- userId: UserID;
- requestCache: RequestCache;
- }): Promise<void> {
+ async sendJoinSystemMessage({guildId, userId}: {guildId: GuildID; userId: UserID}): Promise<void> {
const guild = await this.guildRepository.findUnique(guildId);
if (!guild?.systemChannelId) return;
const systemChannel = await this.channelRepository.channelData.findUnique(guild.systemChannelId);
diff --git a/fluxer_api/src/api/channel/services/message/MessageWriteLock.ts b/fluxer_api/src/api/channel/services/message/MessageWriteLock.ts
index ca3eb0ff1..88482bac1 100644
--- a/fluxer_api/src/api/channel/services/message/MessageWriteLock.ts
+++ b/fluxer_api/src/api/channel/services/message/MessageWriteLock.ts
@@ -1,15 +1,10 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import type {ChannelID, MessageID} from '@app/api/BrandedTypes';
+import {withRetryingLock} from '@app/api/channel/utils/RetryingLock';
import type {Message} from '@app/api/models/Message';
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import {ThrottledError} from '@fluxer/errors/src/domains/core/ThrottledError';
import type {ICacheService} from '@pkgs/cache/src/ICacheService';
-const MESSAGE_WRITE_LOCK_TTL_SECONDS = 5;
-const MESSAGE_WRITE_LOCK_ACQUIRE_ATTEMPTS = 6;
-const MESSAGE_WRITE_LOCK_RETRY_DELAY_MS = 50;
-
export interface MessageWriteLockReader {
getMessage(channelId: ChannelID, messageId: MessageID): Promise<Message | null>;
}
@@ -25,25 +20,7 @@ export class MessageWriteLock {
) {}
async withLock<T>(channelId: ChannelID, messageId: MessageID, fn: () => Promise<T>): Promise<T> {
- const lockKey = messageWriteLockKey(channelId, messageId);
- let lockToken: string | null = null;
- for (let attempt = 0; attempt < MESSAGE_WRITE_LOCK_ACQUIRE_ATTEMPTS; attempt++) {
- lockToken = await this.cacheService.acquireLock(lockKey, MESSAGE_WRITE_LOCK_TTL_SECONDS);
- if (lockToken) break;
- await new Promise((resolve) => setTimeout(resolve, MESSAGE_WRITE_LOCK_RETRY_DELAY_MS * (attempt + 1)));
- }
- if (!lockToken) {
- throw new ThrottledError({
- code: APIErrorCodes.RESOURCE_LOCKED,
- retryAfterSeconds: 1,
- data: {retry_after: 1},
- });
- }
- try {
- return await fn();
- } finally {
- await this.cacheService.releaseLock(lockKey, lockToken).catch(() => {});
- }
+ return withRetryingLock(this.cacheService, messageWriteLockKey(channelId, messageId), fn);
}
async withFreshMessage<T>(
diff --git a/fluxer_api/src/api/channel/services/message/UserMessageDeletionService.ts b/fluxer_api/src/api/channel/services/message/UserMessageDeletionService.ts
index cc374aaf0..7e8c1b21d 100644
--- a/fluxer_api/src/api/channel/services/message/UserMessageDeletionService.ts
+++ b/fluxer_api/src/api/channel/services/message/UserMessageDeletionService.ts
@@ -63,17 +63,13 @@ export class UserMessageDeletionService {
constructor(private readonly deps: UserMessageDeletionServiceDeps) {}
- async deleteUserMessagesInScope(
- userId: UserID,
- scope: DeleteUserMessagesScope,
- options: Omit<BulkDeleteUserMessagesOptions, 'channelIdAllowlist'> = {},
- ): Promise<number> {
+ async deleteUserMessagesInScope(userId: UserID, scope: DeleteUserMessagesScope): Promise<number> {
const channelIdAllowlist = await this.resolveChannelAllowlist(scope);
if (channelIdAllowlist.size === 0) {
Logger.debug({userId: userId.toString()}, 'No channels in scope for bulk user message deletion');
return 0;
}
- return this.deleteUserMessagesBulk(userId, {...options, channelIdAllowlist});
+ return this.deleteUserMessagesBulk(userId, {channelIdAllowlist});
}
async deleteUserMessagesBulk(userId: UserID, options: BulkDeleteUserMessagesOptions = {}): Promise<number> {
diff --git a/fluxer_api/src/api/channel/utils/RetryingLock.ts b/fluxer_api/src/api/channel/utils/RetryingLock.ts
new file mode 100644
index 000000000..4ee774d8f
--- /dev/null
+++ b/fluxer_api/src/api/channel/utils/RetryingLock.ts
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
+import {ThrottledError} from '@fluxer/errors/src/domains/core/ThrottledError';
+import type {ICacheService} from '@pkgs/cache/src/ICacheService';
+
+const LOCK_TTL_SECONDS = 5;
+const LOCK_ACQUIRE_ATTEMPTS = 6;
+const LOCK_RETRY_DELAY_MS = 50;
+
+export async function withRetryingLock<T>(
+ cacheService: ICacheService,
+ lockKey: string,
+ fn: () => Promise<T>,
+ keepAliveTtlSeconds?: number,
+): Promise<T> {
+ const ttlSeconds = keepAliveTtlSeconds ?? LOCK_TTL_SECONDS;
+ let lockToken: string | null = null;
+ for (let attempt = 0; attempt < LOCK_ACQUIRE_ATTEMPTS; attempt++) {
+ lockToken = await cacheService.acquireLock(lockKey, ttlSeconds);
+ if (lockToken) break;
+ await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_DELAY_MS * (attempt + 1)));
+ }
+ if (!lockToken) {
+ throw new ThrottledError({
+ code: APIErrorCodes.RESOURCE_LOCKED,
+ retryAfterSeconds: 1,
+ data: {retry_after: 1},
+ });
+ }
+ const token = lockToken;
+ const keepAlive =
+ keepAliveTtlSeconds === undefined
+ ? null
+ : setInterval(
+ () => {
+ cacheService.extendLock(lockKey, token, keepAliveTtlSeconds).catch(() => {});
+ },
+ (keepAliveTtlSeconds * 1000) / 3,
+ );
+ try {
+ return await fn();
+ } finally {
+ if (keepAlive) clearInterval(keepAlive);
+ await cacheService.releaseLock(lockKey, token).catch(() => {});
+ }
+}
diff --git a/fluxer_api/src/api/guild/GuildModel.ts b/fluxer_api/src/api/guild/GuildModel.ts
index 407d0f85b..78046f028 100644
--- a/fluxer_api/src/api/guild/GuildModel.ts
+++ b/fluxer_api/src/api/guild/GuildModel.ts
@@ -56,24 +56,8 @@ export function mapGuildToGuildResponse(
permissions?: bigint | null;
},
): GuildResponse {
- const iconHash = stripGuildIconForFeatures(guild.iconHash, guild.features);
- const bannerHash = stripGuildBannerForFeatures(guild.bannerHash, guild.features);
- const splashHash = stripGuildSplashForFeatures(guild.splashHash, guild.features);
- const embedSplashHash = stripGuildSplashForFeatures(guild.embedSplashHash, guild.features);
return {
- id: guild.id.toString(),
- name: guild.name,
- icon: iconHash,
- banner: bannerHash,
- banner_width: bannerHash ? guild.bannerWidth : null,
- banner_height: bannerHash ? guild.bannerHeight : null,
- splash: splashHash,
- splash_width: splashHash ? guild.splashWidth : null,
- splash_height: splashHash ? guild.splashHeight : null,
- embed_splash: embedSplashHash,
- embed_splash_width: embedSplashHash ? guild.embedSplashWidth : null,
- embed_splash_height: embedSplashHash ? guild.embedSplashHeight : null,
- splash_card_alignment: guild.splashCardAlignment,
+ ...mapGuildToPartialResponse(guild),
vanity_url_code: guild.vanityUrlCode,
owner_id: guild.ownerId.toString(),
system_channel_id: guild.systemChannelId ? guild.systemChannelId.toString() : null,
@@ -81,7 +65,6 @@ export function mapGuildToGuildResponse(
rules_channel_id: guild.rulesChannelId ? guild.rulesChannelId.toString() : null,
afk_channel_id: guild.afkChannelId ? guild.afkChannelId.toString() : null,
afk_timeout: guild.afkTimeout,
- features: mapGuildFeatures(guild.features),
verification_level: guild.verificationLevel,
mfa_level: guild.mfaLevel,
nsfw_level: guild.nsfwLevel,
diff --git a/fluxer_api/src/api/guild/repositories/GuildRepository.ts b/fluxer_api/src/api/guild/repositories/GuildRepository.ts
index 5c1ed0903..ba606cfc6 100644
--- a/fluxer_api/src/api/guild/repositories/GuildRepository.ts
+++ b/fluxer_api/src/api/guild/repositories/GuildRepository.ts
@@ -300,7 +300,7 @@ export class GuildRepository {
return result ? Number(result.count) : 0;
}
- async upsertMember(data: GuildMemberRow, oldData?: GuildMemberRow | null): Promise<GuildMember> {
+ async upsertMember(data: GuildMemberRow): Promise<GuildMember> {
const guildId = data.guild_id;
const userId = data.user_id;
const result = await executeVersionedUpdate<GuildMemberRow, 'guild_id' | 'user_id'>(
@@ -673,7 +673,7 @@ export class GuildRepository {
return emojis.map((emoji) => new GuildEmoji(emoji));
}
- async upsertEmoji(data: GuildEmojiRow, oldData?: GuildEmojiRow | null): Promise<GuildEmoji> {
+ async upsertEmoji(data: GuildEmojiRow): Promise<GuildEmoji> {
const guildId = data.guild_id;
const emojiId = data.emoji_id;
const result = await executeVersionedUpdate<GuildEmojiRow, 'guild_id' | 'emoji_id'>(
@@ -726,7 +726,7 @@ export class GuildRepository {
return stickers.map((sticker) => new GuildSticker(sticker));
}
- async upsertSticker(data: GuildStickerRow, oldData?: GuildStickerRow | null): Promise<GuildSticker> {
+ async upsertSticker(data: GuildStickerRow): Promise<GuildSticker> {
const guildId = data.guild_id;
const stickerId = data.sticker_id;
const result = await executeVersionedUpdate<GuildStickerRow, 'guild_id' | 'sticker_id'>(
diff --git a/fluxer_api/src/api/guild/services/GuildSearchService.ts b/fluxer_api/src/api/guild/services/GuildSearchService.ts
index 81d061b3d..63eafba99 100644
--- a/fluxer_api/src/api/guild/services/GuildSearchService.ts
+++ b/fluxer_api/src/api/guild/services/GuildSearchService.ts
@@ -14,11 +14,10 @@ import type {UserCacheService} from '@app/api/infrastructure/UserCacheService';
import type {RequestCache} from '@app/api/middleware/RequestCacheMiddleware';
import type {Channel} from '@app/api/models/Channel';
import {getMessageSearchService} from '@app/api/SearchFactory';
-import {buildMessageSearchFilters} from '@app/api/search/BuildMessageSearchFilters';
-import {channelNeedsReindexing} from '@app/api/search/ChannelIndexingUtils';
+import {channelNeedsReindexing, queueIndexingChannels} from '@app/api/search/ChannelIndexingUtils';
import {MessageSearchResponseMapper} from '@app/api/search/MessageSearchResponseMapper';
-import {searchExistingMessages} from '@app/api/search/MessageSearchResultReconciler';
-import {channelRequiresAgeVerification} from '@app/api/search/SearchNsfwUtils';
+import {emptyMessageSearchResponse, runMessageSearch} from '@app/api/search/MessageSearchResultReconciler';
+import {channelRequiresAgeVerification, getCanUserAccessNsfw} from '@app/api/search/SearchNsfwUtils';
import {accessibleRequestedThreadIds, accessibleThreadIds} from '@app/api/search/ThreadSearchScope';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import {mapWithConcurrency} from '@app/api/utils/ConcurrencyUtils';
@@ -75,7 +74,7 @@ export class GuildSearchService {
}
const includeNsfwRequested = searchParams.include_nsfw ?? false;
const canUserAccessNsfw =
- guildIsAgeRestricted || includeNsfwRequested ? await this.getCanUserAccessNsfw(userId) : false;
+ guildIsAgeRestricted || includeNsfwRequested ? await getCanUserAccessNsfw(this.userRepository, userId) : false;
if (guildIsAgeRestricted && !canUserAccessNsfw) {
throw new NsfwContentRequiresAgeVerificationError();
}
@@ -136,15 +135,7 @@ export class GuildSearchService {
validChannelIds.push(nsfwFilteredIds[i]!);
}
if (validChannelIds.length === 0) {
- const hitsPerPage = searchParams.hits_per_page ?? 25;
- const page = searchParams.page ?? 1;
- return {
- channels: [],
- messages: [],
- total: 0,
- hits_per_page: hitsPerPage,
- page,
- };
+ return emptyMessageSearchResponse(searchParams);
}
let channelsToIndex = validChannelIds
.filter((channelId) => {
@@ -157,18 +148,7 @@ export class GuildSearchService {
threadSearchIndexEnqueueCappedTotal.inc();
}
if (channelsToIndex.length > 0) {
- await mapWithConcurrency(channelsToIndex, CHANNEL_INDEX_JOB_ENQUEUE_CONCURRENCY, (channelId) =>
- this.workerService.addJob(
- 'indexChannelMessages',
- {
- channelId,
- },
- {
- jobKey: `indexChannelMessages-${channelId}`,
- maxAttempts: 3,
- },
- ),
- );
+ await queueIndexingChannels(this.workerService, channelsToIndex);
return {indexing: true};
}
let searchChannelIds: Array<string>;
@@ -183,34 +163,17 @@ export class GuildSearchService {
} else {
searchChannelIds = validChannelIds.map((id) => id.toString());
}
- const filters = buildMessageSearchFilters(searchParams, searchChannelIds);
- const hitsPerPage = searchParams.hits_per_page ?? 25;
- const page = searchParams.page ?? 1;
- const cursor = searchParams.cursor;
- const result = await searchExistingMessages({
+ return runMessageSearch({
searchService,
messageRepository: this.channelRepository,
- query: searchParams.content ?? '',
- filters,
- hitsPerPage,
- page,
- cursor,
- });
- const mappedResponses = await this.responseMapper.mapSearchResultToResponses(
- result.messages,
+ responseMapper: this.responseMapper,
+ filterParams: searchParams,
+ searchParams,
+ channelIds: searchChannelIds,
userId,
viewer,
requestCache,
- );
- return {
- messages: mappedResponses.messages,
- channels: mappedResponses.channels,
- total: result.total,
- hits_per_page: hitsPerPage,
- page,
- cursor: result.cursor,
- ...(mappedResponses.threads ? {threads: mappedResponses.threads, members: mappedResponses.members} : {}),
- };
+ });
}
async searchAllGuilds(params: {
@@ -228,7 +191,7 @@ export class GuildSearchService {
const {accessibleChannels, unindexedChannelIds, guildNsfwLevels, parentCategories, threadParents} =
await this.collectAccessibleGuildChannels(userId, viewer, channelIds);
if (unindexedChannelIds.size > 0) {
- await this.queueIndexingChannels(unindexedChannelIds);
+ await queueIndexingChannels(this.workerService, unindexedChannelIds);
return {indexing: true};
}
let searchChannelIds = [...accessibleChannels.keys(), ...threadParents.keys()];
@@ -244,7 +207,7 @@ export class GuildSearchService {
const includeNsfwRequested = searchParams.include_nsfw ?? false;
let canIncludeNsfw = false;
if (includeNsfwRequested) {
- canIncludeNsfw = await this.getCanUserAccessNsfw(userId);
+ canIncludeNsfw = await getCanUserAccessNsfw(this.userRepository, userId);
}
searchChannelIds = searchChannelIds.filter((channelIdStr) => {
const channel = accessibleChannels.get(channelIdStr) ?? threadParents.get(channelIdStr);
@@ -262,44 +225,19 @@ export class GuildSearchService {
return true;
});
if (searchChannelIds.length === 0) {
- const hitsPerPage = searchParams.hits_per_page ?? 25;
- const page = searchParams.page ?? 1;
- return {
- channels: [],
- messages: [],
- total: 0,
- hits_per_page: hitsPerPage,
- page,
- };
+ return emptyMessageSearchResponse(searchParams);
}
- const filters = buildMessageSearchFilters(searchParams, searchChannelIds);
- const hitsPerPage = searchParams.hits_per_page ?? 25;
- const page = searchParams.page ?? 1;
- const cursor = searchParams.cursor;
- const result = await searchExistingMessages({
+ return runMessageSearch({
searchService,
messageRepository: this.channelRepository,
- query: searchParams.content ?? '',
- filters,
- hitsPerPage,
- page,
- cursor,
- });
- const mappedResponses = await this.responseMapper.mapSearchResultToResponses(
- result.messages,
+ responseMapper: this.responseMapper,
+ filterParams: searchParams,
+ searchParams,
+ channelIds: searchChannelIds,
userId,
viewer,
requestCache,
- );
- return {
- messages: mappedResponses.messages,
- channels: mappedResponses.channels,
- total: result.total,
- hits_per_page: hitsPerPage,
- page,
- cursor: result.cursor,
- ...(mappedResponses.threads ? {threads: mappedResponses.threads, members: mappedResponses.members} : {}),
- };
+ });
}
private async threadSearchChannelIds(params: {
diff --git a/fluxer_api/src/api/guild/services/ThreadPermissionBits.ts b/fluxer_api/src/api/guild/services/ThreadPermissionBits.ts
index cd98c0d67..ea1a157a7 100644
--- a/fluxer_api/src/api/guild/services/ThreadPermissionBits.ts
+++ b/fluxer_api/src/api/guild/services/ThreadPermissionBits.ts
@@ -51,16 +51,7 @@ export async function shouldMaskThreadPermissionBits(
values: Iterable<bigint | null | undefined>,
): Promise<boolean> {
if (!viewer || viewer.kind === 'system') return false;
- let present = false;
- for (const value of values) {
- if (hasThreadPermissionBits(value)) {
- present = true;
- break;
- }
- }
- if (!present) return false;
-
- return !viewerActive(viewer, guildId);
+ return [...values].some(hasThreadPermissionBits) && !viewerActive(viewer, guildId);
}
export async function maskChannelResponseThreadBits(
diff --git a/fluxer_api/src/api/guild/services/content/EmojiService.ts b/fluxer_api/src/api/guild/services/content/EmojiService.ts
index 053bd8a44..713e2b501 100644
--- a/fluxer_api/src/api/guild/services/content/EmojiService.ts
+++ b/fluxer_api/src/api/guild/services/content/EmojiService.ts
@@ -58,14 +58,7 @@ export class EmojiService {
auditLogReason?: string | null,
): Promise<GuildEmojiResponse> {
const {user, guildId, name, image} = params;
- const guildData = await this.gatewayService.getGuildData({userId: user.id, guildId});
- await this.contentHelpers.checkPermission({userId: user.id, guildId, permission: Permissions.CREATE_EXPRESSIONS});
- const allEmojis = await this.guildRepository.listEmojis(guildId);
- const guildFeatures = guildData.features;
- const hasUnlimitedEmoji = guildFeatures.includes(GuildFeatures.UNLIMITED_EMOJI);
- const maxEmojis = hasUnlimitedEmoji
- ? MAX_GUILD_EXPRESSION_SLOTS_UNLIMITED
- : resolveGuildLimit(this.limitConfigService, 'max_guild_emojis', MAX_GUILD_EMOJIS, guildFeatures);
+ const {allEmojis, guildFeatures, maxEmojis} = await this.loadEmojiSlots(user.id, guildId);
if (allEmojis.length >= maxEmojis) {
throw new MaxGuildEmojisError(maxEmojis);
}
@@ -89,17 +82,7 @@ export class EmojiService {
animated,
version: 1,
});
- const updatedEmojis = [...allEmojis, emoji];
- await this.dispatchGuildEmojisUpdate({guildId, emojis: updatedEmojis});
- await this.contentHelpers.guildAuditLogService.record({
- guildId,
- userId: user.id,
- action: AuditLogActionType.EMOJI_CREATE,
- targetId: emoji.id,
- auditLogReason: auditLogReason ?? null,
- changes: this.contentHelpers.guildAuditLogService.computeChanges(null, serializeEmojiForAudit(emoji)),
- });
- return mapGuildEmojiToResponse(emoji);
+ return this.finishEmojiCreate(guildId, user, allEmojis, emoji, auditLogReason);
}
async cloneEmoji(
@@ -117,14 +100,7 @@ export class EmojiService {
if (!sourceGuild?.features.has(GuildFeatures.CLONE_EMOJI_ENABLED)) {
throw new MissingAccessError();
}
- const guildData = await this.gatewayService.getGuildData({userId: user.id, guildId});
- await this.contentHelpers.checkPermission({userId: user.id, guildId, permission: Permissions.CREATE_EXPRESSIONS});
- const allEmojis = await this.guildRepository.listEmojis(guildId);
- const guildFeatures = guildData.features;
- const hasUnlimitedEmoji = guildFeatures.includes(GuildFeatures.UNLIMITED_EMOJI);
- const maxEmojis = hasUnlimitedEmoji
- ? MAX_GUILD_EXPRESSION_SLOTS_UNLIMITED
- : resolveGuildLimit(this.limitConfigService, 'max_guild_emojis', MAX_GUILD_EMOJIS, guildFeatures);
+ const {allEmojis, maxEmojis} = await this.loadEmojiSlots(user.id, guildId);
if (allEmojis.length >= maxEmojis) {
throw new MaxGuildEmojisError(maxEmojis);
}
@@ -138,17 +114,7 @@ export class EmojiService {
animated: sourceEmoji.isAnimated,
version: 1,
});
- const updatedEmojis = [...allEmojis, emoji];
- await this.dispatchGuildEmojisUpdate({guildId, emojis: updatedEmojis});
- await this.contentHelpers.guildAuditLogService.record({
- guildId,
- userId: user.id,
- action: AuditLogActionType.EMOJI_CREATE,
- targetId: emoji.id,
- auditLogReason: auditLogReason ?? null,
- changes: this.contentHelpers.guildAuditLogService.computeChanges(null, serializeEmojiForAudit(emoji)),
- });
- return mapGuildEmojiToResponse(emoji);
+ return this.finishEmojiCreate(guildId, user, allEmojis, emoji, auditLogReason);
}
async bulkCreateEmojis(
@@ -169,14 +135,7 @@ export class EmojiService {
}>;
}> {
const {user, guildId, emojis} = params;
- const guildData = await this.gatewayService.getGuildData({userId: user.id, guildId});
- await this.contentHelpers.checkPermission({userId: user.id, guildId, permission: Permissions.CREATE_EXPRESSIONS});
- const allEmojis = await this.guildRepository.listEmojis(guildId);
- const guildFeatures = guildData.features;
- const hasUnlimitedEmoji = guildFeatures.includes(GuildFeatures.UNLIMITED_EMOJI);
- const maxEmojis = hasUnlimitedEmoji
- ? MAX_GUILD_EXPRESSION_SLOTS_UNLIMITED
- : resolveGuildLimit(this.limitConfigService, 'max_guild_emojis', MAX_GUILD_EMOJIS, guildFeatures);
+ const {allEmojis, guildFeatures, maxEmojis} = await this.loadEmojiSlots(user.id, guildId);
let emojiCount = allEmojis.length;
const success: Array<GuildEmojiResponse> = [];
const failed: Array<{
@@ -225,18 +184,7 @@ export class EmojiService {
if (newEmojis.length > 0) {
const updatedEmojis = [...allEmojis, ...newEmojis];
await this.dispatchGuildEmojisUpdate({guildId, emojis: updatedEmojis});
- await Promise.all(
- newEmojis.map((emoji) =>
- this.contentHelpers.guildAuditLogService.record({
- guildId,
- userId: user.id,
- action: AuditLogActionType.EMOJI_CREATE,
- targetId: emoji.id,
- auditLogReason: auditLogReason ?? null,
- changes: this.contentHelpers.guildAuditLogService.computeChanges(null, serializeEmojiForAudit(emoji)),
- }),
- ),
- );
+ await Promise.all(newEmojis.map((emoji) => this.recordEmojiCreate(guildId, user, emoji, auditLogReason)));
}
return {success, failed};
}
@@ -308,6 +256,48 @@ export class EmojiService {
});
}
+ private async loadEmojiSlots(
+ userId: UserID,
+ guildId: GuildID,
+ ): Promise<{allEmojis: Array<GuildEmoji>; guildFeatures: Array<string>; maxEmojis: number}> {
+ const guildData = await this.gatewayService.getGuildData({userId, guildId});
+ await this.contentHelpers.checkPermission({userId, guildId, permission: Permissions.CREATE_EXPRESSIONS});
+ const allEmojis = await this.guildRepository.listEmojis(guildId);
+ const guildFeatures = guildData.features;
+ const maxEmojis = guildFeatures.includes(GuildFeatures.UNLIMITED_EMOJI)
+ ? MAX_GUILD_EXPRESSION_SLOTS_UNLIMITED
+ : resolveGuildLimit(this.limitConfigService, 'max_guild_emojis', MAX_GUILD_EMOJIS, guildFeatures);
+ return {allEmojis, guildFeatures, maxEmojis};
+ }
+
+ private async finishEmojiCreate(
+ guildId: GuildID,
+ user: User,
+ allEmojis: Array<GuildEmoji>,
+ emoji: GuildEmoji,
+ auditLogReason?: string | null,
+ ): Promise<GuildEmojiResponse> {
+ await this.dispatchGuildEmojisUpdate({guildId, emojis: [...allEmojis, emoji]});
+ await this.recordEmojiCreate(guildId, user, emoji, auditLogReason);
+ return mapGuildEmojiToResponse(emoji);
+ }
+
+ private async recordEmojiCreate(
+ guildId: GuildID,
+ user: User,
+ emoji: GuildEmoji,
+ auditLogReason?: string | null,
+ ): Promise<void> {
+ await this.contentHelpers.guildAuditLogService.record({
+ guildId,
+ userId: user.id,
+ action: AuditLogActionType.EMOJI_CREATE,
+ targetId: emoji.id,
+ auditLogReason: auditLogReason ?? null,
+ changes: this.contentHelpers.guildAuditLogService.computeChanges(null, serializeEmojiForAudit(emoji)),
+ });
+ }
+
private async dispatchGuildEmojisUpdate(params: {guildId: GuildID; emojis: Array<GuildEmoji>}): Promise<void> {
const {guildId, emojis} = params;
await this.gatewayService.dispatchGuild({
diff --git a/fluxer_api/src/api/guild/services/content/StickerService.ts b/fluxer_api/src/api/guild/services/content/StickerService.ts
index 501c996f7..d6cf6dd44 100644
--- a/fluxer_api/src/api/guild/services/content/StickerService.ts
+++ b/fluxer_api/src/api/guild/services/content/StickerService.ts
@@ -74,16 +74,8 @@ export class StickerService {
contentModerationService.scanText(name, stickerModCtx);
contentModerationService.scanText(description, stickerModCtx);
contentModerationService.scanText(tags.join(' '), stickerModCtx);
- const guildData = await this.gatewayService.getGuildData({userId: user.id, guildId});
- await this.contentHelpers.checkPermission({userId: user.id, guildId, permission: Permissions.CREATE_EXPRESSIONS});
- const allStickers = await this.guildRepository.listStickers(guildId);
- const stickerCount = allStickers.length;
- const guildFeatures = guildData.features;
- const hasUnlimitedStickers = guildFeatures.includes(GuildFeatures.UNLIMITED_STICKERS);
- const maxStickers = hasUnlimitedStickers
- ? MAX_GUILD_EXPRESSION_SLOTS_UNLIMITED
- : resolveGuildLimit(this.limitConfigService, 'max_guild_stickers', MAX_GUILD_STICKERS, guildFeatures);
- if (stickerCount >= maxStickers) {
+ const {allStickers, guildFeatures, maxStickers} = await this.loadStickerSlots(user.id, guildId);
+ if (allStickers.length >= maxStickers) {
throw new MaxGuildStickersStaticError(maxStickers);
}
const {animated, imageBuffer} = await this.avatarService.processSticker({
@@ -103,17 +95,7 @@ export class StickerService {
creator_id: user.id,
version: 1,
});
- const updatedStickers = [...allStickers, sticker];
- await this.dispatchGuildStickersUpdate({guildId, stickers: updatedStickers});
- await this.contentHelpers.guildAuditLogService.record({
- guildId,
- userId: user.id,
- action: AuditLogActionType.STICKER_CREATE,
- targetId: sticker.id,
- auditLogReason: auditLogReason ?? null,
- changes: this.contentHelpers.guildAuditLogService.computeChanges(null, serializeStickerForAudit(sticker)),
- });
- return mapGuildStickerToResponse(sticker);
+ return this.finishStickerCreate(guildId, user, allStickers, sticker, auditLogReason);
}
async cloneSticker(
@@ -131,16 +113,8 @@ export class StickerService {
if (!sourceGuild?.features.has(GuildFeatures.CLONE_STICKER_ENABLED)) {
throw new MissingAccessError();
}
- const guildData = await this.gatewayService.getGuildData({userId: user.id, guildId});
- await this.contentHelpers.checkPermission({userId: user.id, guildId, permission: Permissions.CREATE_EXPRESSIONS});
- const allStickers = await this.guildRepository.listStickers(guildId);
- const stickerCount = allStickers.length;
- const guildFeatures = guildData.features;
- const hasUnlimitedStickers = guildFeatures.includes(GuildFeatures.UNLIMITED_STICKERS);
- const maxStickers = hasUnlimitedStickers
- ? MAX_GUILD_EXPRESSION_SLOTS_UNLIMITED
- : resolveGuildLimit(this.limitConfigService, 'max_guild_stickers', MAX_GUILD_STICKERS, guildFeatures);
- if (stickerCount >= maxStickers) {
+ const {allStickers, maxStickers} = await this.loadStickerSlots(user.id, guildId);
+ if (allStickers.length >= maxStickers) {
throw new MaxGuildStickersStaticError(maxStickers);
}
const stickerId = createStickerID(await this.snowflakeService.generate());
@@ -155,17 +129,7 @@ export class StickerService {
creator_id: user.id,
version: 1,
});
- const updatedStickers = [...allStickers, sticker];
- await this.dispatchGuildStickersUpdate({guildId, stickers: updatedStickers});
- await this.contentHelpers.guildAuditLogService.record({
- guildId,
- userId: user.id,
- action: AuditLogActionType.STICKER_CREATE,
- targetId: sticker.id,
- auditLogReason: auditLogReason ?? null,
- changes: this.contentHelpers.guildAuditLogService.computeChanges(null, serializeStickerForAudit(sticker)),
- });
- return mapGuildStickerToResponse(sticker);
+ return this.finishStickerCreate(guildId, user, allStickers, sticker, auditLogReason);
}
async bulkCreateStickers(
@@ -188,14 +152,7 @@ export class StickerService {
}>;
}> {
const {user, guildId, stickers} = params;
- const guildData = await this.gatewayService.getGuildData({userId: user.id, guildId});
- await this.contentHelpers.checkPermission({userId: user.id, guildId, permission: Permissions.CREATE_EXPRESSIONS});
- const allStickers = await this.guildRepository.listStickers(guildId);
- const guildFeatures = guildData.features;
- const hasUnlimitedStickers = guildFeatures.includes(GuildFeatures.UNLIMITED_STICKERS);
- const maxStickers = hasUnlimitedStickers
- ? MAX_GUILD_EXPRESSION_SLOTS_UNLIMITED
- : resolveGuildLimit(this.limitConfigService, 'max_guild_stickers', MAX_GUILD_STICKERS, guildFeatures);
+ const {allStickers, guildFeatures, maxStickers} = await this.loadStickerSlots(user.id, guildId);
let stickerCount = allStickers.length;
const success: Array<GuildStickerResponse> = [];
const failed: Array<{
@@ -251,18 +208,7 @@ export class StickerService {
if (newStickers.length > 0) {
const updatedStickers = [...allStickers, ...newStickers];
await this.dispatchGuildStickersUpdate({guildId, stickers: updatedStickers});
- await Promise.all(
- newStickers.map((sticker) =>
- this.contentHelpers.guildAuditLogService.record({
- guildId,
- userId: user.id,
- action: AuditLogActionType.STICKER_CREATE,
- targetId: sticker.id,
- auditLogReason: auditLogReason ?? null,
- changes: this.contentHelpers.guildAuditLogService.computeChanges(null, serializeStickerForAudit(sticker)),
- }),
- ),
- );
+ await Promise.all(newStickers.map((sticker) => this.recordStickerCreate(guildId, user, sticker, auditLogReason)));
}
return {success, failed};
}
@@ -351,6 +297,48 @@ export class StickerService {
});
}
+ private async loadStickerSlots(
+ userId: UserID,
+ guildId: GuildID,
+ ): Promise<{allStickers: Array<GuildSticker>; guildFeatures: Array<string>; maxStickers: number}> {
+ const guildData = await this.gatewayService.getGuildData({userId, guildId});
+ await this.contentHelpers.checkPermission({userId, guildId, permission: Permissions.CREATE_EXPRESSIONS});
+ const allStickers = await this.guildRepository.listStickers(guildId);
+ const guildFeatures = guildData.features;
+ const maxStickers = guildFeatures.includes(GuildFeatures.UNLIMITED_STICKERS)
+ ? MAX_GUILD_EXPRESSION_SLOTS_UNLIMITED
+ : resolveGuildLimit(this.limitConfigService, 'max_guild_stickers', MAX_GUILD_STICKERS, guildFeatures);
+ return {allStickers, guildFeatures, maxStickers};
+ }
+
+ private async finishStickerCreate(
+ guildId: GuildID,
+ user: User,
+ allStickers: Array<GuildSticker>,
+ sticker: GuildSticker,
+ auditLogReason?: string | null,
+ ): Promise<GuildStickerResponse> {
+ await this.dispatchGuildStickersUpdate({guildId, stickers: [...allStickers, sticker]});
+ await this.recordStickerCreate(guildId, user, sticker, auditLogReason);
+ return mapGuildStickerToResponse(sticker);
+ }
+
+ private async recordStickerCreate(
+ guildId: GuildID,
+ user: User,
+ sticker: GuildSticker,
+ auditLogReason?: string | null,
+ ): Promise<void> {
+ await this.contentHelpers.guildAuditLogService.record({
+ guildId,
+ userId: user.id,
+ action: AuditLogActionType.STICKER_CREATE,
+ targetId: sticker.id,
+ auditLogReason: auditLogReason ?? null,
+ changes: this.contentHelpers.guildAuditLogService.computeChanges(null, serializeStickerForAudit(sticker)),
+ });
+ }
+
private async dispatchGuildStickersUpdate(params: {guildId: GuildID; stickers: Array<GuildSticker>}): Promise<void> {
const {guildId, stickers} = params;
await this.gatewayService.dispatchGuild({
diff --git a/fluxer_api/src/api/guild/services/member/GuildMemberOperationsService.ts b/fluxer_api/src/api/guild/services/member/GuildMemberOperationsService.ts
index e91e6d96a..7ada9330d 100644
--- a/fluxer_api/src/api/guild/services/member/GuildMemberOperationsService.ts
+++ b/fluxer_api/src/api/guild/services/member/GuildMemberOperationsService.ts
@@ -513,7 +513,7 @@ export class GuildMemberOperationsService {
void this.searchIndexService.indexMember(guildMember, user, {includeDefault});
}
if (sendJoinMessage && !(guild.systemChannelFlags & SystemChannelFlags.SUPPRESS_JOIN_NOTIFICATIONS)) {
- await this.channelService.messages.system.sendJoinSystemMessage({guildId, userId, requestCache});
+ await this.channelService.messages.system.sendJoinSystemMessage({guildId, userId});
}
void emitActivity('guild_joined', userId.toString(), {
user_id: userId.toString(),
diff --git a/fluxer_api/src/api/infrastructure/DisabledLiveKitService.ts b/fluxer_api/src/api/infrastructure/DisabledLiveKitService.ts
index 57a5341f8..304d16586 100644
--- a/fluxer_api/src/api/infrastructure/DisabledLiveKitService.ts
+++ b/fluxer_api/src/api/infrastructure/DisabledLiveKitService.ts
@@ -1,88 +1,25 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import type {ChannelID, GuildID, UserID} from '@app/api/BrandedTypes';
import type {ILiveKitService, ListParticipantsResult} from '@app/api/infrastructure/ILiveKitService';
import type {VoiceRegionMetadata, VoiceServerRecord} from '@app/api/voice/VoiceModel';
-interface CreateTokenParams {
- userId: UserID;
- guildId?: GuildID;
- channelId: ChannelID;
- connectionId: string;
- regionId: string;
- serverId: string;
- mute?: boolean;
- deaf?: boolean;
- canSpeak?: boolean;
- canStream?: boolean;
- canVideo?: boolean;
-}
-
-interface UpdateParticipantParams {
- userId: UserID;
- guildId?: GuildID;
- channelId: ChannelID;
- connectionId: string;
- regionId: string;
- serverId: string;
- mute?: boolean;
- deaf?: boolean;
-}
-
-interface DisconnectParticipantParams {
- userId: UserID;
- guildId?: GuildID;
- channelId: ChannelID;
- connectionId: string;
- regionId: string;
- serverId: string;
-}
-
-interface MuteMicrophoneTrackParams {
- userId: UserID;
- guildId?: GuildID;
- channelId: ChannelID;
- connectionId: string;
- regionId: string;
- serverId: string;
- trackSid: string;
-}
-
-interface UpdateParticipantPermissionsParams {
- userId: UserID;
- guildId?: GuildID;
- channelId: ChannelID;
- connectionId: string;
- regionId: string;
- serverId: string;
- canSpeak: boolean;
- canStream: boolean;
- canVideo: boolean;
- deaf?: boolean;
-}
-
export class DisabledLiveKitService implements ILiveKitService {
- async createToken(_params: CreateTokenParams): Promise<{
+ async createToken(): Promise<{
token: string;
endpoint: string;
}> {
throw new Error('Voice is disabled');
}
- async updateParticipant(_params: UpdateParticipantParams): Promise<void> {}
+ async updateParticipant(): Promise<void> {}
- async updateParticipantPermissions(_params: UpdateParticipantPermissionsParams): Promise<void> {}
+ async updateParticipantPermissions(): Promise<void> {}
- async muteMicrophoneTrack(_params: MuteMicrophoneTrackParams): Promise<void> {}
+ async muteMicrophoneTrack(): Promise<void> {}
- async disconnectParticipant(_params: DisconnectParticipantParams): Promise<void> {}
+ async disconnectParticipant(): Promise<void> {}
- async listParticipants(_params: {
- guildId?: GuildID;
- channelId: ChannelID;
- regionId: string;
- serverId: string;
- }): Promise<ListParticipantsResult> {
+ async listParticipants(): Promise<ListParticipantsResult> {
return {status: 'ok', participants: []};
}
@@ -94,7 +31,7 @@ export class DisabledLiveKitService implements ILiveKitService {
return [];
}
- getServer(_regionId: string, _serverId: string): VoiceServerRecord | null {
+ getServer(): VoiceServerRecord | null {
return null;
}
}
diff --git a/fluxer_api/src/api/infrastructure/GatewayService.ts b/fluxer_api/src/api/infrastructure/GatewayService.ts
index 7358c197b..f64941d5e 100644
--- a/fluxer_api/src/api/infrastructure/GatewayService.ts
+++ b/fluxer_api/src/api/infrastructure/GatewayService.ts
@@ -19,6 +19,7 @@ import {
type GuildChannelAuthContext,
} from '@app/api/infrastructure/IGatewayService';
import {Logger} from '@app/api/Logger';
+import {chunkArray} from '@app/api/utils/ArrayUtils';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {CallAlreadyExistsError} from '@fluxer/errors/src/domains/channel/CallAlreadyExistsError';
import {InvalidChannelTypeForCallError} from '@fluxer/errors/src/domains/channel/InvalidChannelTypeForCallError';
@@ -51,6 +52,10 @@ const GATEWAY_ERROR_TO_DOMAIN_ERROR: Record<string, () => Error> = {
[GatewayRpcMethodErrorCodes.TARGET_MISSING_CONNECT]: () => new MissingPermissionsError(),
[GatewayRpcMethodErrorCodes.INVALID_PARAMS]: () => new BadRequestError({code: APIErrorCodes.INVALID_FORM_BODY}),
[GatewayRpcMethodErrorCodes.BATCH_TOO_LARGE]: () => new BadRequestError({code: APIErrorCodes.INVALID_FORM_BODY}),
+ [GatewayRpcMethodErrorCodes.TIMEOUT]: () => new GatewayTimeoutError(),
+ [GatewayRpcMethodErrorCodes.GUILD_OVERLOADED]: () => new ServiceUnavailableError({headers: {'Retry-After': '1'}}),
+ [GatewayRpcMethodErrorCodes.OVERLOADED]: () => new ServiceUnavailableError(),
+ [GatewayRpcMethodErrorCodes.NO_RESPONDERS]: () => new ServiceUnavailableError(),
};
interface DispatchGuildParams {
@@ -76,7 +81,7 @@ interface ClearPushChannelNotificationsParams {
messageId: MessageID;
}
-interface GuildDataParams {
+interface GuildUserParams {
guildId: GuildID;
userId: UserID;
}
@@ -182,20 +187,38 @@ type PendingRequest<T> = {
timeoutId: NodeJS.Timeout | null;
};
+type SettleableRequest = Omit<PendingRequest<unknown>, 'resolve'>;
+
+type BatchEntry<T> = [string, Array<PendingRequest<T>>];
+
+interface BatchLane<T> {
+ readonly method: string;
+ readonly pending: Map<string, Array<PendingRequest<T>>>;
+ timeout: NodeJS.Timeout | null;
+ active: number;
+ readonly run: (entry: BatchEntry<T>) => Promise<void>;
+}
+
+interface GuildMemberResult {
+ success: boolean;
+ memberData?: GuildMemberResponse;
+}
+
export class GatewayService {
private rpcClient: GatewayRpcClient;
- private pendingGuildDataRequests = new Map<string, Array<PendingRequest<GuildResponse>>>();
- private pendingGuildMemberRequests = new Map<
- string,
- Array<
- PendingRequest<{
- success: boolean;
- memberData?: GuildMemberResponse;
- }>
- >
- >();
- private pendingPermissionRequests = new Map<string, Array<PendingRequest<boolean>>>();
- private pendingAuthContextRequests = new Map<string, Array<PendingRequest<GuildChannelAuthContext>>>();
+ private readonly guildDataLane = this.createLane<GuildResponse>('guild.get_data', (entry) =>
+ this.processGuildDataEntry(entry),
+ );
+ private readonly guildMemberLane = this.createLane<GuildMemberResult>('guild.get_member', (entry) =>
+ this.processGuildMemberEntry(entry),
+ );
+ private readonly permissionLane = this.createLane<boolean>('guild.check_permission', (entry) =>
+ this.processPermissionEntry(entry),
+ );
+ private readonly authContextLane = this.createLane<GuildChannelAuthContext>('guild.get_auth_context', (entry) =>
+ this.processAuthContextEntry(entry),
+ );
+ private readonly lanes = [this.guildDataLane, this.guildMemberLane, this.permissionLane, this.authContextLane];
private pendingBatchRequestCount = 0;
private authContextUnsupportedUntil = 0;
private readonly BATCH_DELAY_MS = ms('5 milliseconds');
@@ -249,7 +272,7 @@ export class GatewayService {
);
}
- private settlePendingRequest<T>(request: PendingRequest<T>, settle: () => void): void {
+ private settlePendingRequest(request: SettleableRequest, settle: () => void): void {
if (request.settled) {
return;
}
@@ -268,49 +291,23 @@ export class GatewayService {
}
}
- private rejectPendingRequests<T>(requests: Array<PendingRequest<T>>, error: Error): void {
+ private rejectPendingRequests(requests: ReadonlyArray<SettleableRequest>, error: Error): void {
for (const request of requests) {
this.settlePendingRequest(request, () => request.reject(error));
}
}
- private scheduleGuildDataBatch(): void {
- if (this.guildDataBatchTimeout || this.activeGuildDataRequests >= this.MAX_BATCH_CONCURRENCY) {
- return;
- }
- this.guildDataBatchTimeout = setTimeout(() => {
- this.guildDataBatchTimeout = null;
- this.processGuildDataQueue();
- }, this.BATCH_DELAY_MS);
- }
-
- private scheduleGuildMemberBatch(): void {
- if (this.guildMemberBatchTimeout || this.activeGuildMemberRequests >= this.MAX_BATCH_CONCURRENCY) {
- return;
- }
- this.guildMemberBatchTimeout = setTimeout(() => {
- this.guildMemberBatchTimeout = null;
- this.processGuildMemberQueue();
- }, this.BATCH_DELAY_MS);
+ private createLane<T>(method: string, run: (entry: BatchEntry<T>) => Promise<void>): BatchLane<T> {
+ return {method, pending: new Map(), timeout: null, active: 0, run};
}
- private schedulePermissionBatch(): void {
- if (this.permissionBatchTimeout || this.activePermissionRequests >= this.MAX_BATCH_CONCURRENCY) {
+ private scheduleBatch<T>(lane: BatchLane<T>): void {
+ if (lane.timeout || lane.active >= this.MAX_BATCH_CONCURRENCY) {
return;
}
- this.permissionBatchTimeout = setTimeout(() => {
- this.permissionBatchTimeout = null;
- this.processPermissionQueue();
- }, this.BATCH_DELAY_MS);
- }
-
- private scheduleAuthContextBatch(): void {
- if (this.authContextBatchTimeout || this.activeAuthContextRequests >= this.MAX_BATCH_CONCURRENCY) {
- return;
- }
- this.authContextBatchTimeout = setTimeout(() => {
- this.authContextBatchTimeout = null;
- this.processAuthContextQueue();
+ lane.timeout = setTimeout(() => {
+ lane.timeout = null;
+ this.processQueue(lane);
}, this.BATCH_DELAY_MS);
}
@@ -329,122 +326,81 @@ export class GatewayService {
return entries;
}
- private processGuildDataQueue(): void {
- const availableSlots = this.MAX_BATCH_CONCURRENCY - this.activeGuildDataRequests;
+ private processQueue<T>(lane: BatchLane<T>): void {
+ const availableSlots = this.MAX_BATCH_CONCURRENCY - lane.active;
if (availableSlots <= 0) {
return;
}
- const entries = this.takePendingEntries(this.pendingGuildDataRequests, availableSlots);
+ const entries = this.takePendingEntries(lane.pending, availableSlots);
if (entries.length === 0) {
return;
}
- const totalGuildDataRequests = entries.reduce((sum, [, pending]) => sum + pending.length, 0);
+ const totalRequests = entries.reduce((sum, [, pending]) => sum + pending.length, 0);
Logger.debug(
- `[gateway-batch] Processing guild.get_data batch: ${entries.length} unique requests (${totalGuildDataRequests} total)`,
+ `[gateway-batch] Processing ${lane.method} batch: ${entries.length} unique requests (${totalRequests} total)`,
);
for (const entry of entries) {
- this.activeGuildDataRequests += 1;
- void this.processGuildDataEntry(entry).finally(() => {
- this.activeGuildDataRequests = Math.max(0, this.activeGuildDataRequests - 1);
- if (this.pendingGuildDataRequests.size > 0) {
- this.scheduleGuildDataBatch();
+ lane.active += 1;
+ void lane.run(entry).finally(() => {
+ lane.active = Math.max(0, lane.active - 1);
+ if (lane.pending.size > 0) {
+ this.scheduleBatch(lane);
}
});
}
- if (this.pendingGuildDataRequests.size > 0) {
- this.scheduleGuildDataBatch();
+ if (lane.pending.size > 0) {
+ this.scheduleBatch(lane);
}
}
- private processGuildMemberQueue(): void {
- const availableSlots = this.MAX_BATCH_CONCURRENCY - this.activeGuildMemberRequests;
- if (availableSlots <= 0) {
- return;
- }
- const entries = this.takePendingEntries(this.pendingGuildMemberRequests, availableSlots);
- if (entries.length === 0) {
- return;
- }
- const totalGuildMemberRequests = entries.reduce((sum, [, pending]) => sum + pending.length, 0);
- Logger.debug(
- `[gateway-batch] Processing guild.get_member batch: ${entries.length} unique requests (${totalGuildMemberRequests} total)`,
- );
- for (const entry of entries) {
- this.activeGuildMemberRequests += 1;
- void this.processGuildMemberEntry(entry).finally(() => {
- this.activeGuildMemberRequests = Math.max(0, this.activeGuildMemberRequests - 1);
- if (this.pendingGuildMemberRequests.size > 0) {
- this.scheduleGuildMemberBatch();
- }
- });
- }
- if (this.pendingGuildMemberRequests.size > 0) {
- this.scheduleGuildMemberBatch();
- }
+ private enqueueBatchRequest<T>(lane: BatchLane<T>, key: string): Promise<T> {
+ return new Promise<T>((resolve, reject) => {
+ if (this.pendingBatchRequestCount >= this.MAX_PENDING_BATCH_REQUESTS) {
+ reject(new ServiceUnavailableError());
+ return;
+ }
+ const pendingRequest: PendingRequest<T> = {
+ resolve,
+ reject,
+ settled: false,
+ timeoutId: null,
+ };
+ pendingRequest.timeoutId = setTimeout(() => {
+ this.rejectPendingRequests([pendingRequest], new GatewayTimeoutError());
+ this.removePendingRequest(lane, key, pendingRequest);
+ }, this.PENDING_REQUEST_TIMEOUT_MS);
+ const pending = lane.pending.get(key) || [];
+ pending.push(pendingRequest);
+ lane.pending.set(key, pending);
+ this.pendingBatchRequestCount += 1;
+ Logger.debug(`[gateway-batch] Queued ${lane.method} request ${key}, total pending: ${pending.length}`);
+ this.scheduleBatch(lane);
+ });
}
- private processPermissionQueue(): void {
- const availableSlots = this.MAX_BATCH_CONCURRENCY - this.activePermissionRequests;
- if (availableSlots <= 0) {
+ private removePendingRequest<T>(lane: BatchLane<T>, key: string, request: PendingRequest<T>): void {
+ const pending = lane.pending.get(key);
+ const index = pending ? pending.indexOf(request) : -1;
+ if (!pending || index < 0) {
return;
}
- const entries = this.takePendingEntries(this.pendingPermissionRequests, availableSlots);
- if (entries.length === 0) {
- return;
- }
- const totalPermissionRequests = entries.reduce((sum, [, pending]) => sum + pending.length, 0);
- Logger.debug(
- `[gateway-batch] Processing guild.check_permission batch: ${entries.length} unique requests (${totalPermissionRequests} total)`,
- );
- for (const entry of entries) {
- this.activePermissionRequests += 1;
- void this.processPermissionEntry(entry).finally(() => {
- this.activePermissionRequests = Math.max(0, this.activePermissionRequests - 1);
- if (this.pendingPermissionRequests.size > 0) {
- this.schedulePermissionBatch();
- }
- });
- }
- if (this.pendingPermissionRequests.size > 0) {
- this.schedulePermissionBatch();
+ pending.splice(index, 1);
+ if (pending.length === 0) {
+ lane.pending.delete(key);
}
}
private rejectAllPendingBatchRequests(error: Error): void {
- for (const pendingRequests of this.pendingGuildDataRequests.values()) {
- this.rejectPendingRequests(pendingRequests, error);
+ for (const lane of this.lanes) {
+ for (const pendingRequests of lane.pending.values()) {
+ this.rejectPendingRequests(pendingRequests, error);
+ }
+ lane.pending.clear();
}
this.pendingBatchRequestCount = 0;
}
- private processAuthContextQueue(): void {
- const availableSlots = this.MAX_BATCH_CONCURRENCY - this.activeAuthContextRequests;
- if (availableSlots <= 0) {
- return;
- }
- const entries = this.takePendingEntries(this.pendingAuthContextRequests, availableSlots);
- if (entries.length === 0) {
- return;
- }
- const totalAuthContextRequests = entries.reduce((sum, [, pending]) => sum + pending.length, 0);
- Logger.debug(
- `[gateway-batch] Processing guild.get_auth_context batch: ${entries.length} unique requests (${totalAuthContextRequests} total)`,
- );
- for (const entry of entries) {
- this.activeAuthContextRequests += 1;
- void this.processAuthContextEntry(entry).finally(() => {
- this.activeAuthContextRequests = Math.max(0, this.activeAuthContextRequests - 1);
- if (this.pendingAuthContextRequests.size > 0) {
- this.scheduleAuthContextBatch();
- }
- });
- }
- if (this.pendingAuthContextRequests.size > 0) {
- this.scheduleAuthContextBatch();
- }
- }
-
- private async processGuildDataEntry([key, pending]: [string, Array<PendingRequest<GuildResponse>>]): Promise<void> {
+ private async processGuildDataEntry([key, pending]: BatchEntry<GuildResponse>): Promise<void> {
try {
const [guildIdStr, userIdStr, skipCheck] = key.split('-');
const guildId = BigInt(guildIdStr) as GuildID;
@@ -462,15 +418,7 @@ export class GatewayService {
}
}
- private async processGuildMemberEntry([key, pending]: [
- string,
- Array<
- PendingRequest<{
- success: boolean;
- memberData?: GuildMemberResponse;
- }>
- >,
- ]): Promise<void> {
+ private async processGuildMemberEntry([key, pending]: BatchEntry<GuildMemberResult>): Promise<void> {
try {
const [guildIdStr, userIdStr] = key.split('-');
const guildId = BigInt(guildIdStr) as GuildID;
@@ -492,7 +440,7 @@ export class GatewayService {
}
}
- private async processPermissionEntry([key, pending]: [string, Array<PendingRequest<boolean>>]): Promise<void> {
+ private async processPermissionEntry([key, pending]: BatchEntry<boolean>): Promise<void> {
try {
const [guildIdStr, userIdStr, permissionStr, channelIdStr] = key.split('-');
const guildId = BigInt(guildIdStr) as GuildID;
@@ -515,10 +463,7 @@ export class GatewayService {
}
}
- private async processAuthContextEntry([key, pending]: [
- string,
- Array<PendingRequest<GuildChannelAuthContext>>,
- ]): Promise<void> {
+ private async processAuthContextEntry([key, pending]: BatchEntry<GuildChannelAuthContext>): Promise<void> {
const [guildIdStr, userIdStr, channelIdStr] = key.split('-');
const guildId = BigInt(guildIdStr) as GuildID;
const userId = BigInt(userIdStr) as UserID;
@@ -622,15 +567,11 @@ export class GatewayService {
guildId: GuildID;
settings: unknown;
}): Promise<void> {
- try {
- await this.rpcClient.call('push.sync_user_guild_settings', {
- user_id: userId.toString(),
- guild_id: guildId.toString(),
- user_guild_settings: settings,
- });
- } catch (error) {
- throw this.transformGatewayError(error);
- }
+ await this.call('push.sync_user_guild_settings', {
+ user_id: userId.toString(),
+ guild_id: guildId.toString(),
+ user_guild_settings: settings,
+ });
}
async getGuildCounts(guildId: GuildID): Promise<{
@@ -685,35 +626,11 @@ export class GatewayService {
guildId,
userId,
skipMembershipCheck,
- }: GuildDataParams & {
+ }: GuildUserParams & {
skipMembershipCheck?: boolean;
}): Promise<GuildResponse> {
const key = `${guildId.toString()}-${userId.toString()}-${skipMembershipCheck ? 'skip' : 'check'}`;
- return new Promise<GuildResponse>((resolve, reject) => {
- if (this.pendingBatchRequestCount >= this.MAX_PENDING_BATCH_REQUESTS) {
- reject(new ServiceUnavailableError());
- return;
- }
- const pendingRequest: PendingRequest<GuildResponse> = {
- resolve,
- reject,
- settled: false,
- timeoutId: null,
- };
- pendingRequest.timeoutId = setTimeout(() => {
- const error = new GatewayTimeoutError();
- this.rejectPendingRequests([pendingRequest], error);
- this.removePendingGuildDataRequest(key, pendingRequest);
- }, this.PENDING_REQUEST_TIMEOUT_MS);
- const pending = this.pendingGuildDataRequests.get(key) || [];
- pending.push(pendingRequest);
- this.pendingGuildDataRequests.set(key, pending);
- this.pendingBatchRequestCount += 1;
- Logger.debug(
- `[gateway-batch] Queued guild.get_data request for guild ${guildId.toString()}, user ${userId.toString()}, total pending: ${pending.length}`,
- );
- this.scheduleGuildDataBatch();
- });
+ return this.enqueueBatchRequest(this.guildDataLane, key);
}
async getGuildAuthContext({guildId, userId, channelId}: GuildAuthContextParams): Promise<GuildChannelAuthContext> {
@@ -721,114 +638,15 @@ export class GatewayService {
return await this.getGuildAuthContextFromGuildData({guildId, userId, channelId});
}
const key = `${guildId.toString()}-${userId.toString()}-${channelId ? channelId.toString() : '0'}`;
- return new Promise<GuildChannelAuthContext>((resolve, reject) => {
- if (this.pendingBatchRequestCount >= this.MAX_PENDING_BATCH_REQUESTS) {
- reject(new ServiceUnavailableError());
- return;
- }
- const pendingRequest: PendingRequest<GuildChannelAuthContext> = {
- resolve,
- reject,
- settled: false,
- timeoutId: null,
- };
- pendingRequest.timeoutId = setTimeout(() => {
- const error = new GatewayTimeoutError();
- this.rejectPendingRequests([pendingRequest], error);
- this.removePendingAuthContextRequest(key, pendingRequest);
- }, this.PENDING_REQUEST_TIMEOUT_MS);
- const pending = this.pendingAuthContextRequests.get(key) || [];
- pending.push(pendingRequest);
- this.pendingAuthContextRequests.set(key, pending);
- this.pendingBatchRequestCount += 1;
- this.scheduleAuthContextBatch();
- });
+ return this.enqueueBatchRequest(this.authContextLane, key);
}
- private removePendingAuthContextRequest(key: string, request: PendingRequest<GuildChannelAuthContext>): void {
- const pending = this.pendingAuthContextRequests.get(key);
- if (pending) {
- const index = pending.indexOf(request);
- if (index >= 0) {
- pending.splice(index, 1);
- if (pending.length === 0) {
- this.pendingAuthContextRequests.delete(key);
- }
- }
- }
- }
-
- private removePendingGuildDataRequest(key: string, request: PendingRequest<GuildResponse>): void {
- const pending = this.pendingGuildDataRequests.get(key);
- if (pending) {
- const index = pending.indexOf(request);
- if (index >= 0) {
- pending.splice(index, 1);
- if (pending.length === 0) {
- this.pendingGuildDataRequests.delete(key);
- }
- }
- }
- }
-
- async getGuildMember({guildId, userId}: GuildMemberParams): Promise<{
- success: boolean;
- memberData?: GuildMemberResponse;
- }> {
+ async getGuildMember({guildId, userId}: GuildUserParams): Promise<GuildMemberResult> {
const key = `${guildId.toString()}-${userId.toString()}`;
- return new Promise<{
- success: boolean;
- memberData?: GuildMemberResponse;
- }>((resolve, reject) => {
- if (this.pendingBatchRequestCount >= this.MAX_PENDING_BATCH_REQUESTS) {
- reject(new ServiceUnavailableError());
- return;
- }
- const pendingRequest: PendingRequest<{
- success: boolean;
- memberData?: GuildMemberResponse;
- }> = {
- resolve,
- reject,
- settled: false,
- timeoutId: null,
- };
- pendingRequest.timeoutId = setTimeout(() => {
- const error = new GatewayTimeoutError();
- this.rejectPendingRequests([pendingRequest], error);
- this.removePendingGuildMemberRequest(key, pendingRequest);
- }, this.PENDING_REQUEST_TIMEOUT_MS);
- const pending = this.pendingGuildMemberRequests.get(key) || [];
- pending.push(pendingRequest);
- this.pendingGuildMemberRequests.set(key, pending);
- this.pendingBatchRequestCount += 1;
- Logger.debug(
- `[gateway-batch] Queued guild.get_member request for guild ${guildId.toString()}, user ${userId.toString()}, total pending: ${pending.length}`,
- );
- this.scheduleGuildMemberBatch();
- });
- }
-
- private removePendingGuildMemberRequest(
- key: string,
- request: PendingRequest<{
- success: boolean;
- memberData?: GuildMemberResponse;
- }>,
- ): void {
- const pending = this.pendingGuildMemberRequests.get(key);
- if (pending) {
- const index = pending.indexOf(request);
- if (index >= 0) {
- pending.splice(index, 1);
- if (pending.length === 0) {
- this.pendingGuildMemberRequests.delete(key);
- }
- }
- }
+ return this.enqueueBatchRequest(this.guildMemberLane, key);
}
- async hasGuildMember({guildId, userId}: HasMemberParams): Promise<boolean> {
+ async hasGuildMember({guildId, userId}: GuildUserParams): Promise<boolean> {
const result = await this.call<{
has_member: boolean;
}>('guild.has_member', {
@@ -927,7 +745,7 @@ export class GatewayService {
};
}
- async getUserPermissions({guildId, userId, channelId}: UserPermissionsParams): Promise<bigint> {
+ async getUserPermissions({guildId, userId, channelId}: GuildAuthContextParams): Promise<bigint> {
const result = await this.call<{
permissions: string;
}>('guild.get_user_permissions', {
@@ -952,7 +770,7 @@ export class GatewayService {
return permissionsMap;
}
const results = await Promise.all(
- batches.map((batch) =>
+ chunkArray(guildIds, USER_PERMISSIONS_BATCH_SIZE).map((batch) =>
this.call<{
permissions: Array<{
guild_id: string;
@@ -976,44 +794,7 @@ export class GatewayService {
async checkPermission({guildId, userId, permission, channelId}: CheckPermissionParams): Promise<boolean> {
const key = `${guildId.toString()}-${userId.toString()}-${permission.toString()}-${channelId?.toString() || '0'}`;
- return new Promise<boolean>((resolve, reject) => {
- if (this.pendingBatchRequestCount >= this.MAX_PENDING_BATCH_REQUESTS) {
- reject(new ServiceUnavailableError());
- return;
- }
- const pendingRequest: PendingRequest<boolean> = {
- resolve,
- reject,
- settled: false,
- timeoutId: null,
- };
- pendingRequest.timeoutId = setTimeout(() => {
- const error = new GatewayTimeoutError();
- this.rejectPendingRequests([pendingRequest], error);
- this.removePendingPermissionRequest(key, pendingRequest);
- }, this.PENDING_REQUEST_TIMEOUT_MS);
- const pending = this.pendingPermissionRequests.get(key) || [];
- pending.push(pendingRequest);
- this.pendingPermissionRequests.set(key, pending);
- this.pendingBatchRequestCount += 1;
- Logger.debug(
- `[gateway-batch] Queued guild.check_permission request for guild ${guildId.toString()}, user ${userId.toString()}, channel ${channelId?.toString() || 'none'}, permission ${permission.toString()}, total pending: ${pending.length}`,
- );
- this.schedulePermissionBatch();
- });
- }
-
- private removePendingPermissionRequest(key: string, request: PendingRequest<boolean>): void {
- const pending = this.pendingPermissionRequests.get(key);
- if (pending) {
- const index = pending.indexOf(request);
- if (index >= 0) {
- pending.splice(index, 1);
- if (pending.length === 0) {
- this.pendingPermissionRequests.delete(key);
- }
- }
- }
+ return this.enqueueBatchRequest(this.permissionLane, key);
}
async canManageRoles({guildId, userId, targetUserId, roleId}: CanManageRolesParams): Promise<boolean> {
@@ -1060,7 +841,7 @@ export class GatewayService {
return result.can_manage;
}
- async getViewableChannels({guildId, userId}: ViewableChannelsParams): Promise<Array<ChannelID>> {
+ async getViewableChannels({guildId, userId}: GuildUserParams): Promise<Array<ChannelID>> {
const result = await this.call<{
channel_ids: Array<string>;
}>('guild.get_viewable_channels', {
@@ -1136,14 +917,14 @@ export class GatewayService {
return result.channel_id ? createChannelID(BigInt(result.channel_id)) : null;
}
- async joinGuild({userId, guildId}: JoinGuildParams): Promise<void> {
+ async joinGuild({userId, guildId}: GuildUserParams): Promise<void> {
await this.call('presence.join_guild', {
user_id: userId.toString(),
guild_id: guildId.toString(),
});
}
- async leaveGuild({userId, guildId}: LeaveGuildParams): Promise<void> {
+ async leaveGuild({userId, guildId}: GuildUserParams): Promise<void> {
await this.call('presence.leave_guild', {
user_id: userId.toString(),
guild_id: guildId.toString(),
@@ -1461,21 +1242,11 @@ export class GatewayService {
}
destroy(): void {
- if (this.guildDataBatchTimeout) {
- clearTimeout(this.guildDataBatchTimeout);
- this.guildDataBatchTimeout = null;
- }
- if (this.guildMemberBatchTimeout) {
- clearTimeout(this.guildMemberBatchTimeout);
- this.guildMemberBatchTimeout = null;
- }
- if (this.permissionBatchTimeout) {
- clearTimeout(this.permissionBatchTimeout);
- this.permissionBatchTimeout = null;
- }
- if (this.authContextBatchTimeout) {
- clearTimeout(this.authContextBatchTimeout);
- this.authContextBatchTimeout = null;
+ for (const lane of this.lanes) {
+ if (lane.timeout) {
+ clearTimeout(lane.timeout);
+ lane.timeout = null;
+ }
}
this.rejectAllPendingBatchRequests(new ServiceUnavailableError());
}
diff --git a/fluxer_api/src/api/infrastructure/ILiveKitService.ts b/fluxer_api/src/api/infrastructure/ILiveKitService.ts
index 17b4a6bbe..094c58f7f 100644
--- a/fluxer_api/src/api/infrastructure/ILiveKitService.ts
+++ b/fluxer_api/src/api/infrastructure/ILiveKitService.ts
@@ -3,7 +3,7 @@
import type {ChannelID, GuildID, UserID} from '@app/api/BrandedTypes';
import type {VoiceRegionMetadata, VoiceServerRecord} from '@app/api/voice/VoiceModel';
-interface CreateTokenParams {
+export interface CreateTokenParams {
userId: UserID;
guildId?: GuildID;
channelId: ChannelID;
@@ -18,7 +18,7 @@ interface CreateTokenParams {
canVideo?: boolean;
}
-interface UpdateParticipantParams {
+export interface UpdateParticipantParams {
userId: UserID;
guildId?: GuildID;
channelId: ChannelID;
@@ -32,7 +32,7 @@ interface UpdateParticipantParams {
canVideo?: boolean;
}
-interface MuteMicrophoneTrackParams {
+export interface MuteMicrophoneTrackParams {
userId: UserID;
guildId?: GuildID;
channelId: ChannelID;
@@ -42,7 +42,7 @@ interface MuteMicrophoneTrackParams {
trackSid: string;
}
-interface UpdateParticipantPermissionsParams {
+export interface UpdateParticipantPermissionsParams {
userId: UserID;
guildId?: GuildID;
channelId: ChannelID;
@@ -55,7 +55,7 @@ interface UpdateParticipantPermissionsParams {
deaf?: boolean;
}
-interface DisconnectParticipantParams {
+export interface DisconnectParticipantParams {
userId: UserID;
guildId?: GuildID;
channelId: ChannelID;
@@ -64,7 +64,7 @@ interface DisconnectParticipantParams {
serverId: string;
}
-interface ListParticipantsParams {
+export interface ListParticipantsParams {
guildId?: GuildID;
channelId: ChannelID;
regionId: string;
diff --git a/fluxer_api/src/api/infrastructure/LiveKitService.ts b/fluxer_api/src/api/infrastructure/LiveKitService.ts
index cbffc6a76..7793725cb 100644
--- a/fluxer_api/src/api/infrastructure/LiveKitService.ts
+++ b/fluxer_api/src/api/infrastructure/LiveKitService.ts
@@ -2,79 +2,25 @@
import type {ChannelID, GuildID, UserID} from '@app/api/BrandedTypes';
import {Config} from '@app/api/Config';
-import type {ListParticipantsResult} from '@app/api/infrastructure/ILiveKitService';
-import {ILiveKitService} from '@app/api/infrastructure/ILiveKitService';
+import {
+ type CreateTokenParams,
+ type DisconnectParticipantParams,
+ ILiveKitService,
+ type ListParticipantsParams,
+ type ListParticipantsResult,
+ type MuteMicrophoneTrackParams,
+ type UpdateParticipantParams,
+ type UpdateParticipantPermissionsParams,
+} from '@app/api/infrastructure/ILiveKitService';
import {Logger} from '@app/api/Logger';
import type {VoiceRegionMetadata, VoiceServerRecord} from '@app/api/voice/VoiceModel';
import type {VoiceTopology} from '@app/api/voice/VoiceTopology';
import {AccessToken, RoomServiceClient, type TrackInfo, TrackSource} from 'livekit-server-sdk';
-interface CreateTokenParams {
- userId: UserID;
- guildId?: GuildID;
- channelId: ChannelID;
- connectionId: string;
- tokenNonce: string;
- regionId: string;
- serverId: string;
- mute?: boolean;
- deaf?: boolean;
- canSpeak?: boolean;
- canStream?: boolean;
- canVideo?: boolean;
-}
-
-interface UpdateParticipantParams {
- userId: UserID;
- guildId?: GuildID;
- channelId: ChannelID;
- connectionId: string;
- regionId: string;
- serverId: string;
- mute?: boolean;
- deaf?: boolean;
- canSpeak?: boolean;
- canStream?: boolean;
- canVideo?: boolean;
-}
-
-interface DisconnectParticipantParams {
- userId: UserID;
- guildId?: GuildID;
- channelId: ChannelID;
- connectionId: string;
- regionId: string;
- serverId: string;
-}
-
-interface MuteMicrophoneTrackParams {
- userId: UserID;
- guildId?: GuildID;
- channelId: ChannelID;
- connectionId: string;
- regionId: string;
- serverId: string;
- trackSid: string;
-}
-
-interface UpdateParticipantPermissionsParams {
- userId: UserID;
- guildId?: GuildID;
- channelId: ChannelID;
- connectionId: string;
- regionId: string;
- serverId: string;
- canSpeak: boolean;
- canStream: boolean;
- canVideo: boolean;
- deaf?: boolean;
-}
-
interface ServerClientConfig {
endpoint: string;
apiKey: string;
apiSecret: string;
- isActive: boolean;
roomServiceClient: RoomServiceClient;
}
@@ -261,28 +207,14 @@ export class LiveKitService extends ILiveKitService {
await server.roomServiceClient.updateParticipant(roomName, participantIdentity, undefined, {
...participantPermission,
});
- if (!canStream && participant.tracks) {
- for (const track of participant.tracks) {
- if (
- (track.source === TrackSource.SCREEN_SHARE || track.source === TrackSource.SCREEN_SHARE_AUDIO) &&
- track.sid
- ) {
- await server.roomServiceClient.mutePublishedTrack(roomName, participantIdentity, track.sid, true);
- }
- }
- }
- if (!canSpeak && participant.tracks) {
- for (const track of participant.tracks) {
- if (track.source === TrackSource.MICROPHONE && track.sid) {
- await server.roomServiceClient.mutePublishedTrack(roomName, participantIdentity, track.sid, true);
- }
- }
- }
- if (!canVideo && participant.tracks) {
- for (const track of participant.tracks) {
- if (track.source === TrackSource.CAMERA && track.sid) {
- await server.roomServiceClient.mutePublishedTrack(roomName, participantIdentity, track.sid, true);
- }
+ const revokedSources = computeLiveKitPublishSources({
+ canSpeak: !canSpeak,
+ canStream: !canStream,
+ canVideo: !canVideo,
+ });
+ for (const track of participant.tracks) {
+ if (track.sid && revokedSources.includes(track.source)) {
+ await server.roomServiceClient.mutePublishedTrack(roomName, participantIdentity, track.sid, true);
}
}
Logger.debug({participantIdentity, roomName, canSpeak, canStream, canVideo}, 'Updated participant permissions');
@@ -347,12 +279,7 @@ export class LiveKitService extends ILiveKitService {
}
}
- async listParticipants(params: {
- guildId?: GuildID;
- channelId: ChannelID;
- regionId: string;
- serverId: string;
- }): Promise<ListParticipantsResult> {
+ async listParticipants(params: ListParticipantsParams): Promise<ListParticipantsResult> {
const {guildId, channelId, regionId, serverId} = params;
const roomName = this.getRoomName(guildId, channelId);
const server = this.tryResolveServerClient(regionId, serverId);
@@ -399,11 +326,7 @@ export class LiveKitService extends ILiveKitService {
}
private tryResolveServerClient(regionId: string, serverId: string): ServerClientConfig | null {
- const region = this.serverClients.get(regionId);
- if (!region) {
- return null;
- }
- return region.get(serverId) ?? null;
+ return this.serverClients.get(regionId)?.get(serverId) ?? null;
}
getDefaultRegionId(): string | null {
@@ -453,7 +376,6 @@ export class LiveKitService extends ILiveKitService {
endpoint: server.endpoint,
apiKey: server.apiKey,
apiSecret: server.apiSecret,
- isActive: server.isActive,
roomServiceClient: createRoomServiceClient(roomServiceEndpoint, server.apiKey, server.apiSecret),
});
}
diff --git a/fluxer_api/src/api/middleware/ServiceSingletons.ts b/fluxer_api/src/api/middleware/ServiceSingletons.ts
index f34473384..44c077b83 100644
--- a/fluxer_api/src/api/middleware/ServiceSingletons.ts
+++ b/fluxer_api/src/api/middleware/ServiceSingletons.ts
@@ -61,7 +61,7 @@ import {
releaseSnowflakeService,
type SnowflakeServiceHandle,
} from '@app/api/middleware/ServiceRegistry';
-import {clearSingletonsForTesting, singleton} from '@app/api/middleware/Singleton';
+import {clearSingletonsForTesting, keyedSingleton, singleton} from '@app/api/middleware/Singleton';
import {BotAuthService} from '@app/api/oauth/BotAuthService';
import {BotMfaMirrorService} from '@app/api/oauth/BotMfaMirrorService';
import {ApplicationRepository} from '@app/api/oauth/repositories/ApplicationRepository';
@@ -289,23 +289,25 @@ export const getPurgeQueue: () => IPurgeQueue = singleton(() =>
);
export const getAssetDeletionQueue: () => IAssetDeletionQueue = singleton(() => new AssetDeletionQueue(getKVClient()));
-let bulkMessageDeletionQueueClient: IKVProvider | null = null;
-let bulkMessageDeletionQueue: KVBulkMessageDeletionQueueService | null = null;
-
-let threadAutoArchiveQueueClient: IKVProvider | null = null;
-let threadAutoArchiveQueue: KVThreadAutoArchiveQueueService | null = null;
-
-let premiumStateQueueClient: IKVProvider | null = null;
-let premiumStateQueue: PremiumStateReconciliationQueueService | null = null;
-
-let activityTrackerClient: IKVProvider | null = null;
-let activityTracker: KVActivityTracker | null = null;
-
-let activityBufferClient: IKVProvider | null = null;
-let activityBuffer: UserActivityBuffer | null = null;
-
-let accountDeletionQueueClient: IKVProvider | null = null;
-let accountDeletionQueue: KVAccountDeletionQueueService | null = null;
+export const getKVBulkMessageDeletionQueue = keyedSingleton(
+ getKVClient,
+ (kv) => new KVBulkMessageDeletionQueueService(kv, getUserRepository()),
+);
+export const getKVThreadAutoArchiveQueue = keyedSingleton(getKVClient, (kv) => new KVThreadAutoArchiveQueueService(kv));
+export const getPremiumStateReconciliationQueueService = keyedSingleton(
+ getKVClient,
+ (kv) => new PremiumStateReconciliationQueueService(kv),
+);
+export const getKVActivityTracker = keyedSingleton(
+ getKVClient,
+ (kv) => new KVActivityTracker(kv),
+ (tracker) => tracker.shutdown(),
+);
+export const getUserActivityBuffer = keyedSingleton(getKVClient, (kv) => new UserActivityBuffer(kv));
+export const getKVAccountDeletionQueue = keyedSingleton(
+ getKVClient,
+ (kv) => new KVAccountDeletionQueueService(kv, getUserRepository()),
+);
export const getThemeService = singleton(() => new ThemeService(getStorageService()));
export const getAttachmentUploadTraceRepository = singleton(() => new AttachmentUploadTraceRepository());
diff --git a/fluxer_api/src/api/middleware/Singleton.ts b/fluxer_api/src/api/middleware/Singleton.ts
index d0d58b081..899ba2d1d 100644
--- a/fluxer_api/src/api/middleware/Singleton.ts
+++ b/fluxer_api/src/api/middleware/Singleton.ts
@@ -18,6 +18,30 @@ export function singleton<T>(factory: () => T, teardown?: (instance: T) => void)
};
}
+export function keyedSingleton<K, T>(
+ source: () => K,
+ factory: (key: K) => T,
+ teardown?: (instance: T) => void,
+): () => T {
+ let instance: T | undefined;
+ let instanceKey: K | undefined;
+ singletonClearers.push(() => {
+ if (instance !== undefined) {
+ teardown?.(instance);
+ }
+ instance = undefined;
+ instanceKey = undefined;
+ });
+ return () => {
+ const key = source();
+ if (instance === undefined || instanceKey !== key) {
+ instance = factory(key);
+ instanceKey = key;
+ }
+ return instance;
+ };
+}
+
export function clearSingletonsForTesting(): void {
for (const clear of singletonClearers) {
clear();
diff --git a/fluxer_api/src/api/oauth/OAuth2Mappers.ts b/fluxer_api/src/api/oauth/OAuth2Mappers.ts
index 63c18995c..69d0a4475 100644
--- a/fluxer_api/src/api/oauth/OAuth2Mappers.ts
+++ b/fluxer_api/src/api/oauth/OAuth2Mappers.ts
@@ -4,8 +4,7 @@ import {stripBannerForUser} from '@app/api/infrastructure/AssetEntitlementUtils'
import type {Application} from '@app/api/models/Application';
import type {User} from '@app/api/models/User';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
-import {mapUserToPartialResponse} from '@app/api/user/UserMappers';
-import {type UserAuthenticatorType, UserAuthenticatorTypes} from '@fluxer/constants/src/UserConstants';
+import {getActiveAuthenticatorTypes, mapUserToPartialResponse} from '@app/api/user/UserMappers';
import type {
ApplicationBotResponse,
ApplicationResponse,
@@ -17,13 +16,6 @@ export function findBotUser(users: Pick<UserRepository, 'findUnique'>, applicati
return application.botUserId ? users.findUnique(application.botUserId) : Promise.resolve(null);
}
-function getActiveAuthenticatorTypes(user: User): Array<UserAuthenticatorType> {
- return Array.from(user.authenticatorTypes ?? []).filter(
- (type): type is UserAuthenticatorType =>
- type === UserAuthenticatorTypes.TOTP || type === UserAuthenticatorTypes.WEBAUTHN,
- );
-}
-
export function mapBotUserToResponse(
user: User,
opts?: {
diff --git a/fluxer_api/src/api/rpc/RpcService.ts b/fluxer_api/src/api/rpc/RpcService.ts
index 10493126c..abcfe4008 100644
--- a/fluxer_api/src/api/rpc/RpcService.ts
+++ b/fluxer_api/src/api/rpc/RpcService.ts
@@ -302,6 +302,13 @@ export class RpcService {
return sticker;
}
+ private requireVoiceService(): VoiceService {
+ if (this.voiceService === null) {
+ throw new Error('Voice is not enabled on this server');
+ }
+ return this.voiceService;
+ }
+
async handleRpcRequest({request, requestCache}: HandleRpcRequestParams): Promise<RpcResponse> {
switch (request.type) {
case 'session':
@@ -401,10 +408,7 @@ export class RpcService {
{type: 'voice_get_token', guildId: request.guild_id, channelId: request.channel_id, userId: request.user_id},
'RPC voice_get_token received',
);
- if (this.voiceService === null) {
- throw new Error('Voice is not enabled on this server');
- }
- const result = await this.voiceService.getVoiceToken({
+ const result = await this.requireVoiceService().getVoiceToken({
guildId: request.guild_id !== undefined ? createGuildID(request.guild_id) : undefined,
channelId: createChannelID(request.channel_id),
userId: createUserID(request.user_id),
@@ -427,10 +431,7 @@ export class RpcService {
};
}
case 'voice_force_disconnect_participant': {
- if (this.voiceService === null) {
- throw new Error('Voice is not enabled on this server');
- }
- await this.voiceService.disconnectParticipant({
+ await this.requireVoiceService().disconnectParticipant({
guildId: request.guild_id !== undefined ? createGuildID(request.guild_id) : undefined,
channelId: createChannelID(request.channel_id),
userId: createUserID(request.user_id),
@@ -442,10 +443,7 @@ export class RpcService {
};
}
case 'voice_update_participant': {
- if (this.voiceService === null) {
- throw new Error('Voice is not enabled on this server');
- }
- await this.voiceService.updateParticipant({
+ await this.requireVoiceService().updateParticipant({
guildId: request.guild_id !== undefined ? createGuildID(request.guild_id) : undefined,
channelId: createChannelID(request.channel_id),
userId: createUserID(request.user_id),
@@ -461,10 +459,7 @@ export class RpcService {
};
}
case 'voice_update_participant_permissions': {
- if (this.voiceService === null) {
- throw new Error('Voice is not enabled on this server');
- }
- await this.voiceService.updateParticipantPermissions({
+ await this.requireVoiceService().updateParticipantPermissions({
guildId: request.guild_id !== undefined ? createGuildID(request.guild_id) : undefined,
channelId: createChannelID(request.channel_id),
userId: createUserID(request.user_id),
diff --git a/fluxer_api/src/api/search/ChannelIndexingUtils.ts b/fluxer_api/src/api/search/ChannelIndexingUtils.ts
index 6e580a1d3..3f651d288 100644
--- a/fluxer_api/src/api/search/ChannelIndexingUtils.ts
+++ b/fluxer_api/src/api/search/ChannelIndexingUtils.ts
@@ -1,6 +1,11 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import {mapWithConcurrency} from '@app/api/utils/ConcurrencyUtils';
+import type {WorkerTaskName} from '@app/api/worker/WorkerLaneConfig';
import {CHANNEL_REINDEX_AFTER_TIMESTAMP} from '@fluxer/constants/src/ChannelConstants';
+import type {IWorkerService} from '@pkgs/worker/src/contracts/IWorkerService';
+
+const CHANNEL_INDEX_JOB_ENQUEUE_CONCURRENCY = 16;
export function channelNeedsReindexing(
indexedAt: Date | null | undefined,
@@ -12,3 +17,19 @@ export function channelNeedsReindexing(
const indexedAtSeconds = Math.floor(indexedAt.getTime() / 1000);
return indexedAtSeconds < cutoffSeconds;
}
+
+export async function queueIndexingChannels(
+ workerService: IWorkerService<WorkerTaskName>,
+ channelIds: Iterable<string>,
+): Promise<void> {
+ await mapWithConcurrency(Array.from(channelIds), CHANNEL_INDEX_JOB_ENQUEUE_CONCURRENCY, (channelId) =>
+ workerService.addJob(
+ 'indexChannelMessages',
+ {channelId},
+ {
+ jobKey: `indexChannelMessages-${channelId}`,
+ maxAttempts: 3,
+ },
+ ),
+ );
+}
diff --git a/fluxer_api/src/api/search/GlobalSearchService.ts b/fluxer_api/src/api/search/GlobalSearchService.ts
index b62d959c1..b0b472558 100644
--- a/fluxer_api/src/api/search/GlobalSearchService.ts
+++ b/fluxer_api/src/api/search/GlobalSearchService.ts
@@ -14,27 +14,23 @@ import type {UserCacheService} from '@app/api/infrastructure/UserCacheService';
import type {RequestCache} from '@app/api/middleware/RequestCacheMiddleware';
import type {Channel} from '@app/api/models/Channel';
import {getMessageSearchService} from '@app/api/SearchFactory';
-import {buildMessageSearchFilters} from '@app/api/search/BuildMessageSearchFilters';
-import {channelNeedsReindexing} from '@app/api/search/ChannelIndexingUtils';
+import {channelNeedsReindexing, queueIndexingChannels} from '@app/api/search/ChannelIndexingUtils';
import type {IMessageSearchService} from '@app/api/search/IMessageSearchService';
import {MessageSearchResponseMapper} from '@app/api/search/MessageSearchResponseMapper';
-import {searchExistingMessages} from '@app/api/search/MessageSearchResultReconciler';
-import {channelRequiresAgeVerification} from '@app/api/search/SearchNsfwUtils';
+import {emptyMessageSearchResponse, runMessageSearch} from '@app/api/search/MessageSearchResultReconciler';
+import {channelRequiresAgeVerification, getCanUserAccessNsfw} from '@app/api/search/SearchNsfwUtils';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
-import {canUserAccessNsfwContent} from '@app/api/utils/AgeUtils';
import {mapWithConcurrency} from '@app/api/utils/ConcurrencyUtils';
import type {WorkerTaskName} from '@app/api/worker/WorkerLaneConfig';
import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
import {GuildNSFWLevel} from '@fluxer/constants/src/GuildConstants';
import {FeatureTemporarilyDisabledError} from '@fluxer/errors/src/domains/core/FeatureTemporarilyDisabledError';
import {MissingPermissionsError} from '@fluxer/errors/src/domains/core/MissingPermissionsError';
-import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';
import type {MessageSearchRequest} from '@fluxer/schema/src/domains/message/MessageRequestSchemas';
import type {MessageSearchResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
import type {IWorkerService} from '@pkgs/worker/src/contracts/IWorkerService';
const CHANNEL_INDEX_CHECK_CONCURRENCY = 32;
-const CHANNEL_INDEX_JOB_ENQUEUE_CONCURRENCY = 16;
export class GlobalSearchService {
private readonly responseMapper: MessageSearchResponseMapper;
@@ -75,15 +71,7 @@ export class GlobalSearchService {
});
const finalChannelIds = this.filterRequestedChannelIds(dmChannelIds, params.requestedChannelIds);
if (finalChannelIds.length === 0) {
- const hitsPerPage = params.searchParams.hits_per_page ?? 25;
- const page = params.searchParams.page ?? 1;
- return {
- channels: [],
- messages: [],
- total: 0,
- hits_per_page: hitsPerPage,
- page,
- };
+ return emptyMessageSearchResponse(params.searchParams);
}
const needsIndexing = await this.ensureChannelsIndexed(finalChannelIds);
if (needsIndexing) {
@@ -107,7 +95,7 @@ export class GlobalSearchService {
]);
const {accessibleChannels, unindexedChannelIds, guildNsfwLevels, parentCategories, threadParents} = guildAccess;
if (unindexedChannelIds.size > 0) {
- await this.queueIndexingChannels(unindexedChannelIds);
+ await queueIndexingChannels(this.workerService, unindexedChannelIds);
return {indexing: true};
}
const guildChannelIds = [...accessibleChannels.keys(), ...threadParents.keys()];
@@ -125,7 +113,7 @@ export class GlobalSearchService {
const includeNsfwRequested = params.searchParams.include_nsfw ?? false;
let canIncludeNsfw = false;
if (includeNsfwRequested) {
- canIncludeNsfw = await this.getCanUserAccessNsfw(params.userId);
+ canIncludeNsfw = await getCanUserAccessNsfw(this.userRepository, params.userId);
}
const finalChannelIds = validatedChannelIds.filter((channelIdStr) => {
const channel = accessibleChannels.get(channelIdStr) ?? threadParents.get(channelIdStr);
@@ -143,15 +131,7 @@ export class GlobalSearchService {
return true;
});
if (finalChannelIds.length === 0) {
- const hitsPerPage = params.searchParams.hits_per_page ?? 25;
- const page = params.searchParams.page ?? 1;
- return {
- channels: [],
- messages: [],
- total: 0,
- hits_per_page: hitsPerPage,
- page,
- };
+ return emptyMessageSearchResponse(params.searchParams);
}
const needsIndexing = await this.ensureChannelsIndexed(
threadParents.size > 0 ? finalChannelIds.filter((id) => !threadParents.has(id)) : finalChannelIds,
@@ -220,23 +200,10 @@ export class GlobalSearchService {
if (unindexed.size === 0) {
return false;
}
- await this.queueIndexingChannels(unindexed);
+ await queueIndexingChannels(this.workerService, unindexed);
return true;
}
- private async queueIndexingChannels(channelIds: Iterable<string>): Promise<void> {
- await mapWithConcurrency(Array.from(channelIds), CHANNEL_INDEX_JOB_ENQUEUE_CONCURRENCY, async (channelId) => {
- await this.workerService.addJob(
- 'indexChannelMessages',
- {channelId},
- {
- jobKey: `indexChannelMessages-${channelId}`,
- maxAttempts: 3,
- },
- );
- });
- }
-
private async runSearch(
channelIds: Array<string>,
userId: UserID,
@@ -244,43 +211,16 @@ export class GlobalSearchService {
searchParams: MessageSearchRequest,
requestCache: RequestCache,
): Promise<MessageSearchResponse> {
- const searchService = this.getMessageSearchService();
- const normalizedSearchParams = {...searchParams, channel_id: undefined};
- const filters = buildMessageSearchFilters(normalizedSearchParams, channelIds);
- const hitsPerPage = searchParams.hits_per_page ?? 25;
- const page = searchParams.page ?? 1;
- const cursor = searchParams.cursor;
- const result = await searchExistingMessages({
- searchService,
+ return runMessageSearch({
+ searchService: this.getMessageSearchService(),
messageRepository: this.channelRepository,
- query: searchParams.content ?? '',
- filters,
- hitsPerPage,
- page,
- cursor,
- });
- const mappedResponses = await this.responseMapper.mapSearchResultToResponses(
- result.messages,
+ responseMapper: this.responseMapper,
+ filterParams: {...searchParams, channel_id: undefined},
+ searchParams,
+ channelIds,
userId,
viewer,
requestCache,
- );
- return {
- messages: mappedResponses.messages,
- channels: mappedResponses.channels,
- total: result.total,
- hits_per_page: hitsPerPage,
- page,
- cursor: result.cursor,
- ...(mappedResponses.threads ? {threads: mappedResponses.threads, members: mappedResponses.members} : {}),
- };
- }
-
- private async getCanUserAccessNsfw(userId: UserID): Promise<boolean> {
- const user = await this.userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
- return canUserAccessNsfwContent(user);
+ });
}
}
diff --git a/fluxer_api/src/api/search/MessageSearchResultReconciler.ts b/fluxer_api/src/api/search/MessageSearchResultReconciler.ts
index 16ed157ed..493972cd6 100644
--- a/fluxer_api/src/api/search/MessageSearchResultReconciler.ts
+++ b/fluxer_api/src/api/search/MessageSearchResultReconciler.ts
@@ -1,14 +1,20 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {type ChannelID, createChannelID, createMessageID, type MessageID} from '@app/api/BrandedTypes';
+import {type ChannelID, createChannelID, createMessageID, type MessageID, type UserID} from '@app/api/BrandedTypes';
import type {MessageRepository} from '@app/api/channel/repositories/MessageRepository';
+import type {ThreadViewer} from '@app/api/experiment/ChannelThreadsGate';
import {Logger} from '@app/api/Logger';
+import type {RequestCache} from '@app/api/middleware/RequestCacheMiddleware';
import type {Message} from '@app/api/models/Message';
+import {buildMessageSearchFilters} from '@app/api/search/BuildMessageSearchFilters';
import type {IMessageSearchService} from '@app/api/search/IMessageSearchService';
import {deleteMessageSearchDocuments} from '@app/api/search/MessageSearchIndexCleanup';
+import type {MessageSearchResponseMapper} from '@app/api/search/MessageSearchResponseMapper';
import {mapWithConcurrency} from '@app/api/utils/ConcurrencyUtils';
import type {SearchResult} from '@fluxer/schema/src/contracts/search/SearchAdapterTypes';
import type {MessageSearchFilters, SearchableMessage} from '@fluxer/schema/src/contracts/search/SearchDocumentTypes';
+import type {MessageSearchRequest} from '@fluxer/schema/src/domains/message/MessageRequestSchemas';
+import type {MessageSearchResultsResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
const RECONCILE_BATCH_SIZE = 250;
const MAX_RECONCILE_PAGES = 40;
@@ -88,6 +94,65 @@ export async function searchExistingMessages({
});
}
+export function emptyMessageSearchResponse(searchParams: MessageSearchRequest): MessageSearchResultsResponse {
+ return {
+ channels: [],
+ messages: [],
+ total: 0,
+ hits_per_page: searchParams.hits_per_page ?? 25,
+ page: searchParams.page ?? 1,
+ };
+}
+
+export async function runMessageSearch({
+ searchService,
+ messageRepository,
+ responseMapper,
+ filterParams,
+ searchParams,
+ channelIds,
+ userId,
+ viewer,
+ requestCache,
+}: {
+ searchService: IMessageSearchService;
+ messageRepository: MessageLookupRepository;
+ responseMapper: MessageSearchResponseMapper;
+ filterParams: MessageSearchRequest;
+ searchParams: MessageSearchRequest;
+ channelIds: Array<string>;
+ userId: UserID;
+ viewer: ThreadViewer;
+ requestCache: RequestCache;
+}): Promise<MessageSearchResultsResponse> {
+ const hitsPerPage = searchParams.hits_per_page ?? 25;
+ const page = searchParams.page ?? 1;
+ const result = await searchExistingMessages({
+ searchService,
+ messageRepository,
+ query: searchParams.content ?? '',
+ filters: buildMessageSearchFilters(filterParams, channelIds),
+ hitsPerPage,
+ page,
+ cursor: searchParams.cursor,
+ });
+ const mappedResponses = await responseMapper.mapSearchResultToResponses(
+ result.messages,
+ userId,
+ viewer,
+ requestCache,
+ );
+ return {
+ messages: mappedResponses.messages,
+ channels: mappedResponses.channels,
+ total: result.total,
+ hits_per_page: hitsPerPage,
+ page,
+ cursor: result.cursor,
+ ...(mappedResponses.threads ? {threads: mappedResponses.threads, members: mappedResponses.members} : {}),
+ };
+}
+
async function reconcileOffsetSearchResult({
searchService,
messageRepository,
diff --git a/fluxer_api/src/api/search/SearchAdapterServiceBase.ts b/fluxer_api/src/api/search/SearchAdapterServiceBase.ts
index 10ed43dcc..d98ca21a4 100644
--- a/fluxer_api/src/api/search/SearchAdapterServiceBase.ts
+++ b/fluxer_api/src/api/search/SearchAdapterServiceBase.ts
@@ -8,11 +8,7 @@ export abstract class SearchAdapterServiceBase<
TDocument,
TAdapter extends ISearchAdapter<TFilters, TDocument>,
> {
- protected readonly adapter: TAdapter;
-
- protected constructor(adapter: TAdapter) {
- this.adapter = adapter;
- }
+ constructor(protected readonly adapter: TAdapter) {}
initialize(): Promise<void> {
return this.adapter.initialize();
diff --git a/fluxer_api/src/api/search/SearchNsfwUtils.ts b/fluxer_api/src/api/search/SearchNsfwUtils.ts
index 36ecb6737..8230ec952 100644
--- a/fluxer_api/src/api/search/SearchNsfwUtils.ts
+++ b/fluxer_api/src/api/search/SearchNsfwUtils.ts
@@ -1,13 +1,17 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import type {UserID} from '@app/api/BrandedTypes';
import {
channelToContentWarningView,
computeEffectiveChannelNsfw,
resolveEffectiveThreadNsfw,
} from '@app/api/channel/utils/EffectiveContentWarning';
import type {Channel} from '@app/api/models/Channel';
+import type {UserRepository} from '@app/api/user/repositories/UserRepository';
+import {canUserAccessNsfwContent} from '@app/api/utils/AgeUtils';
import {ContentWarningLevel} from '@fluxer/constants/src/GuildConstants';
import {THREAD_CHANNEL_TYPES} from '@fluxer/constants/src/ThreadConstants';
+import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';
export function channelRequiresAgeVerification(
channel: Channel,
@@ -31,3 +35,11 @@ export function channelRequiresAgeVerification(
guild,
);
}
+
+export async function getCanUserAccessNsfw(userRepository: UserRepository, userId: UserID): Promise<boolean> {
+ const user = await userRepository.findUnique(userId);
+ if (!user) {
+ throw new UnknownUserError();
+ }
+ return canUserAccessNsfwContent(user);
+}
diff --git a/fluxer_api/src/api/search/SearchServices.ts b/fluxer_api/src/api/search/SearchServices.ts
index 91da1724e..afd5594c4 100644
--- a/fluxer_api/src/api/search/SearchServices.ts
+++ b/fluxer_api/src/api/search/SearchServices.ts
@@ -80,10 +80,6 @@ export class MessageSearchService
>
implements IMessageSearchService
{
- constructor(adapter: TermSearchAdapter<MessageSearchFilters, SearchableMessage>) {
- super(adapter);
- }
-
async indexMessage(message: Message, authorIsBot?: boolean): Promise<void> {
await this.indexDocument(convertToSearchableMessage(message, authorIsBot));
}
@@ -181,10 +177,6 @@ export class UserSearchService
extends SearchAdapterServiceBase<UserSearchFilters, SearchableUser, ISearchAdapter<UserSearchFilters, SearchableUser>>
implements IUserSearchService
{
- constructor(adapter: ISearchAdapter<UserSearchFilters, SearchableUser>) {
- super(adapter);
- }
-
async indexUser(user: User): Promise<void> {
await this.indexDocument(convertToSearchableUser(user));
}
@@ -218,10 +210,6 @@ export class ReportSearchService
>
implements IReportSearchService
{
- constructor(adapter: ISearchAdapter<ReportSearchFilters, SearchableReport>) {
- super(adapter);
- }
-
async indexReport(report: IARSubmission): Promise<void> {
await this.indexDocument(convertToSearchableReport(report));
}
@@ -263,10 +251,6 @@ export class AuditLogSearchService
>
implements IAuditLogSearchService
{
- constructor(adapter: ISearchAdapter<AuditLogSearchFilters, SearchableAuditLog>) {
- super(adapter);
- }
-
async indexAuditLog(log: AdminAuditLog): Promise<void> {
await this.indexDocument(convertToSearchableAuditLog(log));
}
@@ -296,10 +280,6 @@ export class GuildMemberSearchService
>
implements IGuildMemberSearchService
{
- constructor(adapter: TermSearchAdapter<GuildMemberSearchFilters, SearchableGuildMember>) {
- super(adapter);
- }
-
async indexMember(member: GuildMember, user: User): Promise<void> {
await this.indexDocument(convertToSearchableGuildMember(member, user));
}
diff --git a/fluxer_api/src/api/search/SearchTaskTracker.ts b/fluxer_api/src/api/search/SearchTaskTracker.ts
index 52e5a69b1..b3820eab4 100644
--- a/fluxer_api/src/api/search/SearchTaskTracker.ts
+++ b/fluxer_api/src/api/search/SearchTaskTracker.ts
@@ -4,6 +4,8 @@ let trackingEnabled = false;
const pendingTasks = new Set<Promise<unknown>>();
+const DRAIN_TIMEOUT_MS = 30000;
+
export function enableSearchTaskTracking(): void {
trackingEnabled = true;
}
@@ -19,12 +21,11 @@ export function trackSearchTask<T>(promise: Promise<T>): Promise<T> {
return promise;
}
-export async function drainSearchTasks(options?: {timeoutMs?: number}): Promise<void> {
+export async function drainSearchTasks(): Promise<void> {
if (!trackingEnabled) {
return;
}
- const timeoutMs = options?.timeoutMs ?? 30000;
- const deadline = Date.now() + timeoutMs;
+ const deadline = Date.now() + DRAIN_TIMEOUT_MS;
while (pendingTasks.size > 0) {
const snapshot = Array.from(pendingTasks);
const remainingMs = deadline - Date.now();
diff --git a/fluxer_api/src/api/search/meilisearch/MeilisearchDomainAdapters.ts b/fluxer_api/src/api/search/meilisearch/MeilisearchDomainAdapters.ts
index 4a129a7f0..89a1e6be9 100644
--- a/fluxer_api/src/api/search/meilisearch/MeilisearchDomainAdapters.ts
+++ b/fluxer_api/src/api/search/meilisearch/MeilisearchDomainAdapters.ts
@@ -69,64 +69,34 @@ function buildMessageFilters(filters: MessageSearchFilters): Array<MeilisearchFi
if (filters.channelId) clauses.push(meiliTermFilter('channelId', filters.channelId));
if (filters.channelIds && filters.channelIds.length > 0)
clauses.push(meiliTermsFilter('channelId', filters.channelIds));
- if (filters.excludeChannelIds && filters.excludeChannelIds.length > 0) {
- clauses.push(...meiliExcludeAny('channelId', filters.excludeChannelIds));
- }
+ clauses.push(...meiliExcludeAny('channelId', filters.excludeChannelIds ?? []));
if (filters.authorId && filters.authorId.length > 0) clauses.push(meiliTermsFilter('authorId', filters.authorId));
- if (filters.excludeAuthorIds && filters.excludeAuthorIds.length > 0) {
- clauses.push(...meiliExcludeAny('authorId', filters.excludeAuthorIds));
- }
+ clauses.push(...meiliExcludeAny('authorId', filters.excludeAuthorIds ?? []));
if (filters.authorType && filters.authorType.length > 0)
clauses.push(meiliTermsFilter('authorType', filters.authorType));
- if (filters.excludeAuthorType && filters.excludeAuthorType.length > 0) {
- clauses.push(...meiliExcludeAny('authorType', filters.excludeAuthorType));
- }
- if (filters.mentions && filters.mentions.length > 0)
- clauses.push(...meiliAndTerms('mentionedUserIds', filters.mentions));
- if (filters.excludeMentions && filters.excludeMentions.length > 0) {
- clauses.push(...meiliExcludeAny('mentionedUserIds', filters.excludeMentions));
- }
+ clauses.push(...meiliExcludeAny('authorType', filters.excludeAuthorType ?? []));
+ clauses.push(...meiliAndTerms('mentionedUserIds', filters.mentions ?? []));
+ clauses.push(...meiliExcludeAny('mentionedUserIds', filters.excludeMentions ?? []));
if (filters.mentionEveryone !== undefined) clauses.push(meiliTermFilter('mentionEveryone', filters.mentionEveryone));
if (filters.pinned !== undefined) clauses.push(meiliTermFilter('isPinned', filters.pinned));
- if (filters.has && filters.has.length > 0) {
- for (const hasType of filters.has) {
- const field = HAS_FIELD_MAP[hasType];
- if (field) clauses.push(meiliTermFilter(field, true));
- }
- }
- if (filters.excludeHas && filters.excludeHas.length > 0) {
- for (const hasType of filters.excludeHas) {
- const field = HAS_FIELD_MAP[hasType];
- if (field) clauses.push(meiliTermFilter(field, false));
- }
- }
- if (filters.embedType && filters.embedType.length > 0)
- clauses.push(...meiliAndTerms('embedTypes', filters.embedType));
- if (filters.excludeEmbedTypes && filters.excludeEmbedTypes.length > 0) {
- clauses.push(...meiliExcludeAny('embedTypes', filters.excludeEmbedTypes));
+ for (const hasType of filters.has ?? []) {
+ const field = HAS_FIELD_MAP[hasType];
+ if (field) clauses.push(meiliTermFilter(field, true));
}
- if (filters.embedProvider && filters.embedProvider.length > 0)
- clauses.push(...meiliAndTerms('embedProviders', filters.embedProvider));
- if (filters.excludeEmbedProviders && filters.excludeEmbedProviders.length > 0) {
- clauses.push(...meiliExcludeAny('embedProviders', filters.excludeEmbedProviders));
- }
- if (filters.linkHostname && filters.linkHostname.length > 0)
- clauses.push(...meiliAndTerms('linkHostnames', filters.linkHostname));
- if (filters.excludeLinkHostnames && filters.excludeLinkHostnames.length > 0) {
- clauses.push(...meiliExcludeAny('linkHostnames', filters.excludeLinkHostnames));
- }
- if (filters.attachmentFilename && filters.attachmentFilename.length > 0) {
- clauses.push(...meiliAndTerms('attachmentFilenames', filters.attachmentFilename));
- }
- if (filters.excludeAttachmentFilenames && filters.excludeAttachmentFilenames.length > 0) {
- clauses.push(...meiliExcludeAny('attachmentFilenames', filters.excludeAttachmentFilenames));
- }
- if (filters.attachmentExtension && filters.attachmentExtension.length > 0) {
- clauses.push(...meiliAndTerms('attachmentExtensions', filters.attachmentExtension));
- }
- if (filters.excludeAttachmentExtensions && filters.excludeAttachmentExtensions.length > 0) {
- clauses.push(...meiliExcludeAny('attachmentExtensions', filters.excludeAttachmentExtensions));
+ for (const hasType of filters.excludeHas ?? []) {
+ const field = HAS_FIELD_MAP[hasType];
+ if (field) clauses.push(meiliTermFilter(field, false));
}
+ clauses.push(...meiliAndTerms('embedTypes', filters.embedType ?? []));
+ clauses.push(...meiliExcludeAny('embedTypes', filters.excludeEmbedTypes ?? []));
+ clauses.push(...meiliAndTerms('embedProviders', filters.embedProvider ?? []));
+ clauses.push(...meiliExcludeAny('embedProviders', filters.excludeEmbedProviders ?? []));
+ clauses.push(...meiliAndTerms('linkHostnames', filters.linkHostname ?? []));
+ clauses.push(...meiliExcludeAny('linkHostnames', filters.excludeLinkHostnames ?? []));
+ clauses.push(...meiliAndTerms('attachmentFilenames', filters.attachmentFilename ?? []));
+ clauses.push(...meiliExcludeAny('attachmentFilenames', filters.excludeAttachmentFilenames ?? []));
+ clauses.push(...meiliAndTerms('attachmentExtensions', filters.attachmentExtension ?? []));
+ clauses.push(...meiliExcludeAny('attachmentExtensions', filters.excludeAttachmentExtensions ?? []));
if (filters.maxId != null) clauses.push(meiliRangeFilter('createdAt', {lt: snowflakeSeconds(filters.maxId)}));
if (filters.minId != null) clauses.push(meiliRangeFilter('createdAt', {gt: snowflakeSeconds(filters.minId)}));
return compactMeiliFilters(clauses);
@@ -145,8 +115,7 @@ function buildGuildFilters(filters: GuildSearchFilters): Array<MeilisearchFilter
clauses.push(meiliTermFilter('verificationLevel', filters.verificationLevel));
if (filters.mfaLevel !== undefined) clauses.push(meiliTermFilter('mfaLevel', filters.mfaLevel));
if (filters.nsfwLevel !== undefined) clauses.push(meiliTermFilter('nsfwLevel', filters.nsfwLevel));
- if (filters.hasFeature && filters.hasFeature.length > 0)
- clauses.push(...meiliAndTerms('features', filters.hasFeature));
+ clauses.push(...meiliAndTerms('features', filters.hasFeature ?? []));
if (filters.isDiscoverable !== undefined) clauses.push(meiliTermFilter('isDiscoverable', filters.isDiscoverable));
if (filters.discoveryCategory !== undefined)
clauses.push(meiliTermFilter('discoveryCategory', filters.discoveryCategory));
@@ -173,7 +142,7 @@ function buildUserFilters(filters: UserSearchFilters): Array<MeilisearchFilter |
filters.isPendingDeletion ? meiliExistsFilter('pendingDeletionAt') : meiliNotExistsFilter('pendingDeletionAt'),
);
}
- if (filters.hasAcl && filters.hasAcl.length > 0) clauses.push(...meiliAndTerms('acls', filters.hasAcl));
+ clauses.push(...meiliAndTerms('acls', filters.hasAcl ?? []));
if (filters.createdAtGreaterThanOrEqual !== undefined) {
clauses.push(meiliRangeFilter('createdAt', {gte: filters.createdAtGreaterThanOrEqual}));
}
@@ -209,16 +178,14 @@ function buildAuditLogFilters(filters: AuditLogSearchFilters): Array<Meilisearch
if (filters.targetId) clauses.push(meiliTermFilter('targetId', filters.targetId));
if (filters.action) clauses.push(meiliTermFilter('action', filters.action));
if (filters.actions && filters.actions.length > 0) clauses.push(meiliTermsFilter('action', filters.actions));
- if (filters.excludeActions && filters.excludeActions.length > 0) {
- clauses.push(...meiliExcludeAny('action', filters.excludeActions));
- }
+ clauses.push(...meiliExcludeAny('action', filters.excludeActions ?? []));
return compactMeiliFilters(clauses);
}
function buildGuildMemberFilters(filters: GuildMemberSearchFilters): Array<MeilisearchFilter | undefined> {
const clauses: Array<MeilisearchFilter | undefined> = [];
clauses.push(meiliTermFilter('guildId', filters.guildId));
- if (filters.roleIds && filters.roleIds.length > 0) clauses.push(...meiliAndTerms('roleIds', filters.roleIds));
+ clauses.push(...meiliAndTerms('roleIds', filters.roleIds ?? []));
if (filters.joinedAtGte !== undefined) clauses.push(meiliRangeFilter('joinedAt', {gte: filters.joinedAtGte}));
if (filters.joinedAtLte !== undefined) clauses.push(meiliRangeFilter('joinedAt', {lte: filters.joinedAtLte}));
if (filters.joinSourceType && filters.joinSourceType.length > 0) {
diff --git a/fluxer_api/src/api/search/thread/ThreadSearchIndex.ts b/fluxer_api/src/api/search/thread/ThreadSearchIndex.ts
index 66a737f2c..5b64dd488 100644
--- a/fluxer_api/src/api/search/thread/ThreadSearchIndex.ts
+++ b/fluxer_api/src/api/search/thread/ThreadSearchIndex.ts
@@ -15,10 +15,6 @@ export class ThreadSearchIndex
{
private initializing: Promise<void> | null = null;
- constructor(adapter: ISearchAdapter<ThreadSearchFilters, SearchableThread>) {
- super(adapter);
- }
-
ready(): Promise<void> {
if (this.isAvailable()) return Promise.resolve();
this.initializing ??= this.initialize().catch((error) => {
diff --git a/fluxer_api/src/api/user/UserMappers.ts b/fluxer_api/src/api/user/UserMappers.ts
index bf1a4e7ae..8a3db0cb7 100644
--- a/fluxer_api/src/api/user/UserMappers.ts
+++ b/fluxer_api/src/api/user/UserMappers.ts
@@ -59,7 +59,7 @@ function mapUserFlagsToPublicBitfield(user: User): number {
return Number(flags & getVisiblePublicUserFlags(flags));
}
-function getActiveAuthenticatorTypes(user: User): Array<UserAuthenticatorType> {
+export function getActiveAuthenticatorTypes(user: User): Array<UserAuthenticatorType> {
return Array.from(user.authenticatorTypes ?? []).filter(
(type): type is UserAuthenticatorType =>
type === UserAuthenticatorTypes.TOTP || type === UserAuthenticatorTypes.WEBAUTHN,
diff --git a/fluxer_api/src/api/user/repositories/GiftCodeRepository.ts b/fluxer_api/src/api/user/repositories/GiftCodeRepository.ts
index 1b866da72..4b733ca6d 100644
--- a/fluxer_api/src/api/user/repositories/GiftCodeRepository.ts
+++ b/fluxer_api/src/api/user/repositories/GiftCodeRepository.ts
@@ -109,33 +109,16 @@ export class GiftCodeRepository {
}
async findGiftCodesByCreator(userId: UserID): Promise<Array<GiftCode>> {
- const codes = await fetchMany<{
- code: string;
- }>(FETCH_GIFT_CODES_BY_CREATOR_QUERY, {
- created_by_user_id: userId,
- });
- if (codes.length === 0) {
- return [];
- }
- const gifts: Array<GiftCode> = [];
- for (const {code} of codes) {
- const gift = await this.findGiftCode(code);
- if (gift) {
- gifts.push(gift);
- }
- }
- return gifts;
+ const codes = await fetchMany<{code: string}>(FETCH_GIFT_CODES_BY_CREATOR_QUERY, {created_by_user_id: userId});
+ return this.loadGiftCodes(codes);
}
async findGiftCodesByRedeemer(userId: UserID): Promise<Array<GiftCode>> {
- const codes = await fetchMany<{
- code: string;
- }>(FETCH_GIFT_CODES_BY_REDEEMER_QUERY, {
- redeemed_by_user_id: userId,
- });
- if (codes.length === 0) {
- return [];
- }
+ const codes = await fetchMany<{code: string}>(FETCH_GIFT_CODES_BY_REDEEMER_QUERY, {redeemed_by_user_id: userId});
+ return this.loadGiftCodes(codes);
+ }
+
+ private async loadGiftCodes(codes: Array<{code: string}>): Promise<Array<GiftCode>> {
const gifts: Array<GiftCode> = [];
for (const {code} of codes) {
const gift = await this.findGiftCode(code);
diff --git a/fluxer_api/src/api/user/repositories/UserRepository.ts b/fluxer_api/src/api/user/repositories/UserRepository.ts
index a24a3f0b5..09940aab0 100644
--- a/fluxer_api/src/api/user/repositories/UserRepository.ts
+++ b/fluxer_api/src/api/user/repositories/UserRepository.ts
@@ -682,21 +682,7 @@ export class UserRepository {
return this.pushSubscriptionRepository.deleteAllPushSubscriptions(userId);
}
- async createPayment(data: {
- checkout_session_id: string;
- user_id: UserID;
- price_id: string;
- product_type: string;
- status: string;
- is_gift: boolean;
- created_at: Date;
- purchase_geoip_country_code?: string | null;
- purchase_client_country_code?: string | null;
- eu_withdrawal_waiver_required?: boolean;
- eu_withdrawal_waiver_accepted?: boolean;
- eu_withdrawal_waiver_accepted_at?: Date | null;
- eu_withdrawal_waiver_text_version?: string | null;
- }): Promise<void> {
+ async createPayment(data: Parameters<PaymentRepository['createPayment']>[0]): Promise<void> {
return this.paymentRepository.createPayment(data);
}
diff --git a/fluxer_api/src/api/user/services/UserAccountLifecycleService.ts b/fluxer_api/src/api/user/services/UserAccountLifecycleService.ts
index badc2e362..68d97a01a 100644
--- a/fluxer_api/src/api/user/services/UserAccountLifecycleService.ts
+++ b/fluxer_api/src/api/user/services/UserAccountLifecycleService.ts
@@ -31,10 +31,7 @@ export class UserAccountLifecycleService {
constructor(private readonly deps: UserAccountLifecycleServiceDeps) {}
async selfDisable(userId: UserID): Promise<void> {
- const user = await this.deps.userAccountRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await this.deps.userAccountRepository.findUniqueAssert(userId);
const updatedUser = await this.deps.userAccountRepository.updateFlags(
userId,
(flags) => flags | UserFlags.DISABLED,
@@ -46,10 +43,7 @@ export class UserAccountLifecycleService {
}
async selfDelete(userId: UserID): Promise<void> {
- const user = await this.deps.userAccountRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await this.deps.userAccountRepository.findUniqueAssert(userId);
const ownedGuildIds = await this.deps.guildRepository.listOwnedGuildIds(userId);
if (ownedGuildIds.length > 0) {
throw new UserOwnsGuildsError();
diff --git a/fluxer_api/src/api/user/services/UserAccountLookupService.ts b/fluxer_api/src/api/user/services/UserAccountLookupService.ts
index 8c063fa63..746b53e97 100644
--- a/fluxer_api/src/api/user/services/UserAccountLookupService.ts
+++ b/fluxer_api/src/api/user/services/UserAccountLookupService.ts
@@ -70,8 +70,7 @@ export class UserAccountLookupService {
restrictProfile: boolean;
}> {
const {userId, targetId, guildId, withMutualFriends, withMutualGuilds, requestCache} = params;
- const user = await this.deps.userAccountRepository.findUnique(targetId);
- if (!user) throw new UnknownUserError();
+ const user = await this.deps.userAccountRepository.findUniqueAssert(targetId);
if (userId !== targetId) {
await this.validateProfileAccess(userId, targetId, user);
}
diff --git a/fluxer_api/src/api/user/services/UserAccountNotesService.ts b/fluxer_api/src/api/user/services/UserAccountNotesService.ts
index e28825499..840af1f2d 100644
--- a/fluxer_api/src/api/user/services/UserAccountNotesService.ts
+++ b/fluxer_api/src/api/user/services/UserAccountNotesService.ts
@@ -3,7 +3,6 @@
import type {UserID} from '@app/api/BrandedTypes';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import type {UserAccountUpdatePropagator} from '@app/api/user/services/UserAccountUpdatePropagator';
-import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';
interface UserAccountNotesServiceDeps {
userAccountRepository: UserRepository;
@@ -29,8 +28,7 @@ export class UserAccountNotesService {
async setUserNote(params: {userId: UserID; targetId: UserID; note: string | null}): Promise<void> {
const {userId, targetId, note} = params;
- const targetUser = await this.deps.userAccountRepository.findUnique(targetId);
- if (!targetUser) throw new UnknownUserError();
+ await this.deps.userAccountRepository.findUniqueAssert(targetId);
if (note) {
await this.deps.userAccountRepository.upsertUserNote(userId, targetId, note);
} else {
diff --git a/fluxer_api/src/api/user/services/UserAccountSettingsService.ts b/fluxer_api/src/api/user/services/UserAccountSettingsService.ts
index cd4b47536..f6ca433e0 100644
--- a/fluxer_api/src/api/user/services/UserAccountSettingsService.ts
+++ b/fluxer_api/src/api/user/services/UserAccountSettingsService.ts
@@ -422,8 +422,7 @@ export class UserAccountSettingsService {
requestCache: RequestCache;
}): Promise<User> {
const {userId, shareVoiceActivity, requestCache} = params;
- const user = await this.deps.userAccountRepository.findUnique(userId);
- if (!user) throw new UnknownUserError();
+ const user = await this.deps.userAccountRepository.findUniqueAssert(userId);
const lastChange = user.lastVoiceActivitySharingChangeAt;
const now = new Date();
if (lastChange != null) {
diff --git a/fluxer_api/src/api/user/services/UserChannelRequestService.ts b/fluxer_api/src/api/user/services/UserChannelRequestService.ts
index df5bf5f5f..d021355b0 100644
--- a/fluxer_api/src/api/user/services/UserChannelRequestService.ts
+++ b/fluxer_api/src/api/user/services/UserChannelRequestService.ts
@@ -84,18 +84,20 @@ export class UserChannelRequestService {
}
async pinChannel(params: UserChannelPinParams): Promise<void> {
- await this.userChannelService.pinDmChannel({
+ await this.userChannelService.setDmChannelPinned({
userId: params.userId,
viewer: params.viewer,
channelId: params.channelId,
+ pinned: true,
});
}
async unpinChannel(params: UserChannelPinParams): Promise<void> {
- await this.userChannelService.unpinDmChannel({
+ await this.userChannelService.setDmChannelPinned({
userId: params.userId,
viewer: params.viewer,
channelId: params.channelId,
+ pinned: false,
});
}
}
diff --git a/fluxer_api/src/api/user/services/UserChannelService.ts b/fluxer_api/src/api/user/services/UserChannelService.ts
index a26f64872..4dd44148d 100644
--- a/fluxer_api/src/api/user/services/UserChannelService.ts
+++ b/fluxer_api/src/api/user/services/UserChannelService.ts
@@ -137,8 +137,7 @@ export class UserChannelService {
userCacheService: UserCacheService;
requestCache: RequestCache;
}): Promise<Channel> {
- const callingUser = await this.userRepository.findUnique(userId);
- if (!callingUser) throw new UnknownUserError();
+ const callingUser = await this.userRepository.findUniqueAssert(userId);
assertTierAllows(
callingUser,
data.recipients !== undefined ? TierGatedActions.GROUP_DM : TierGatedActions.DIRECT_MESSAGE,
@@ -189,16 +188,14 @@ export class UserChannelService {
requestCache: RequestCache;
}): Promise<Channel> {
if (suppressed) {
- const targetUser = await this.userRepository.findUnique(recipientId);
- if (!targetUser) throw new UnknownUserError();
+ await this.userRepository.findUniqueAssert(recipientId);
return await this.createOrOpenLocalOnlyDMChannel({userId, recipientId, userCacheService, requestCache});
}
const existingChannel = await this.userRepository.findExistingDmState(userId, recipientId);
if (existingChannel) {
return await this.reopenExistingDMChannel({userId, existingChannel, userCacheService, requestCache});
}
- const targetUser = await this.userRepository.findUnique(recipientId);
- if (!targetUser) throw new UnknownUserError();
+ await this.userRepository.findUniqueAssert(recipientId);
return await this.createNewDMChannel({userId, recipientId, userCacheService, requestCache});
}
@@ -226,38 +223,16 @@ export class UserChannelService {
}
}
- async pinDmChannel({
- userId,
- channelId,
- viewer,
- }: {
- userId: UserID;
- viewer: ThreadViewer;
- channelId: ChannelID;
- }): Promise<void> {
- const channel = await this.channelService.channelData.operations.getChannel({userId, viewer, channelId});
- if (channel.type !== ChannelTypes.DM && channel.type !== ChannelTypes.GROUP_DM) {
- throw InputValidationError.fromCode('channel_id', ValidationErrorCodes.CHANNEL_MUST_BE_DM_OR_GROUP_DM);
- }
- if (!channel.recipientIds.has(userId)) {
- throw new MissingAccessError();
- }
- const newPinnedDMs = await this.userRepository.addPinnedDm(userId, channelId);
- await this.gatewayService.dispatchPresence({
- userId: userId,
- event: 'USER_PINNED_DMS_UPDATE',
- data: newPinnedDMs.map(String),
- });
- }
-
- async unpinDmChannel({
+ async setDmChannelPinned({
userId,
channelId,
viewer,
+ pinned,
}: {
userId: UserID;
viewer: ThreadViewer;
channelId: ChannelID;
+ pinned: boolean;
}): Promise<void> {
const channel = await this.channelService.channelData.operations.getChannel({userId, viewer, channelId});
if (channel.type !== ChannelTypes.DM && channel.type !== ChannelTypes.GROUP_DM) {
@@ -266,7 +241,9 @@ export class UserChannelService {
if (!channel.recipientIds.has(userId)) {
throw new MissingAccessError();
}
- const newPinnedDMs = await this.userRepository.removePinnedDm(userId, channelId);
+ const newPinnedDMs = pinned
+ ? await this.userRepository.addPinnedDm(userId, channelId)
+ : await this.userRepository.removePinnedDm(userId, channelId);
await this.gatewayService.dispatchPresence({
userId: userId,
event: 'USER_PINNED_DMS_UPDATE',
diff --git a/fluxer_api/src/api/user/services/UserContentService.ts b/fluxer_api/src/api/user/services/UserContentService.ts
index de0c3970a..bfaa2267f 100644
--- a/fluxer_api/src/api/user/services/UserContentService.ts
+++ b/fluxer_api/src/api/user/services/UserContentService.ts
@@ -419,10 +419,7 @@ export class UserContentService {
channelId: ChannelID;
messageId: MessageID;
}): Promise<void> {
- const user = await this.userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await this.userRepository.findUniqueAssert(userId);
const savedMessageCount = await this.userRepository.countSavedMessages(userId);
const ctx = createLimitMatchContext({user});
const maxBookmarks = resolveLimitSafe(
@@ -661,8 +658,7 @@ export class UserContentService {
userId: UserID,
filter: HarvestSelfDataRequest | null,
): Promise<HarvestCreationResponse> {
- const user = await this.userRepository.findUnique(userId);
- if (!user) throw new UnknownUserError();
+ await this.userRepository.findUniqueAssert(userId);
const harvestId = await this.snowflakeService.generate();
const harvest = new UserHarvest({
user_id: userId,
diff --git a/fluxer_api/src/api/user/services/UserRelationshipService.ts b/fluxer_api/src/api/user/services/UserRelationshipService.ts
index 21d5a7d15..c177fe742 100644
--- a/fluxer_api/src/api/user/services/UserRelationshipService.ts
+++ b/fluxer_api/src/api/user/services/UserRelationshipService.ts
@@ -161,10 +161,7 @@ export class UserRelationshipService {
if (userId === targetId) {
throw new CannotSendFriendRequestToSelfError();
}
- const targetUserForAttempt = await this.userRepository.findUnique(targetId);
- if (!targetUserForAttempt) {
- throw new UnknownUserError();
- }
+ const targetUserForAttempt = await this.userRepository.findUniqueAssert(targetId);
if (this.isDeletedUser(targetUserForAttempt)) {
throw new FriendRequestBlockedError();
}
@@ -224,18 +221,12 @@ export class UserRelationshipService {
if ((await getInstanceConfigRepository().getInstancePolicyConfig()).friends_disabled) {
throw new FriendsDisabledError();
}
- const user = await this.userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
+ const user = await this.userRepository.findUniqueAssert(userId);
if (this.isDeletedUser(user)) {
throw new FriendRequestBlockedError();
}
assertTierAllows(user, TierGatedActions.FRIEND_ACCEPT, NO_TIER_CONTEXT);
- const requesterUser = await this.userRepository.findUnique(targetId);
- if (!requesterUser) {
- throw new UnknownUserError();
- }
+ const requesterUser = await this.userRepository.findUniqueAssert(targetId);
if (this.isDeletedUser(requesterUser)) {
throw new FriendRequestBlockedError();
}
@@ -250,29 +241,7 @@ export class UserRelationshipService {
await this.validateRelationshipCounts({userId, targetId});
await this.userRepository.deleteRelationship(userId, targetId, RelationshipTypes.INCOMING_REQUEST);
await this.userRepository.deleteRelationship(targetId, userId, RelationshipTypes.OUTGOING_REQUEST);
- const now = new Date();
- const [userDefault, targetDefault] = await Promise.all([
- this.userRepository.findSettings(userId).then((s) => s?.defaultShareVoiceActivity ?? true),
- this.userRepository.findSettings(targetId).then((s) => s?.defaultShareVoiceActivity ?? true),
- ]);
- const userRelationship = await this.userRepository.upsertRelationship({
- source_user_id: userId,
- target_user_id: targetId,
- type: RelationshipTypes.FRIEND,
- nickname: null,
- since: now,
- share_voice_activity: userDefault,
- version: 1,
- });
- const targetRelationship = await this.userRepository.upsertRelationship({
- source_user_id: targetId,
- target_user_id: userId,
- type: RelationshipTypes.FRIEND,
- nickname: null,
- since: now,
- share_voice_activity: targetDefault,
- version: 1,
- });
+ const [userRelationship, targetRelationship] = await this.upsertMutualFriendship(userId, targetId);
await this.dispatchRelationshipUpdate({
userId,
relationship: userRelationship,
@@ -299,10 +268,7 @@ export class UserRelationshipService {
userCacheService: UserCacheService;
requestCache: RequestCache;
}): Promise<Relationship> {
- const targetUser = await this.userRepository.findUnique(targetId);
- if (!targetUser) {
- throw new UnknownUserError();
- }
+ const targetUser = await this.userRepository.findUniqueAssert(targetId);
if (targetUser.isSystem) {
throw new CannotBlockSystemUserError();
}
@@ -471,27 +437,7 @@ export class UserRelationshipService {
userCacheService: UserCacheService;
requestCache: RequestCache;
}): Promise<Relationship> {
- if (userId === targetId) {
- throw new CannotSendFriendRequestToSelfError();
- }
- const requesterUser = await this.userRepository.findUnique(userId);
- if (!requesterUser) {
- throw new UnknownUserError();
- }
- if (this.isDeletedUser(requesterUser)) {
- throw new FriendRequestBlockedError();
- }
- assertTierAllows(requesterUser, TierGatedActions.FRIEND_REQUEST, NO_TIER_CONTEXT);
- if (requesterUser.isBot) {
- throw new BotsCannotSendFriendRequestsError();
- }
- const targetUser = await this.userRepository.findUnique(targetId);
- if (!targetUser) {
- throw new UnknownUserError();
- }
- if (this.isDeletedUser(targetUser)) {
- throw new FriendRequestBlockedError();
- }
+ await this.loadFriendRequestUsers(userId, targetId);
const [
userFriend,
userBlocked,
@@ -535,29 +481,7 @@ export class UserRelationshipService {
? [this.userRepository.deleteRelationship(targetId, userId, RelationshipTypes.OUTGOING_REQUEST)]
: []),
]);
- const now = new Date();
- const [userDefaultStaff, targetDefaultStaff] = await Promise.all([
- this.userRepository.findSettings(userId).then((s) => s?.defaultShareVoiceActivity ?? true),
- this.userRepository.findSettings(targetId).then((s) => s?.defaultShareVoiceActivity ?? true),
- ]);
- const userRelationship = await this.userRepository.upsertRelationship({
- source_user_id: userId,
- target_user_id: targetId,
- type: RelationshipTypes.FRIEND,
- nickname: null,
- since: now,
- share_voice_activity: userDefaultStaff,
- version: 1,
- });
- const targetRelationship = await this.userRepository.upsertRelationship({
- source_user_id: targetId,
- target_user_id: userId,
- type: RelationshipTypes.FRIEND,
- nickname: null,
- since: now,
- share_voice_activity: targetDefaultStaff,
- version: 1,
- });
+ const [userRelationship, targetRelationship] = await this.upsertMutualFriendship(userId, targetId);
const hadUserRelationship = userFriend != null || hasExtraUserRelationship;
const hadTargetRelationship = targetFriend != null || hasExtraTargetRelationship;
if (hadUserRelationship) {
@@ -581,26 +505,54 @@ export class UserRelationshipService {
return userRelationship;
}
- private async validateFriendRequest({userId, targetId}: {userId: UserID; targetId: UserID}): Promise<User> {
+ private async loadFriendRequestUsers(userId: UserID, targetId: UserID): Promise<User> {
if (userId === targetId) {
throw new CannotSendFriendRequestToSelfError();
}
- const requesterUser = await this.userRepository.findUnique(userId);
- if (!requesterUser) {
- throw new UnknownUserError();
- }
+ const requesterUser = await this.userRepository.findUniqueAssert(userId);
if (this.isDeletedUser(requesterUser)) {
throw new FriendRequestBlockedError();
}
assertTierAllows(requesterUser, TierGatedActions.FRIEND_REQUEST, NO_TIER_CONTEXT);
- if (requesterUser?.isBot) {
+ if (requesterUser.isBot) {
throw new BotsCannotSendFriendRequestsError();
}
- const targetUser = await this.userRepository.findUnique(targetId);
- if (!targetUser) throw new UnknownUserError();
+ const targetUser = await this.userRepository.findUniqueAssert(targetId);
if (this.isDeletedUser(targetUser)) {
throw new FriendRequestBlockedError();
}
+ return targetUser;
+ }
+
+ private async upsertMutualFriendship(userId: UserID, targetId: UserID): Promise<[Relationship, Relationship]> {
+ const now = new Date();
+ const [userDefault, targetDefault] = await Promise.all([
+ this.userRepository.findSettings(userId).then((s) => s?.defaultShareVoiceActivity ?? true),
+ this.userRepository.findSettings(targetId).then((s) => s?.defaultShareVoiceActivity ?? true),
+ ]);
+ const userRelationship = await this.userRepository.upsertRelationship({
+ source_user_id: userId,
+ target_user_id: targetId,
+ type: RelationshipTypes.FRIEND,
+ nickname: null,
+ since: now,
+ share_voice_activity: userDefault,
+ version: 1,
+ });
+ const targetRelationship = await this.userRepository.upsertRelationship({
+ source_user_id: targetId,
+ target_user_id: userId,
+ type: RelationshipTypes.FRIEND,
+ nickname: null,
+ since: now,
+ share_voice_activity: targetDefault,
+ version: 1,
+ });
+ return [userRelationship, targetRelationship];
+ }
+
+ private async validateFriendRequest({userId, targetId}: {userId: UserID; targetId: UserID}): Promise<User> {
+ const targetUser = await this.loadFriendRequestUsers(userId, targetId);
const targetIsFriendlyBot =
targetUser.isBot && (targetUser.flags & UserFlags.FRIENDLY_BOT) === UserFlags.FRIENDLY_BOT;
if (targetUser.isBot && !targetIsFriendlyBot) {
@@ -711,10 +663,7 @@ export class UserRelationshipService {
if (requesterUser.isBot) {
throw new BotsCannotSendFriendRequestsError();
}
- const targetUser = await this.userRepository.findUnique(targetId);
- if (!targetUser) {
- throw new UnknownUserError();
- }
+ const targetUser = await this.userRepository.findUniqueAssert(targetId);
if (this.isDeletedUser(targetUser)) {
throw new FriendRequestBlockedError();
}
diff --git a/fluxer_api/src/api/utils/AuditSerializationUtils.ts b/fluxer_api/src/api/utils/AuditSerializationUtils.ts
index ecae91bf9..e50f19021 100644
--- a/fluxer_api/src/api/utils/AuditSerializationUtils.ts
+++ b/fluxer_api/src/api/utils/AuditSerializationUtils.ts
@@ -4,7 +4,6 @@ import type {Channel} from '@app/api/models/Channel';
import type {Guild} from '@app/api/models/Guild';
import type {GuildEmoji} from '@app/api/models/GuildEmoji';
import type {GuildSticker} from '@app/api/models/GuildSticker';
-import {toIdString, toSortedIdArray} from '@app/api/utils/IdUtils';
import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
export function serializeGuildForAudit(guild: Guild): Record<string, unknown> {
@@ -24,7 +23,7 @@ export function serializeGuildForAudit(guild: Guild): Record<string, unknown> {
embed_splash_hash: guild.embedSplashHash ?? null,
embed_splash_width: guild.embedSplashWidth ?? null,
embed_splash_height: guild.embedSplashHeight ?? null,
- features: toSortedIdArray(guild.features),
+ features: [...guild.features].sort(),
verification_level: guild.verificationLevel,
mfa_level: guild.mfaLevel,
nsfw_level: guild.nsfwLevel,
@@ -33,10 +32,10 @@ export function serializeGuildForAudit(guild: Guild): Record<string, unknown> {
content_warning_text: guild.contentWarningText,
explicit_content_filter: guild.explicitContentFilter,
default_message_notifications: guild.defaultMessageNotifications,
- system_channel_id: toIdString(guild.systemChannelId),
+ system_channel_id: guild.systemChannelId?.toString() ?? null,
system_channel_flags: guild.systemChannelFlags,
- rules_channel_id: toIdString(guild.rulesChannelId),
- afk_channel_id: toIdString(guild.afkChannelId),
+ rules_channel_id: guild.rulesChannelId?.toString() ?? null,
+ afk_channel_id: guild.afkChannelId?.toString() ?? null,
afk_timeout: guild.afkTimeout,
disabled_operations: guild.disabledOperations,
member_count: guild.memberCount,
@@ -51,7 +50,7 @@ export function serializeChannelForAudit(channel: Channel): Record<string, unkno
name: channel.name ?? null,
topic: channel.topic ?? null,
...(channel.type === ChannelTypes.GUILD_LINK ? {url: channel.url ?? null} : {}),
- parent_id: toIdString(channel.parentId),
+ parent_id: channel.parentId?.toString() ?? null,
position: channel.position,
nsfw: channel.nsfwOverride,
content_warning_level: channel.contentWarningLevel,
diff --git a/fluxer_api/src/api/utils/IdUtils.ts b/fluxer_api/src/api/utils/IdUtils.ts
deleted file mode 100644
index 753dc13cd..000000000
--- a/fluxer_api/src/api/utils/IdUtils.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {ChannelID, EmojiID, GuildID, RoleID, StickerID, UserID} from '@app/api/BrandedTypes';
-
-export function toIdString(
- value: GuildID | ChannelID | RoleID | UserID | EmojiID | StickerID | bigint | string | null | undefined,
-): string | null {
- if (value === null || value === undefined) {
- return null;
- }
- return value.toString();
-}
-
-function toIdArray<
- T extends {
- toString(): string;
- },
->(values: Array<T> | Set<T> | null | undefined): Array<string> {
- if (!values) return [];
- return Array.from(values).map((v) => v.toString());
-}
-
-export function toSortedIdArray<
- T extends {
- toString(): string;
- },
->(values: Array<T> | Set<T> | null | undefined): Array<string> {
- return toIdArray(values).sort();
-}
diff --git a/fluxer_api/src/api/utils/UsernameGenerator.ts b/fluxer_api/src/api/utils/UsernameGenerator.ts
index 771721d07..4a02a14b6 100644
--- a/fluxer_api/src/api/utils/UsernameGenerator.ts
+++ b/fluxer_api/src/api/utils/UsernameGenerator.ts
@@ -5,8 +5,8 @@ import {readFileSync} from 'node:fs';
import {resolveAssetPath} from '@app/api/utils/AssetPaths';
import {UsernameType} from '@fluxer/schema/src/primitives/UserValidators';
-const scales = readFileSync(resolveAssetPath('words', 'scales.txt'), 'utf-8').trim().split('\n').filter(Boolean);
-const tails = readFileSync(resolveAssetPath('words', 'tails.txt'), 'utf-8').trim().split('\n').filter(Boolean);
+export const scales = readFileSync(resolveAssetPath('words', 'scales.txt'), 'utf-8').trim().split('\n').filter(Boolean);
+export const tails = readFileSync(resolveAssetPath('words', 'tails.txt'), 'utf-8').trim().split('\n').filter(Boolean);
type IndexPicker = (size: number) => number;
diff --git a/fluxer_api/src/api/webhook/ChannelFollowService.ts b/fluxer_api/src/api/webhook/ChannelFollowService.ts
index 1db33f6a4..323c25a48 100644
--- a/fluxer_api/src/api/webhook/ChannelFollowService.ts
+++ b/fluxer_api/src/api/webhook/ChannelFollowService.ts
@@ -13,7 +13,6 @@ import {contentModerationService} from '@app/api/infrastructure/ContentModeratio
import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
import type {ISnowflakeService} from '@app/api/infrastructure/ISnowflakeService';
import {Logger} from '@app/api/Logger';
-import type {RequestCache} from '@app/api/middleware/RequestCacheMiddleware';
import type {Channel} from '@app/api/models/Channel';
import type {Webhook} from '@app/api/models/Webhook';
import * as RandomUtils from '@app/api/utils/RandomUtils';
@@ -44,7 +43,6 @@ interface FollowChannelParams {
viewer: ThreadViewer;
channelId: ChannelID;
webhookChannelId: ChannelID;
- requestCache: RequestCache;
auditLogReason?: string | null;
}
@@ -78,7 +76,7 @@ export class ChannelFollowService {
) {}
async followChannel(params: FollowChannelParams): Promise<FollowedChannel> {
- const {userId, viewer, channelId, webhookChannelId, requestCache, auditLogReason} = params;
+ const {userId, viewer, channelId, webhookChannelId, auditLogReason} = params;
const sourceAuth = await this.channelService.channelData.auth.getChannelAuthenticated({userId, channelId, viewer});
const source = sourceAuth.channel;
const sourceGuild = sourceAuth.guild;
@@ -172,7 +170,6 @@ export class ChannelFollowService {
userId,
source: currentSource,
targetChannel,
- requestCache,
});
return {channelId: source.id, webhookId: webhook.id};
}
@@ -246,7 +243,6 @@ export class ChannelFollowService {
userId: UserID;
source: Channel;
targetChannel: GuildChannel;
- requestCache: RequestCache;
}): Promise<void> {
try {
const messageId = createMessageID(await this.snowflakeService.generateForChannel(targetChannel.id));
diff --git a/fluxer_api/src/api/webhook/WebhookController.ts b/fluxer_api/src/api/webhook/WebhookController.ts
index 8782dcf53..da5143f7b 100644
--- a/fluxer_api/src/api/webhook/WebhookController.ts
+++ b/fluxer_api/src/api/webhook/WebhookController.ts
@@ -485,7 +485,7 @@ export function WebhookController(app: HonoApp) {
Validator('query', WebhookMessageQueryRequest),
async (ctx) => {
const {webhook_id: webhookId, token, message_id: messageId} = ctx.req.valid('param');
- await ctx.get('webhookRequestService').deleteWebhookMessage({
+ await ctx.get('webhookService').deleteWebhookMessage({
webhookId: createWebhookID(webhookId),
token: createWebhookToken(token),
threadId: ctx.req.query('thread_id'),
@@ -513,7 +513,7 @@ export function WebhookController(app: HonoApp) {
Validator('json', GitHubWebhook),
async (ctx) => {
const {webhook_id: webhookId, token} = ctx.req.valid('param');
- await ctx.get('webhookRequestService').executeGitHubWebhook({
+ await ctx.get('webhookService').executeGitHubWebhook({
webhookId: createWebhookID(webhookId),
token: createWebhookToken(token),
threadId: ctx.req.query('thread_id'),
@@ -571,7 +571,7 @@ export function WebhookController(app: HonoApp) {
Validator('json', InstatusWebhook),
async (ctx) => {
const {webhook_id: webhookId, token} = ctx.req.valid('param');
- await ctx.get('webhookRequestService').executeInstatusWebhook({
+ await ctx.get('webhookService').executeInstatusWebhook({
webhookId: createWebhookID(webhookId),
token: createWebhookToken(token),
data: ctx.req.valid('json'),
@@ -598,7 +598,7 @@ export function WebhookController(app: HonoApp) {
Validator('json', LibredeskWebhook),
async (ctx) => {
const {webhook_id: webhookId, token} = ctx.req.valid('param');
- await ctx.get('webhookRequestService').executeLibredeskWebhook({
+ await ctx.get('webhookService').executeLibredeskWebhook({
webhookId: createWebhookID(webhookId),
token: createWebhookToken(token),
threadId: ctx.req.query('thread_id'),
diff --git a/fluxer_api/src/api/webhook/WebhookRequestService.ts b/fluxer_api/src/api/webhook/WebhookRequestService.ts
index 4ac9aba95..078752cfd 100644
--- a/fluxer_api/src/api/webhook/WebhookRequestService.ts
+++ b/fluxer_api/src/api/webhook/WebhookRequestService.ts
@@ -24,9 +24,6 @@ import {
} from '@app/api/webhook/WebhookModel';
import type {WebhookExecuteMessageData, WebhookService} from '@app/api/webhook/WebhookService';
import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import type {GitHubWebhook} from '@fluxer/schema/src/domains/webhook/GitHubWebhookSchemas';
-import type {InstatusWebhook} from '@fluxer/schema/src/domains/webhook/InstatusWebhookSchemas';
-import type {LibredeskWebhook} from '@fluxer/schema/src/domains/webhook/LibredeskWebhookSchemas';
import type {
SlackWebhookRequest,
WebhookCreateRequest,
@@ -133,24 +130,6 @@ interface WebhookEditMessageParams {
requestCache: RequestCache;
}
-interface WebhookDeleteMessageParams {
- webhookId: WebhookID;
- token: WebhookToken;
- threadId?: string;
- messageId: MessageID;
- requestCache: RequestCache;
-}
-
-interface WebhookExecuteGitHubParams {
- webhookId: WebhookID;
- token: WebhookToken;
- threadId?: string;
- event: string;
- delivery: string;
- data: GitHubWebhook;
- requestCache: RequestCache;
-}
-
interface WebhookExecuteSlackParams {
webhookId: WebhookID;
token: WebhookToken;
@@ -159,21 +138,6 @@ interface WebhookExecuteSlackParams {
requestCache: RequestCache;
}
-interface WebhookExecuteInstatusParams {
- webhookId: WebhookID;
- token: WebhookToken;
- data: InstatusWebhook;
- requestCache: RequestCache;
-}
-
-interface WebhookExecuteLibredeskParams {
- webhookId: WebhookID;
- token: WebhookToken;
- threadId?: string;
- data: LibredeskWebhook;
- requestCache: RequestCache;
-}
-
interface LiveKitWebhookParams {
body: string;
authHeader?: string;
@@ -323,7 +287,7 @@ export class WebhookRequestService {
if (!params.wait) {
return null;
}
- return this.mapMessageResponse(message, params.requestCache);
+ return this.mapMessageResponse(message);
}
async getWebhookMessage(params: WebhookGetMessageParams): Promise<MessageResponse> {
@@ -333,7 +297,7 @@ export class WebhookRequestService {
threadId: params.threadId,
messageId: params.messageId,
});
- return this.mapMessageResponse(message, params.requestCache);
+ return this.mapMessageResponse(message);
}
async editWebhookMessage(params: WebhookEditMessageParams): Promise<MessageResponse> {
@@ -345,23 +309,7 @@ export class WebhookRequestService {
data: params.data,
requestCache: params.requestCache,
});
- return this.mapMessageResponse(message, params.requestCache);
- }
-
- async deleteWebhookMessage(params: WebhookDeleteMessageParams): Promise<void> {
- await this.webhookService.deleteWebhookMessage(params);
- }
-
- async executeGitHubWebhook(params: WebhookExecuteGitHubParams): Promise<void> {
- await this.webhookService.executeGitHubWebhook(params);
- }
-
- async executeInstatusWebhook(params: WebhookExecuteInstatusParams): Promise<void> {
- await this.webhookService.executeInstatusWebhook(params);
- }
-
- async executeLibredeskWebhook(params: WebhookExecuteLibredeskParams): Promise<void> {
- await this.webhookService.executeLibredeskWebhook(params);
+ return this.mapMessageResponse(message);
}
async executeSlackWebhook(params: WebhookExecuteSlackParams): Promise<void> {
@@ -403,7 +351,7 @@ export class WebhookRequestService {
return new Response(response.body, {status: response.status});
}
- private async mapMessageResponse(message: Message, _requestCache: RequestCache): Promise<MessageResponse> {
+ private async mapMessageResponse(message: Message): Promise<MessageResponse> {
const channel = await this.channelRepository.channelData.findUnique(message.channelId);
const response = await createMessageResponseDataService().buildMessage({
userId: createUserID(0n),
diff --git a/fluxer_api/src/api/words/Words.ts b/fluxer_api/src/api/words/Words.ts
index 50c376c60..98785881c 100644
--- a/fluxer_api/src/api/words/Words.ts
+++ b/fluxer_api/src/api/words/Words.ts
@@ -1,48 +1,8 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {randomInt} from 'node:crypto';
-import * as fs from 'node:fs';
-import {resolveAssetPath} from '@app/api/utils/AssetPaths';
-
-let tails: Array<string> | undefined;
-let scales: Array<string> | undefined;
-
-function getTails(): Array<string> {
- if (!tails) {
- initWords();
- }
- return tails!;
-}
-
-function getScales(): Array<string> {
- if (!scales) {
- initWords();
- }
- return scales!;
-}
+import {scales, tails} from '@app/api/utils/UsernameGenerator';
export function generateConnectionId(): string {
- const scaleWords = getScales();
- const tailWords = getTails();
- const scale = scaleWords[randomInt(scaleWords.length)];
- const tail = tailWords[randomInt(tailWords.length)];
- return `${tail}-${scale}`;
-}
-
-function initWords(): void {
- tails = parseWordsFile(resolveAssetPath('words', 'tails.txt'));
- scales = parseWordsFile(resolveAssetPath('words', 'scales.txt'));
-}
-
-function parseWordsFile(filePath: string): Array<string> {
- const content = fs.readFileSync(filePath, 'utf-8');
- const lines = content.split('\n');
- const words: Array<string> = [];
- for (const line of lines) {
- const trimmed = line.trim();
- if (trimmed && !trimmed.startsWith('#')) {
- words.push(trimmed);
- }
- }
- return words;
+ return `${tails[randomInt(tails.length)]}-${scales[randomInt(scales.length)]}`;
}