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

@ -46,7 +46,7 @@ export const list = query({
let items = await ctx.db
.query("alerts")
.withIndex("by_tenant", (q) => q.eq("tenantId", tenantId))
.collect()
.take(100)
if (companyId) items = items.filter((a) => a.companyId === companyId)
if (typeof start === "number") items = items.filter((a) => a.createdAt >= start)
if (typeof end === "number") items = items.filter((a) => a.createdAt < end)
@ -62,7 +62,7 @@ export const managersForCompany = query({
const users = await ctx.db
.query("users")
.withIndex("by_tenant_company", (q) => q.eq("tenantId", tenantId).eq("companyId", companyId))
.collect()
.take(100)
return users.filter((u) => (u.role ?? "").toUpperCase() === "MANAGER")
},
})
@ -78,7 +78,7 @@ export const lastForCompanyBySlug = query({
const items = await ctx.db
.query("alerts")
.withIndex("by_tenant", (q) => q.eq("tenantId", tenantId))
.collect()
.take(100)
const matches = items.filter((a) => a.companyId === company._id)
if (matches.length === 0) return null
const last = matches.sort((a, b) => b.createdAt - a.createdAt)[0]
@ -94,12 +94,15 @@ export const lastForCompaniesBySlugs = query({
const alerts = await ctx.db
.query("alerts")
.withIndex("by_tenant", (q) => q.eq("tenantId", tenantId))
.collect()
.take(100)
// Buscar todas as companies do tenant de uma vez
const allCompanies = await ctx.db
.query("companies")
.withIndex("by_tenant", (q) => q.eq("tenantId", tenantId))
.take(1000)
const companiesBySlug = new Map(allCompanies.map(c => [c.slug, c]))
for (const slug of slugs) {
const company = await ctx.db
.query("companies")
.withIndex("by_tenant_slug", (q) => q.eq("tenantId", tenantId).eq("slug", slug))
.first()
const company = companiesBySlug.get(slug)
if (!company) {
result[slug] = null
continue