projects/sdk/src/internal/role-hierarchy-workflow.ts

/**
 * Role hierarchy checks that fetch the required guild data, with opt-in reuse of enabled resource caches.
 * Invariant: Checks describe the observed data and never authorize an action.
 * Implements [SDK contracts: Delivery, requests and caches](/docs/SDK-CONTRACTS.md#delivery-requests-and-caches)
 */
import * as Effect from "effect/Effect"
import type { CanManageOptions, GuildOperationFailure, GuildRole, MemberReference, RoleReference } from "#sdk/guilds"
import { GuildOperationError } from "#sdk/guilds"
import { ClientClosedError } from "#sdk/errors"
import { composedStepFacts } from "#sdk/api-errors"
import { closedBeforeSend } from "#sdk/internal/rest/closed"
import type { ClientOwner } from "./client.js"
import { failures, mapFailureCause } from "./effect-failures.js"
import { guildFetch, memberFetch, roleList } from "./guilds.js"
import { inputId, record } from "./decode/primitives.js"
import { suspendInput } from "./defects.js"
import { evaluateMemberHierarchy, evaluateRoleManagement } from "./role-hierarchy.js"
import { validateRequestOptions } from "./request-options.js"
import { InputValidationFailure, inputValidationFailure, unsupportedKeyFailure } from "#sdk/input-validation"
import type { RequestOptions } from "#sdk/client"

type HierarchyOperation = "members.fetchCanManage" | "roles.fetchCanManage"

type HierarchyOwner = Pick<ClientOwner, "guild" | "logical" | "getResource" | "getSelfMember" | "fetchSelfMember"> & {
    readonly defaultTimeoutMs?: number
}

const inputFailure = (operation: HierarchyOperation, failure: InputValidationFailure) =>
    new GuildOperationError({
        operation,
        reason: "input",
        outcome: "notDispatched",
        inputValidation: failure.detail,
    })

const timeoutFailure = (operation: HierarchyOperation) =>
    new GuildOperationError({ operation, reason: "timeout", outcome: "notDispatched" })

/** Map a cache lookup refused by a closing client to the closure that REST reads report, as no request was sent */
const closedBeforeRead = <A>(lookup: Effect.Effect<A, ClientClosedError | GuildOperationError>) =>
    lookup.pipe(
        mapFailureCause(failures(ClientClosedError, GuildOperationError), (error) =>
            error instanceof ClientClosedError ? closedBeforeSend() : error,
        ),
    )

function memberTarget(value: unknown): MemberReference | InputValidationFailure {
    if (!record(value)) return inputValidationFailure("target", "type", "Hierarchy target must be an object")
    const unsupported = unsupportedKeyFailure(value, ["guildId", "userId"], "target", "the hierarchy target")
    if (unsupported) return unsupported
    // Read each field once, so the validated IDs are the ones fetched
    const guildId = inputId(value.guildId)
    if (guildId === undefined)
        return inputValidationFailure(
            "target.guildId",
            "format",
            "Guild IDs must be decimal strings, because JavaScript numbers cannot hold Fluxer IDs exactly",
        )
    const userId = inputId(value.userId)
    if (userId === undefined)
        return inputValidationFailure(
            "target.userId",
            "format",
            "User IDs must be decimal strings, because JavaScript numbers cannot hold Fluxer IDs exactly",
        )
    return { guildId, userId }
}

function roleTarget(value: unknown): RoleReference | InputValidationFailure {
    if (!record(value)) return inputValidationFailure("role", "type", "Role reference must be an object")
    const unsupported = unsupportedKeyFailure(value, ["guildId", "id"], "role", "the role reference")
    if (unsupported) return unsupported
    // Read each field once, so the validated IDs are the ones fetched
    const guildId = inputId(value.guildId)
    if (guildId === undefined)
        return inputValidationFailure(
            "role.guildId",
            "format",
            "Guild IDs must be decimal strings, because JavaScript numbers cannot hold Fluxer IDs exactly",
        )
    const id = inputId(value.id)
    if (id === undefined)
        return inputValidationFailure(
            "role.id",
            "format",
            "Role IDs must be decimal strings, because JavaScript numbers cannot hold Fluxer IDs exactly",
        )
    return { guildId, id }
}

function options(value: unknown): CanManageOptions | InputValidationFailure {
    const validated = validateRequestOptions(value, {
        keys: ["timeoutMs", "signal", "actorUserId", "preferCache"],
        validateSignal: true,
        label: "the hierarchy options",
        objectMessage: "Hierarchy options must be an object",
        timeoutMessage: "Hierarchy timeout must be an integer from 1 through 2,147,483,647 ms",
        signalMessage: "Hierarchy signal must be an AbortSignal",
    })
    if (validated instanceof InputValidationFailure) return validated
    const recordValue = value as Record<string, unknown> | undefined
    const rawActorUserId = recordValue?.actorUserId
    const actorUserId = rawActorUserId === undefined ? undefined : inputId(rawActorUserId)
    if (rawActorUserId !== undefined && actorUserId === undefined)
        return inputValidationFailure(
            "options.actorUserId",
            "format",
            "User IDs must be decimal strings, because JavaScript numbers cannot hold Fluxer IDs exactly",
        )
    const preferCache = recordValue?.preferCache
    if (preferCache !== undefined && typeof preferCache !== "boolean")
        return inputValidationFailure("options.preferCache", "type", "The option preferCache must be a boolean")
    // Keep only the validated settings: The requests use their own remaining deadlines
    return {
        ...(actorUserId === undefined ? {} : { actorUserId }),
        ...(validated.timeoutMs === undefined ? {} : { timeoutMs: validated.timeoutMs }),
        ...(preferCache === undefined ? {} : { preferCache }),
    }
}

function remaining(deadline: number, now: () => number): RequestOptions | undefined {
    const timeoutMs = Math.floor(deadline - now())
    return timeoutMs > 0 ? { timeoutMs } : undefined
}

const remoteFailure =
    (operation: HierarchyOperation) =>
    (error: GuildOperationFailure): GuildOperationFailure => {
        if (error instanceof GuildOperationError)
            return new GuildOperationError({
                operation,
                reason: error.reason === "input" ? "response" : error.reason,
                outcome: error.outcome,
                status: error.status,
                retryAfterMs: error.retryAfterMs,
                apiError: error.apiError,
                ...composedStepFacts(error),
            })
        return error
    }

/** Shared guild, actor and role readers with optional cache-first lookup under one shared deadline */
function hierarchyReaders(
    owner: HierarchyOwner,
    operation: HierarchyOperation,
    guildId: string,
    validOptions: CanManageOptions,
) {
    const preferCache = validOptions.preferCache === true
    const now = () => owner.logical.now()
    const deadline = now() + (validOptions.timeoutMs ?? owner.defaultTimeoutMs ?? 30_000)
    const remote = <A>(run: (budget: RequestOptions) => Effect.Effect<A, GuildOperationFailure>) =>
        Effect.suspend((): Effect.Effect<A, GuildOperationFailure> => {
            const budget = remaining(deadline, now)
            return budget ? run(budget) : Effect.fail(timeoutFailure(operation))
        })
    const readGuild = Effect.gen(function* () {
        return (
            (preferCache ? yield* closedBeforeRead(owner.getResource("guilds", guildId)) : undefined) ??
            (yield* remote((budget) => owner.guild("guilds.fetch", () => guildFetch(guildId), budget)))
        )
    })
    const readActor = Effect.gen(function* () {
        if (validOptions.actorUserId === undefined)
            return (
                (preferCache ? yield* closedBeforeRead(owner.getSelfMember(guildId)) : undefined) ??
                (yield* remote((budget) => owner.fetchSelfMember(guildId, budget)))
            )
        const actorRef = { guildId, userId: validOptions.actorUserId }
        return (
            (preferCache ? yield* closedBeforeRead(owner.getResource("members", actorRef)) : undefined) ??
            (yield* remote((budget) => owner.guild("members.fetch", () => memberFetch(actorRef), budget)))
        )
    })
    const readRoles = (neededRoleIds?: readonly string[]) =>
        Effect.gen(function* () {
            if (preferCache && neededRoleIds !== undefined) {
                const uniqueIds = [...new Set(neededRoleIds)]
                const cached = yield* Effect.forEach(uniqueIds, (id) =>
                    closedBeforeRead(owner.getResource("roles", { guildId, id })),
                )
                if (cached.every((role): role is GuildRole => role !== undefined)) return cached
            }
            return yield* remote((budget) => owner.guild("roles.fetchAll", () => roleList(guildId), budget))
        })
    return { preferCache, remote, readGuild, readActor, readRoles }
}

/** Fetches the four independent hierarchy inputs in parallel under one deadline (or uses enabled caches when
 * preferCache is true), then evaluates the pure local rule.
 * The actor is the bot unless actorUserId names another member of the target's guild
 */
export function fetchCanManage(
    owner: HierarchyOwner,
    input: MemberReference,
    suppliedOptions?: CanManageOptions,
): Effect.Effect<boolean, GuildOperationFailure> {
    // Reading and validating the caller target and options is marked as application input
    return suspendInput(() => {
        const member = memberTarget(input)
        const validOptions = options(suppliedOptions)
        if (member instanceof InputValidationFailure) return Effect.fail(inputFailure("members.fetchCanManage", member))
        if (validOptions instanceof InputValidationFailure)
            return Effect.fail(inputFailure("members.fetchCanManage", validOptions))
        return Effect.gen(function* () {
            const { preferCache, remote, readGuild, readActor, readRoles } = hierarchyReaders(
                owner,
                "members.fetchCanManage",
                member.guildId,
                validOptions,
            )
            const readTarget = Effect.gen(function* () {
                return (
                    (preferCache ? yield* closedBeforeRead(owner.getResource("members", member)) : undefined) ??
                    (yield* remote((budget) => owner.guild("members.fetch", () => memberFetch(member), budget)))
                )
            })
            const [guild, actor, targetMember, roles] = yield* (
                preferCache
                    ? Effect.all(
                          [
                              readGuild,
                              Effect.all([readActor, readTarget], { concurrency: 2 }).pipe(
                                  Effect.flatMap(([fetchedActor, fetchedTarget]) =>
                                      readRoles([...fetchedActor.roleIds, ...fetchedTarget.roleIds]).pipe(
                                          Effect.map(
                                              (fetchedRoles) => [fetchedActor, fetchedTarget, fetchedRoles] as const,
                                          ),
                                      ),
                                  ),
                              ),
                          ],
                          { concurrency: 2 },
                      ).pipe(
                          Effect.map(
                              ([fetchedGuild, [fetchedActor, fetchedTarget, fetchedRoles]]) =>
                                  [fetchedGuild, fetchedActor, fetchedTarget, fetchedRoles] as const,
                          ),
                      )
                    : Effect.all([readGuild, readActor, readTarget, readRoles()], { concurrency: "unbounded" })
            ).pipe(
                mapFailureCause(
                    failures(GuildOperationError, ClientClosedError),
                    remoteFailure("members.fetchCanManage"),
                ),
            )
            const manageable = evaluateMemberHierarchy({ guild, actor, target: targetMember, roles })
            return manageable === undefined
                ? yield* Effect.fail(
                      new GuildOperationError({
                          operation: "members.fetchCanManage",
                          reason: "response",
                          outcome: "unknown",
                          // Every step was a read, so nothing can have changed
                          read: true,
                      }),
                  )
                : manageable
        })
    })
}

/** Fetches the guild, actor member and roles under one deadline (or uses enabled caches when preferCache is true),
 * then evaluates hierarchy.canManageRole against the target role.
 * Fails with reason notFound when the guild's roles do not include the requested role ID
 */
export function fetchCanManageRole(
    owner: HierarchyOwner,
    input: RoleReference,
    suppliedOptions?: CanManageOptions,
): Effect.Effect<boolean, GuildOperationFailure> {
    return suspendInput(() => {
        const role = roleTarget(input)
        const validOptions = options(suppliedOptions)
        if (role instanceof InputValidationFailure) return Effect.fail(inputFailure("roles.fetchCanManage", role))
        if (validOptions instanceof InputValidationFailure)
            return Effect.fail(inputFailure("roles.fetchCanManage", validOptions))
        return Effect.gen(function* () {
            const { preferCache, readGuild, readActor, readRoles } = hierarchyReaders(
                owner,
                "roles.fetchCanManage",
                role.guildId,
                validOptions,
            )
            const [guild, actor, roles] = yield* (
                preferCache
                    ? Effect.all(
                          [
                              readGuild,
                              readActor.pipe(
                                  Effect.flatMap((fetchedActor) =>
                                      readRoles([role.id, ...fetchedActor.roleIds]).pipe(
                                          Effect.map((fetchedRoles) => [fetchedActor, fetchedRoles] as const),
                                      ),
                                  ),
                              ),
                          ],
                          { concurrency: 2 },
                      ).pipe(
                          Effect.map(
                              ([fetchedGuild, [fetchedActor, fetchedRoles]]) =>
                                  [fetchedGuild, fetchedActor, fetchedRoles] as const,
                          ),
                      )
                    : Effect.all([readGuild, readActor, readRoles()], { concurrency: "unbounded" })
            ).pipe(
                mapFailureCause(
                    failures(GuildOperationError, ClientClosedError),
                    remoteFailure("roles.fetchCanManage"),
                ),
            )
            const targetRole = roles.find((item) => item.id === role.id)
            if (!targetRole)
                return yield* Effect.fail(
                    new GuildOperationError({
                        operation: "roles.fetchCanManage",
                        reason: "notFound",
                        outcome: "rejected",
                        read: true,
                    }),
                )
            const manageable = evaluateRoleManagement({ guild, actor, role: targetRole, roles })
            return manageable === undefined
                ? yield* Effect.fail(
                      new GuildOperationError({
                          operation: "roles.fetchCanManage",
                          reason: "response",
                          outcome: "unknown",
                          read: true,
                      }),
                  )
                : manageable
        })
    })
}