fix(convex): corrigir memory leak com .collect() sem limite e adicionar otimizacoes

Problema: Convex backend consumindo 16GB+ de RAM causando OOM kills

Correcoes aplicadas:
- Substituido todos os .collect() por .take(LIMIT) em 27+ arquivos
- Adicionado indice by_usbPolicyStatus para otimizar query de maquinas
- Corrigido N+1 problem em alerts.ts usando Map lookup
- Corrigido full table scan em usbPolicy.ts
- Corrigido subscription leaks no frontend (tickets-view, use-ticket-categories)
- Atualizado versao do Convex backend para precompiled-2025-12-04-cc6af4c

Arquivos principais modificados:
- convex/*.ts - limites em todas as queries .collect()
- convex/schema.ts - novo indice by_usbPolicyStatus
- convex/alerts.ts - N+1 fix com Map
- convex/usbPolicy.ts - uso do novo indice
- src/components/tickets/tickets-view.tsx - skip condicional
- src/hooks/use-ticket-categories.ts - skip condicional

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
esdrasrenan 2025-12-09 21:30:06 -03:00
parent a4b46b08ba
commit 638faeb287
33 changed files with 139 additions and 128 deletions

View file

@ -635,7 +635,7 @@ async function fetchTemplateSummaries(ctx: AnyCtx, tenantId: string): Promise<Te
const templates = await ctx.db
.query("ticketFormTemplates")
.withIndex("by_tenant", (q) => q.eq("tenantId", tenantId))
.collect();
.take(100);
if (!templates.length) {
return TICKET_FORM_CONFIG.map((template) => ({
key: template.key,
@ -682,7 +682,7 @@ async function fetchTicketFieldsByScopes(
const allFields = await ctx.db
.query("ticketFields")
.withIndex("by_tenant", (q) => q.eq("tenantId", tenantId))
.collect();
.take(100);
const addFieldToScope = (scopeKey: string, field: Doc<"ticketFields">) => {
const originalKey = scopeLookup.get(scopeKey);
@ -746,7 +746,7 @@ async function fetchViewerScopedFormSettings(
const allSettings = await ctx.db
.query("ticketFormSettings")
.withIndex("by_tenant", (q) => q.eq("tenantId", tenantId))
.collect();
.take(100);
for (const setting of allSettings) {
if (!keySet.has(setting.template)) {
@ -813,7 +813,7 @@ async function ensureTicketFormDefaultsForTenant(ctx: MutationCtx, tenantId: str
const existing = await ctx.db
.query("ticketFields")
.withIndex("by_tenant_scope", (q) => q.eq("tenantId", tenantId).eq("scope", template.key))
.collect();
.take(100);
if (template.key === "admissao") {
for (const key of OPTIONAL_ADMISSION_FIELD_KEYS) {
const field = existing.find((f) => f.key === key);
@ -1026,7 +1026,7 @@ async function computeAgentWorkTotals(
const sessions = await ctx.db
.query("ticketWorkSessions")
.withIndex("by_ticket", (q) => q.eq("ticketId", ticketId))
.collect();
.take(50);
if (!sessions.length) {
return [];
@ -1435,7 +1435,7 @@ async function normalizeCustomFieldValues(
const definitions = await ctx.db
.query("ticketFields")
.withIndex("by_tenant", (q) => q.eq("tenantId", tenantId))
.collect();
.take(100);
const scopedDefinitions = definitions.filter((definition) => {
const fieldScope = (definition.scope ?? "all").toLowerCase();
@ -1951,7 +1951,7 @@ export const getById = query({
const comments = await ctx.db
.query("ticketComments")
.withIndex("by_ticket", (q) => q.eq("ticketId", id))
.collect();
.take(50);
const canViewInternalComments = role === "ADMIN" || role === "AGENT";
const visibleComments = canViewInternalComments
? comments
@ -1965,7 +1965,7 @@ export const getById = query({
let timelineRecords = await ctx.db
.query("ticketEvents")
.withIndex("by_ticket", (q) => q.eq("ticketId", id))
.collect();
.take(50);
if (!(role === "ADMIN" || role === "AGENT")) {
timelineRecords = timelineRecords.filter((event) => {
@ -2317,7 +2317,7 @@ export const create = mutation({
const queues = await ctx.db
.query("queues")
.withIndex("by_tenant", (q) => q.eq("tenantId", args.tenantId))
.collect()
.take(100)
const preferred = queues.find((q) => q.slug === "chamados") || queues.find((q) => q.name === "Chamados") || null
if (preferred) {
resolvedQueueId = preferred._id as Id<"queues">
@ -3085,7 +3085,7 @@ export const listChatMessages = query({
const messages = await ctx.db
.query("ticketChatMessages")
.withIndex("by_ticket_created", (q) => q.eq("ticketId", ticketId))
.collect()
.take(50)
// Verificar maquina e sessao de chat ao vivo
let liveChat: {