All files / services guildEventLogging.ts

100% Statements 644/644
100% Branches 93/93
100% Functions 24/24
100% Lines 644/644

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645138x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 1x 18x 18x 18x 18x 18x 18x 18x 19x 19x 18x 18x 18x 19x 1x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 17x 17x 17x 17x 17x 19x 19x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 19x 1x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 2x 2x 18x 18x 16x 18x 3x 3x 18x 18x 1x 1x 18x 18x 1x 1x 18x 18x 11x 18x 1x 1x 18x 18x 10x 18x 2x 2x 18x 18x 1x 1x 18x 18x 7x 18x 1x 1x 18x 18x 6x 18x 2x 2x 18x 18x 4x 4x 4x 18x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 18x 18x 3x 18x 18x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 18x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 1x 1x 6x 6x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 6x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 1x 13x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 1x 18x 18x 18x 18x 18x 18x 18x 18x 1x 1x 1x 1x 1x 1x 1x 18x 1x 10x 10x 10x 10x 10x 10x 10x 8x 8x 10x 10x 2x 10x 1x 1x 10x 1x 8x 8x 8x 8x 8x 1x 5x 5x 5x 1x 4x 4x 1x 1x 4x 4x 4x 1x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 1x 9x 9x 9x 1x 14x 14x 14x 14x 14x 14x 14x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x  
import {
  escapeMarkdown,
  PermissionFlagsBits,
  type Guild,
  type GuildBasedChannel,
  type GuildBan,
  type GuildMember,
  type Message,
  type MessageCreateOptions,
  type PartialMessage,
  type PartialGuildMember,
  type PermissionsBitField,
  type Role,
} from "discord.js"
 
import {
  convexBotClient,
  type DiscordGuildEventRecord,
  type DiscordGuildEventRecordResult,
} from "@/services/convexBotClient"
import {
  fetchDiscordGuildRuntimeConfig,
  type DiscordGuildRuntimeConfigResult,
} from "@/services/guildRuntimeConfig"
import {
  reportDiscordRuntimeError,
  type DiscordRuntimeErrorReporter,
} from "@/services/runtimeErrorReporter"
import { botLogError } from "@/utils/botLog"
import { redactLogText } from "@workspace/logger"
import { formatDiscordGuildEventType } from "@workspace/shared/discordGuildEventLabels"
import type { DiscordGuildRuntimeConfigLogLevel } from "@workspace/shared/discordRuntimeConfig"
 
type RuntimeConfigFetcher = (
  discordGuildId: string
) => Promise<DiscordGuildRuntimeConfigResult>
 
type GuildEventPersister = (
  event: DiscordGuildEventRecord
) => Promise<DiscordGuildEventRecordResult | null>
 
type GuildEventFormatter = (
  event: DiscordGuildEventRecord
) => MessageCreateOptions
 
export type DiscordGuildEventProcessingResult = {
  persistence: "recorded" | "failed"
  delivery:
    | "sent"
    | "deduplicated"
    | "configUnavailable"
    | "loggingDisabled"
    | "filteredByLogLevel"
    | "missingLogChannel"
    | "guildUnavailable"
    | "channelUnavailable"
    | "channelUnsupported"
    | "botMemberUnavailable"
    | "missingBasePermissions"
    | "formatFailed"
    | "sendFailed"
}
 
type GuildEventLoggingOptions = {
  fetchConfig?: RuntimeConfigFetcher
  persistEvent?: GuildEventPersister
  formatLogMessage?: GuildEventFormatter
  logError?: typeof botLogError
  reportRuntimeError?: DiscordRuntimeErrorReporter
}
 
type GuildEventContext = {
  guild?: Guild | null
}
 
type LogSendableChannel = GuildBasedChannel & {
  send(message: MessageCreateOptions): Promise<unknown>
  permissionsFor(member: GuildMember): Readonly<PermissionsBitField> | null
}
 
const baseLogPermissions = [
  PermissionFlagsBits.ViewChannel,
  PermissionFlagsBits.SendMessages,
] as const
 
const eventMinimumLogLevel: Record<
  DiscordGuildEventRecord["eventType"],
  Exclude<DiscordGuildRuntimeConfigLogLevel, "none">
> = {
  guildBanAdd: "minimal",
  guildBanRemove: "minimal",
  guildMemberAdd: "medium",
  guildMemberRemove: "medium",
  channelCreate: "medium",
  channelDelete: "medium",
  roleCreate: "medium",
  roleDelete: "medium",
  messageDelete: "maximum",
}
 
const logLevelRank: Record<DiscordGuildRuntimeConfigLogLevel, number> = {
  none: 0,
  minimal: 1,
  medium: 2,
  maximum: 3,
}
 
export async function handleDiscordGuildEvent(
  event: DiscordGuildEventRecord,
  context: GuildEventContext,
  options: GuildEventLoggingOptions = {}
): Promise<DiscordGuildEventProcessingResult> {
  const logError = options.logError ?? botLogError
  const reportRuntimeError =
    options.reportRuntimeError ?? reportDiscordRuntimeError
  const persistenceResult = await persistDiscordGuildEvent(event, {
    persistEvent: options.persistEvent ?? convexBotClient.recordGuildEvent,
    logError,
    reportRuntimeError,
  })
  const delivery = persistenceResult.deduplicated
    ? "deduplicated"
    : await deliverDiscordGuildEventLog(event, context, {
        fetchConfig: options.fetchConfig ?? fetchDiscordGuildRuntimeConfig,
        formatLogMessage:
          options.formatLogMessage ?? formatGuildEventLogMessage,
        logError,
        reportRuntimeError,
      })
 
  return {
    persistence: persistenceResult.status,
    delivery,
  }
}
 
async function persistDiscordGuildEvent(
  event: DiscordGuildEventRecord,
  options: {
    persistEvent: GuildEventPersister
    logError: typeof botLogError
    reportRuntimeError: DiscordRuntimeErrorReporter
  }
): Promise<{
  status: "recorded" | "failed"
  deduplicated: boolean
}> {
  try {
    const result = await options.persistEvent(event)
 
    if (result !== null) {
      return {
        status: "recorded",
        deduplicated: result.deduplicated,
      }
    }
 
    options.logError("Discord guild event persistence failed.", undefined, {
      discordGuildId: event.discordGuildId,
      eventName: event.eventType,
    })
 
    await reportGuildEventRuntimeError({
      error: new Error("Convex guild event record returned null."),
      event,
      operation: "persistGuildEvent",
      message: "Discord guild event persistence failed.",
      logError: options.logError,
      reportRuntimeError: options.reportRuntimeError,
    })
 
    return {
      status: "failed",
      deduplicated: false,
    }
  } catch (error) {
    options.logError("Discord guild event persistence failed.", error, {
      discordGuildId: event.discordGuildId,
      eventName: event.eventType,
    })
 
    await reportGuildEventRuntimeError({
      error,
      event,
      operation: "persistGuildEvent",
      message: "Discord guild event persistence failed.",
      logError: options.logError,
      reportRuntimeError: options.reportRuntimeError,
    })
 
    return {
      status: "failed",
      deduplicated: false,
    }
  }
}
 
async function deliverDiscordGuildEventLog(
  event: DiscordGuildEventRecord,
  context: GuildEventContext,
  options: {
    fetchConfig: RuntimeConfigFetcher
    formatLogMessage: GuildEventFormatter
    logError: typeof botLogError
    reportRuntimeError: DiscordRuntimeErrorReporter
  }
): Promise<DiscordGuildEventProcessingResult["delivery"]> {
  const configResult = await fetchRuntimeConfigQuietly(
    event,
    options.fetchConfig,
    options.logError
  )
 
  if (configResult?.status !== "ready") {
    return "configUnavailable"
  }
 
  const { loggingEnabled, logChannelId, logLevel } = configResult.config
 
  if (!loggingEnabled) {
    return "loggingDisabled"
  }
 
  if (!shouldMirrorDiscordGuildEvent(event.eventType, logLevel)) {
    return "filteredByLogLevel"
  }
 
  if (!logChannelId) {
    return "missingLogChannel"
  }
 
  const guild = context.guild
 
  if (!guild) {
    return "guildUnavailable"
  }
 
  const channel = await resolveConfiguredLogChannel(guild, logChannelId)
 
  if (!channel) {
    return "channelUnavailable"
  }
 
  if (!isTextSendableChannel(channel)) {
    return "channelUnsupported"
  }
 
  const botMember = guild.members.me
 
  if (!botMember) {
    return "botMemberUnavailable"
  }
 
  const permissions = channel.permissionsFor(botMember)
 
  if (!permissions?.has(baseLogPermissions)) {
    return "missingBasePermissions"
  }
 
  let message: MessageCreateOptions
 
  try {
    message = options.formatLogMessage(event)
  } catch (error) {
    options.logError("Discord guild event log formatting failed.", error, {
      discordGuildId: event.discordGuildId,
      eventName: event.eventType,
      discordChannelId: channel.id,
    })
 
    await reportGuildEventRuntimeError({
      error,
      event,
      operation: "formatGuildEventLog",
      message: "Discord guild event log formatting failed.",
      channelId: channel.id,
      logError: options.logError,
      reportRuntimeError: options.reportRuntimeError,
    })
 
    return "formatFailed"
  }
 
  try {
    await channel.send(message)
    return "sent"
  } catch (error) {
    options.logError("Discord guild event log delivery failed.", error, {
      discordGuildId: event.discordGuildId,
      eventName: event.eventType,
      discordChannelId: channel.id,
    })
 
    await reportGuildEventRuntimeError({
      error,
      event,
      operation: "sendGuildEventLog",
      message: "Discord guild event log delivery failed.",
      channelId: channel.id,
      logError: options.logError,
      reportRuntimeError: options.reportRuntimeError,
    })
 
    return "sendFailed"
  }
}
 
export function shouldMirrorDiscordGuildEvent(
  eventType: DiscordGuildEventRecord["eventType"],
  configuredLevel: DiscordGuildRuntimeConfigLogLevel | undefined
): boolean {
  const effectiveLevel = configuredLevel ?? "maximum"
 
  return (
    logLevelRank[effectiveLevel] >=
    logLevelRank[eventMinimumLogLevel[eventType]]
  )
}
 
export function normalizeGuildMemberAdd(
  member: GuildMember,
  occurredAt = member.joinedTimestamp ?? Date.now()
): DiscordGuildEventRecord {
  return {
    discordGuildId: member.guild.id,
    eventType: "guildMemberAdd",
    targetType: "member",
    targetDiscordId: member.id,
    targetDisplayName: member.displayName,
    metadata: {
      bot: member.user.bot,
    },
    occurredAt,
    dedupeKey: buildDedupeKey(
      "guildMemberAdd",
      member.guild.id,
      member.id,
      occurredAt
    ),
  }
}
 
export function normalizeGuildMemberRemove(
  member: GuildMember | PartialGuildMember,
  occurredAt = Date.now()
): DiscordGuildEventRecord {
  return {
    discordGuildId: member.guild.id,
    eventType: "guildMemberRemove",
    targetType: "member",
    targetDiscordId: member.id,
    targetDisplayName: member.displayName,
    metadata: {
      bot: member.user.bot,
    },
    occurredAt,
    dedupeKey: buildDedupeKey(
      "guildMemberRemove",
      member.guild.id,
      member.id,
      getDedupeWindow(occurredAt)
    ),
  }
}
 
export function normalizeGuildBanAdd(
  ban: GuildBan,
  occurredAt = Date.now()
): DiscordGuildEventRecord {
  return {
    discordGuildId: ban.guild.id,
    eventType: "guildBanAdd",
    targetType: "user",
    targetDiscordId: ban.user.id,
    targetDisplayName: getUserDisplayName(ban.user),
    reason: ban.reason ?? undefined,
    occurredAt,
    dedupeKey: buildDedupeKey(
      "guildBanAdd",
      ban.guild.id,
      ban.user.id,
      getDedupeWindow(occurredAt)
    ),
  }
}
 
export function normalizeGuildBanRemove(
  ban: GuildBan,
  occurredAt = Date.now()
): DiscordGuildEventRecord {
  return {
    discordGuildId: ban.guild.id,
    eventType: "guildBanRemove",
    targetType: "user",
    targetDiscordId: ban.user.id,
    targetDisplayName: getUserDisplayName(ban.user),
    reason: ban.reason ?? undefined,
    occurredAt,
    dedupeKey: buildDedupeKey(
      "guildBanRemove",
      ban.guild.id,
      ban.user.id,
      getDedupeWindow(occurredAt)
    ),
  }
}
 
export function normalizeChannelCreate(
  channel: GuildBasedChannel,
  occurredAt = getTimestampOrNow(channel.createdTimestamp)
): DiscordGuildEventRecord {
  return {
    discordGuildId: channel.guild.id,
    eventType: "channelCreate",
    targetType: "channel",
    targetDiscordId: channel.id,
    targetDisplayName: "name" in channel ? channel.name : undefined,
    channelId: channel.id,
    metadata: {
      channelType: String(channel.type),
    },
    occurredAt,
    dedupeKey: buildDedupeKey(
      "channelCreate",
      channel.guild.id,
      channel.id,
      occurredAt
    ),
  }
}
 
export function normalizeChannelDelete(
  channel: GuildBasedChannel,
  occurredAt = Date.now()
): DiscordGuildEventRecord {
  return {
    discordGuildId: channel.guild.id,
    eventType: "channelDelete",
    targetType: "channel",
    targetDiscordId: channel.id,
    targetDisplayName: "name" in channel ? channel.name : undefined,
    channelId: channel.id,
    metadata: {
      channelType: String(channel.type),
    },
    occurredAt,
    dedupeKey: buildDedupeKey("channelDelete", channel.guild.id, channel.id),
  }
}
 
export function normalizeRoleCreate(
  role: Role,
  occurredAt = getTimestampOrNow(role.createdTimestamp)
): DiscordGuildEventRecord {
  return {
    discordGuildId: role.guild.id,
    eventType: "roleCreate",
    targetType: "role",
    targetDiscordId: role.id,
    targetDisplayName: role.name,
    roleId: role.id,
    occurredAt,
    dedupeKey: buildDedupeKey("roleCreate", role.guild.id, role.id, occurredAt),
  }
}
 
export function normalizeRoleDelete(
  role: Role,
  occurredAt = Date.now()
): DiscordGuildEventRecord {
  return {
    discordGuildId: role.guild.id,
    eventType: "roleDelete",
    targetType: "role",
    targetDiscordId: role.id,
    targetDisplayName: role.name,
    roleId: role.id,
    occurredAt,
    dedupeKey: buildDedupeKey("roleDelete", role.guild.id, role.id),
  }
}
 
export function normalizeMessageDelete(
  message: Message | PartialMessage,
  occurredAt = Date.now()
): DiscordGuildEventRecord | null {
  if (!message.guildId) {
    return null
  }
 
  return {
    discordGuildId: message.guildId,
    eventType: "messageDelete",
    targetType: "message",
    targetDiscordId: message.id,
    channelId: message.channelId,
    metadata: {
      partial: message.partial,
    },
    occurredAt,
    dedupeKey: buildDedupeKey("messageDelete", message.guildId, message.id),
  }
}
 
export function formatGuildEventLogMessage(
  event: DiscordGuildEventRecord
): MessageCreateOptions {
  const lines = [
    `**${formatDiscordGuildEventType(event.eventType)}**`,
    `Target: ${formatTarget(event)}`,
    `Time: <t:${Math.floor(event.occurredAt / 1000)}:F>`,
    ...(event.actorDiscordUserId ? [`Actor: ${event.actorDiscordUserId}`] : []),
    ...(event.reason
      ? [`Reason: ${escapeMarkdown(redactLogText(event.reason))}`]
      : []),
  ]
 
  return {
    content: lines.join("\n"),
    allowedMentions: {
      parse: [],
      roles: [],
      users: [],
    },
  }
}
 
async function fetchRuntimeConfigQuietly(
  event: DiscordGuildEventRecord,
  fetchConfig: RuntimeConfigFetcher,
  logError: typeof botLogError
): Promise<DiscordGuildRuntimeConfigResult | null> {
  try {
    return await fetchConfig(event.discordGuildId)
  } catch (error) {
    logError("Discord guild event runtime config fetch failed.", error, {
      discordGuildId: event.discordGuildId,
      eventName: event.eventType,
    })
 
    return null
  }
}
 
async function resolveConfiguredLogChannel(
  guild: Guild,
  channelId: string
): Promise<GuildBasedChannel | null> {
  const cachedChannel = guild.channels.cache.get(channelId)
 
  if (cachedChannel) {
    return cachedChannel
  }
 
  try {
    return await guild.channels.fetch(channelId)
  } catch {
    return null
  }
}
 
function isTextSendableChannel(
  channel: GuildBasedChannel | null
): channel is LogSendableChannel {
  return Boolean(channel?.isTextBased() && channel.isSendable())
}
 
function getUserDisplayName(user: GuildBan["user"]): string {
  return user.globalName ?? user.displayName ?? user.username
}
 
function getTimestampOrNow(value: number | null | undefined): number {
  if (typeof value === "number" && Number.isSafeInteger(value) && value > 0) {
    return value
  }
 
  return Date.now()
}
 
function buildDedupeKey(
  eventType: DiscordGuildEventRecord["eventType"],
  discordGuildId: string,
  subjectId: string,
  discriminator?: number
): string {
  return [eventType, discordGuildId, subjectId, discriminator]
    .filter((value) => value !== undefined)
    .join(":")
}
 
function getDedupeWindow(occurredAt: number): number {
  return Math.floor(occurredAt / 5_000)
}
 
function formatTarget(event: DiscordGuildEventRecord): string {
  const label = event.targetDisplayName?.trim()
  const id =
    event.targetDiscordId ?? event.channelId ?? event.roleId ?? "unknown target"
 
  return label ? `${escapeMarkdown(label)} (${id})` : id
}
 
async function reportGuildEventRuntimeError(args: {
  error: unknown
  event: DiscordGuildEventRecord
  operation: "persistGuildEvent" | "formatGuildEventLog" | "sendGuildEventLog"
  message: string
  channelId?: string
  logError: typeof botLogError
  reportRuntimeError: DiscordRuntimeErrorReporter
}) {
  try {
    await args.reportRuntimeError({
      severity: "error",
      serviceArea: "logging",
      message: args.message,
      error: args.error,
      discordGuildId: args.event.discordGuildId,
      eventName: args.event.eventType,
      operation: args.operation,
      fingerprint: args.channelId
        ? `logging:${args.operation}:${args.event.discordGuildId}:${args.channelId}:${args.event.eventType}`
        : `logging:${args.operation}:${args.event.discordGuildId}:${args.event.eventType}`,
      metadata: {
        eventType: args.event.eventType,
        targetType: args.event.targetType,
        targetDiscordId: args.event.targetDiscordId,
        channelId: args.channelId ?? args.event.channelId,
        roleId: args.event.roleId,
      },
    })
  } catch (reportError) {
    args.logError(
      "Discord guild event runtime error report failed.",
      reportError,
      {
        discordGuildId: args.event.discordGuildId,
        eventName: args.event.eventType,
        operation: args.operation,
        discordChannelId: args.channelId,
      }
    )
  }
}