feat(deploy): fase 6 — Dockerfile para Coolify, PWA y guía de despliegue
- Dockerfile: python:3.12-slim + uv --frozen, no root, HEALTHCHECK sobre /api/health, un worker con --proxy-headers para el Traefik de Coolify - HEAD explícito en /api/health y /api/export (curl -I del criterio 12; export HEAD devuelve el Content-Length exacto sin generar audio) - PWA: manifest, iconos generados con numpy+stdlib, apple-touch-icon - docker-compose.dev.yml (solo local), .dockerignore - deploy/coolify.md: recurso, deploy key, webhook Gitea, dominio, volumen - versión 0.2.0 · smoke test del contenedor en local: healthy
This commit is contained in:
1 parent
1a6977a59e
commit
fc506ac7c6
16 files changed
+288
-24
No files matched your search
@@ -0,0 +1,13 @@
|
||||
.git
|
||||
node_modules
|
||||
test-results
|
||||
playwright-report
|
||||
backend/.venv
|
||||
backend/var
|
||||
docs
|
||||
scripts
|
||||
**/__pycache__
|
||||
**/.pytest_cache
|
||||
**/.ruff_cache
|
||||
*.wav
|
||||
*.flac
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
# Imagen de producción · la construye Coolify (build pack: Dockerfile)
|
||||
FROM python:3.12-slim
|
||||
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.10.6 /uv /uvx /usr/local/bin/
|
||||
|
||||
# libsndfile por si la wheel de soundfile no trae la suya
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends libsndfile1 \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& useradd --create-home app
|
||||
|
||||
ENV UV_LINK_MODE=copy \
|
||||
UV_PYTHON_DOWNLOADS=never \
|
||||
UV_COMPILE_BYTECODE=1 \
|
||||
BINAURAL_CACHE_DIR=/data/cache
|
||||
|
||||
# Capa de dependencias (cacheable): solo lockfile y metadatos
|
||||
WORKDIR /app/backend
|
||||
COPY backend/pyproject.toml backend/uv.lock ./
|
||||
RUN uv sync --frozen --no-dev --no-install-project
|
||||
|
||||
# Código y frontend
|
||||
COPY backend /app/backend
|
||||
COPY web /app/web
|
||||
RUN uv sync --frozen --no-dev \
|
||||
&& mkdir -p /data/cache \
|
||||
&& chown -R app:app /data /app
|
||||
|
||||
USER app
|
||||
EXPOSE 8000
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||
CMD ["python", "-c", "import urllib.request,sys; r=urllib.request.urlopen('http://127.0.0.1:8000/api/health', timeout=4); sys.exit(0 if r.status==200 else 1)"]
|
||||
|
||||
# Un solo worker (1 vCPU compartida); proxy-headers para el Traefik de Coolify
|
||||
CMD ["/app/backend/.venv/bin/uvicorn", "binaural.api:app", \
|
||||
"--host", "0.0.0.0", "--port", "8000", \
|
||||
"--proxy-headers", "--forwarded-allow-ips=*"]
|
||||
@@ -27,9 +27,28 @@ uv run binaural presets
|
||||
uv run binaural export --preset foco --out foco.wav
|
||||
```
|
||||
|
||||
## Correr con Docker (igual que producción)
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.dev.yml up --build
|
||||
```
|
||||
|
||||
## Despliegue
|
||||
|
||||
Coolify (VPS de Collina) → `https://binaurals.collinasystems.com.mx`.
|
||||
Pasos exactos en [deploy/coolify.md](deploy/coolify.md).
|
||||
Coolify (VPS de Collina) → `https://binaurals.collinasystems.com.mx`,
|
||||
detrás del Traefik de Coolify (TLS automático). Auto-deploy por webhook
|
||||
de Gitea en cada push a `main`. Pasos exactos de la UI en
|
||||
[deploy/coolify.md](deploy/coolify.md). Rollback: redeploy de un
|
||||
despliegue anterior en Coolify o fijar un tag (`v0.2.0`).
|
||||
|
||||
*(README en construcción: se completa fase a fase.)*
|
||||
## Pruebas
|
||||
|
||||
```bash
|
||||
cd backend && uv run pytest -v # motor + API (criterios 1-9)
|
||||
npx playwright test # frontend en Chromium (criterio 10)
|
||||
```
|
||||
|
||||
El guion de pruebas manuales en iPhone + AirPods Pro 3 (criterio 11) está
|
||||
en [docs/pruebas-dispositivo.md](docs/pruebas-dispositivo.md).
|
||||
|
||||
En iPhone: Compartir → **Añadir a pantalla de inicio** instala la PWA.
|
||||
@@ -1,3 +1,3 @@
|
||||
"""Generador de tonos binaurales alpha/beta · Collina."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
__version__ = "0.2.0"
|
||||
+36
-18
@@ -9,14 +9,14 @@ from typing import Literal
|
||||
|
||||
import numpy as np
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
from fastapi.responses import FileResponse, Response, StreamingResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from . import __version__
|
||||
from .export import tamano_wav, wav_streaming
|
||||
from .noise import TipoRuido, generar_loop, wav_loop_cacheado
|
||||
from .presets import Preset, cargar_presets
|
||||
from .session import schedule_de_preset
|
||||
from .session import Schedule, schedule_de_preset
|
||||
from .synth import SR_DEFECTO
|
||||
|
||||
SRS_VALIDOS = (44100, 48000)
|
||||
@@ -49,6 +49,7 @@ def _loop_en_memoria(tipo: TipoRuido, sr: int) -> np.ndarray:
|
||||
return generar_loop(tipo, sr)
|
||||
|
||||
|
||||
@app.head("/api/health")
|
||||
@app.get("/api/health")
|
||||
def health() -> dict[str, str]:
|
||||
"""Latido para el healthcheck del contenedor."""
|
||||
@@ -92,14 +93,10 @@ def loop_ruido(tipo: Literal["pink", "rain"], sr: int = SR_DEFECTO) -> FileRespo
|
||||
return FileResponse(ruta, media_type="audio/wav", filename=f"{tipo}.wav")
|
||||
|
||||
|
||||
@app.get("/api/export")
|
||||
def exportar(
|
||||
preset: str,
|
||||
duration: float | None = None,
|
||||
format: Literal["wav", "flac"] = "wav",
|
||||
sr: int = SR_DEFECTO,
|
||||
) -> StreamingResponse:
|
||||
"""WAV en streaming: cabecera conocida de antemano, Content-Length exacto."""
|
||||
def _preparar_export(
|
||||
preset: str, duration: float | None, format: str, sr: int
|
||||
) -> tuple[Preset, Schedule, dict[str, str]]:
|
||||
"""Valida parámetros y calcula las cabeceras exactas del WAV."""
|
||||
if format != "wav":
|
||||
raise HTTPException(400, "por ahora solo format=wav; flac llega en la fase 5")
|
||||
_validar_sr(sr)
|
||||
@@ -108,6 +105,34 @@ def exportar(
|
||||
schedule = schedule_de_preset(p, duration)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc)) from exc
|
||||
cabeceras = {
|
||||
"Content-Length": str(tamano_wav(schedule, sr)),
|
||||
"Content-Disposition": f'attachment; filename="{p.name}.wav"',
|
||||
}
|
||||
return p, schedule, cabeceras
|
||||
|
||||
|
||||
@app.head("/api/export")
|
||||
def exportar_cabeceras(
|
||||
preset: str,
|
||||
duration: float | None = None,
|
||||
format: Literal["wav", "flac"] = "wav",
|
||||
sr: int = SR_DEFECTO,
|
||||
) -> Response:
|
||||
"""Solo las cabeceras (tamaño exacto) sin generar un sample de audio."""
|
||||
_, _, cabeceras = _preparar_export(preset, duration, format, sr)
|
||||
return Response(media_type="audio/wav", headers=cabeceras)
|
||||
|
||||
|
||||
@app.get("/api/export")
|
||||
def exportar(
|
||||
preset: str,
|
||||
duration: float | None = None,
|
||||
format: Literal["wav", "flac"] = "wav",
|
||||
sr: int = SR_DEFECTO,
|
||||
) -> StreamingResponse:
|
||||
"""WAV en streaming: cabecera conocida de antemano, Content-Length exacto."""
|
||||
p, schedule, cabeceras = _preparar_export(preset, duration, format, sr)
|
||||
loop = _loop_en_memoria(p.noise, sr) if p.noise != "none" else None
|
||||
if not _export_ocupado.acquire(blocking=False):
|
||||
raise HTTPException(429, "ya hay un export en curso; espera a que termine")
|
||||
@@ -118,14 +143,7 @@ def exportar(
|
||||
finally:
|
||||
_export_ocupado.release()
|
||||
|
||||
return StreamingResponse(
|
||||
generar(),
|
||||
media_type="audio/wav",
|
||||
headers={
|
||||
"Content-Length": str(tamano_wav(schedule, sr)),
|
||||
"Content-Disposition": f'attachment; filename="{p.name}.wav"',
|
||||
},
|
||||
)
|
||||
return StreamingResponse(generar(), media_type="audio/wav", headers=cabeceras)
|
||||
|
||||
|
||||
if DIR_WEB.is_dir():
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "binaural"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
description = "Generador web de tonos binaurales alpha/beta · Collina"
|
||||
requires-python = ">=3.11"
|
||||
dependencies = [
|
||||
|
||||
@@ -104,3 +104,13 @@ def test_frontend_estatico(cliente):
|
||||
r = cliente.get("/")
|
||||
assert r.status_code == 200
|
||||
assert "text/html" in r.headers["content-type"]
|
||||
|
||||
|
||||
def test_head_health_y_export(cliente):
|
||||
"""curl -I debe funcionar (criterio 12): HEAD con cabeceras exactas."""
|
||||
assert cliente.head("/api/health").status_code == 200
|
||||
r = cliente.head("/api/export", params={"preset": "foco", "duration": 25})
|
||||
assert r.status_code == 200
|
||||
assert r.content == b""
|
||||
# mismo Content-Length que anunciaría el GET: (25*60+1.5)*44100 samples * 4 B + 44
|
||||
assert int(r.headers["content-length"]) == round((25 * 60 + 1.5) * 44100) * 4 + 44
|
||||
Generated
+1
-1
@@ -39,7 +39,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "binaural"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "fastapi" },
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
# Despliegue en Coolify · binaurals.collinasystems.com.mx
|
||||
|
||||
Pasos exactos en la UI de Coolify del VPS de Collina (`191.101.233.43`).
|
||||
Traefik de Coolify ya ocupa 80/443 y emite TLS: **no** hay que tocar
|
||||
firewall, DNS (el subdominio ya apunta al VPS) ni levantar otro proxy.
|
||||
|
||||
## 1 · Clave de despliegue (solo lectura)
|
||||
|
||||
1. Coolify → **Keys & Tokens → Private Keys → + Add**: genera una clave
|
||||
ed25519 nueva (nómbrala `binaurals-deploy`). Copia la **clave pública**.
|
||||
2. Gitea → repo `collina-admin/collina-binaurals` → **Settings →
|
||||
Deploy Keys → Add Deploy Key**: pega la clave pública, **sin** acceso
|
||||
de escritura.
|
||||
|
||||
> Si el Gitea de Collina no expone SSH (la clave falla al clonar), usa el
|
||||
> plan B: crea en Gitea un **token de acceso** de solo lectura limitado a
|
||||
> este repo y da la URL como
|
||||
> `http://<token>@gitea-…sslip.io/collina-admin/collina-binaurals.git`
|
||||
> en un recurso de tipo *Public Repository*.
|
||||
|
||||
## 2 · Crear el recurso
|
||||
|
||||
1. Coolify → proyecto de Collina → **+ New → Application →
|
||||
Private Repository (with deploy key)**.
|
||||
2. Repositorio: la URL SSH del repo en Gitea · rama **`main`** · clave
|
||||
`binaurals-deploy`.
|
||||
3. **Build Pack: `Dockerfile`** (está en la raíz del repo).
|
||||
4. **Port** (puerto expuesto): `8000`.
|
||||
|
||||
## 3 · Configuración del recurso
|
||||
|
||||
| Sección | Valor |
|
||||
|---|---|
|
||||
| **Domains** | `https://binaurals.collinasystems.com.mx` *(si el subdominio estuviera asignado a otro recurso, libéralo primero)* |
|
||||
| **Storages → + Add** | Volume mount → destino **`/data/cache`** (cache de loops de ruido) |
|
||||
| **Advanced / Resources → Memory** | `512m` (comparte VPS con Gitea y el resto) |
|
||||
| **Health check** | lo trae el propio Dockerfile (`/api/health`); no hace falta configurar nada en la UI |
|
||||
|
||||
Sin variables de entorno: la app funciona detrás de cualquier host.
|
||||
|
||||
## 4 · Primer deploy
|
||||
|
||||
**Deploy** y mirar los logs de build. Al terminar, el contenedor debe
|
||||
quedar **healthy** (el swap sin caída de Coolify depende de eso).
|
||||
|
||||
Verificación desde fuera del VPS:
|
||||
|
||||
```bash
|
||||
curl -I https://binaurals.collinasystems.com.mx/api/health # → 200, cert válido
|
||||
curl -I http://binaurals.collinasystems.com.mx/api/health # → redirige a https
|
||||
curl -I "https://binaurals.collinasystems.com.mx/api/export?preset=foco&duration=25"
|
||||
# → 200 con Content-Length 264864644 (25 min, sin generar audio)
|
||||
```
|
||||
|
||||
## 5 · Auto-deploy por webhook
|
||||
|
||||
1. En el recurso → **Webhooks**: copia la URL de webhook (formato
|
||||
`https://<coolify>/webhooks/source/gitea/events/manual`) y el
|
||||
**secreto** que muestra Coolify.
|
||||
2. Gitea → repo → **Settings → Webhooks → Add Webhook → Gitea**:
|
||||
- Target URL: la URL copiada
|
||||
- Method: `POST` · Content type: `application/json`
|
||||
- Secret: el secreto de Coolify
|
||||
- Trigger: **Push events** · rama `main`
|
||||
3. Probar: *Test Delivery* en Gitea, o un push a `main` → Coolify debe
|
||||
arrancar un deploy solo.
|
||||
|
||||
## 6 · Rollback
|
||||
|
||||
- Coolify → recurso → **Deployments** → redeploy de un despliegue anterior, o
|
||||
- fijar el recurso a un tag del repo (p. ej. `v0.2.0`) y desplegar.
|
||||
|
||||
## Notas de operación
|
||||
|
||||
- La imagen corre como usuario no root, un solo worker de uvicorn con
|
||||
`--proxy-headers --forwarded-allow-ips=*` (respeta `X-Forwarded-Proto`
|
||||
de Traefik).
|
||||
- Máximo 1 export concurrente por proceso (el segundo recibe 429).
|
||||
- No hay datos de usuario en el servidor (los presets propios viven en el
|
||||
`localStorage` del navegador); el volumen solo guarda cache regenerable.
|
||||
@@ -0,0 +1,15 @@
|
||||
# Solo para correr la imagen de producción en local. Coolify NO usa este
|
||||
# archivo: construye el Dockerfile directamente.
|
||||
# docker compose -f docker-compose.dev.yml up --build
|
||||
services:
|
||||
binaural:
|
||||
build: .
|
||||
ports:
|
||||
- "8000:8000"
|
||||
mem_limit: 512m
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- cache:/data/cache
|
||||
|
||||
volumes:
|
||||
cache:
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Genera los iconos PWA (PNG) sin dependencias más allá de numpy.
|
||||
|
||||
Uso: uv run --project backend python scripts/generar_iconos.py
|
||||
"""
|
||||
|
||||
import struct
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
DIR_ICONS = Path(__file__).resolve().parents[1] / "web" / "icons"
|
||||
|
||||
|
||||
def escribir_png(ruta: Path, rgb: np.ndarray) -> None:
|
||||
"""Escribe un PNG RGB 8-bit (sin filtros) usando solo stdlib."""
|
||||
alto, ancho, _ = rgb.shape
|
||||
|
||||
def chunk(tipo: bytes, datos: bytes) -> bytes:
|
||||
cuerpo = tipo + datos
|
||||
return struct.pack(">I", len(datos)) + cuerpo + struct.pack(">I", zlib.crc32(cuerpo))
|
||||
|
||||
filas = b"".join(b"\x00" + rgb[y].tobytes() for y in range(alto))
|
||||
ruta.write_bytes(
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", struct.pack(">IIBBBBB", ancho, alto, 8, 2, 0, 0, 0))
|
||||
+ chunk(b"IDAT", zlib.compress(filas, 9))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
|
||||
def icono(n: int) -> np.ndarray:
|
||||
"""Dos anillos entrelazados (L teal, R ámbar) sobre fondo oscuro."""
|
||||
y, x = np.mgrid[0:n, 0:n] / n
|
||||
img = np.zeros((n, n, 3))
|
||||
img[:] = np.array([13, 17, 23]) / 255 # --fondo
|
||||
|
||||
def anillo(cx: float, cy: float, r: float, grosor: float, color: tuple) -> np.ndarray:
|
||||
d = np.hypot(x - cx, y - cy)
|
||||
return np.exp(-(((d - r) / grosor) ** 2))[..., None] * (np.array(color) / 255)
|
||||
|
||||
img += anillo(0.40, 0.5, 0.24, 0.02, (88, 196, 220)) # oído izquierdo · alpha
|
||||
img += anillo(0.60, 0.5, 0.24, 0.02, (240, 168, 60)) # oído derecho · beta
|
||||
d_centro = np.hypot(x - 0.5, y - 0.5)
|
||||
img += (np.exp(-((d_centro / 0.09) ** 2)) * 0.30)[..., None] # batido al centro
|
||||
return (np.clip(img, 0, 1) * 255).astype(np.uint8)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
DIR_ICONS.mkdir(parents=True, exist_ok=True)
|
||||
for lado in (512, 192, 180):
|
||||
escribir_png(DIR_ICONS / f"icono-{lado}.png", icono(lado))
|
||||
print(f"icono-{lado}.png")
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 111 KiB |
@@ -5,6 +5,11 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="theme-color" content="#0d1117">
|
||||
<title>Binaurales · Collina</title>
|
||||
<link rel="manifest" href="manifest.json">
|
||||
<link rel="icon" href="icons/icono-192.png" type="image/png">
|
||||
<link rel="apple-touch-icon" href="icons/icono-180.png">
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "Binaurales · Collina",
|
||||
"short_name": "Binaurales",
|
||||
"description": "Generador de tonos binaurales alpha/beta con ruido de fondo.",
|
||||
"start_url": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#0d1117",
|
||||
"theme_color": "#0d1117",
|
||||
"icons": [
|
||||
{ "src": "icons/icono-192.png", "sizes": "192x192", "type": "image/png" },
|
||||
{ "src": "icons/icono-512.png", "sizes": "512x512", "type": "image/png" }
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user