Repository navigation
fix(realtime): replace SSE with polling and push notifications to reduce Vercel usage - #22
Merged
Merged
Conversation
- Agrega tipo 'realtime' a rate-limit.ts con 2 puntos por minuto por usuario. - Aplica rate limit en /api/realtime antes de abrir conexión SSE. - Hace maxDuration configurable via REALTIME_MAX_DURATION (default 30s).
- Reemplaza backoff exponencial por escalera 5s/15s/30s. - Tras 3 errores consecutivos cambia a polling cada 30s. - Cierra conexión en background, offline y redes 2G. - Feature flag NEXT_PUBLIC_REALTIME_ENABLED para apagar realtime. - Expone estado 'polling' en el contexto.
- connectivity-indicator ahora lee el estado del RealtimeContext. - Muestra estado amarillo 'Sync' cuando realtime está en polling/connecting. - Agrega tooltip explicativo en español para cada estado. - Mantiene labels Online/Offline/Sync para compatibilidad con tests E2E.
- Envuelve fetchResilient con Promise.race de 15s. - Si no resuelve, cierra modal y muestra mensaje reconfortante. - Previene botón 'Guardando...' pegado en casos extremos.
- Agrega campo 'disabled' al RealtimeContextValue. - RealtimeStatusBanner muestra aviso al usuario cuando realtime está deshabilitado por feature flag (NEXT_PUBLIC_REALTIME_ENABLED=false). - Banner se renderiza en (app)/layout.tsx dentro del RealtimeProvider. Para activar: setear NEXT_PUBLIC_REALTIME_ENABLED=false en Vercel y redeployar. Para desactivar SSE en emergencia y detener consumo de Vercel Functions.
- Nuevo hook usePollingRefetch(callback, intervalMs) que ejecuta
callback cada intervalMs mientras la pestaña es visible y hay internet.
- Pausa en background y offline.
- Reemplaza useRealtimeListener en todas las pantallas:
- /clientes, /pedidos (30s), /fiados, /alertas, /repartidor (30s),
/embarques, /recurrentes, /produccion, /gastos, /compras,
/trabajadores, /trabajadores/[id], /cierre.
- Elimina dependencia de SSE para refrescar datos en pantalla.
- 30s en pantallas criticas (repartidor, pedidos); 60s en el resto.
- POST /api/pedidos: notifica 'Nuevo pedido' a todos los usuarios con suscripcion push. - POST /api/clientes: notifica 'Nuevo cliente' a todos. - POST /api/embarques/[id]/enviar: notifica 'Embarque en ruta' solo al repartidor asignado (sendPushToUser). - POST /api/embarques/[id]/cerrar: notifica 'Embarque cerrado' a todos. Cada push incluye url especifica para abrir la pantalla correspondiente y un tag para dedup en el Service Worker. Fire-and-forget: no bloquea la respuesta del endpoint.
- Revertir fiados-table y alertas-table a la nueva arquitectura de main (reciben datos via props; no usan usePedidos interno). - En index.tsx, consolidar las 3 llamadas a useRealtimeListener en una sola llamada a usePollingRefetch que refetchea los 3 datasets cada 30s. - Mantiene las 3 instancias de usePedidos en index.tsx (scope: general, fiados, alertas) tal como las dejo el refactor de main.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
casasleonj
pushed a commit
that referenced
this pull request
Aug 21, 2026
… -> 0) — LINT TOTAL A CERO Septimo y ultimo batch de la limpieza de react-hooks/set-state-in-effect. Con este batch el total de issues de eslint del repo (npx eslint . --max-warnings 999) llega a CERO -- cierra la limpieza de deuda tecnica de lint iniciada con no-explicit-any (326 -> 0) y continuada con set-state-in-effect (65 -> 0), 36 batches en total a lo largo de toda la sesion. Cambios: - clientes-client/index.tsx (5 ocurrencias): sync de total/totalPages y clientes cuando el Server Component re-renderiza, movido a render-time (Pattern A); sync de negocios del panel cuando cambia selectedCliente, movido a render-time (Pattern A, ya que setNegocios tambien se llama desde fetches async en otros puntos del archivo -- no es 100% derivable); fetch-on-mount de loadAllClientes + deep-link ?openCliente=ID (dispara fetch real), ambos eslint-disable puntual. - pedidos-client/index.tsx (3 ocurrencias): sync de searchInput desde la prop search (mismo mecanismo lastCommittedSearchRef ya documentado en AGENTS.md #22), movido a render-time; window.matchMedia al montar (SSR-unsafe) + fetch-on-mount de loadAllPedidos, eslint-disable puntual. - repartidor-client.tsx: poll de IndexedDB (Dexie) al montar, eslint-disable puntual. - pedido-form-unified/index.tsx (4 ocurrencias, el form central de pedidos): todos eslint-disable puntual dado el alto riesgo de reestructurar un formulario de negocio critico -- resolverPreciosCliente() (fetch real), sync de direccion/barrio keyed deliberadamente en .id (ya documentado con exhaustive-deps disable previo), reset de fiadosStatus ligado al mismo efecto de fetch abortable, y poblado del form desde pedidoInicial (keyed en .id, incluye revalidacion silenciosa con red mas abajo en el mismo efecto). Ajuste post-verificacion: el comentario inicial rompio un test de regresion (solo-para-este-pedido-checkbox.test.ts) que hace slice(200) del source buscando setSoloParaEstePedido(false) cerca de "if (!pedidoInicial) return" -- comentario acortado y reordenado para mantener el test verde sin perder la documentacion. - venta-rapida-form/index.tsx: resolverPrecios() (fetch real), eslint-disable puntual. Verificacion: - npx eslint <5 archivos> --max-warnings 999 -> limpio - npx tsc --noEmit (repo completo) -> 0 errores - npx eslint . --max-warnings 999 --format json -> total 14 -> 0 (react-hooks/set-state-in-effect 14 -> 0, no-explicit-any en 0 desde PR #110) -- CERO issues de eslint en todo el repositorio - npx vitest run (repo completo) -> primera corrida detecto 1 regresion (test de regex sobre el source, ver nota arriba); corregida y reverificada: 233 archivos, 2461 tests, 0 fallos, 0 regresiones Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01YUrNA2cKnFKdNJgHEYow42
casasleonj
added a commit
that referenced
this pull request
Aug 21, 2026
… -> 0) — LINT TOTAL A CERO (#117) Septimo y ultimo batch de la limpieza de react-hooks/set-state-in-effect. Con este batch el total de issues de eslint del repo (npx eslint . --max-warnings 999) llega a CERO -- cierra la limpieza de deuda tecnica de lint iniciada con no-explicit-any (326 -> 0) y continuada con set-state-in-effect (65 -> 0), 36 batches en total a lo largo de toda la sesion. Cambios: - clientes-client/index.tsx (5 ocurrencias): sync de total/totalPages y clientes cuando el Server Component re-renderiza, movido a render-time (Pattern A); sync de negocios del panel cuando cambia selectedCliente, movido a render-time (Pattern A, ya que setNegocios tambien se llama desde fetches async en otros puntos del archivo -- no es 100% derivable); fetch-on-mount de loadAllClientes + deep-link ?openCliente=ID (dispara fetch real), ambos eslint-disable puntual. - pedidos-client/index.tsx (3 ocurrencias): sync de searchInput desde la prop search (mismo mecanismo lastCommittedSearchRef ya documentado en AGENTS.md #22), movido a render-time; window.matchMedia al montar (SSR-unsafe) + fetch-on-mount de loadAllPedidos, eslint-disable puntual. - repartidor-client.tsx: poll de IndexedDB (Dexie) al montar, eslint-disable puntual. - pedido-form-unified/index.tsx (4 ocurrencias, el form central de pedidos): todos eslint-disable puntual dado el alto riesgo de reestructurar un formulario de negocio critico -- resolverPreciosCliente() (fetch real), sync de direccion/barrio keyed deliberadamente en .id (ya documentado con exhaustive-deps disable previo), reset de fiadosStatus ligado al mismo efecto de fetch abortable, y poblado del form desde pedidoInicial (keyed en .id, incluye revalidacion silenciosa con red mas abajo en el mismo efecto). Ajuste post-verificacion: el comentario inicial rompio un test de regresion (solo-para-este-pedido-checkbox.test.ts) que hace slice(200) del source buscando setSoloParaEstePedido(false) cerca de "if (!pedidoInicial) return" -- comentario acortado y reordenado para mantener el test verde sin perder la documentacion. - venta-rapida-form/index.tsx: resolverPrecios() (fetch real), eslint-disable puntual. Verificacion: - npx eslint <5 archivos> --max-warnings 999 -> limpio - npx tsc --noEmit (repo completo) -> 0 errores - npx eslint . --max-warnings 999 --format json -> total 14 -> 0 (react-hooks/set-state-in-effect 14 -> 0, no-explicit-any en 0 desde PR #110) -- CERO issues de eslint en todo el repositorio - npx vitest run (repo completo) -> primera corrida detecto 1 regresion (test de regex sobre el source, ver nota arriba); corregida y reverificada: 233 archivos, 2461 tests, 0 fallos, 0 regresiones Claude-Session: https://claude.ai/code/session_01YUrNA2cKnFKdNJgHEYow42 Co-authored-by: Claude <[email protected]>
This branch had an error being deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
Replaces the always-on
/api/realtimeSSE connection with short-lived SSE as fallback + per-screen polling, and adds Web Push notifications for critical events.Why
Vercel Hobby usage limits (Fluid Active CPU / Function Invocations / Memory) were exceeded primarily by the long-lived
/api/realtimeSSE function. This change removes the continuous resource drain.Changes
maxDurationon/api/realtime.RealtimeProviderto close SSE in background/offline/2G and fall back to polling.usePollingRefetchhook and use it across clientes, pedidos, repartidor, embarques, recurrentes, produccion, gastos, compras, trabajadores, and cierre screens.usePedidosrefactor in pedidos.Required environment variables (Vercel)
Deploy check
/api/realtimeinvocations drop to 0 and push subscription still works.