File size: 11,668 Bytes
5eaf0b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb6f9f2
 
 
 
 
 
5eaf0b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0345daa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eaf0b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75f92fd
 
 
 
 
 
 
5eaf0b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0345daa
5eaf0b4
 
 
 
 
 
0345daa
5eaf0b4
 
 
 
fe8c0ed
5eaf0b4
 
fe8c0ed
5eaf0b4
fe8c0ed
5eaf0b4
 
 
 
 
0345daa
5eaf0b4
 
 
 
 
 
 
 
 
0345daa
 
5eaf0b4
 
 
 
 
 
 
0345daa
5eaf0b4
 
 
 
 
 
 
 
 
 
 
 
0345daa
5eaf0b4
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
"""
Acceso a datos del worker (lo usa tasks.py).

- Modo "api" (workers residenciales): llama a la API con el token del usuario (MELODIX_USER_TOKEN)
  y el nombre del equipo. El equipo no tiene credenciales de la base de datos.
- Modo "db" (Hugging Face, define SPACE_ID): llama directo a app/utils/worker_ops.py.

WORKER_DATOS=db|api fuerza el modo (por ejemplo, para desarrollo).
"""
import logging
import os
import socket
import time

logger = logging.getLogger(__name__)

MODO = os.getenv("WORKER_DATOS") or ("db" if os.getenv("SPACE_ID") else "api")
MODO_DIRECTO = MODO == "db"
API_URL = (os.getenv("MELODIX_API_URL") or "https://isaac105-melodix-api.hf.space").rstrip("/")

# Lo fija tasks.py cuando Celery conoce el nombre del nodo (celery@<equipo>)
_hostname = socket.gethostname()


def fijar_hostname(hostname: str):
    global _hostname
    if hostname:
        _hostname = hostname


class ErrorDatosWorker(Exception):
    """La API rechazó la operación o no respondió."""


# ---------------------------------------------------------------------------
# Transporte
# ---------------------------------------------------------------------------

def _cabeceras():
    tokens = os.getenv("MELODIX_USER_TOKEN", "")
    return {"X-Worker-Tokens": tokens, "X-Worker-Host": _hostname}


def _api(metodo: str, ruta: str, json=None, intentos: int = 3, timeout: int = 20):
    import requests
    ultimo = None
    for i in range(intentos):
        try:
            r = requests.request(metodo, f"{API_URL}/workers/datos{ruta}", json=json,
                                 headers=_cabeceras(), timeout=timeout)
            if r.status_code < 300:
                return r.json()
            if r.status_code == 429:
                # HF limitó las peticiones de esta IP: se levanta solo en unos minutos, hay que esperar
                ultimo = ErrorDatosWorker("429: la API limitó las peticiones (Too Many Requests)")
                if i < intentos - 1:
                    time.sleep(30 * (i + 1))
                continue
            if r.status_code < 500:
                # Error del pedido (token, permiso, datos): reintentar no lo arregla
                raise ErrorDatosWorker(f"{r.status_code}: {r.text[:200]}")
            ultimo = ErrorDatosWorker(f"{r.status_code}: {r.text[:200]}")
        except ErrorDatosWorker:
            raise
        except Exception as e:
            ultimo = e
        if i < intentos - 1:
            time.sleep(min(2 ** i * 2, 30))
    raise ErrorDatosWorker(f"La API no respondió ({ruta}): {ultimo}")


class _Sesion:
    """Sesión de BD + filas del equipo para el modo directo."""
    def __enter__(self):
        from app.database import SessionLocal
        from app.models.process import Worker
        self.db = SessionLocal()
        w = self.db.query(Worker).filter(Worker.hostname == _hostname).first()
        self.workers = [w] if w else []
        return self

    def __exit__(self, *exc):
        self.db.close()


def _ops():
    from app.utils import worker_ops
    return worker_ops


# ---------------------------------------------------------------------------
# Operaciones
# ---------------------------------------------------------------------------

def info_worker() -> dict:
    """{'user_ids': [...], 'suspendido': bool}"""
    if MODO_DIRECTO:
        with _Sesion() as s:
            return _ops().info_worker(s.workers)
    return _api("GET", "/info")


def actualizar_estado(status: str):
    if MODO_DIRECTO:
        with _Sesion() as s:
            _ops().actualizar_estado(s.db, s.workers, status)
        return
    _api("POST", "/estado", {"status": status})


def latido() -> dict:
    """Solo modo API (en HF el heartbeat también registra el worker; lo hace tasks.py)."""
    return _api("POST", "/latido", intentos=1)


def pedir_trabajo():
    """Siguiente canción de este equipo ({nombre, id, args, kwargs}) o None. Solo modo API."""
    return _api("POST", "/trabajo", intentos=1, timeout=30).get("trabajo")


def _enviar_archivo(task_id: str, nombre: str, ruta: str) -> bool:
    import requests
    url = f"{API_URL}/workers/datos/tareas/{task_id}/archivos/{nombre}"
    cabeceras = {**_cabeceras(), "Content-Type": "application/octet-stream"}
    for i in range(4):
        try:
            with open(ruta, "rb") as f:
                r = requests.put(url, data=f, headers=cabeceras, timeout=(30, 1800))
            if r.status_code < 300:
                return True
            if r.status_code == 429:
                time.sleep(30 * (i + 1))
                continue
            if r.status_code < 500:
                logger.error(f"[{task_id}] La API rechazó {nombre}: {r.status_code} {r.text[:200]}")
                return False
            logger.warning(f"[{task_id}] Error {r.status_code} subiendo {nombre}, intento {i + 1}")
        except Exception as e:
            logger.warning(f"[{task_id}] Fallo subiendo {nombre}, intento {i + 1}: {str(e)[:160]}")
        time.sleep(min(2 ** i * 5, 60))
    return False


def subir_a_hf(files, commit_message: str = "Subir archivos") -> dict:
    """
    Sube archivos al dataset. files: [(ruta_local, 'stems/<task_id>/<nombre>')]; devuelve
    {object_name: url} de los subidos. Hugging Face usa su token; los residenciales pasan por la API.
    """
    if MODO_DIRECTO:
        from app.utils.hf_storage import upload_many_to_hf
        return upload_many_to_hf(files, commit_message=commit_message)

    files = [(ruta, nombre) for ruta, nombre in files if os.path.exists(ruta)]
    if not files:
        return {}
    task_id = files[0][1].split("/")[1]
    for _ in range(2):
        nombres = [clave.rsplit("/", 1)[1] for ruta, clave in files
                   if _enviar_archivo(task_id, clave.rsplit("/", 1)[1], ruta)]
        if not nombres:
            return {}
        lote = _api("POST", f"/tareas/{task_id}/archivos/confirmar",
                    {"archivos": nombres, "mensaje": commit_message}, intentos=4, timeout=60)["lote"]
        limite = time.time() + 1800
        estado = {"estado": "subiendo"}
        while estado["estado"] == "subiendo" and time.time() < limite:
            time.sleep(5)
            try:
                estado = _api("GET", f"/archivos/lote/{lote}", intentos=3, timeout=20)
            except ErrorDatosWorker as e:
                logger.warning(f"[{task_id}] No se pudo consultar la subida: {str(e)[:160]}")
        if estado["estado"] == "listo":
            return estado.get("urls") or {}
        if estado["estado"] != "desconocido":
            return {}
        logger.warning(f"[{task_id}] La API se reinició durante la subida: se envían de nuevo.")
    return {}


def reclamar(task_id: str) -> bool:
    if MODO_DIRECTO:
        with _Sesion() as s:
            return _ops().reclamar(s.db, s.workers, task_id, confiable=True)
    return bool(_api("POST", f"/tareas/{task_id}/reclamar")["ok"])


def tarea_existe(task_id: str) -> bool:
    if MODO_DIRECTO:
        with _Sesion() as s:
            return _ops().tarea_existe(s.db, task_id)
    return bool(_api("GET", f"/tareas/{task_id}/existe")["existe"])


def guardar_etapa(task_id: str, progreso: int, mensaje: str):
    if MODO_DIRECTO:
        with _Sesion() as s:
            _ops().guardar_etapa(s.db, s.workers, task_id, progreso, mensaje, confiable=True)
        return
    _api("POST", f"/tareas/{task_id}/etapa", {"p": progreso, "m": mensaje}, intentos=1, timeout=10)


def marcar_armonia_inline(task_id: str):
    if MODO_DIRECTO:
        with _Sesion() as s:
            _ops().marcar_armonia_inline(s.db, s.workers, task_id, confiable=True)
        return
    _api("POST", f"/tareas/{task_id}/armonia-inline")


def reconocer(task_id: str, datos: dict) -> dict:
    if MODO_DIRECTO:
        with _Sesion() as s:
            return _ops().reconocer(s.db, s.workers, task_id, datos, confiable=True)
    return _api("POST", f"/tareas/{task_id}/reconocer", datos, intentos=2, timeout=30)


def completar(task_id: str, datos: dict) -> bool:
    """El resultado ya está en HF: insistir bastante para no dejar la pista en 'procesando'."""
    if MODO_DIRECTO:
        with _Sesion() as s:
            return _ops().completar(s.db, s.workers, task_id, datos, confiable=True)
    return bool(_api("POST", f"/tareas/{task_id}/completar", datos, intentos=6, timeout=30)["ok"])


def fallar(task_id: str, error: str):
    if MODO_DIRECTO:
        with _Sesion() as s:
            _ops().fallar(s.db, s.workers, task_id, error, confiable=True)
        return
    _api("POST", f"/tareas/{task_id}/fallar", {"error": (error or "")[:250]}, intentos=6, timeout=30)


def respaldo_local(task_id: str, datos: dict):
    if MODO_DIRECTO:
        with _Sesion() as s:
            _ops().respaldo_local(s.db, s.workers, task_id, datos, confiable=True)
        return
    _api("POST", f"/tareas/{task_id}/respaldo", datos, intentos=6, timeout=30)


def datos_armonia(task_id: str) -> dict:
    """{'existe', 'urls', 'chords', 'folder'}"""
    if MODO_DIRECTO:
        with _Sesion() as s:
            return _ops().datos_armonia(s.db, s.workers, task_id, confiable=True)
    return _api("GET", f"/tareas/{task_id}/armonia")


def etapa_armonia(task_id: str, progreso: int, mensaje: str):
    if MODO_DIRECTO:
        with _Sesion() as s:
            _ops().etapa_armonia(s.db, s.workers, task_id, progreso, mensaje, confiable=True)
        return
    _api("POST", f"/tareas/{task_id}/armonia/etapa", {"p": progreso, "m": mensaje}, intentos=1, timeout=10)


def completar_armonia(task_id: str, urls: dict, hashes=None):
    if MODO_DIRECTO:
        with _Sesion() as s:
            _ops().completar_armonia(s.db, s.workers, task_id, urls, hashes, confiable=True)
        return
    _api("POST", f"/tareas/{task_id}/armonia/completar", {"urls": urls, "hashes": hashes}, intentos=6, timeout=30)


def error_armonia(task_id: str):
    if MODO_DIRECTO:
        with _Sesion() as s:
            _ops().error_armonia(s.db, s.workers, task_id, confiable=True)
        return
    _api("POST", f"/tareas/{task_id}/armonia/error")


# ---------------------------------------------------------------------------
# Limpieza de credenciales viejas
# ---------------------------------------------------------------------------

CLAVES_PROHIBIDAS = ("DATABASE_URL", "SECRET_KEY", "SUPABASE_JWT_SECRET")
# Con el motor que pide trabajo a la API tampoco hacen falta estas
CLAVES_SIN_BROKER = ("BROKER_URL", "REDIS_URL", "CLOUDAMQP_URL", "HF_TOKEN")


def es_worker_instalado(dir_api: str) -> bool:
    """El instalador deja version.txt junto a la carpeta MelodixAPI (C:\\MelodixWorker). El repo no lo tiene."""
    return os.path.exists(os.path.join(os.path.dirname(os.path.abspath(dir_api)), "version.txt"))


def limpiar_credenciales_env(ruta_env: str, extra: tuple = ()) -> list:
    """
    Los instaladores viejos dejaban credenciales de producción en el .env del worker. En modo API
    no se usan: se borran del archivo. Devuelve las claves borradas.
    Solo en un worker instalado: nunca toca el .env de desarrollo del repositorio.
    """
    if MODO_DIRECTO or not os.path.exists(ruta_env) or not es_worker_instalado(os.path.dirname(ruta_env)):
        return []
    with open(ruta_env, encoding="utf-8-sig") as f:
        lineas = f.readlines()
    quedan, borradas = [], []
    for linea in lineas:
        clave = linea.split("=", 1)[0].strip()
        if clave in CLAVES_PROHIBIDAS or clave in extra:
            borradas.append(clave)
        else:
            quedan.append(linea)
    if borradas:
        with open(ruta_env, "w", encoding="utf-8") as f:
            f.writelines(quedan)
    return borradas