feat(guild): add staff-only planned join waves feature (#4081)

This commit is contained in:
Hampus authored and GitHub committed 2026-11-14 03:30:51 +01:00
1 parent d75a9f6769
commit a5d5424598
35 files changed
+696 -37

No files matched your search

+19 -3
View File
@@ -19288,6 +19288,12 @@
"type": "array",
"items": {"allOf": [{"$ref": "#/components/schemas/GuildFeatureSchema"}]}
},
"planned_join_waves_until": {
"description": "When PLANNED_JOIN_WAVES ends, as an ISO 8601 timestamp in the future. Null keeps it on with no end, and leaving it out keeps the current end. Only accepted while the guild has or gains PLANNED_JOIN_WAVES",
"nullable": true,
"type": "string",
"pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:?\\d{2})?$"
},
"badge_ids": {"allOf": [{"$ref": "#/components/schemas/CustomBadgeIdsType"}]},
"fields": {
"maxItems": 10,
@@ -19375,6 +19381,13 @@
"rules_channel_id": {"nullable": true, "allOf": [{"$ref": "#/components/schemas/SnowflakeStringType"}]},
"disabled_operations": {"$ref": "#/components/schemas/Int32Type"},
"member_count": {"$ref": "#/components/schemas/Int32Type"},
"planned_join_waves_until": {
"nullable": true,
"description": "When PLANNED_JOIN_WAVES ends, or null when it has no end or is off",
"type": "string",
"format": "date-time",
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
},
"channels": {
"type": "array",
"items": {
@@ -19462,6 +19475,7 @@
"rules_channel_id",
"disabled_operations",
"member_count",
"planned_join_waves_until",
"channels",
"roles"
],
@@ -21745,7 +21759,7 @@
"description": "Why the action is taken"
},
"GuildFeatureSchema": {
"description": "A guild feature flag Known values: ANIMATED_ICON, ANIMATED_BANNER, AUDIO_BITRATE_128_KBPS, AUDIO_BITRATE_256_KBPS, AUDIO_BITRATE_384_KBPS, BANNER, CLONE_EMOJI_DISABLED, CLONE_EMOJI_ENABLED, CLONE_STICKER_DISABLED, CLONE_STICKER_ENABLED, DETACHED_BANNER, INVITE_SPLASH, INVITES_DISABLED, RAID_DETECTED, TEXT_CHANNEL_FLEXIBLE_NAMES, HIDE_OWNER_CROWN, MORE_EMOJI, MORE_STICKERS, UNLIMITED_EMOJI, UNLIMITED_STICKERS, EXPRESSION_PURGE_ALLOWED, VANITY_URL, DISCOVERABLE, PARTNERED, VERIFIED, VIP_VOICE, VOICE_E2EE, UNAVAILABLE_FOR_EVERYONE, UNAVAILABLE_FOR_EVERYONE_BUT_STAFF, UNAVAILABLE_HIDDEN, VISIONARY, LARGE_GUILD_OVERRIDE, VERY_LARGE_GUILD, ANNOUNCEMENT_CHANNELS_DISABLED, VISITS_ENABLED, MEMBER_DMS_DISABLED (other values allowed)",
"description": "A guild feature flag Known values: ANIMATED_ICON, ANIMATED_BANNER, AUDIO_BITRATE_128_KBPS, AUDIO_BITRATE_256_KBPS, AUDIO_BITRATE_384_KBPS, BANNER, CLONE_EMOJI_DISABLED, CLONE_EMOJI_ENABLED, CLONE_STICKER_DISABLED, CLONE_STICKER_ENABLED, DETACHED_BANNER, INVITE_SPLASH, INVITES_DISABLED, RAID_DETECTED, TEXT_CHANNEL_FLEXIBLE_NAMES, HIDE_OWNER_CROWN, MORE_EMOJI, MORE_STICKERS, UNLIMITED_EMOJI, UNLIMITED_STICKERS, EXPRESSION_PURGE_ALLOWED, VANITY_URL, DISCOVERABLE, PARTNERED, VERIFIED, VIP_VOICE, VOICE_E2EE, UNAVAILABLE_FOR_EVERYONE, UNAVAILABLE_FOR_EVERYONE_BUT_STAFF, UNAVAILABLE_HIDDEN, VISIONARY, LARGE_GUILD_OVERRIDE, VERY_LARGE_GUILD, ANNOUNCEMENT_CHANNELS_DISABLED, VISITS_ENABLED, MEMBER_DMS_DISABLED, PLANNED_JOIN_WAVES (other values allowed)",
"x-enumNames": [
"ANIMATED_ICON",
"ANIMATED_BANNER",
@@ -21782,7 +21796,8 @@
"VERY_LARGE_GUILD",
"ANNOUNCEMENT_CHANNELS_DISABLED",
"VISITS_ENABLED",
"MEMBER_DMS_DISABLED"
"MEMBER_DMS_DISABLED",
"PLANNED_JOIN_WAVES"
],
"x-enumDescriptions": [
"Guild can have an animated icon",
@@ -21820,7 +21835,8 @@
"Guild has increased member capacity enabled",
"Guild cannot publish announcement messages or gain new followers",
"People with an invite or a discovery listing can read channels that @everyone can see without joining",
"Members who aren't friends can't use the guild as a shared guild for direct messages"
"Members who aren't friends can't use the guild as a shared guild for direct messages",
"Guild expects large planned waves of new members. Invites are not paused after a raid"
],
"type": "string"
},
+3
View File
@@ -413,6 +413,9 @@ pub const GUILD_FEATURES: &[&str] = &[
"ANNOUNCEMENT_CHANNELS_DISABLED",
"VISITS_ENABLED",
"MEMBER_DMS_DISABLED",
"PLANNED_JOIN_WAVES",
];
pub const PLANNED_JOIN_WAVES: &str = "PLANNED_JOIN_WAVES";
pub const DEPRECATED_GUILD_FEATURES: &[&str] = &["CLONE_EMOJI_DISABLED", "CLONE_STICKER_DISABLED"];
+15 -6
View File
@@ -53,16 +53,25 @@ impl AdminApiClient {
guild_id: &str,
add_features: &[String],
remove_features: &[String],
planned_join_waves_until: Option<Option<&str>>,
) -> ApiResult<()> {
let body = generated_types::UpdateGuildRequest {
let mut body = serde_json::to_value(generated_types::UpdateGuildRequest {
add_features: guild_features(add_features),
remove_features: guild_features(remove_features),
..Default::default()
};
self.generated()
.update_admin_guild(&snowflake(guild_id), &body)
.await
.map_err(|e| self.generated_error(e))?;
})
.map_err(|e| ApiError::Parse(e.to_string()))?;
if let Some(until) = planned_join_waves_until {
body["planned_join_waves_until"] = serde_json::json!(until);
}
let _: serde_json::Value = self
.send(
Method::PATCH,
&format!("/admin/guilds/{}", urlencoding::encode(guild_id)),
Some(&body),
None,
)
.await?;
Ok(())
}
+1
View File
@@ -223,6 +223,7 @@ pub struct GuildDetailInfo {
pub disabled_operations: Option<i32>,
#[serde(default)]
pub member_count: u64,
pub planned_join_waves_until: Option<String>,
#[serde(default)]
pub channels: Vec<GuildChannelSummary>,
#[serde(default)]
+40 -3
View File
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
use crate::{
admin_flags::PLANNED_JOIN_WAVES,
api::{
client::{AdminApiClient, ApiResultExt},
generated::types::CommunityRemovalBasis,
@@ -215,7 +216,8 @@ async fn dispatch_guild_action(
let get = |k: &str| form.clean(k);
match action {
"update_features" => {
let (add_features, remove_features) = if form.contains_key("features[]")
let (add_features, remove_features, planned_join_waves_until) = if form
.contains_key("features[]")
|| form.contains_key("features")
|| form.contains_key("custom_features")
{
@@ -247,16 +249,30 @@ async fn dispatch_guild_action(
.filter(|feature| !desired_set.contains(feature.as_str()))
.cloned()
.collect();
(add_features, remove_features)
let planned_join_waves_until = if desired_set.contains(PLANNED_JOIN_WAVES) {
match parse_planned_join_waves_until(form) {
Ok(until) => Some(until),
Err(message) => return FlashData::error(message),
}
} else {
None
};
(add_features, remove_features, planned_join_waves_until)
} else {
(
form.list_values_any(&["add_features[]", "add_features"]),
form.list_values_any(&["remove_features[]", "remove_features"]),
None,
)
};
action_result(
client
.update_guild_features(guild_id, &add_features, &remove_features)
.update_guild_features(
guild_id,
&add_features,
&remove_features,
planned_join_waves_until.as_ref().map(Option::as_deref),
)
.await,
"Guild features updated",
"Failed to update guild features",
@@ -518,6 +534,27 @@ fn action_result<T, E: std::fmt::Display>(
}
}
fn parse_planned_join_waves_until(form: &MultiValueForm) -> Result<Option<String>, &'static str> {
let Some(value) = form.clean("planned_join_waves_until") else {
return Ok(None);
};
let with_seconds = if value.len() == 16 {
format!("{value}:00")
} else {
value
};
let format = time::format_description::parse_borrowed::<2>(
"[year]-[month]-[day]T[hour]:[minute]:[second]",
)
.map_err(|_| "Failed to read the end date")?;
time::PrimitiveDateTime::parse(&with_seconds, &format)
.map_err(|_| "Enter the end date as a date and time")?
.assume_utc()
.format(&time::format_description::well_known::Rfc3339)
.map(Some)
.map_err(|_| "Failed to format the end date")
}
fn unique_strings(values: Vec<String>) -> Vec<String> {
let mut seen = BTreeSet::new();
values
@@ -78,7 +78,7 @@ pub fn simple_tab_content(
guild_detail_tabs::overview::overview_tab(config, guild, csrf_token, admin_acls)
}
"features" => {
guild_detail_tabs::features::features_tab(config, &guild_info, csrf_token, admin_acls)
guild_detail_tabs::features::features_tab(config, guild, csrf_token, admin_acls)
}
"settings" => guild_detail_tabs::settings::settings_tab(
config,
@@ -1,12 +1,14 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
use crate::admin_flags::{DEPRECATED_GUILD_FEATURES, GUILD_FEATURES};
use crate::admin_flags::{DEPRECATED_GUILD_FEATURES, GUILD_FEATURES, PLANNED_JOIN_WAVES};
use crate::{
acl,
api::types::GuildInfo,
api::types::GuildDetailInfo,
config::AdminConfig,
templates::components::{
form::{Checkbox, csrf_input, form_actions, submit_button},
form::{
Checkbox, FORM_INPUT_CLASS, csrf_input, form_actions, form_field_group, submit_button,
},
page_container::card_with_header,
},
};
@@ -14,6 +16,19 @@ use maud::{Markup, html};
const HOSTED_ONLY: &[&str] = &["VISIONARY", "VIP_VOICE"];
fn planned_join_waves_end(guild: &GuildDetailInfo) -> Option<String> {
if !guild.features.iter().any(|f| f == PLANNED_JOIN_WAVES) {
return None;
}
Some(match guild.planned_join_waves_until.as_deref() {
Some(until) => format!(
"Planned join waves end on {} UTC.",
until.chars().take(16).collect::<String>().replace('T', " ")
),
None => "Planned join waves are permanent.".to_owned(),
})
}
fn feature_label(feature: &str) -> String {
if DEPRECATED_GUILD_FEATURES.contains(&feature) {
format!("{feature} (deprecated, no longer enforced)")
@@ -24,7 +39,7 @@ fn feature_label(feature: &str) -> String {
pub fn features_tab(
config: &AdminConfig,
guild: &GuildInfo,
guild: &GuildDetailInfo,
csrf_token: &str,
admin_acls: &[String],
) -> Markup {
@@ -49,6 +64,11 @@ pub fn features_tab(
.filter(|f| !features_list.contains(&f.as_str()))
.map(String::as_str)
.collect();
let waves_until_value: String = guild
.planned_join_waves_until
.as_deref()
.map(|until| until.chars().take(16).collect())
.unwrap_or_default();
html! {
div class="space-y-6" {
(card_with_header("Guild Features", html! {
@@ -69,6 +89,25 @@ pub fn features_tab(
}.render())
}
}
div class="mt-6 border-t border-neutral-200 pt-6 space-y-2" {
@if let Some(end) = planned_join_waves_end(guild) {
p class="text-sm text-neutral-700" { (end) }
}
(form_field_group(
"Planned join waves end (UTC, optional)",
"planned_join_waves_until",
false,
None,
Some("Used only while PLANNED_JOIN_WAVES is selected. Leave it empty to keep the \
feature on with no end date. When the date passes, the feature is \
removed automatically."),
html! {
input type="datetime-local" id="planned_join_waves_until"
name="planned_join_waves_until" value=(waves_until_value)
class=(FORM_INPUT_CLASS);
},
))
}
div class="mt-6 border-t border-neutral-200 pt-6 space-y-2" {
label class="block text-sm font-medium text-neutral-700" {
"Custom Features"
@@ -95,7 +134,7 @@ pub fn features_tab(
}
}
fn features_tab_readonly(guild: &GuildInfo, features_list: &[&str]) -> Markup {
fn features_tab_readonly(guild: &GuildDetailInfo, features_list: &[&str]) -> Markup {
let enabled: Vec<&str> = features_list
.iter()
.filter(|f| guild.features.iter().any(|g| g == **f))
@@ -132,6 +171,9 @@ fn features_tab_readonly(guild: &GuildInfo, features_list: &[&str]) -> Markup {
}
}
}
@if let Some(end) = planned_join_waves_end(guild) {
p class="mt-4 text-sm text-neutral-700" { (end) }
}
}))
}
}
+2
View File
@@ -35,6 +35,7 @@ import type {UserCacheService} from '@app/api/infrastructure/UserCacheService';
import type {InviteRepository} from '@app/api/invite/InviteRepository';
import {JobAdminService} from '@app/api/jobs/JobAdminService';
import type {JobLedgerRepository} from '@app/api/jobs/JobLedgerRepository';
import {getKVClient} from '@app/api/middleware/ServiceRegistry';
import {
getCustomBadgeCatalog,
getEnforcementDecisionRepository,
@@ -182,6 +183,7 @@ export class AdminService {
discoveryRepository: getGuildDiscoveryRepository(),
enforcement: this.enforcementService,
customBadgeCatalog: getCustomBadgeCatalog(),
kvClient: getKVClient(),
});
this.messageShredService = new AdminMessageShredService({
apiContext: this.apiContext,
@@ -60,7 +60,9 @@ function hasGuildSettingsUpdate(body: UpdateGuildRequest): boolean {
}
function hasGuildFeatureUpdate(body: UpdateGuildRequest): boolean {
return body.add_features !== undefined || body.remove_features !== undefined;
return (
body.add_features !== undefined || body.remove_features !== undefined || body.planned_join_waves_until !== undefined
);
}
function selectGuildUpdateACLs(body: UpdateGuildRequest): Array<string> {
@@ -206,6 +208,10 @@ export function GuildAdminController(app: HonoApp) {
guildId: createGuildID(guildIdRaw),
addFeatures: body.add_features ?? [],
removeFeatures: body.remove_features ?? [],
plannedJoinWavesUntil:
body.planned_join_waves_until == null
? body.planned_join_waves_until
: new Date(body.planned_join_waves_until),
adminUserId,
auditLogReason,
});
@@ -20,6 +20,7 @@ import type {InviteRepository} from '@app/api/invite/InviteRepository';
import {createRequestCache} from '@app/api/middleware/RequestCacheMiddleware';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import type {ListGuildAuditLogsRequest} from '@fluxer/schema/src/domains/admin/AdminGuildSchemas';
import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';
interface AdminGuildServiceDeps {
guildRepository: GuildRepository;
@@ -33,6 +34,7 @@ interface AdminGuildServiceDeps {
discoveryRepository: GuildDiscoveryRepository;
enforcement: EnforcementDecisionService;
customBadgeCatalog: Pick<CustomBadgeCatalog, 'getByIds' | 'state'>;
kvClient: Pick<IKVProvider, 'zadd' | 'zrem' | 'sadd' | 'srem'>;
}
export class AdminGuildService {
@@ -64,6 +66,7 @@ export class AdminGuildService {
updatePropagator: this.updatePropagator,
guildService: deps.guildService,
customBadgeCatalog: deps.customBadgeCatalog,
schedule: deps.kvClient,
});
this.vanityService = new AdminGuildVanityService({
guildRepository: deps.guildRepository,
@@ -70,6 +70,7 @@ export class AdminGuildLookupService {
rules_channel_id: guild.rulesChannelId?.toString() ?? null,
disabled_operations: guild.disabledOperations,
member_count: guild.memberCount,
planned_join_waves_until: guild.plannedJoinWavesUntil?.toISOString() ?? null,
channels: channels.map((c) => ({
id: c.id.toString(),
name: c.name,
@@ -10,7 +10,11 @@ import type {GuildRow} from '@app/api/database/types/GuildTypes';
import type {GuildDiscoveryRepository} from '@app/api/guild/repositories/GuildDiscoveryRepository';
import type {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
import {hasDiscoveryAutoApproval} from '@app/api/guild/services/GuildDiscoveryService';
import {staffEditTouchesInvitePause} from '@app/api/guild/services/GuildInvitePauseApplier';
import {
GUILD_PLANNED_JOIN_WAVES_KEY,
GUILD_PLANNED_JOIN_WAVES_SCHEDULE_KEY,
staffEditTouchesInvitePause,
} from '@app/api/guild/services/GuildInvitePauseApplier';
import type {GuildService} from '@app/api/guild/services/GuildService';
import {onGuildVisitSettingsChanged} from '@app/api/guild/visits/GuildVisitLifecycle';
import {emitGuildFeaturesChanged} from '@app/api/infrastructure/activity/GuildEvents';
@@ -19,6 +23,7 @@ import type {CustomBadgeCatalog} from '@app/api/instance/custom_badges/CustomBad
import {Logger} from '@app/api/Logger';
import {DiscoveryApplicationStatus} from '@fluxer/constants/src/DiscoveryConstants';
import {GuildFeatures} from '@fluxer/constants/src/GuildConstants';
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
import {UnknownGuildError} from '@fluxer/errors/src/domains/guild/UnknownGuildError';
import {UnknownGuildRoleError} from '@fluxer/errors/src/domains/guild/UnknownGuildRoleError';
import type {
@@ -27,6 +32,7 @@ import type {
UpdateGuildNameRequest,
UpdateGuildSettingsRequest,
} from '@fluxer/schema/src/domains/admin/AdminGuildSchemas';
import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';
interface AdminGuildUpdateServiceDeps {
guildRepository: GuildRepository;
@@ -36,6 +42,11 @@ interface AdminGuildUpdateServiceDeps {
updatePropagator: AdminGuildUpdatePropagator;
guildService: Pick<GuildService, 'withUpdateLock'>;
customBadgeCatalog: Pick<CustomBadgeCatalog, 'getByIds' | 'state'>;
schedule: Pick<IKVProvider, 'zadd' | 'zrem' | 'sadd' | 'srem'>;
}
function sameMinute(a: Date, b: Date | null): boolean {
return b !== null && Math.floor(a.getTime() / 60_000) === Math.floor(b.getTime() / 60_000);
}
export class AdminGuildUpdateService {
@@ -45,21 +56,30 @@ export class AdminGuildUpdateService {
guildId,
addFeatures,
removeFeatures,
plannedJoinWavesUntil,
adminUserId,
auditLogReason,
}: {
guildId: GuildID;
addFeatures: Array<string>;
removeFeatures: Array<string>;
plannedJoinWavesUntil?: Date | null;
adminUserId: UserID;
auditLogReason: string | null;
}) {
const {guildRepository, discoveryRepository, auditService, updatePropagator, guildService} = this.deps;
const {guildRepository, discoveryRepository, auditService, updatePropagator, guildService, schedule} = this.deps;
const {guild, newFeatures, updatedGuild} = await guildService.withUpdateLock(guildId, async () => {
const guild = await guildRepository.findUnique(guildId);
if (!guild) {
throw new UnknownGuildError();
}
let wavesUntil = plannedJoinWavesUntil;
if (wavesUntil && wavesUntil.getTime() <= Date.now()) {
if (!sameMinute(wavesUntil, guild.plannedJoinWavesUntil)) {
throw InputValidationError.create('planned_join_waves_until', 'The end date must be in the future');
}
wavesUntil = undefined;
}
const newFeatures = new Set(guild.features);
for (const feature of addFeatures) {
newFeatures.add(feature);
@@ -83,7 +103,34 @@ export class AdminGuildUpdateService {
if (staffEditTouchesInvitePause(guild, [...addFeatures, ...removeFeatures])) {
patch.invites_paused_until = null;
}
const hasWaves = newFeatures.has(GuildFeatures.PLANNED_JOIN_WAVES);
if (hasWaves) {
if (wavesUntil !== undefined) patch.planned_join_waves_until = wavesUntil;
} else if (wavesUntil != null) {
throw InputValidationError.create(
'planned_join_waves_until',
'Planned join waves must be on to set an end date',
);
} else if (guild.plannedJoinWavesUntil !== null) {
patch.planned_join_waves_until = null;
}
if (hasWaves) {
await schedule.sadd(GUILD_PLANNED_JOIN_WAVES_KEY, guildId.toString());
}
if (patch.planned_join_waves_until) {
await schedule.zadd(
GUILD_PLANNED_JOIN_WAVES_SCHEDULE_KEY,
patch.planned_join_waves_until.getTime(),
guildId.toString(),
);
}
const updatedGuild = await guildRepository.upsertPartial(guildId, patch, guild.toRow());
if (patch.planned_join_waves_until === null && guild.plannedJoinWavesUntil !== null) {
await schedule.zrem(GUILD_PLANNED_JOIN_WAVES_SCHEDULE_KEY, guildId.toString());
}
if (!hasWaves && guild.features.has(GuildFeatures.PLANNED_JOIN_WAVES)) {
await schedule.srem(GUILD_PLANNED_JOIN_WAVES_KEY, guildId.toString());
}
return {guild, newFeatures, updatedGuild};
});
await onGuildVisitSettingsChanged({guildId, before: guild, after: updatedGuild});
@@ -107,6 +154,7 @@ export class AdminGuildUpdateService {
['add_features', addFeatures.join(',')],
['remove_features', removeFeatures.join(',')],
['new_features', Array.from(newFeatures).join(',')],
['planned_join_waves_until', updatedGuild.plannedJoinWavesUntil?.toISOString() ?? ''],
]),
});
return {
@@ -51,6 +51,7 @@ export interface GuildRow {
members_indexed_at: Date | null;
message_history_cutoff: Date | null;
invites_paused_until: Date | null;
planned_join_waves_until: Date | null;
version: number;
}
@@ -91,6 +92,7 @@ export const GUILD_COLUMNS = [
'members_indexed_at',
'message_history_cutoff',
'invites_paused_until',
'planned_join_waves_until',
'version',
] as const satisfies ReadonlyArray<keyof GuildRow>;
@@ -2,6 +2,7 @@
import {createGuildID} from '@app/api/BrandedTypes';
import {SYSTEM_USER_ID} from '@app/api/constants/Core';
import type {GuildRow} from '@app/api/database/types/GuildTypes';
import type {GuildAuditLogService} from '@app/api/guild/GuildAuditLogService';
import {mapGuildToGuildResponse} from '@app/api/guild/GuildModel';
import {type GuildUpdateLocks, withGuildUpdateLock} from '@app/api/guild/GuildUpdateLock';
@@ -12,7 +13,7 @@ import {
type FeatureSource,
INVITES_ALREADY_PAUSED,
} from '@app/api/infrastructure/activity/Contract.generated';
import {emitGuildFeaturesChanged} from '@app/api/infrastructure/activity/GuildEvents';
import {emitGuildFeaturesChanged, emitPlannedJoinWavesRestated} from '@app/api/infrastructure/activity/GuildEvents';
import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
import {Logger} from '@app/api/Logger';
import type {Guild} from '@app/api/models/Guild';
@@ -23,12 +24,15 @@ import {GuildFeatures} from '@fluxer/constants/src/GuildConstants';
import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';
export const GUILD_INVITE_PAUSE_SCHEDULE_KEY = 'guild:invite_pause:lifts';
export const GUILD_PLANNED_JOIN_WAVES_SCHEDULE_KEY = 'guild:planned_join_waves:ends';
export const GUILD_PLANNED_JOIN_WAVES_KEY = 'guild:planned_join_waves:guilds';
const DAY_MS = 86_400_000;
const INVITE_PAUSE_FEATURES = [GuildFeatures.INVITES_DISABLED, GuildFeatures.RAID_DETECTED] as const;
export interface GuildInvitePauseDeps {
guilds: Pick<GuildRepository, 'findUnique' | 'upsertPartial'>;
locks: GuildUpdateLocks;
schedule: Pick<IKVProvider, 'zadd' | 'zrem' | 'zrangebyscore'>;
schedule: Pick<IKVProvider, 'zadd' | 'zrem' | 'zrangebyscore' | 'sadd' | 'srem' | 'smembers'>;
gateway: Pick<IGatewayService, 'dispatchGuild'>;
auditLog: Pick<GuildAuditLogService, 'record' | 'computeChanges'>;
now?: () => number;
@@ -50,14 +54,13 @@ export function staffEditTouchesInvitePause(guild: Guild, changed: Iterable<stri
return false;
}
async function writePause(
async function writeFeatures(
deps: GuildInvitePauseDeps,
guild: Guild,
features: Set<string>,
until: Date | null,
patch: Partial<GuildRow>,
source: FeatureSource,
): Promise<void> {
const updated = await deps.guilds.upsertPartial(guild.id, {features, invites_paused_until: until}, guild.toRow());
const updated = await deps.guilds.upsertPartial(guild.id, patch, guild.toRow());
try {
await deps.gateway.dispatchGuild({
guildId: guild.id,
@@ -65,7 +68,7 @@ async function writePause(
data: mapGuildToGuildResponse(updated),
});
} catch (error) {
Logger.error({error, guildId: guild.id}, 'Failed to dispatch guild update after invite pause change');
Logger.error({error, guildId: guild.id}, 'Failed to dispatch guild update after a scheduled feature change');
}
const changes = deps.auditLog
.computeChanges(serializeGuildForAudit(guild), serializeGuildForAudit(updated))
@@ -80,7 +83,7 @@ async function writePause(
changes,
});
} catch (error) {
Logger.error({error, guildId: guild.id}, 'Failed to record invite pause change in the guild audit log');
Logger.error({error, guildId: guild.id}, 'Failed to record a scheduled feature change in the guild audit log');
}
}
await emitGuildFeaturesChanged({
@@ -95,7 +98,7 @@ async function writePause(
async function liftPause(deps: GuildInvitePauseDeps, guild: Guild, source: FeatureSource): Promise<void> {
const features = new Set(guild.features);
for (const feature of INVITE_PAUSE_FEATURES) features.delete(feature);
await writePause(deps, guild, features, null, source);
await writeFeatures(deps, guild, {features, invites_paused_until: null}, source);
await deps.schedule.zrem(GUILD_INVITE_PAUSE_SCHEDULE_KEY, guild.id.toString());
}
@@ -114,6 +117,7 @@ export async function applyPauseGuildInvites(
await liftPause(deps, guild, 'action');
return outcomeOf(env, 'applied');
}
if (guild.features.has(GuildFeatures.PLANNED_JOIN_WAVES)) return outcomeOf(env, 'ineligible');
if (current === null && guild.features.has(GuildFeatures.INVITES_DISABLED)) {
return outcomeOf(env, 'noop', null, INVITES_ALREADY_PAUSED);
}
@@ -125,7 +129,7 @@ export async function applyPauseGuildInvites(
const detail = `until_ms=${until}`;
await deps.schedule.zadd(GUILD_INVITE_PAUSE_SCHEDULE_KEY, until, guildId.toString());
if (until === current && features.size === guild.features.size) return outcomeOf(env, 'noop', null, detail);
await writePause(deps, guild, features, new Date(until), 'action');
await writeFeatures(deps, guild, {features, invites_paused_until: new Date(until)}, 'action');
return outcomeOf(env, 'applied', null, detail);
});
}
@@ -158,3 +162,62 @@ export async function liftExpiredGuildInvitePauses(deps: GuildInvitePauseDeps, l
}
return lifted;
}
export async function endExpiredPlannedJoinWaves(deps: GuildInvitePauseDeps, limit: number): Promise<number> {
const now = deps.now?.() ?? Date.now();
const due = await deps.schedule.zrangebyscore(GUILD_PLANNED_JOIN_WAVES_SCHEDULE_KEY, '-inf', now, 'LIMIT', 0, limit);
let ended = 0;
for (const member of due) {
const guildId = createGuildID(BigInt(member));
try {
const done = await withGuildUpdateLock(deps.locks, guildId, async () => {
const guild = await deps.guilds.findUnique(guildId);
const until = guild?.plannedJoinWavesUntil?.getTime() ?? null;
if (!guild || until === null) {
await deps.schedule.zrem(GUILD_PLANNED_JOIN_WAVES_SCHEDULE_KEY, member);
return false;
}
if (until > now) {
await deps.schedule.zadd(GUILD_PLANNED_JOIN_WAVES_SCHEDULE_KEY, until, member);
return false;
}
const features = new Set(guild.features);
features.delete(GuildFeatures.PLANNED_JOIN_WAVES);
await writeFeatures(deps, guild, {features, planned_join_waves_until: null}, 'system');
await deps.schedule.zrem(GUILD_PLANNED_JOIN_WAVES_SCHEDULE_KEY, member);
await deps.schedule.srem(GUILD_PLANNED_JOIN_WAVES_KEY, member);
return true;
});
if (done) ended++;
} catch (error) {
Logger.error({error, guildId: member}, 'Failed to end expired planned join waves');
}
}
return ended;
}
export async function restatePlannedJoinWaves(deps: GuildInvitePauseDeps): Promise<number> {
const now = deps.now?.() ?? Date.now();
const day = Math.floor(now / DAY_MS);
let restated = 0;
for (const member of await deps.schedule.smembers(GUILD_PLANNED_JOIN_WAVES_KEY)) {
const guildId = createGuildID(BigInt(member));
try {
const done = await withGuildUpdateLock(deps.locks, guildId, async () => {
const guild = await deps.guilds.findUnique(guildId);
if (!guild?.features.has(GuildFeatures.PLANNED_JOIN_WAVES)) {
await deps.schedule.srem(GUILD_PLANNED_JOIN_WAVES_KEY, member);
return false;
}
const until = guild.plannedJoinWavesUntil?.getTime() ?? null;
if (until !== null && until <= now) return false;
await emitPlannedJoinWavesRestated({guild, day, meta: workerMeta()});
return true;
});
if (done) restated++;
} catch (error) {
Logger.error({error, guildId: member}, 'Failed to restate planned join waves');
}
}
return restated;
}
@@ -428,6 +428,7 @@ export class GuildOperationsService {
members_indexed_at: null,
message_history_cutoff: null,
invites_paused_until: null,
planned_join_waves_until: null,
version: 1,
};
batch.addPrepared(Guilds.insert(guildData));
@@ -6,9 +6,13 @@ import type {GuildRow} from '@app/api/database/types/GuildTypes';
import {GuildAuditLogService} from '@app/api/guild/GuildAuditLogService';
import {
applyPauseGuildInvites,
endExpiredPlannedJoinWaves,
GUILD_INVITE_PAUSE_SCHEDULE_KEY,
GUILD_PLANNED_JOIN_WAVES_KEY,
GUILD_PLANNED_JOIN_WAVES_SCHEDULE_KEY,
type GuildInvitePauseDeps,
liftExpiredGuildInvitePauses,
restatePlannedJoinWaves,
} from '@app/api/guild/services/GuildInvitePauseApplier';
import {resetActivityEventsForTests, startActivityEvents} from '@app/api/infrastructure/activity/ActivityEvents';
import type {ActivityPublisher} from '@app/api/infrastructure/activity/ActivitySpool';
@@ -42,7 +46,11 @@ function pauseEnvelope(overrides: Partial<PauseEnvelope> = {}): PauseEnvelope {
};
}
function guildRow(features: Iterable<string>, pausedUntil: Date | null = null): GuildRow {
function guildRow(
features: Iterable<string>,
pausedUntil: Date | null = null,
wavesUntil: Date | null = null,
): GuildRow {
return {
guild_id: createGuildID(BigInt(GUILD_ID)),
owner_id: createUserID(1472623911696138262n),
@@ -76,6 +84,7 @@ function guildRow(features: Iterable<string>, pausedUntil: Date | null = null):
members_indexed_at: null,
message_history_cutoff: null,
invites_paused_until: pausedUntil,
planned_join_waves_until: wavesUntil,
version: 1,
};
}
@@ -325,6 +334,9 @@ describe('guild invite pause', () => {
},
zrem: h.schedule.zrem.bind(h.schedule),
zrangebyscore: h.schedule.zrangebyscore.bind(h.schedule),
sadd: h.schedule.sadd.bind(h.schedule),
srem: h.schedule.srem.bind(h.schedule),
smembers: h.schedule.smembers.bind(h.schedule),
};
await expect(applyPauseGuildInvites(h.deps, pauseEnvelope())).rejects.toThrow('kv unavailable');
expect(h.guilds.writes).toBe(0);
@@ -365,6 +377,13 @@ describe('guild invite pause', () => {
expect((await applyPauseGuildInvites(h.deps, pauseEnvelope())).status).toBe('ineligible');
});
it('never pauses a guild that expects planned join waves', async () => {
h.guilds.row = guildRow([...BASE_FEATURES, GuildFeatures.PLANNED_JOIN_WAVES]);
expect((await applyPauseGuildInvites(h.deps, pauseEnvelope())).status).toBe('ineligible');
expect(h.guilds.writes).toBe(0);
expect(await scheduled(h)).toEqual([]);
});
it('lifts an expired pause on the sweep without any action', async () => {
h.guilds.row = guildRow(BASE_FEATURES);
await applyPauseGuildInvites(h.deps, pauseEnvelope());
@@ -400,4 +419,138 @@ describe('guild invite pause', () => {
]);
expect(h.guilds.writes).toBe(0);
});
describe('planned join waves end date', () => {
async function wavesScheduled(): Promise<Array<string>> {
return h.schedule.zrangebyscore(GUILD_PLANNED_JOIN_WAVES_SCHEDULE_KEY, '-inf', '+inf');
}
it('never ends planned join waves that have no end date', async () => {
h.guilds.row = guildRow([...BASE_FEATURES, GuildFeatures.PLANNED_JOIN_WAVES]);
h.clock.now = NOW + 10_000 * HOUR_MS;
expect(await endExpiredPlannedJoinWaves(h.deps, 100)).toBe(0);
expect(h.guilds.current().features.has(GuildFeatures.PLANNED_JOIN_WAVES)).toBe(true);
expect(h.guilds.writes).toBe(0);
});
it('ends planned join waves on the sweep once the end date passes and not before', async () => {
h.guilds.row = guildRow([...BASE_FEATURES, GuildFeatures.PLANNED_JOIN_WAVES], null, new Date(NOW + 2 * HOUR_MS));
await h.schedule.zadd(GUILD_PLANNED_JOIN_WAVES_SCHEDULE_KEY, NOW + 2 * HOUR_MS, GUILD_ID);
await h.schedule.sadd(GUILD_PLANNED_JOIN_WAVES_KEY, GUILD_ID);
h.clock.now = NOW + 2 * HOUR_MS - 1;
expect(await endExpiredPlannedJoinWaves(h.deps, 100)).toBe(0);
expect(h.guilds.current().features.has(GuildFeatures.PLANNED_JOIN_WAVES)).toBe(true);
expect(h.guilds.writes).toBe(0);
h.clock.now = NOW + 2 * HOUR_MS;
expect(await endExpiredPlannedJoinWaves(h.deps, 100)).toBe(1);
const guild = h.guilds.current();
expect([...guild.features]).toEqual(BASE_FEATURES);
expect(guild.plannedJoinWavesUntil).toBeNull();
expect(await wavesScheduled()).toEqual([]);
expect(await h.schedule.smembers(GUILD_PLANNED_JOIN_WAVES_KEY)).toEqual([]);
expect(h.dispatched).toHaveLength(1);
expect(h.audits).toEqual([
{
userId: SYSTEM_USER_ID,
action: AuditLogActionType.GUILD_UPDATE,
changes: [
{
key: 'features',
old_value: [...BASE_FEATURES, GuildFeatures.PLANNED_JOIN_WAVES].sort(),
new_value: [...BASE_FEATURES],
},
],
},
]);
expect(publisher.featureChanges().at(-1)?.data).toEqual({
guild_id: GUILD_ID,
actor_id: null,
source: 'system',
added: [],
removed: [GuildFeatures.PLANNED_JOIN_WAVES],
invites_paused_until_ms: null,
});
expect(
(
await applyPauseGuildInvites(
h.deps,
pauseEnvelope({issued_at_ms: h.clock.now, until_ms: h.clock.now + HOUR_MS}),
)
).status,
).toBe('applied');
});
it('reschedules an entry whose end date moved later', async () => {
h.guilds.row = guildRow([...BASE_FEATURES, GuildFeatures.PLANNED_JOIN_WAVES], null, new Date(NOW + 3 * HOUR_MS));
await h.schedule.zadd(GUILD_PLANNED_JOIN_WAVES_SCHEDULE_KEY, NOW + HOUR_MS, GUILD_ID);
h.clock.now = NOW + HOUR_MS;
expect(await endExpiredPlannedJoinWaves(h.deps, 100)).toBe(0);
expect(
await h.schedule.zrangebyscore(GUILD_PLANNED_JOIN_WAVES_SCHEDULE_KEY, NOW + 3 * HOUR_MS, NOW + 3 * HOUR_MS),
).toEqual([GUILD_ID]);
expect(h.guilds.current().features.has(GuildFeatures.PLANNED_JOIN_WAVES)).toBe(true);
expect(h.guilds.writes).toBe(0);
});
it('drops an entry once the end date was cleared', async () => {
h.guilds.row = guildRow([...BASE_FEATURES, GuildFeatures.PLANNED_JOIN_WAVES]);
await h.schedule.zadd(GUILD_PLANNED_JOIN_WAVES_SCHEDULE_KEY, NOW - 1, GUILD_ID);
expect(await endExpiredPlannedJoinWaves(h.deps, 100)).toBe(0);
expect(await wavesScheduled()).toEqual([]);
expect(h.guilds.current().features.has(GuildFeatures.PLANNED_JOIN_WAVES)).toBe(true);
expect(h.guilds.writes).toBe(0);
});
});
describe('planned join waves restatement', () => {
const DAY_MS = 86_400_000;
it('restates every tracked guild once a day with a fresh event id and the current pause', async () => {
h.guilds.row = guildRow(
[...BASE_FEATURES, GuildFeatures.PLANNED_JOIN_WAVES, GuildFeatures.INVITES_DISABLED],
new Date(NOW + HOUR_MS),
);
await h.schedule.sadd(GUILD_PLANNED_JOIN_WAVES_KEY, GUILD_ID);
expect(await restatePlannedJoinWaves(h.deps)).toBe(1);
h.clock.now = NOW + DAY_MS;
expect(await restatePlannedJoinWaves(h.deps)).toBe(1);
const events = publisher.featureChanges();
expect(events.map((event) => event.data)).toEqual([
{
guild_id: GUILD_ID,
actor_id: null,
source: 'staff',
added: [GuildFeatures.PLANNED_JOIN_WAVES],
removed: [],
invites_paused_until_ms: NOW + HOUR_MS,
},
expect.objectContaining({source: 'staff', added: [GuildFeatures.PLANNED_JOIN_WAVES]}),
]);
const ids = events.map((event) => event.id);
expect(new Set(ids).size).toBe(2);
expect(ids).not.toContain(`guild_features_changed:${GUILD_ID}:${h.guilds.row.version}`);
expect(events[0]?.meta.channel).toBe('worker');
expect(h.guilds.writes).toBe(0);
expect(h.dispatched).toEqual([]);
expect(h.audits).toEqual([]);
});
it('keeps restating a guild whose end date is still ahead and skips one that is about to end', async () => {
h.guilds.row = guildRow([...BASE_FEATURES, GuildFeatures.PLANNED_JOIN_WAVES], null, new Date(NOW + HOUR_MS));
await h.schedule.sadd(GUILD_PLANNED_JOIN_WAVES_KEY, GUILD_ID);
expect(await restatePlannedJoinWaves(h.deps)).toBe(1);
h.clock.now = NOW + HOUR_MS;
expect(await restatePlannedJoinWaves(h.deps)).toBe(0);
expect(publisher.featureChanges()).toHaveLength(1);
expect(await h.schedule.smembers(GUILD_PLANNED_JOIN_WAVES_KEY)).toEqual([GUILD_ID]);
});
it('stops tracking a guild that no longer has planned join waves', async () => {
h.guilds.row = guildRow(BASE_FEATURES);
await h.schedule.sadd(GUILD_PLANNED_JOIN_WAVES_KEY, GUILD_ID);
expect(await restatePlannedJoinWaves(h.deps)).toBe(0);
expect(await h.schedule.smembers(GUILD_PLANNED_JOIN_WAVES_KEY)).toEqual([]);
expect(publisher.featureChanges()).toEqual([]);
});
});
});
@@ -44,6 +44,7 @@ function createGuild(overrides: Partial<GuildRow> = {}): Guild {
members_indexed_at: null,
message_history_cutoff: null,
invites_paused_until: null,
planned_join_waves_until: null,
version: 1,
...overrides,
});
@@ -11,6 +11,7 @@ import {
} from '@app/api/infrastructure/activity/Contract.generated';
import type {Guild} from '@app/api/models/Guild';
import type {Invite} from '@app/api/models/Invite';
import {GuildFeatures} from '@fluxer/constants/src/GuildConstants';
export async function emitGuildCreated(guild: Guild): Promise<void> {
await emitActivity(
@@ -56,6 +57,24 @@ export async function emitGuildFeaturesChanged(params: {
);
}
export async function emitPlannedJoinWavesRestated(params: {guild: Guild; day: number; meta: Meta}): Promise<void> {
const guildId = params.guild.id.toString();
await emitActivity(
'guild_features_changed',
guildKey(guildId),
{
guild_id: guildId,
actor_id: null,
source: 'staff',
added: [GuildFeatures.PLANNED_JOIN_WAVES],
removed: [],
invites_paused_until_ms: params.guild.invitesPausedUntil?.getTime() ?? null,
},
params.meta,
`${guildId}:planned_join_waves:${params.day}`,
);
}
export async function emitInviteCreated(invite: Invite): Promise<void> {
if (!invite.guildId) return;
const guildId = invite.guildId.toString();
@@ -2,7 +2,14 @@
import {createTestAccount, setUserACLs} from '@app/api/auth/tests/AuthTestUtils';
import {createGuildID} from '@app/api/BrandedTypes';
import {applyPauseGuildInvites, type GuildInvitePauseDeps} from '@app/api/guild/services/GuildInvitePauseApplier';
import {
applyPauseGuildInvites,
endExpiredPlannedJoinWaves,
GUILD_PLANNED_JOIN_WAVES_KEY,
GUILD_PLANNED_JOIN_WAVES_SCHEDULE_KEY,
type GuildInvitePauseDeps,
restatePlannedJoinWaves,
} from '@app/api/guild/services/GuildInvitePauseApplier';
import {acceptInvite, createChannelInvite, createGuild, updateGuild} from '@app/api/guild/tests/GuildTestUtils';
import {resetActivityEventsForTests, startActivityEvents} from '@app/api/infrastructure/activity/ActivityEvents';
import type {ActivityPublisher} from '@app/api/infrastructure/activity/ActivitySpool';
@@ -154,4 +161,181 @@ describe('guild activity events', () => {
expect((await storedPause(guild.id)).until?.getTime()).toBe(untilMs);
});
});
describe('planned join waves end date', () => {
let guild: GuildResponse;
let admin: Awaited<ReturnType<typeof createTestAccount>>;
beforeEach(async () => {
const owner = await createTestAccount(harness);
guild = await createGuild(harness, owner.token, 'Planned waves');
admin = await setUserACLs(harness, await createTestAccount(harness), [
'admin:authenticate',
'guild:update:features',
]);
});
async function staffEdit(body: Record<string, unknown>, status: number = HTTP_STATUS.OK): Promise<void> {
await createBuilder(harness, admin.token).patch(`/admin/guilds/${guild.id}`).body(body).expect(status).execute();
}
async function stored(): Promise<{features: Set<string>; until: Date | null}> {
const row = await getGuildRepository().findUnique(createGuildID(BigInt(guild.id)));
return {features: new Set(row!.features), until: row!.plannedJoinWavesUntil};
}
async function scheduledAt(): Promise<number | null> {
const kv = getKVClient();
const all = await kv.zrangebyscore(GUILD_PLANNED_JOIN_WAVES_SCHEDULE_KEY, '-inf', '+inf');
if (!all.includes(guild.id)) return null;
const stored = (await getGuildRepository().findUnique(createGuildID(BigInt(guild.id))))?.plannedJoinWavesUntil;
const at = stored?.getTime() ?? -1;
return (await kv.zrangebyscore(GUILD_PLANNED_JOIN_WAVES_SCHEDULE_KEY, at, at)).includes(guild.id) ? at : -1;
}
async function tracked(): Promise<boolean> {
return (await getKVClient().smembers(GUILD_PLANNED_JOIN_WAVES_KEY)).includes(guild.id);
}
async function storeEnd(at: Date): Promise<void> {
const repository = getGuildRepository();
const current = await repository.findUnique(createGuildID(BigInt(guild.id)));
await repository.upsertPartial(current!.id, {planned_join_waves_until: at}, current!.toRow());
}
test('staff edits keep the tracking set in step and restore a missing entry', async () => {
await staffEdit({add_features: [GuildFeatures.PLANNED_JOIN_WAVES]});
expect(await tracked()).toBe(true);
await getKVClient().srem(GUILD_PLANNED_JOIN_WAVES_KEY, guild.id);
await staffEdit({add_features: [GuildFeatures.VERIFIED]});
expect(await tracked()).toBe(true);
await staffEdit({remove_features: [GuildFeatures.PLANNED_JOIN_WAVES]});
expect(await tracked()).toBe(false);
});
test('the daily restatement tells downstream consumers a permanent exemption is still on', async () => {
await staffEdit({add_features: [GuildFeatures.PLANNED_JOIN_WAVES]});
const staffAdd = publisher.of('guild_features_changed').at(-1);
expect(await restatePlannedJoinWaves(pauseDeps())).toBeGreaterThanOrEqual(1);
const restated = publisher
.of('guild_features_changed')
.filter((event) => event.data.guild_id === guild.id)
.at(-1);
expect(restated?.id).not.toBe(staffAdd?.id);
expect(restated?.data).toEqual({
guild_id: guild.id,
actor_id: null,
source: 'staff',
added: [GuildFeatures.PLANNED_JOIN_WAVES],
removed: [],
invites_paused_until_ms: null,
});
});
test('resaving an end date that has just passed changes nothing', async () => {
await staffEdit({
add_features: [GuildFeatures.PLANNED_JOIN_WAVES],
planned_join_waves_until: new Date(Date.now() + HOUR_MS).toISOString(),
});
const passed = new Date(Math.floor((Date.now() - 60_000) / 60_000) * 60_000 + 30_000);
await storeEnd(passed);
const asTheFormSendsIt = new Date(Math.floor(passed.getTime() / 60_000) * 60_000).toISOString();
await staffEdit({planned_join_waves_until: asTheFormSendsIt});
const after = await stored();
expect(after.features.has(GuildFeatures.PLANNED_JOIN_WAVES)).toBe(true);
expect(after.until?.getTime()).toBe(passed.getTime());
await staffEdit(
{planned_join_waves_until: new Date(passed.getTime() - 3_600_000).toISOString()},
HTTP_STATUS.BAD_REQUEST,
);
expect((await stored()).until?.getTime()).toBe(passed.getTime());
});
test('adding it without an end date keeps it on with nothing scheduled', async () => {
await staffEdit({add_features: [GuildFeatures.PLANNED_JOIN_WAVES]});
const after = await stored();
expect(after.features.has(GuildFeatures.PLANNED_JOIN_WAVES)).toBe(true);
expect(after.until).toBeNull();
expect(await scheduledAt()).toBeNull();
expect(await endExpiredPlannedJoinWaves(pauseDeps(), 100)).toBe(0);
expect((await stored()).features.has(GuildFeatures.PLANNED_JOIN_WAVES)).toBe(true);
});
test('an end date is stored, scheduled, moved by a new date and cleared by a permanent one', async () => {
const first = Date.now() + 2 * HOUR_MS;
await staffEdit({
add_features: [GuildFeatures.PLANNED_JOIN_WAVES],
planned_join_waves_until: new Date(first).toISOString(),
});
expect((await stored()).until?.getTime()).toBe(first);
expect(await scheduledAt()).toBe(first);
const second = Date.now() + 5 * HOUR_MS;
await staffEdit({planned_join_waves_until: new Date(second).toISOString()});
expect((await stored()).until?.getTime()).toBe(second);
expect(await scheduledAt()).toBe(second);
await staffEdit({planned_join_waves_until: null});
const after = await stored();
expect(after.features.has(GuildFeatures.PLANNED_JOIN_WAVES)).toBe(true);
expect(after.until).toBeNull();
expect(await scheduledAt()).toBeNull();
});
test('removing it clears the end date and the schedule', async () => {
await staffEdit({
add_features: [GuildFeatures.PLANNED_JOIN_WAVES],
planned_join_waves_until: new Date(Date.now() + 2 * HOUR_MS).toISOString(),
});
await staffEdit({remove_features: [GuildFeatures.PLANNED_JOIN_WAVES]});
const after = await stored();
expect(after.features.has(GuildFeatures.PLANNED_JOIN_WAVES)).toBe(false);
expect(after.until).toBeNull();
expect(await scheduledAt()).toBeNull();
});
test('an end date in the past or without the feature is refused', async () => {
await staffEdit(
{
add_features: [GuildFeatures.PLANNED_JOIN_WAVES],
planned_join_waves_until: new Date(Date.now() - 1000).toISOString(),
},
HTTP_STATUS.BAD_REQUEST,
);
await staffEdit(
{planned_join_waves_until: new Date(Date.now() + HOUR_MS).toISOString()},
HTTP_STATUS.BAD_REQUEST,
);
const after = await stored();
expect(after.features.has(GuildFeatures.PLANNED_JOIN_WAVES)).toBe(false);
expect(after.until).toBeNull();
expect(await scheduledAt()).toBeNull();
});
test('the sweep removes it after the end date and tells downstream consumers', async () => {
const until = Date.now() + 2 * HOUR_MS;
await staffEdit({
add_features: [GuildFeatures.PLANNED_JOIN_WAVES],
planned_join_waves_until: new Date(until).toISOString(),
});
expect(publisher.of('guild_features_changed').at(-1)?.data).toMatchObject({
source: 'staff',
added: [GuildFeatures.PLANNED_JOIN_WAVES],
});
expect(await endExpiredPlannedJoinWaves({...pauseDeps(), now: () => until - 1}, 100)).toBe(0);
expect((await stored()).features.has(GuildFeatures.PLANNED_JOIN_WAVES)).toBe(true);
expect(await endExpiredPlannedJoinWaves({...pauseDeps(), now: () => until}, 100)).toBe(1);
const after = await stored();
expect(after.features.has(GuildFeatures.PLANNED_JOIN_WAVES)).toBe(false);
expect(after.until).toBeNull();
expect(await scheduledAt()).toBeNull();
expect(await tracked()).toBe(false);
expect(publisher.of('guild_features_changed').at(-1)?.data).toEqual({
guild_id: guild.id,
actor_id: null,
source: 'system',
added: [],
removed: [GuildFeatures.PLANNED_JOIN_WAVES],
invites_paused_until_ms: null,
});
});
});
});
+3
View File
@@ -51,6 +51,7 @@ export class Guild {
readonly membersIndexedAt: Date | null;
readonly messageHistoryCutoff: Date | null;
readonly invitesPausedUntil: Date | null;
readonly plannedJoinWavesUntil: Date | null;
readonly version: number;
constructor(row: GuildRow) {
@@ -93,6 +94,7 @@ export class Guild {
this.membersIndexedAt = row.members_indexed_at ?? null;
this.messageHistoryCutoff = row.message_history_cutoff ?? null;
this.invitesPausedUntil = row.invites_paused_until ?? null;
this.plannedJoinWavesUntil = row.planned_join_waves_until ?? null;
this.version = row.version;
}
@@ -134,6 +136,7 @@ export class Guild {
members_indexed_at: this.membersIndexedAt,
message_history_cutoff: this.messageHistoryCutoff,
invites_paused_until: this.invitesPausedUntil,
planned_join_waves_until: this.plannedJoinWavesUntil,
version: this.version,
};
}
+5 -3
View File
@@ -41441,7 +41441,7 @@
"description": "IDs of the custom badges assigned to it"
},
"GuildFeatureSchema": {
"description": "A guild feature flag Known values: ANIMATED_ICON, ANIMATED_BANNER, AUDIO_BITRATE_128_KBPS, AUDIO_BITRATE_256_KBPS, AUDIO_BITRATE_384_KBPS, BANNER, CLONE_EMOJI_DISABLED, CLONE_EMOJI_ENABLED, CLONE_STICKER_DISABLED, CLONE_STICKER_ENABLED, DETACHED_BANNER, INVITE_SPLASH, INVITES_DISABLED, RAID_DETECTED, TEXT_CHANNEL_FLEXIBLE_NAMES, HIDE_OWNER_CROWN, MORE_EMOJI, MORE_STICKERS, UNLIMITED_EMOJI, UNLIMITED_STICKERS, EXPRESSION_PURGE_ALLOWED, VANITY_URL, DISCOVERABLE, PARTNERED, VERIFIED, VIP_VOICE, VOICE_E2EE, UNAVAILABLE_FOR_EVERYONE, UNAVAILABLE_FOR_EVERYONE_BUT_STAFF, UNAVAILABLE_HIDDEN, VISIONARY, LARGE_GUILD_OVERRIDE, VERY_LARGE_GUILD, ANNOUNCEMENT_CHANNELS_DISABLED, VISITS_ENABLED, MEMBER_DMS_DISABLED (other values allowed)",
"description": "A guild feature flag Known values: ANIMATED_ICON, ANIMATED_BANNER, AUDIO_BITRATE_128_KBPS, AUDIO_BITRATE_256_KBPS, AUDIO_BITRATE_384_KBPS, BANNER, CLONE_EMOJI_DISABLED, CLONE_EMOJI_ENABLED, CLONE_STICKER_DISABLED, CLONE_STICKER_ENABLED, DETACHED_BANNER, INVITE_SPLASH, INVITES_DISABLED, RAID_DETECTED, TEXT_CHANNEL_FLEXIBLE_NAMES, HIDE_OWNER_CROWN, MORE_EMOJI, MORE_STICKERS, UNLIMITED_EMOJI, UNLIMITED_STICKERS, EXPRESSION_PURGE_ALLOWED, VANITY_URL, DISCOVERABLE, PARTNERED, VERIFIED, VIP_VOICE, VOICE_E2EE, UNAVAILABLE_FOR_EVERYONE, UNAVAILABLE_FOR_EVERYONE_BUT_STAFF, UNAVAILABLE_HIDDEN, VISIONARY, LARGE_GUILD_OVERRIDE, VERY_LARGE_GUILD, ANNOUNCEMENT_CHANNELS_DISABLED, VISITS_ENABLED, MEMBER_DMS_DISABLED, PLANNED_JOIN_WAVES (other values allowed)",
"x-enumNames": [
"ANIMATED_ICON",
"ANIMATED_BANNER",
@@ -41478,7 +41478,8 @@
"VERY_LARGE_GUILD",
"ANNOUNCEMENT_CHANNELS_DISABLED",
"VISITS_ENABLED",
"MEMBER_DMS_DISABLED"
"MEMBER_DMS_DISABLED",
"PLANNED_JOIN_WAVES"
],
"x-enumDescriptions": [
"Guild can have an animated icon",
@@ -41516,7 +41517,8 @@
"Guild has increased member capacity enabled",
"Guild cannot publish announcement messages or gain new followers",
"People with an invite or a discovery listing can read channels that @everyone can see without joining",
"Members who aren't friends can't use the guild as a shared guild for direct messages"
"Members who aren't friends can't use the guild as a shared guild for direct messages",
"Guild expects large planned waves of new members. Invites are not paused after a raid"
],
"type": "string"
},
@@ -52,6 +52,7 @@ function guildRow(features: Set<string>, nsfw = false): GuildRow {
members_indexed_at: null,
message_history_cutoff: null,
invites_paused_until: null,
planned_join_waves_until: null,
version: 1,
};
}
@@ -67,6 +67,8 @@ const LANE_CONFIG = {
'bulkDeleteMessagesForUsers',
'drainActivitySpool',
'liftExpiredGuildInvitePauses',
'endExpiredPlannedJoinWaves',
'restatePlannedJoinWaves',
'endGuildVisitsForCode',
'pruneGuildVisits',
'endUnassignedGuildVisits',
+2
View File
@@ -174,6 +174,8 @@ function registerCronJobs(cron: CronScheduler, jobsStreamMaxAgeMs: number, kvCli
enabled: () => singleCommunityJoinPending(kvClient),
});
cron.upsert('liftExpiredGuildInvitePauses', 'liftExpiredGuildInvitePauses', {}, '0 * * * * *', {ledger: false});
cron.upsert('endExpiredPlannedJoinWaves', 'endExpiredPlannedJoinWaves', {}, '0 * * * * *', {ledger: false});
cron.upsert('restatePlannedJoinWaves', 'restatePlannedJoinWaves', {}, '0 20 4 * * *', {ledger: false});
cron.upsert('archiveInactiveThreads', 'archiveInactiveThreads', {}, '0 * * * * *', {
ledger: false,
enabled: () => true,
@@ -22,6 +22,7 @@ import crosspostMessage from '@app/api/worker/tasks/CrosspostMessage';
import crosspostMessageChunk from '@app/api/worker/tasks/CrosspostMessageChunk';
import deleteUserMessagesInGuildByTime from '@app/api/worker/tasks/DeleteUserMessagesInGuildByTime';
import drainActivitySpool from '@app/api/worker/tasks/DrainActivitySpool';
import endExpiredPlannedJoinWaves from '@app/api/worker/tasks/EndExpiredPlannedJoinWaves';
import expireAttachments from '@app/api/worker/tasks/ExpireAttachments';
import expireReportSnapshots from '@app/api/worker/tasks/ExpireReportSnapshots';
import expireStaleJobs from '@app/api/worker/tasks/ExpireStaleJobs';
@@ -72,6 +73,7 @@ import recordOperatorPassDelivery from '@app/api/worker/tasks/RecordOperatorPass
import refreshSearchIndex from '@app/api/worker/tasks/RefreshSearchIndex';
import refreshStorePurchase from '@app/api/worker/tasks/RefreshStorePurchase';
import removeChannelFollowers from '@app/api/worker/tasks/RemoveChannelFollowers';
import restatePlannedJoinWaves from '@app/api/worker/tasks/RestatePlannedJoinWaves';
import scanBillingNotices from '@app/api/worker/tasks/ScanBillingNotices';
import seedThreadPermissions from '@app/api/worker/tasks/SeedThreadPermissions';
import sendBillingEmail from '@app/api/worker/tasks/SendBillingEmail';
@@ -141,6 +143,8 @@ export const workerTasks: Record<WorkerTaskName, WorkerTaskHandler> = {
indexGuildMembers,
joinSingleCommunityMembers,
liftExpiredGuildInvitePauses,
endExpiredPlannedJoinWaves,
restatePlannedJoinWaves,
messageShred,
notifyRegistrationApprovers,
operatorPassOfferCompletion,
@@ -0,0 +1,15 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {endExpiredPlannedJoinWaves} from '@app/api/guild/services/GuildInvitePauseApplier';
import {getWorkerDependencies} from '@app/api/worker/WorkerContext';
import {guildInvitePauseDeps} from '@app/api/worker/WorkerDependencies';
import type {WorkerTaskHandler} from '@pkgs/worker/src/contracts/WorkerTask';
const BATCH_SIZE = 100;
const endExpiredPlannedJoinWavesTask: WorkerTaskHandler = async (_payload, helpers) => {
const ended = await endExpiredPlannedJoinWaves(guildInvitePauseDeps(getWorkerDependencies()), BATCH_SIZE);
if (ended > 0) helpers.logger.info({ended}, 'Ended expired planned join waves');
};
export default endExpiredPlannedJoinWavesTask;
@@ -0,0 +1,13 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {restatePlannedJoinWaves} from '@app/api/guild/services/GuildInvitePauseApplier';
import {getWorkerDependencies} from '@app/api/worker/WorkerContext';
import {guildInvitePauseDeps} from '@app/api/worker/WorkerDependencies';
import type {WorkerTaskHandler} from '@pkgs/worker/src/contracts/WorkerTask';
const restatePlannedJoinWavesTask: WorkerTaskHandler = async (_payload, helpers) => {
const restated = await restatePlannedJoinWaves(guildInvitePauseDeps(getWorkerDependencies()));
if (restated > 0) helpers.logger.info({restated}, 'Restated planned join waves');
};
export default restatePlannedJoinWavesTask;
@@ -137,6 +137,7 @@ export function createAdminBulkServices(deps: WorkerDependencies): AdminBulkServ
discoveryRepository: getGuildDiscoveryRepository(),
enforcement: enforcementService,
customBadgeCatalog: getCustomBadgeCatalog(),
kvClient: deps.kvClient,
});
return {auditService, banManagementService, userService, guildService};
}
@@ -96,6 +96,7 @@ The owner fields are null when the owner account doesn't exist.
| rules_channel_id | ?snowflake | The rules channel |
| disabled_operations | integer | The [disabled guild operations](/http-api/guilds/#disabled-guild-operations) bitfield |
| member_count | integer | The number of members |
| planned_join_waves_until | ?ISO8601 timestamp | When `PLANNED_JOIN_WAVES` ends, or null when it has no end or is off |
| channels | array[[Admin guild channel](#admin-guild-channel-object) object] | Every channel in the guild except threads |
| roles | array[[Admin guild role](#admin-guild-role-object) object] | Every role in the guild |
@@ -270,7 +271,7 @@ Changes a guild, including its owner, and returns the [Admin guild update](#admi
| --- | --- |
| `guild:update:name` | Renaming the guild (`name`) |
| `guild:update:settings` | Clearing images and changing settings (`fields` and every field from `verification_level` to `disabled_operations`) |
| `guild:update:features` | Adding and removing features (`add_features`, `remove_features`) |
| `guild:update:features` | Adding and removing features (`add_features`, `remove_features`, `planned_join_waves_until`) |
| `guild:update:badges` | Replacing the [custom badges](/admin-api/badges/) (`badge_ids`) |
| `guild:update:vanity` | Changing the custom invite code (`vanity_url_code`) |
| `guild:transfer_ownership` | Transferring ownership (`new_owner_id`) |
@@ -286,6 +287,7 @@ To change `afk_channel_id`, `system_channel_id` or `afk_timeout`, use [Modify gu
| new_owner_id?<sup>2</sup> | snowflake | The new owner |
| add_features?<sup>3</sup> | array[string] | [Guild features](/http-api/guilds/#guild-features) to add (at most 100) |
| remove_features?<sup>3</sup> | array[string] | [Guild features](/http-api/guilds/#guild-features) to remove (at most 100) |
| planned_join_waves_until?<sup>5</sup> | ?ISO8601 timestamp | When `PLANNED_JOIN_WAVES` ends, or null to keep it on with no end |
| badge_ids?<sup>4</sup> | array[snowflake] | The guild badges to give, replacing the current ones |
| fields? | array[string] | Images to clear, each `icon`, `banner`, `splash` or `embed_splash` (at most 10) |
| verification_level? | integer | The new [verification level](/http-api/guilds/#verification-levels) |
@@ -306,6 +308,8 @@ To change `afk_channel_id`, `system_channel_id` or `afk_timeout`, use [Modify gu
<sup>4</sup> A list that adds a badge can hold up to `max_per_guild` of the [badge settings](/admin-api/badges/#badge-settings-object), which is at most 200. A list that only removes badges always works
<sup>5</sup> Only accepted while the guild has `PLANNED_JOIN_WAVES` or this request adds it, and the time must be in the future. Sending the current end again, to the minute, changes nothing even if it has just passed. Leaving it out keeps the current end. When the time passes, Fluxer removes the feature. Removing the feature also clears its end
### Response body
| Field | Type | Description |
@@ -341,6 +341,7 @@ Only the [Admin API](/admin-api/guilds/) sets these bits.
| MORE_EMOJI<sup>4</sup> | Raises the emoji limit |
| MORE_STICKERS<sup>4</sup> | Raises the sticker limit |
| PARTNERED | Guild has partnered status |
| PLANNED_JOIN_WAVES | Guild expects large planned waves of new members. Invites aren't paused after a raid |
| RAID_DETECTED | Set together with `INVITES_DISABLED` while invites are paused after a raid |
| TEXT_CHANNEL_FLEXIBLE_NAMES<sup>3</sup> | Text, announcement, forum and media channel names keep uppercase letters, spaces and punctuation |
| UNAVAILABLE_FOR_EVERYONE<sup>5</sup> | Guild is unavailable to every account, including the owner |
+1
View File
@@ -155,6 +155,7 @@ export const GuildFeatures = {
ANNOUNCEMENT_CHANNELS_DISABLED: 'ANNOUNCEMENT_CHANNELS_DISABLED',
VISITS_ENABLED: 'VISITS_ENABLED',
MEMBER_DMS_DISABLED: 'MEMBER_DMS_DISABLED',
PLANNED_JOIN_WAVES: 'PLANNED_JOIN_WAVES',
} as const;
export type GuildFeature = ValueOf<typeof GuildFeatures>;
@@ -12,6 +12,7 @@ import {GuildBanCreateRequest} from '@fluxer/schema/src/domains/guild/GuildReque
import {GuildFeatureSchema} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
import {AuditLogActionTypeSchema} from '@fluxer/schema/src/primitives/AuditLogValidators';
import {VanityURLCodeType} from '@fluxer/schema/src/primitives/ChannelValidators';
import {IsoTimestampStringType} from '@fluxer/schema/src/primitives/DateValidators';
import {
ContentWarningLevelSchema,
DefaultMessageNotificationsSchema,
@@ -276,6 +277,11 @@ export const UpdateGuildRequest = UpdateGuildSettingsRequest.omit({guild_id: tru
new_owner_id: TransferGuildOwnershipRequest.shape.new_owner_id.optional(),
add_features: UpdateGuildFeaturesRequest.shape.add_features.unwrap().optional(),
remove_features: UpdateGuildFeaturesRequest.shape.remove_features.unwrap().optional(),
planned_join_waves_until: IsoTimestampStringType.nullable()
.optional()
.describe(
'When PLANNED_JOIN_WAVES ends, as an ISO 8601 timestamp in the future. Null keeps it on with no end, and leaving it out keeps the current end. Only accepted while the guild has or gains PLANNED_JOIN_WAVES',
),
badge_ids: CustomBadgeIdsType.optional(),
fields: ClearGuildFieldsRequest.shape.fields.optional(),
});
@@ -1692,6 +1692,10 @@ const AdminLookupGuildSchema = z.object({
rules_channel_id: SnowflakeStringType.nullable(),
disabled_operations: Int32Type,
member_count: Int32Type,
planned_join_waves_until: z.iso
.datetime()
.nullable()
.describe('When PLANNED_JOIN_WAVES ends, or null when it has no end or is off'),
channels: z.array(AdminGuildChannelSummarySchema),
roles: z.array(AdminGuildRoleSummarySchema),
});
@@ -125,6 +125,11 @@ export const GuildFeatureSchema = withOpenApiType(
'MEMBER_DMS_DISABLED',
"Members who aren't friends can't use the guild as a shared guild for direct messages",
],
[
GuildFeatures.PLANNED_JOIN_WAVES,
'PLANNED_JOIN_WAVES',
'Guild expects large planned waves of new members. Invites are not paused after a raid',
],
],
'A guild feature flag',
),
+4
View File
@@ -6406,6 +6406,10 @@
{
"name": "invites_paused_until",
"type": "timestamp"
},
{
"name": "planned_join_waves_until",
"type": "timestamp"
}
],
"primary_key": "((guild_id))",