diff --git a/services/delete-info-db.html b/services/delete-info-db.html index 1e8688a..11d0c62 --- a/services/delete-info-db.html +++ b/services/delete-info-db.html @@ -1,20 +1,146 @@ diff --git a/services/delete-info-db.js b/services/delete-info-db.js index c348f0b..19719c1 --- a/services/delete-info-db.js +++ b/services/delete-info-db.js @@ -2,7 +2,281 @@ var mysql = require('mysql'); module.exports = function(RED) { var log = RED.log; - + + // --------------------------------------------------------------------------------------- + // DelInfoDB v2 (version "v2"): purga periodica de mqtt_lecturas con temporizador propio. + // + // La v1 solo borra cuando le llega un mensaje y compara `time` como si fueran milisegundos + // (FROM_UNIXTIME(time * 0.001)); con `time` en segundos (end_range) nunca alcanza la + // fecha de corte. La v2 no necesita mensaje, borra en tandas con LIMIT (de una en una: la conexion + // es unica y compartida con SaveDB y Sender, con una pausa entre sentencias) y se configura con + // reglas: [{ "column": "status", "states": [2], "by": "time", "days": 7, + // "per_device": true, "index": "idx_status_device_time" }] + // column columna de estado: status (cola del capturador) o restful (estado de entrega) + // states valores que se pueden borrar; el 0 (pendiente) no se borra nunca + // by con que fecha se mide la antiguedad: time (epoch en segundos guardado como texto, + // se compara como cadena de 10 cifras), restful_at, sent_time o aswered_time + // days antiguedad minima en dias + // index (opcional) indice que se fuerza para localizar las filas. MariaDB no admite + // FORCE INDEX en DELETE: con `index` o `per_device` cada tanda son dos sentencias, + // un SELECT de ids (covering, con FORCE INDEX) y un DELETE por clave primaria + // per_device (opcional) purga dispositivo a dispositivo: primero los pares (estado, device) + // con filas en esos estados (solo indice) y luego, de uno en uno, status = ? AND + // device = ? AND time < ?. Con un indice (column, device, time) lee solo las + // filas que va a borrar y ninguna de otro estado, sin depender del optimizador + // Sin reglas se usa [{ column: status, states: [2], by: time, days: interval }]: del capturador + // solo se borra lo que el concentrador ya acuso (status 2), nunca lo pendiente (0) ni lo + // enviado sin acuse (3). En el receptor: restful 1 con mas de 7 dias y restful 9 con mas de 30, + // por restful_at (idx_purga da un rango exacto sin dispositivo). + // --------------------------------------------------------------------------------------- + var PURGA_COLUMNAS = ["status", "restful"]; + var PURGA_FECHAS = ["time", "restful_at", "sent_time", "aswered_time"]; + + function reglasDePurga(config) { + var crudas = config.rules; + if (typeof crudas === "string") crudas = crudas.trim() === "" ? null : JSON.parse(crudas); + if (crudas === null || crudas === undefined) { + crudas = [{ column: "status", states: [2], by: "time", days: parseFloat(config.interval) || 7 }]; + } + if (!Array.isArray(crudas) || crudas.length === 0) throw new Error("rules debe ser una lista de reglas"); + return crudas.map(function (r, i) { + var donde = "regla " + (i + 1) + ": "; + var estados = Array.isArray(r.states) ? r.states.map(Number) : []; + if (PURGA_COLUMNAS.indexOf(r.column) === -1) throw new Error(donde + "column debe ser " + PURGA_COLUMNAS.join(" o ")); + if (PURGA_FECHAS.indexOf(r.by) === -1) throw new Error(donde + "by debe ser " + PURGA_FECHAS.join(", ")); + if (estados.length === 0 || estados.some(function (e) { return !(e >= 1 && e <= 255) || Math.floor(e) !== e; })) { + throw new Error(donde + "states: enteros de 1 a 255; el 0 (pendiente) no se borra nunca"); + } + var dias = Number(r.days); + if (!(dias > 0)) throw new Error(donde + "days debe ser mayor que 0"); + if (r.index !== undefined && r.index !== null && r.index !== "" && !/^[A-Za-z0-9_]{1,64}$/.test(String(r.index))) { + throw new Error(donde + "index debe ser el nombre de un indice (letras, cifras y _)"); + } + return { + column: r.column, states: estados, by: r.by, days: dias, + index: r.index ? String(r.index) : null, perDevice: r.per_device === true + }; + }); + } + + function crearPurga(node, config) { + var periodo = 60000 * (parseFloat(config.period) || 60); + var tanda = Math.max(1, Math.min(parseInt(config.batch, 10) || 1000, 50000)); + // Pausa entre dos sentencias de borrado consecutivas de una pasada (no antes de la primera): + // da paso a SaveDB y Sender en la conexion unica. 0 la desactiva. + var pausa = config.pause === undefined || config.pause === "" || isNaN(parseInt(config.pause, 10)) ? 100 : Math.max(0, parseInt(config.pause, 10)); + var reglas = reglasDePurga(config); + var temporizador = null; + var corriendo = false; + var cerrado = false; + var total = 0; + + function consulta(sql, parametros, hecho) { + node.mydbConfig.connection.query(sql, parametros, hecho); + } + + // Condicion de antiguedad (sin funciones sobre la columna indexada) y sus parametros. + function antiguedad(regla, ahora) { + var corte = Math.floor(ahora / 1000 - regla.days * 86400); + if (regla.by === "time") { + return { sql: "`time` < ?", parametros: [String(Math.max(0, corte)).padStart(10, "0")] }; + } + return { + sql: "`" + regla.by + "` IS NOT NULL AND `" + regla.by + "` < FROM_UNIXTIME(?)", + parametros: [Math.max(0, corte)] + }; + } + + var forzar = function (regla) { return regla.index ? " FORCE INDEX (`" + regla.index + "`)" : ""; }; + + // Indices de las reglas: se comprueban una vez, antes de la primera purga. El de una regla tiene que + // existir en mqtt_lecturas y empezar por (column, device, by) si purga por dispositivo, o por + // (column, by) si no. Si no, esa regla se purga sin FORCE INDEX ni por dispositivo (DELETE directo + // en tandas con LIMIT), con log y estado amarillo. + var indicesComprobados = !reglas.some(function (r) { return r.index; }); + var avisoIndices = ""; + + function comprobarIndices(hecho) { + var conIndice = reglas.filter(function (r) { return r.index; }); + var malos = []; + var siguiente = function () { + if (conIndice.length === 0) { + indicesComprobados = true; + if (malos.length) { + avisoIndices = "indice no valido: " + malos.join(", "); + node.status({ fill: "yellow", shape: "ring", text: avisoIndices }); + } + return hecho(null); + } + var regla = conIndice.shift(); + consulta("SELECT column_name AS columna FROM information_schema.statistics WHERE table_schema = DATABASE()" + + " AND table_name = 'mqtt_lecturas' AND index_name = ? ORDER BY seq_in_index", [regla.index], function (err, filas) { + // Sin poder comprobarlo se purga como esta y se vuelve a intentar en la pasada siguiente. + if (err) { log.error(err); return hecho(err); } + var columnas = (filas || []).map(function (f) { return String(f.columna).toLowerCase(); }); + var esperadas = regla.perDevice ? [regla.column, "device", regla.by] : [regla.column, regla.by]; + var vale = esperadas.every(function (c, i) { return columnas[i] === c; }); + if (!vale) { + log.warn("DelInfoDB: el indice " + regla.index + (columnas.length ? " es (" + columnas.join(", ") + ")" : " no existe en mqtt_lecturas") + + " y la regla de " + regla.column + " por " + regla.by + " necesita (" + esperadas.join(", ") + "): se purga sin FORCE INDEX, en tandas con LIMIT"); + malos.push(regla.index); + regla.index = null; + regla.perDevice = false; + } + siguiente(); + }); + }; + siguiente(); + } + + // Una tanda. Devuelve por callback cuantas filas borro. Sin `index` ni `per_device`, un DELETE + // directo; con alguno, un SELECT de ids (covering) y un DELETE por clave primaria. + function tandaDe(regla, ahora, par, hecho) { + var edad = antiguedad(regla, ahora); + if (!regla.index && !regla.perDevice) { + var sql = "DELETE FROM mqtt_lecturas WHERE `" + regla.column + "` IN (" + regla.states.map(function () { return "?"; }).join(",") + ") AND " + edad.sql + " LIMIT ?"; + return consulta(sql, regla.states.concat(edad.parametros, [tanda]), function (err, res) { + hecho(err, res && res.affectedRows ? res.affectedRows : 0); + }); + } + var donde; + var parametros; + if (par) { + donde = "`" + regla.column + "` = ? AND device = ? AND " + edad.sql; + parametros = [par.estado, par.device].concat(edad.parametros); + } else { + donde = "`" + regla.column + "` IN (" + regla.states.map(function () { return "?"; }).join(",") + ") AND " + edad.sql; + parametros = regla.states.concat(edad.parametros); + } + consulta("SELECT id FROM mqtt_lecturas" + forzar(regla) + " WHERE " + donde + " ORDER BY `" + regla.by + "` LIMIT ?", parametros.concat([tanda]), function (err, ids) { + if (err) return hecho(err, 0); + if (!ids || ids.length === 0) return hecho(null, 0); + var lista = ids.map(function (f) { return f.id; }); + // Se repite la condicion de estado: una fila que cambio de estado entre las dos sentencias no se borra. + consulta("DELETE FROM mqtt_lecturas WHERE id IN (" + lista.map(function () { return "?"; }).join(",") + ") AND `" + regla.column + "` IN (" + + regla.states.map(function () { return "?"; }).join(",") + ")", lista.concat(regla.states), function (err2, res) { + hecho(err2, res && res.affectedRows ? res.affectedRows : 0); + }); + }); + } + + // Pares (estado, device) con filas en los estados de la regla: solo indice. + function paresDe(regla, hecho) { + consulta("SELECT DISTINCT `" + regla.column + "` AS estado, device FROM mqtt_lecturas" + forzar(regla) + " WHERE `" + regla.column + "` IN (" + + regla.states.map(function () { return "?"; }).join(",") + ")", regla.states, function (err, filas) { + hecho(err, filas || []); + }); + } + + function contarPendientes(hecho) { + var columnas = reglas.map(function (r) { return r.column; }).filter(function (c, i, todas) { return todas.indexOf(c) === i; }); + var pendientes = {}; + var siguiente = function () { + if (columnas.length === 0) return hecho(pendientes); + var columna = columnas.shift(); + consulta("SELECT COUNT(*) AS n FROM mqtt_lecturas WHERE `" + columna + "` = 0", [], function (err, filas) { + if (err) log.error(err); + else pendientes[columna] = Number(filas && filas[0] ? filas[0].n : 0); + siguiente(); + }); + }; + siguiente(); + } + + function ejecutar(hecho, sinComprobar) { + if (corriendo || cerrado || !node.mydbConfig.connected) return hecho && hecho(); + if (!indicesComprobados && !sinComprobar) { + corriendo = true; + return comprobarIndices(function () { corriendo = false; ejecutar(hecho, true); }); + } + corriendo = true; + var purgadas = 0; + var porRegla = reglas.slice(); + var haBorrado = false; // ya hubo una sentencia de borrado en esta pasada: hay que esperar la pausa + var terminar = function () { + contarPendientes(function (pendientes) { + corriendo = false; + total += purgadas; + var primera = Object.keys(pendientes)[0]; + if (!cerrado) { + node.status({ + fill: avisoIndices ? "yellow" : "green", shape: avisoIndices ? "ring" : "dot", + text: (avisoIndices ? avisoIndices + " · " : "") + "purgadas " + purgadas + " (total " + total + ")" + (primera ? " · pendientes " + pendientes[primera] : "") + }); + node.send({ payload: { msg: "Number of records deleted: " + purgadas, deleted: purgadas, total: total, pending: pendientes } }); + } + if (hecho) hecho(); + }); + }; + // Espera la pausa (salvo antes de la primera sentencia de la pasada) y ejecuta `accion`. + var conPausa = function (accion) { + if (!haBorrado || pausa <= 0) { haBorrado = true; return accion(); } + haBorrado = true; + var t = setTimeout(accion, pausa); + if (t.unref) t.unref(); + }; + // Una regla: tandas seguidas, de una en una, hasta que una no salga llena. Con `per_device`, para cada par. + var purgarRegla = function (regla, pares, terminadaRegla) { + var par = pares ? pares.shift() : null; + if (pares && !par) return terminadaRegla(); + var tandas = function () { + if (cerrado) return terminar(); + conPausa(function () { + if (cerrado) return terminar(); + tandaDe(regla, Date.now(), par, function (err, n) { + if (err) { + // Se registra y se sigue con la siguiente regla: la purga se reintenta en el proximo periodo. + log.error(err); + return terminadaRegla(); + } + purgadas += n; + if (n >= tanda) return tandas(); + if (pares) return purgarRegla(regla, pares, terminadaRegla); + terminadaRegla(); + }); + }); + }; + tandas(); + }; + var siguienteRegla = function () { + if (porRegla.length === 0 || cerrado) return terminar(); + var regla = porRegla.shift(); + if (!regla.perDevice) return purgarRegla(regla, null, siguienteRegla); + paresDe(regla, function (err, filas) { + if (err) { + log.error(err); + return siguienteRegla(); + } + purgarRegla(regla, filas.map(function (f) { return { estado: f.estado, device: f.device }; }), siguienteRegla); + }); + }; + siguienteRegla(); + } + + // La primera purga, 30 s despues de arrancar (o de que la base este disponible); despues, + // una por periodo. Un mensaje de entrada tambien la dispara, pero no hace falta. + function programar(ms) { + if (cerrado) return; + temporizador = setTimeout(function () { + temporizador = null; + if (!node.mydbConfig.connected) return programar(30000); + ejecutar(function () { programar(periodo); }); + }, ms); + if (temporizador.unref) temporizador.unref(); + } + + programar(30000); + + return { + ejecutar: function () { ejecutar(); }, + cerrar: function () { + cerrado = true; + if (temporizador) clearTimeout(temporizador); + temporizador = null; + } + }; + } + function Node(config) { RED.nodes.createNode(this, config); var node = this; @@ -11,6 +285,11 @@ module.exports = function(RED) { this.interval = config.interval; + // "v2": purga periodica con temporizador propio (ver crearPurga). Por defecto v1, que + // borra al recibir un mensaje y compara `time` en milisegundos, como siempre. + this.version = config.version || 'v1'; + var purga = null; + this.mentor = RED.nodes.getNode(config.mentor); this.mentor_id = 0; @@ -21,7 +300,8 @@ module.exports = function(RED) { var node = this; var busy = false; var status = {}; - node.mydbConfig.on("state", function(info) { + // Se guarda el manejador para quitar solo el propio al cerrar: el config node MySQLdb lo comparten varios nodos. + var alCambiarEstadoBd = function (info) { if (info === "connecting") { node.status({fill:"grey",shape:"ring",text:info}); } else if (info === "connected") { node.status({fill:"green",shape:"dot",text:info}); } else { @@ -29,9 +309,22 @@ module.exports = function(RED) { if (info === "PROTOCOL_CONNECTION_LOST") { info = "connection lost"; } node.status({fill:"red",shape:"ring",text:info}); } - }); + }; + node.mydbConfig.on("state", alCambiarEstadoBd); + if (node.version.indexOf("v2") > -1) { + try { + purga = crearPurga(node, config); + } catch (e) { + node.error("DelInfoDB v2: " + e.message); + node.status({fill:"red",shape:"ring",text:"reglas no validas"}); + } + } node.on("input", function(msg) { + if (node.version.indexOf("v2") > -1) { + if (purga) purga.ejecutar(); + return; + } if (node.mydbConfig.connected) { var obj = JSON.parse(msg.payload); msg.code = obj.code; @@ -53,7 +346,8 @@ module.exports = function(RED) { node.on('close', function () { if (node.tout) { clearTimeout(node.tout); } - node.mydbConfig.removeAllListeners(); + if (purga) purga.cerrar(); + node.mydbConfig.removeListener("state", alCambiarEstadoBd); node.status({}); }); } diff --git a/services/mysql-db.js b/services/mysql-db.js index f6b35ae..231c1b8 --- a/services/mysql-db.js +++ b/services/mysql-db.js @@ -16,13 +16,44 @@ module.exports = function(RED) { this.setMaxListeners(0); var node = this; + // Una conexion muerta (el servidor la cerro, un corte de red) no siempre emite 'error': si habia una + // consulta en curso, el error fatal le llega solo a su callback y la conexion queda inservible + // («Cannot enqueue Query after invoking quit», PROTOCOL_ENQUEUE_AFTER_QUIT) para SaveDB, Sender, + // DelInfoDB y Alarms hasta el siguiente ping (290 s). Cualquier error fatal de una consulta da la + // conexion por perdida: se destruye (no vuelve al pool) y se pide otra. + function perder(conexion, err) { + if (node.cerrado || node.connection !== conexion || !node.connected) return; + node.connected = false; + try { conexion.destroy(); } catch (e) { /* ya estaba cerrada */ } + var codigo = err && err.code ? err.code : "PROTOCOL_CONNECTION_LOST"; + node.emit("state", codigo); + if (codigo !== 'PROTOCOL_CONNECTION_LOST' && codigo !== 'ECONNRESET') node.error(err); + if (!node.connecting) doConnect(); + } + + function vigilar(conexion) { + var consultar = conexion.query; + conexion.query = function () { + var args = Array.prototype.slice.call(arguments); + var ultimo = args.length - 1; + if (typeof args[ultimo] === "function") { + var callback = args[ultimo]; + args[ultimo] = function (err) { + if (err && (err.fatal || err.code === 'PROTOCOL_ENQUEUE_AFTER_QUIT')) perder(conexion, err); + return callback.apply(this, arguments); + }; + } + return consultar.apply(conexion, args); + }; + } + function checkVer() { - node.connection.query("SELECT version();", [], function(err, rows) { + var conexion = node.connection; + conexion.query("SELECT version();", [], function(err, rows) { if (err) { - node.connection.release(); - node.error(err); node.status({fill:"red",shape:"ring",text:"Bad Ping"}); - doConnect(); + // Si fue fatal, vigilar() ya la dio por perdida; si no, se da aqui. + perder(conexion, err); } }); } @@ -38,8 +69,15 @@ module.exports = function(RED) { password : node.credentials.password, database : node.dbname, timezone : node.tz, + // concentrador-receptor: el driver usa por defecto UTF8_GENERAL_CI + // (utf8mb3). Un carácter de 4 bytes en el content se rechazaría o + // se sustituiría, rompiendo la copia byte a byte (CR1, C4 I2). + charset : 'UTF8MB4_BIN', insecureAuth: true, - multipleStatements: true, + // concentrador-receptor: sin sentencias múltiples. Con parámetros + // enlazados no hacen falta y amplían el daño de cualquier + // concatenación que quede (S5). + multipleStatements: false, connectionLimit: 25 }); } @@ -52,23 +90,13 @@ module.exports = function(RED) { node.tick = setTimeout(doConnect, reconnect); } else { + vigilar(connection); node.connection = connection; node.connected = true; node.emit("state","connected"); - node.connection.on('error', function(err) { - node.connected = false; - node.connection.release(); - node.emit("state",err.code); - if (err.code === 'PROTOCOL_CONNECTION_LOST') { - doConnect(); // silently reconnect... - } - else if (err.code === 'ECONNRESET') { - doConnect(); // silently reconnect... - } - else { - node.error(err); - doConnect(); - } + connection.on('error', function(err) { + // PROTOCOL_CONNECTION_LOST y ECONNRESET reconectan en silencio; el resto, con error. + perder(connection, err); }); if (!node.check) { node.check = setInterval(checkVer, 290000); } } @@ -82,6 +110,7 @@ module.exports = function(RED) { } this.on('close', function (done) { + node.cerrado = true; if (this.tick) { clearTimeout(this.tick); } if (this.check) { clearInterval(this.check); } node.connected = false; diff --git a/services/receiver.js b/services/receiver.js index 474cc29..b2356ff --- a/services/receiver.js +++ b/services/receiver.js @@ -1,156 +1,553 @@ -module.exports = function(RED) { - var log = RED.log; - function Node(config) { +/** + * Receiver — node-red-contrib-services-mentor@0.0.45, CORREGIDO. + * + * Corrección versionada con patch-package por concentrador-receptor + * (docs/REUTILIZACION_RECEIVER.md, docs/PARCHE_RECEIVER.md). Conserva la idea del + * nodo publicado —suscribirse a `mentor_data`, guardar el sobre en + * `mqtt_lecturas` sin interpretar el `content` y acusar en + * `mentor_answer_`— y corrige los defectos RD1–RD8: + * + * RD1 Solo se acusa tras un INSERT confirmado o un duplicado verificado. Un + * fallo de base no acusa ni pierde: el mensaje espera (G1, G3). + * RD2 Todas las sentencias usan parámetros enlazados (S5). + * RD3 El parseo del sobre está protegido; lo malformado va a cuarentena (S6, G5). + * RD4 Modo estricto: sin variables globales implícitas. + * RD5 Topic y datos del acuse ligados a cada mensaje, no al nodo (C2). + * RD6 (device, time) existente: contenido idéntico = duplicado con acuse; + * distinto = conflicto a cuarentena (G5, C4 I3). La hora de envío del + * capturador (`sent_at`) no cuenta: cambia en cada reenvío (spec 005). + * RD7 mentor_id y alarm con valor por defecto 0 y validados (C1). + * RD8 Se apoya en UNIQUE (device, time): INSERT y, si choca, comparación. + * + * Además, y es lo que cierra el riesgo RN4 de la spec 001: **el PUBACK al broker + * se envía después de persistir**, no al recibir. MQTT.js procesa los paquetes + * entrantes de uno en uno y solo confirma un PUBLISH QoS 1 cuando + * `client.handleMessage(packet, callback)` llama a su callback (punto de + * extensión documentado de MQTT.js para contrapresión). Este nodo lo sustituye + * para retener la confirmación hasta que el mensaje está en `mqtt_lecturas` o en + * `mqtt_cuarentena`. Si la base no está, no se confirma nada, el broker conserva + * el mensaje en la sesión persistente y no entrega más hasta que se libere. + */ +module.exports = function (RED) { + "use strict"; + + var TextDecoder = require("util").TextDecoder; + + var TOPIC_DATOS = "mentor_data"; + var PREFIJO_ACUSE = "mentor_answer_"; + // QoS 1 y no 2: con QoS 2 el broker da el mensaje por entregado en el PUBREC, + // que MQTT.js envía antes de emitir el mensaje, es decir, antes de persistir. + var QOS_SUSCRIPCION = 1; + var QOS_ACUSE = 1; + var TAMANO_MAXIMO = 1048576; // 1 MiB (S6) + var MAX_EXTRACTO_LOG = 512; // S12 + var MAX_DETALLE = 512; // columna mqtt_cuarentena.detail + var ESPERA_MIN_MS = 1000; + var ESPERA_MAX_MS = 15000; + var MAX_MENTOR_ID = 4294967295; // int unsigned + + // Errores de la base que indican que ESTA fila no cabe (dato), no que la base + // no esté disponible. Todo lo demás se trata como transitorio: se reintenta. + // 1048 ER_BAD_NULL_ERROR · 1264 ER_WARN_DATA_OUT_OF_RANGE · 1265 WARN_DATA_TRUNCATED + // 1292 ER_TRUNCATED_WRONG_VALUE · 1300 ER_INVALID_CHARACTER_STRING + // 1366 ER_TRUNCATED_WRONG_VALUE_FOR_FIELD · 1406 ER_DATA_TOO_LONG + var ERRNO_DE_DATO = [1048, 1264, 1265, 1292, 1300, 1366, 1406]; + var ERRNO_DUPLICADO = 1062; // ER_DUP_ENTRY + + var SQL_INSERTAR = + "INSERT INTO mqtt_lecturas (time, device, content, status, mentor_id, alarm) VALUES (?, ?, ?, 2, ?, ?)"; + var SQL_EXISTENTE = "SELECT id, content FROM mqtt_lecturas WHERE device = ? AND time = ? LIMIT 1"; + var SQL_CUARENTENA = + "INSERT INTO mqtt_cuarentena (topic, reason, detail, device, time, mentor_id, lectura_id, payload_bytes, payload) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; + + var CLAVE_CONTROL = "__mentorReceiverControlAcuse"; + + // --------------------------------------------------------------------------- + // Utilidades puras + // --------------------------------------------------------------------------- + + function truncar(texto, maximo) { + texto = String(texto); + return texto.length > maximo ? texto.slice(0, maximo) + "…[truncado]" : texto; + } + + function extracto(payload) { + // Para logs: nunca el payload completo (S12). JSON.stringify escapa saltos + // de línea y caracteres de control, para que no puedan falsear líneas de log. + var texto = Buffer.isBuffer(payload) ? payload.toString("utf8", 0, Math.min(payload.length, MAX_EXTRACTO_LOG)) : String(payload); + return JSON.stringify(truncar(texto, MAX_EXTRACTO_LOG)); + } + + function describirError(err) { + // Nunca err.sql: contiene los valores enlazados (el content completo). + if (!err) return "error desconocido"; + var partes = []; + if (err.code) partes.push(err.code); + if (err.errno) partes.push("errno=" + err.errno); + partes.push(truncar(err.sqlMessage || err.message || String(err), 300)); + return partes.join(" "); + } + + function rechazo(motivo, detalle) { + return { valido: false, motivo: motivo, detalle: truncar(detalle, MAX_DETALLE - 20) }; + } + + function normalizarMentorId(valor) { + if (valor === undefined || valor === null) return { valor: 0, sufijo: "0" }; + if (typeof valor === "number" && Number.isInteger(valor) && valor >= 0 && valor <= MAX_MENTOR_ID) { + return { valor: valor, sufijo: String(valor) }; + } + // Tolerancia: el mentor_id sale de la configuración del capturador y puede + // llegar como cadena de dígitos. Se usa literal en el topic (C2). + if (typeof valor === "string" && /^[0-9]{1,10}$/.test(valor) && Number(valor) <= MAX_MENTOR_ID) { + return { valor: Number(valor), sufijo: valor }; + } + return null; + } + + function normalizarAlarm(valor) { + if (valor === undefined || valor === null) return 0; + if (valor === 0 || valor === 1) return valor; + if (valor === "0" || valor === "1") return Number(valor); + return null; + } + + /** + * Valida el sobre contra C1 sin interpretar el paquete (CR2). Devuelve + * { valido: true, sobre } o { valido: false, motivo, detalle }. + */ + function validarSobre(payload) { + if (!Buffer.isBuffer(payload)) payload = Buffer.from(String(payload), "utf8"); + if (payload.length > TAMANO_MAXIMO) { + return rechazo("TAMANO_EXCEDIDO", payload.length + " bytes > " + TAMANO_MAXIMO); + } + var texto; + try { + texto = new TextDecoder("utf-8", { fatal: true }).decode(payload); + } catch (e) { + return rechazo("NO_UTF8", "el payload no es UTF-8 válido"); + } + var obj; + try { + obj = JSON.parse(texto); + } catch (e) { + return rechazo("NO_JSON", "el payload no es JSON: " + e.message); + } + if (obj === null || typeof obj !== "object" || Array.isArray(obj)) { + return rechazo("NO_OBJETO", "el sobre JSON no es un objeto"); + } + if (typeof obj.device !== "string") { + return rechazo("DEVICE_INVALIDO", "device ausente o no es cadena"); + } + var caracteres = Array.from(obj.device).length; + if (caracteres < 1 || caracteres > 50) { + return rechazo("DEVICE_INVALIDO", "device mide " + caracteres + " caracteres (se admiten 1..50)"); + } + if (typeof obj.time !== "string" || !/^[0-9]{10}$/.test(obj.time)) { + return rechazo("TIME_INVALIDO", "time ausente o no es una cadena de 10 dígitos"); + } + if (typeof obj.content !== "string" || obj.content.length < 2) { + return rechazo("CONTENT_INVALIDO", "content ausente, no es cadena o mide menos de 2 caracteres"); + } + var mentor = normalizarMentorId(obj.mentor_id); + if (!mentor) return rechazo("MENTOR_ID_INVALIDO", "mentor_id no es un entero >= 0"); + var alarm = normalizarAlarm(obj.alarm); + if (alarm === null) return rechazo("ALARM_INVALIDO", "alarm no es 0 ni 1"); + + return { + valido: true, + sobre: { + device: obj.device, // literal (C1.1) + time: obj.time, // literal, como cadena (C1.1) + content: obj.content, // literal (CR1) + mentorId: mentor.valor, + sufijoAcuse: mentor.sufijo, + alarm: alarm + } + }; + } + + function mismoContenido(guardado, recibido) { + if (Buffer.isBuffer(guardado)) { + if (guardado.equals(Buffer.from(recibido, "utf8"))) return true; + guardado = guardado.toString("utf8"); + } else if (guardado === recibido) { + return true; + } + return mismoSalvoHoraDeEnvio(guardado, recibido); + } + + /** + * Spec 005: el capturador pone en cada publicación la hora de su reloj (`sent_at`, spec 021 + * del capturador), así que un reenvío del mismo paquete trae otro `sent_at`. No es un + * conflicto: se compara el paquete sin ese campo. Cualquier otra diferencia sí lo es. + */ + function mismoSalvoHoraDeEnvio(guardado, recibido) { + if (typeof guardado !== "string" || typeof recibido !== "string") return false; + if (guardado.indexOf('"sent_at"') === -1 && recibido.indexOf('"sent_at"') === -1) return false; + var a, b; + try { + a = JSON.parse(guardado); + b = JSON.parse(recibido); + } catch (e) { + return false; + } + if (!esObjeto(a) || !esObjeto(b)) return false; + delete a.sent_at; + delete b.sent_at; + return JSON.stringify(a) === JSON.stringify(b); + } + + function esObjeto(v) { + return v !== null && typeof v === "object" && !Array.isArray(v); + } + + function dormir(ms) { + return new Promise(function (resolve) { + setTimeout(resolve, ms); + }); + } + + function abandono() { + var e = new Error("procesamiento abandonado: la conexión MQTT cambió o el nodo se cerró"); + e.abandono = true; + return e; + } + + /** + * Instala, una vez por cliente MQTT.js, la retención del PUBACK. Los paquetes + * que no ha reclamado este nodo siguen el camino normal. + */ + function controlDeAcuse(client) { + if (client[CLAVE_CONTROL]) return client[CLAVE_CONTROL]; + var control = { tareas: new WeakMap() }; + var original = client.handleMessage; + client.handleMessage = function (packet, callback) { + var tarea = packet ? control.tareas.get(packet) : undefined; + if (!tarea) return original.call(client, packet, callback); + control.tareas.delete(packet); + tarea.then(function (confirmar) { + // Solo se confirma si el mensaje quedó persistido y la conexión por la que + // llegó sigue siendo la actual. Si no, el broker lo reentregará. + if (confirmar === true) callback(); + }); + }; + Object.defineProperty(client, CLAVE_CONTROL, { value: control, enumerable: false }); + return control; + } + + // --------------------------------------------------------------------------- + // Nodo + // --------------------------------------------------------------------------- + function Node(config) { RED.nodes.createNode(this, config); var node = this; - this.mqtt = RED.nodes.getNode(config.mqtt); - - this.broker = config.mqtt; - this.brokerConn = RED.nodes.getNode(this.broker); + node.brokerConn = RED.nodes.getNode(config.mqtt); + node.mydbConfig = RED.nodes.getNode(config.mysql); + var cerrado = false; + var contadores = { guardados: 0, duplicados: 0, conflictos: 0, cuarentena: 0 }; + var bdCaida = false; - this.mydb = config.mysql; - this.mydbConfig = RED.nodes.getNode(this.mydb); + function consultar(sql, parametros) { + return new Promise(function (resolve, reject) { + var pool = node.mydbConfig && node.mydbConfig.pool; + if (!pool) { + var e = new Error("el pool de la base de recepción aún no está inicializado"); + e.code = "POOL_NO_INICIALIZADO"; + return reject(e); + } + pool.query(sql, parametros, function (err, resultado) { + if (err) reject(err); + else resolve(resultado); + }); + }); + } - this.channel = 0; - this.qos = 2; + function actualizarEstado() { + if (bdCaida) { + node.status({ fill: "red", shape: "ring", text: "base de recepción no disponible: reteniendo" }); + return; + } + var texto = contadores.guardados + " guardados · " + contadores.duplicados + " duplicados"; + if (contadores.cuarentena || contadores.conflictos) { + texto += " · " + (contadores.cuarentena + contadores.conflictos) + " en cuarentena"; + node.status({ fill: "yellow", shape: "dot", text: texto }); + } else { + node.status({ fill: "green", shape: "dot", text: texto }); + } + } - if (this.mydbConfig) { - this.mydbConfig.connect(); - var busy = false; - var status = {}; - node.mydbConfig.on("state", function(info) { - if (info === "connecting") { node.status({fill:"grey",shape:"ring",text:info}); } - else if (info === "connected") { node.status({fill:"green",shape:"dot",text:info}); } - else { - if (info === "ECONNREFUSED") { info = "connection refused"; } - if (info === "PROTOCOL_CONNECTION_LOST") { info = "connection lost"; } - node.status({fill:"red",shape:"ring",text:info}); + /** + * Ejecuta `operacion` hasta que tenga éxito. Cualquier rechazo que llegue + * aquí es transitorio (base caída, permisos, tabla ausente…): se espera con + * backoff y se reintenta, sin acusar ni confirmar (G1, G3). + */ + function conReintentos(etapa, operacion, vigente) { + var intentos = 0; + function paso() { + if (!vigente()) return Promise.reject(abandono()); + return operacion().catch(function (err) { + if (err && err.abandono) throw err; + intentos++; + if (!bdCaida || intentos === 1 || intentos % 20 === 0) { + node.warn( + "ALERTA base de recepción no disponible en '" + etapa + "' (intento " + intentos + "): " + + describirError(err) + ". El mensaje no se acusa ni se confirma al broker; se reintenta." + ); + } + bdCaida = true; + actualizarEstado(); + var espera = Math.min(ESPERA_MAX_MS, ESPERA_MIN_MS * Math.pow(2, Math.min(intentos - 1, 10))); + return dormir(espera).then(paso); + }); + } + return paso().then(function (resultado) { + if (bdCaida) { + bdCaida = false; + node.log("base de recepción disponible de nuevo tras " + intentos + " reintentos en '" + etapa + "'"); } - }); + return resultado; + }); + } - node.on('close', function () { - if (node.tout) { clearTimeout(node.tout); } - node.mydbConfig.removeAllListeners(); - node.status({}); - }); - } else { - this.error("MySQL database not configured"); - } - - if (this.brokerConn) { - this.status({fill:"red",shape:"ring",text:"node-red:common.status.disconnected"}); - node.brokerConn.register(this); - this.brokerConn.subscribe('mentor_data',this.qos,function(topic,msg,packet) { - switch (topic) - { - case "mentor_data": - var obj = JSON.parse(msg.toString()); - var mentor_id = obj.mentor_id; - node.channel = "mentor_answer_" + mentor_id; - obj.alarm = obj.alarm || 0; - node.alarm = obj.alarm; - - existRecord(node, obj, function (exist, err) { - if (err) { log.error(err); } - else - { - if (!exist) - { saveRecord(node, obj, mentor_id, function (r, err) { - if (err) { log.error(err); } - else - { - getAndSendRecord(obj, node); - } - }); - } - else - {node.send({payload: {msg:"Record already found ", data: obj}}); getAndSendRecord(obj, node);} - } + function guardarCuarentena(topic, motivo, detalle, payload, clave) { + clave = clave || {}; + var bytes = Buffer.isBuffer(payload) ? payload : Buffer.from(String(payload), "utf8"); + return consultar(SQL_CUARENTENA, [ + topic, + motivo, + truncar(detalle, MAX_DETALLE - 20), + clave.device === undefined ? null : clave.device, + clave.time === undefined ? null : clave.time, + clave.mentorId === undefined ? null : clave.mentorId, + clave.lecturaId === undefined ? null : clave.lecturaId, + bytes.length, + bytes + ]).then(function (r) { + return r.insertId; + }); + } + + /** + * INSERT con UNIQUE (device, time) como árbitro (RD8). Devuelve el desenlace; + * rechaza solo con errores transitorios. + */ + function persistirSobre(topic, sobre, payload) { + var clave = { device: sobre.device, time: sobre.time, mentorId: sobre.mentorId }; + return consultar(SQL_INSERTAR, [sobre.time, sobre.device, sobre.content, sobre.mentorId, sobre.alarm]).then( + function (r) { + return { tipo: "guardado", id: r.insertId }; + }, + function (err) { + if (err && err.errno === ERRNO_DUPLICADO) { + return consultar(SQL_EXISTENTE, [sobre.device, sobre.time]).then(function (filas) { + if (!filas || filas.length === 0) { + // Chocó la clave pero la fila no aparece: estado inesperado. Se trata + // como transitorio para no acusar sin haber verificado nada. + var e = new Error("ER_DUP_ENTRY sin fila existente para la clave"); + e.code = "DUPLICADO_SIN_FILA"; + throw e; + } + var existente = filas[0]; + if (mismoContenido(existente.content, sobre.content)) { + return { tipo: "duplicado", id: existente.id }; + } + clave.lecturaId = existente.id; + return guardarCuarentena( + topic, + "CONFLICTO_CONTENIDO", + "(device, time) ya existe en mqtt_lecturas.id=" + existente.id + " con content distinto", + payload, + clave + ).then(function (idCuarentena) { + return { tipo: "conflicto", id: existente.id, cuarentena: idCuarentena }; + }); + }); + } + if (err && ERRNO_DE_DATO.indexOf(err.errno) !== -1) { + return guardarCuarentena(topic, "ERROR_BD_PERMANENTE", describirError(err), payload, clave).then( + function (idCuarentena) { + return { tipo: "error_dato", cuarentena: idCuarentena, error: err }; } ); - break; - default: - log.error(topic); - break; + } + throw err; } - }, this.id); - if (this.brokerConn.connected) { - node.status({fill:"green",shape:"dot",text:"node-red:common.status.connected"}); + ); + } + + function publicarAcuse(sobre) { + // RD5: todo lo del acuse sale del sobre de ESTE mensaje. + var mensaje = { + topic: PREFIJO_ACUSE + sobre.sufijoAcuse, + payload: JSON.stringify({ device: sobre.device, time: sobre.time, status: 2 }), + qos: QOS_ACUSE, + retain: false + }; + if (!node.brokerConn || !node.brokerConn.connected) { + node.warn( + "acuse no publicado (broker desconectado) device=" + JSON.stringify(sobre.device) + " time=" + sobre.time + + ": el mensaje no se confirma y el broker lo reentregará" + ); + return false; } - this.on('close', function(done) { - node.brokerConn.deregister(node,done); + // No se espera el PUBACK del acuse: llega por el mismo flujo de entrada que + // está retenido hasta que este mensaje termine, y esperarlo sería un + // bloqueo mutuo. MQTT.js lo guarda en su almacén de salida y lo reenvía. + node.brokerConn.publish(mensaje, function (err) { + if (err) { + node.warn("fallo al publicar el acuse en " + mensaje.topic + ": " + describirError(err)); + } }); + return true; } - } - - function saveRecord(node, obj, mentor_id, callback) - { - if (node.mydbConfig.connected) { - var sql = "INSERT INTO mqtt_lecturas(time, device, content, status, mentor_id, alarm) VALUES ('"+ obj.time +"','"+obj.device+"','"+obj.content+"', 2, "+mentor_id+",'"+obj.alarm+"');"; - node.mydbConfig.connection.query(sql, [], function(err, rows) { - if (err) { log.error(err); callback(null, err); } - else - { - node.send({payload: {msg:rows.insertId + " Inserted.", data: obj}}); - callback (true, null); + /** + * Procesa un mensaje de mentor_data. Resuelve true si se puede confirmar al + * broker (persistido en lecturas o en cuarentena y conexión vigente). + */ + function procesar(topic, payload, vigente) { + var validacion = validarSobre(payload); + var bytes = Buffer.isBuffer(payload) ? payload.length : Buffer.byteLength(String(payload)); + + if (!validacion.valido) { + return conReintentos("cuarentena", function () { + return guardarCuarentena(topic, validacion.motivo, validacion.detalle, payload); + }, vigente).then(function (idCuarentena) { + contadores.cuarentena++; + node.warn( + "cuarentena id=" + idCuarentena + " motivo=" + validacion.motivo + " bytes=" + bytes + " detalle=" + + JSON.stringify(validacion.detalle) + " extracto=" + extracto(payload) + " (sin acuse)" + ); + node.send({ payload: { resultado: "cuarentena", motivo: validacion.motivo, cuarentena: idCuarentena } }); + actualizarEstado(); + return vigente(); + }); + } + + var sobre = validacion.sobre; + return conReintentos("guardar", function () { + return persistirSobre(topic, sobre, payload); + }, vigente).then(function (desenlace) { + var clave = "device=" + JSON.stringify(sobre.device) + " time=" + sobre.time; + if (desenlace.tipo === "guardado") { + contadores.guardados++; + publicarAcuse(sobre); + } else if (desenlace.tipo === "duplicado") { + contadores.duplicados++; + node.log("duplicado idéntico " + clave + " (mqtt_lecturas.id=" + desenlace.id + "): se acusa sin fila nueva"); + publicarAcuse(sobre); + } else if (desenlace.tipo === "conflicto") { + contadores.conflictos++; + node.error( + "CONFLICTO " + clave + ": ya existe mqtt_lecturas.id=" + desenlace.id + " con content distinto; " + + "el nuevo queda en mqtt_cuarentena.id=" + desenlace.cuarentena + " (se acusa: persistido en cuarentena)" + ); + publicarAcuse(sobre); + } else { + contadores.cuarentena++; + node.error( + "cuarentena id=" + desenlace.cuarentena + " motivo=ERROR_BD_PERMANENTE " + clave + ": " + + describirError(desenlace.error) + " (sin acuse)" + ); } + node.send({ + payload: { + resultado: desenlace.tipo, + device: sobre.device, + time: sobre.time, + id: desenlace.id, + cuarentena: desenlace.cuarentena + } + }); + actualizarEstado(); + return vigente(); }); } - else { - node.error("Database not connected",msg); - status = {fill:"red",shape:"ring",text:"not yet connected"}; - callback(null, null); - } - - } - function existRecord(node,obj,callback) - { - if (node.mydbConfig.connected) { - var sql = "SELECT count(*) as _count FROM mqtt_lecturas WHERE device='"+obj.device+"' AND time*1="+ obj.time; - node.mydbConfig.connection.query(sql, [], function(err, rows) { - if (err) { log.error(err); callback(null, err); } - else - { - if (rows[0]._count > 0 ) - callback (true, null); - else - callback(false, null); + function alRecibir(topic, payload, packet) { + if (topic !== TOPIC_DATOS) { + node.warn("topic inesperado ignorado: " + truncar(topic, 100)); + return; + } + var client = node.brokerConn && node.brokerConn.client; + var stream = client ? client.stream : null; + function vigente() { + return ( + !cerrado && + !!client && + node.brokerConn.client === client && + client.stream === stream && + client.connected === true + ); + } + var tarea; + try { + tarea = procesar(topic, payload, vigente); + } catch (err) { + tarea = Promise.reject(err); + } + tarea = tarea.catch(function (err) { + if (!(err && err.abandono)) { + node.error("fallo inesperado procesando mentor_data (no se confirma al broker): " + describirError(err)); } + return false; }); + // Síncrono: Node-RED invoca este callback durante el evento 'message', y + // MQTT.js llama a handleMessage justo después, en el mismo turno. + if (client && packet) controlDeAcuse(client).tareas.set(packet, tarea); } - else { - node.error("Database not connected",null); - status = {fill:"red",shape:"ring",text:"not yet connected"}; - callback(null, null); + + function alCambiarBd(info) { + if (info === "connected") { + if (!bdCaida) actualizarEstado(); + } else if (info === "connecting") { + node.status({ fill: "grey", shape: "ring", text: "conectando a la base de recepción" }); + } else if (info && String(info).trim()) { + node.status({ fill: "red", shape: "ring", text: "base de recepción: " + truncar(info, 40) }); + } } - } - function getAndSendRecord(obj, node) - { - var _msg = {}; - _msg.device = obj.device; - _msg.time = obj.time; - _msg.status = 2; - if (node.brokerConn) { - msg = {}; - msg.qos = 2; - msg.retain = false; - msg.payload = JSON.stringify(_msg); - msg.topic = node.channel; - msg.alarm = node.alarm; - node.brokerConn.publish(msg); - node.status({fill:"red",shape:"ring",text:"node-red:common.status.disconnected"}); - if (node.brokerConn.connected) { - node.status({fill:"green",shape:"dot",text:"node-red:common.status.connected"}); - } + if (!node.mydbConfig) { + // Sin base no se suscribe: suscribirse sería consumir sin poder persistir. + node.error("Receiver sin base de datos configurada: no se suscribe a " + TOPIC_DATOS); + return; } + node.mydbConfig.on("state", alCambiarBd); + node.mydbConfig.connect(); + if (!node.brokerConn) { + node.error("Receiver sin broker MQTT configurado"); + } else { + node.status({ fill: "red", shape: "ring", text: "node-red:common.status.disconnected" }); + node.brokerConn.register(node); + node.brokerConn.subscribe(TOPIC_DATOS, { qos: QOS_SUSCRIPCION }, alRecibir, node.id); + if (node.brokerConn.connected) { + node.status({ fill: "green", shape: "dot", text: "node-red:common.status.connected" }); + } + } + + node.on("close", function (removed, done) { + cerrado = true; + // Solo los listeners propios: el config node es compartido. + node.mydbConfig.removeListener("state", alCambiarBd); + node.status({}); + // Sin unsubscribe: la suscripción de la sesión persistente debe sobrevivir + // al cierre y al redespliegue (G2; además autoUnsubscribe: false). + if (node.brokerConn) { + node.brokerConn.deregister(node, done); + } else { + done(); + } + }); } RED.nodes.registerType("Receiver", Node); + + // Expuesto solo para las pruebas del receptor; no forma parte de la API del nodo. + Node._paraPruebas = { validarSobre: validarSobre, normalizarMentorId: normalizarMentorId, normalizarAlarm: normalizarAlarm }; }; diff --git a/services/save-db.html b/services/save-db.html index e0e1f16..1b25ba0 --- a/services/save-db.html +++ b/services/save-db.html @@ -14,6 +14,18 @@ icon: "service.png", label: function() { return this.name||"SaveDB"; + }, + oneditprepare: function () { + // Antes era texto libre: un valor que no sea v1 ni v2 se conserva como opcion. + var v = this.version; + if (!v) $("#node-input-version").val("v1"); + if (v && !$("#node-input-version option[value='" + v + "']").length) { + $("#node-input-version").append($("