mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-18 05:53:05 +00:00
As funções rodavam no default iad1 (Virgínia) enquanto o Neon fica em sa-east-1 (São Paulo): cada query do Payload atravessava o equador duas vezes (~120 ms por ida-e-volta) e uma página do /campanha faz uma dúzia. Medido em produção: 410-470 ms de TTFB para um 307 que não toca o banco. - vercel.json fixa regions: [gru1], mesma região AWS do banco (Hobby permite uma região, mas permite escolher qual). - loadStatewideSuggestedGoals passa a ser exportada e é disparada dentro do Promise.all que já lê o escopo, na lista e no dashboard: o read do global campaignGoals saía sozinho no fim da requisição. - loadMunicipalityScope lê os pledges em paralelo quando o ator é irrestrito e não há filtro (aí o IN de 435 ids não exclui nada); qualquer escopo mais estreito continua esperando os ids. Débitos medidos no caminho e registrados em TECH-DEBT: o fan-out de leituras do ator em getFreshCampaignUser (~5 por render) e a leitura dupla em authenticateCampaignToken.
158 lines
5.9 KiB
TypeScript
158 lines
5.9 KiB
TypeScript
import 'server-only'
|
|
|
|
import { cache } from 'react'
|
|
|
|
import type { Payload } from 'payload'
|
|
|
|
import {
|
|
DEFAULT_VOTE_ESTIMATE_SCENARIO,
|
|
VOTE_ESTIMATE_SCENARIOS,
|
|
zeroByVoteEstimateScenario,
|
|
type VoteEstimateScenario,
|
|
type VoteEstimateScenarioFields,
|
|
} from '@/lib/voteEstimate'
|
|
import type { CampaignUser, User } from '@/payload-types'
|
|
import { loadCampaignGoals } from '@/utilities/campaignGoals'
|
|
import {
|
|
aggregateGoalCoverage,
|
|
computeGoalCoverage,
|
|
computeGoalCoverageByScenario,
|
|
type MunicipalityGoalCoverage,
|
|
} from '@/utilities/goalCoverage'
|
|
import {
|
|
computeMunicipalityPotential,
|
|
computeStatewideSuggestedGoals,
|
|
type MunicipalityPotential,
|
|
type SuggestedGoalByScenario,
|
|
} from '@/utilities/municipalityPotential'
|
|
import {
|
|
computeMunicipalityTerritorialClass,
|
|
type MunicipalityTerritorialClassification,
|
|
} from '@/utilities/municipalityTerritorialClass'
|
|
import {
|
|
emptyMunicipalityPledgeAggregate,
|
|
type MunicipalityPledgeAggregate,
|
|
} from '@/utilities/votePledgeViews'
|
|
|
|
type GoalAccountReader = CampaignUser | User
|
|
|
|
/**
|
|
* E8 "conta da cadeira" — request-scoped statewide suggested-goal ladder
|
|
* (`campaignGoals` global + `computeStatewideSuggestedGoals`), degrau 1 da
|
|
* caching ladder. Every surface (dashboard, list overview, list rows, detail
|
|
* card) needs the SAME goals — the optimistic scenario's growth factor is
|
|
* `stateGoal / Σ base` over the full 435-slug catalog, so this always runs
|
|
* over the whole catalog, never a filtered scope, and is
|
|
* `cache()`-deduplicated so dashboard + list + detail don't each recompute it
|
|
* on requests that touch more than one.
|
|
*
|
|
* Exported so a page can start it inside the `Promise.all` that already reads
|
|
* the scope: the coverage bundle needs it, and awaiting it only at the bundle
|
|
* call site left one global read (plus the catalog-wide pure computation) alone
|
|
* at the tail of the request.
|
|
*/
|
|
export const loadStatewideSuggestedGoals = cache(
|
|
async (payload: Payload, user: GoalAccountReader) => {
|
|
const goals = await loadCampaignGoals(payload, user)
|
|
return computeStatewideSuggestedGoals(goals)
|
|
},
|
|
)
|
|
|
|
export type MunicipalityGoalCoverageBundle = {
|
|
coverageByMunicipalityID: Map<number, Record<VoteEstimateScenario, MunicipalityGoalCoverage>>
|
|
/** Sum of every municipality's coverage in `municipalities`, per scenario (dashboard/overview metric). */
|
|
aggregateByScenario: Record<VoteEstimateScenario, MunicipalityGoalCoverage>
|
|
}
|
|
|
|
/**
|
|
* Per-scenario goal coverage for a scope of municipalities (dashboard total,
|
|
* or the list's filtered overview) plus the per-municipality breakdown the
|
|
* list rows pick a scenario from client-side — mirrors
|
|
* `rollupMunicipalityStaffVotes`'s "compute all 3 scenarios server-side, pick
|
|
* client-side" shape.
|
|
*/
|
|
export const loadMunicipalityGoalCoverageBundle = async (
|
|
payload: Payload,
|
|
user: GoalAccountReader,
|
|
municipalities: ReadonlyArray<{
|
|
id: number
|
|
slug: string
|
|
expectedVotes?: VoteEstimateScenarioFields | null
|
|
}>,
|
|
pledgeAggregates: Map<number, MunicipalityPledgeAggregate>,
|
|
): Promise<MunicipalityGoalCoverageBundle> => {
|
|
const { suggestedGoalBySlug } = await loadStatewideSuggestedGoals(payload, user)
|
|
|
|
const coverageByMunicipalityID = new Map<
|
|
number,
|
|
Record<VoteEstimateScenario, MunicipalityGoalCoverage>
|
|
>()
|
|
for (const municipality of municipalities) {
|
|
const pledgeAggregate =
|
|
pledgeAggregates.get(municipality.id) ?? emptyMunicipalityPledgeAggregate
|
|
const suggestedGoalByScenario =
|
|
suggestedGoalBySlug.get(municipality.slug) ?? emptySuggestedGoalByScenario
|
|
coverageByMunicipalityID.set(
|
|
municipality.id,
|
|
computeGoalCoverageByScenario(
|
|
municipality.expectedVotes,
|
|
suggestedGoalByScenario,
|
|
pledgeAggregate,
|
|
),
|
|
)
|
|
}
|
|
|
|
const coverages = [...coverageByMunicipalityID.values()]
|
|
const aggregateByScenario = {} as Record<VoteEstimateScenario, MunicipalityGoalCoverage>
|
|
for (const scenario of VOTE_ESTIMATE_SCENARIOS) {
|
|
aggregateByScenario[scenario] = aggregateGoalCoverage(
|
|
coverages.map((coverageByScenario) => coverageByScenario[scenario]),
|
|
)
|
|
}
|
|
|
|
return { coverageByMunicipalityID, aggregateByScenario }
|
|
}
|
|
|
|
/** Unknown slug (never in the catalog): zero goal in every scenario, never mutated. */
|
|
const emptySuggestedGoalByScenario: Readonly<SuggestedGoalByScenario> = zeroByVoteEstimateScenario()
|
|
|
|
export type MunicipalityGoalAccount = {
|
|
/** Fixed to the `central` scenario, like `goalCoverage` below. */
|
|
suggestedGoal: number
|
|
/** Fixed to the `central` scenario — the detail page has no scenario selector. */
|
|
goalCoverage: MunicipalityGoalCoverage
|
|
potential: MunicipalityPotential
|
|
/** E10 — the one-word reading of `potential` plus the factors behind it. */
|
|
territorialClass: MunicipalityTerritorialClassification
|
|
}
|
|
|
|
/**
|
|
* One município's full "conta da cadeira": suggested goal, coverage (central
|
|
* scenario), and the diagnostic potential block (teto do campo, captura,
|
|
* share intracampo, roll-off) — the detail page's "Conta da cadeira" card.
|
|
*/
|
|
export const loadMunicipalityGoalAccount = async (
|
|
payload: Payload,
|
|
user: GoalAccountReader,
|
|
municipality: { slug: string; expectedVotes?: VoteEstimateScenarioFields | null },
|
|
pledgeAggregate: MunicipalityPledgeAggregate,
|
|
): Promise<MunicipalityGoalAccount> => {
|
|
const { suggestedGoalBySlug, potentialBySlug } = await loadStatewideSuggestedGoals(payload, user)
|
|
const suggestedGoalByScenario =
|
|
suggestedGoalBySlug.get(municipality.slug) ?? emptySuggestedGoalByScenario
|
|
const goalCoverage = computeGoalCoverage(
|
|
municipality.expectedVotes,
|
|
suggestedGoalByScenario,
|
|
pledgeAggregate,
|
|
DEFAULT_VOTE_ESTIMATE_SCENARIO,
|
|
)
|
|
const potential =
|
|
potentialBySlug.get(municipality.slug) ?? computeMunicipalityPotential(municipality.slug)
|
|
|
|
return {
|
|
suggestedGoal: suggestedGoalByScenario[DEFAULT_VOTE_ESTIMATE_SCENARIO],
|
|
goalCoverage,
|
|
potential,
|
|
territorialClass: computeMunicipalityTerritorialClass(municipality.slug),
|
|
}
|
|
}
|