|
| 1 | +#!/usr/bin/env async-service |
| 2 | +# frozen_string_literal: true |
| 3 | + |
| 4 | +# Released under the MIT License. |
| 5 | +# Copyright, 2025, by Samuel Williams. |
| 6 | + |
| 7 | +require "async/service/supervisor" |
| 8 | +require "async/service/managed/service" |
| 9 | +require "async/utilization" |
| 10 | +require "io/endpoint/host_endpoint" |
| 11 | + |
| 12 | +class EchoService < Async::Service::Managed::Service |
| 13 | + def initialize(...) |
| 14 | + super |
| 15 | + |
| 16 | + @bound_endpoint = nil |
| 17 | + @endpoint = nil |
| 18 | + end |
| 19 | + |
| 20 | + # Prepare the bound endpoint for the server. |
| 21 | + def start |
| 22 | + @endpoint = IO::Endpoint.tcp("127.0.0.1", 8080) |
| 23 | + |
| 24 | + Sync do |
| 25 | + @bound_endpoint = @endpoint.bound |
| 26 | + end |
| 27 | + |
| 28 | + Console.info(self, "Starting echo server on #{@endpoint}") |
| 29 | + |
| 30 | + super |
| 31 | + end |
| 32 | + |
| 33 | + def run(instance, evaluator) |
| 34 | + evaluator.prepare!(instance) |
| 35 | + |
| 36 | + instance.ready! |
| 37 | + |
| 38 | + registry = evaluator.utilization_registry |
| 39 | + connections_total = registry.metric(:connections_total) |
| 40 | + connections_active = registry.metric(:connections_active) |
| 41 | + messages_total = registry.metric(:messages_total) |
| 42 | + |
| 43 | + Async do |task| |
| 44 | + @bound_endpoint.accept do |peer| |
| 45 | + connections_total.increment |
| 46 | + connections_active.track do |
| 47 | + Console.info(self, "Client connected", peer: peer) |
| 48 | + |
| 49 | + peer.each_line do |line| |
| 50 | + messages_total.increment |
| 51 | + peer.write(line) |
| 52 | + end |
| 53 | + |
| 54 | + Console.info(self, "Client disconnected", peer: peer) |
| 55 | + end |
| 56 | + end |
| 57 | + end |
| 58 | + |
| 59 | + # Return the bound endpoint for health checking |
| 60 | + @bound_endpoint |
| 61 | + end |
| 62 | + |
| 63 | + # Close the bound endpoint. |
| 64 | + def stop(...) |
| 65 | + if @bound_endpoint |
| 66 | + @bound_endpoint.close |
| 67 | + @bound_endpoint = nil |
| 68 | + end |
| 69 | + |
| 70 | + @endpoint = nil |
| 71 | + |
| 72 | + super |
| 73 | + end |
| 74 | +end |
| 75 | + |
| 76 | +service "echo" do |
| 77 | + include Async::Service::Managed::Environment |
| 78 | + include Async::Service::Supervisor::Supervised |
| 79 | + |
| 80 | + service_class EchoService |
| 81 | + |
| 82 | + utilization_schema do |
| 83 | + { |
| 84 | + connections_total: :u64, |
| 85 | + connections_active: :u32, |
| 86 | + messages_total: :u64 |
| 87 | + } |
| 88 | + end |
| 89 | +end |
| 90 | + |
| 91 | +service "supervisor" do |
| 92 | + include Async::Service::Supervisor::Environment |
| 93 | + |
| 94 | + monitors do |
| 95 | + [ |
| 96 | + Async::Service::Supervisor::UtilizationMonitor.new( |
| 97 | + path: "utilization.shm", |
| 98 | + interval: 1 |
| 99 | + ) |
| 100 | + ] |
| 101 | + end |
| 102 | +end |
0 commit comments