projects/bot/src/usage.ts

import { ServiceUsage, type ServiceUsageRequest } from "@neonflux/contracts/service"
import { Duration, Effect, Schema } from "effect"
import { BackendRequestError, createBackendRequest } from "./backend-http.ts"
import type { BackendConfig } from "./config.ts"
import { readCosts } from "./costs.ts"
import { warnFailure } from "./contained.ts"

/** The bot reports its billed calls this often, so the bill guard costs one call every five minutes */
export const usageReportMs = 300000

/** The bill guard state from the latest usage report. Optional work stops while it is paused */
export function createUsageGuard() {
    let state: ServiceUsage["state"] = "normal",
        announced = false
    return {
        paused: () => state === "paused",
        apply: (usage: ServiceUsage) =>
            Effect.gen(function* () {
                // The budget lives in the deployment, so the first answer is the bot's first view of it
                if (!announced)
                    yield* Effect.logInfo(`Backend budget: ${usage.budget === null ? "not set" : usage.state}`)
                announced = true
                const reached = `${usage.calls} of the ${usage.budget} backend calls budgeted for ${usage.month}`
                if (usage.warn) yield* Effect.logWarning(`Backend usage reached ${reached}`)
                if (usage.state === "paused" && state !== "paused")
                    yield* Effect.logWarning(
                        `Optional work is paused at ${reached}. Moderation, protections and commands keep running`,
                    )
                if (usage.state !== "paused" && state === "paused") yield* Effect.logInfo("Optional work resumed")
                state = usage.state
            }),
        /** The deployment's budget setting is invalid, so the guard cannot count. Optional work waits until a report succeeds again */
        misconfigured: () =>
            Effect.gen(function* () {
                if (state !== "paused")
                    yield* Effect.logWarning(
                        "The Convex deployment's bill guard setting is invalid, and its logs name the variable to fix. Optional work is paused until then. Moderation, protections and commands keep running",
                    )
                state = "paused"
            }),
    }
}
export type UsageGuard = ReturnType<typeof createUsageGuard>

// Reports the process's billed calls since the last accepted report, at startup, every five minutes and on shutdown. The
// answer carries the guard state, so checking it costs nothing more. A failed report keeps its calls for the next one, and
// a report whose answer was lost may be counted twice, which errs toward pausing early
export function startUsageReporter(backend: BackendConfig, guard: UsageGuard) {
    const post = createBackendRequest(backend)
    let reported = 0,
        failing = false
    const report = Effect.gen(function* () {
        const counted = readCosts().backendRequests
        const answer = yield* post("/service/usage", { calls: counted - reported } satisfies ServiceUsageRequest).pipe(
            Effect.flatMap(Schema.decodeUnknownEffect(ServiceUsage)),
            Effect.catch((error) =>
                Effect.succeed(
                    error instanceof BackendRequestError && error.code === "USAGE_BUDGET_INVALID"
                        ? ("misconfigured" as const)
                        : { failed: error },
                ),
            ),
        )
        if (answer === "misconfigured") {
            failing = false
            yield* guard.misconfigured()
            return
        }
        if ("failed" in answer) {
            if (!failing)
                yield* warnFailure(
                    "Backend usage could not be reported. The next report includes these calls",
                    answer.failed,
                )
            failing = true
            return
        }
        const usage = answer
        failing = false
        reported = counted
        yield* guard.apply(usage)
    })
    return Effect.gen(function* () {
        // Registered before the loop, so closing interrupts the loop first
        yield* Effect.addFinalizer(() => report.pipe(Effect.catchCause(() => Effect.void)))
        yield* Effect.gen(function* () {
            for (;;) {
                yield* report
                yield* Effect.sleep(Duration.millis(usageReportMs))
            }
        }).pipe(Effect.forkScoped({ startImmediately: true }))
    })
}