using CompServ.ClientLibrary; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using static CompServ.CompServConst; namespace CompServ.Hub { [ApiController] public class HubController(HubWorkerHolder hubWorkerHolder, ILogger logger) : ControllerBase { [HttpGet] [Route(ApiPathHubRootForCheckAlive)] public ActionResult CheckAlive() => Content(AliveMessageHub); [HttpPost] [Route(ApiPathHubRegisterWorker)] public async Task Register() { var wr = HttpContext.Request.ExtractWorkerRegister(); if (wr.port == null || wr.ratio == null) return StatusCode(400, "missing required header"); var url = $"http://{Request.HttpContext.Connection.RemoteIpAddress}:{wr.port}"; var workerClient = new CompServWorkerClient(url); if (await workerClient.CheckAliveAsync()) hubWorkerHolder.RegisterWorker(url, wr.ratio.Value); else logger.LogWarning("Worker no alive, skip register. url: " + url + " ratio: " + wr.ratio); return Empty; } [HttpPost] [Route(ApiPathHubUnRegisterWorker)] public async Task UnRegister() { var wr = HttpContext.Request.ExtractWorkerRegister(); if (wr.port == null) return StatusCode(400, "missing required header"); var url = $"http://{Request.HttpContext.Connection.RemoteIpAddress}:{wr.port}"; hubWorkerHolder.UnRegisterWorker(url); return Empty; } [HttpGet] [Route(ApiPathHubGetWorker)] public async Task GetWorker() { var url = await hubWorkerHolder.GetWorkerAsync(); return Content(url); } } }