using MP.Data.Services.IOC; using NLog; namespace MP.IOC.Endpoints { public static class IobEndpoints { #region Public Methods public static void MapIobHighPerformanceEndpoints(this IEndpointRouteBuilder app) { // 1. Root di test base: api/IOB e api/IOB/alive app.MapGet("api/IOB", () => "OK"); app.MapGet("api/IOB/alive", () => "OK"); // 2. Il metodo Enabled ad alto traffico: api/IOB/enabled/{id} app.MapGet("api/IOB/enabled/{id}", async (string id, IIocService iocService, HttpContext context) => { if (string.IsNullOrEmpty(id)) return Results.BadRequest("Missing ID"); try { bool isEnabled = await iocService.IobInsEnabAsync(id); return isEnabled ? Results.Ok("OK") : Results.UnprocessableEntity("NO"); } catch (Exception ex) { Log.Error(ex, "Errore durante la verifica abilitazione per {Id}", id); return Results.StatusCode(500); } }); // 3. Metodo: GetCurrODL (api/IOB/getCurrODL/{id}) app.MapGet("api/IOB/getCurrODL/{id}", async (string id, IIocService iocService, HttpContext context) => { if (string.IsNullOrEmpty(id)) { context.Response.StatusCode = StatusCodes.Status400BadRequest; return "Missing ID"; } if (id.Contains('|')) { id = id.Replace('|', '#'); } try { var odl = await iocService.GetCurrOdlAsync(id); // Ottimizzazione: Se 'odl' è già una stringa, ritornala direttamente. // Se è un oggetto o un numero, il C# gestirà l'estrazione. Evitiamo $"{odl}" che alloca memoria inutilmente. return odl?.ToString() ?? string.Empty; } catch (Exception exc) { Log.Error(exc, "Errore GetCurrODL | macchina {MachineId}", id); context.Response.StatusCode = StatusCodes.Status500InternalServerError; return "NO"; } }); #if false // 4. Metodo: SetCounter (api/IOB/setCounter/{id}?counter=10) // Nota: 'counter' viene letto automaticamente dalla Query String grazie al Model Binding automatico app.MapGet("api/IOB/setCounter/{id}", async (string id, string counter, IIocService iocService, HttpContext context) => { if (string.IsNullOrEmpty(id)) { context.Response.StatusCode = StatusCodes.Status400BadRequest; return "Missing ID"; } // Ottimizzazione: esegui il Replace solo se il carattere è effettivamente presente if (id.Contains('|')) { id = id.Replace('|', '#'); } // Se il log di Debug è disattivato in produzione, eviti l'allocazione della stringa interpolata if (Log.IsDebugEnabled) { Log.Debug($"Salvataggio counter | id: {id} | pzCount: {counter}"); } try { string answ = await iocService.SaveCounterAsync(id, counter); return answ; // Ritorna direttamente la stringa (Status 200 di default, zero allocazioni di ObjectResult) } catch (Exception exc) { // Usiamo la stringa formattata standard di NLog per evitare Environment.NewLine manuale Log.Error(exc, "Errore in SetCounter per macchina {MachineId}", id); context.Response.StatusCode = StatusCodes.Status500InternalServerError; return "NO"; } }); #endif } #endregion Public Methods #region Private Fields private static Logger Log = LogManager.GetCurrentClassLogger(); #endregion Private Fields } }