Skip to main content

ggen_core/codegen/
elixir.rs

1//! Elixir microservice code generation
2//!
3//! This module generates Elixir microservices with GenServer supervision trees,
4//! configuration files, and test scaffolding from service specifications.
5
6use std::fmt::Write;
7
8/// Elixir microservice code generator
9pub struct ElixirGenerator;
10
11/// Service specification for Elixir code generation
12#[derive(Clone, Debug)]
13pub struct ServiceSpec {
14    pub name: String,
15    pub module_name: String,
16    pub description: Option<String>,
17    pub supervisor: Option<String>,
18    pub config: Option<String>,
19}
20
21impl ElixirGenerator {
22    /// Generate a GenServer module from a service specification
23    ///
24    /// Creates a module with use GenServer, requires Logger, and callback stubs
25    /// including start_link, init, handle_call, and handle_cast.
26    pub fn generate_module(spec: &ServiceSpec) -> Result<String, String> {
27        let mut output = String::new();
28
29        // File header
30        writeln!(
31            output,
32            "defmodule {} {{\n  @moduledoc \"\"\"\n  {}\n  \"\"\"\n\n  use GenServer\n  require Logger",
33            spec.module_name,
34            spec.description.as_deref().unwrap_or(&format!("{} microservice", spec.name))
35        )
36        .map_err(|e| e.to_string())?;
37
38        writeln!(output, "\n\n  # Public API\n").map_err(|e| e.to_string())?;
39
40        // start_link function
41        writeln!(
42            output,
43            "  def start_link(opts) do\n    GenServer.start_link(__MODULE__, opts, name: __MODULE__)\n  end"
44        )
45        .map_err(|e| e.to_string())?;
46
47        // init callback
48        writeln!(
49            output,
50            "\n\n  # GenServer Callbacks\n\n  def init(opts) do\n    Logger.info(\"Initializing {} with opts: #{{inspect(opts)}}\")\n    {{\n      :ok,\n      %{{\n        module: __MODULE__,\n        opts: opts,\n        started_at: System.monotonic_time(:millisecond)\n      }}\n    }}\n  end",
51            spec.name
52        )
53        .map_err(|e| e.to_string())?;
54
55        // handle_call callback
56        writeln!(
57            output,
58            "\n\n  def handle_call(request, _from, state) do\n    Logger.debug(\"handle_call: #{{inspect(request)}}\")\n    {{\n      :reply,\n      {{:error, :not_implemented}},\n      state\n    }}\n  end"
59        )
60        .map_err(|e| e.to_string())?;
61
62        // handle_cast callback
63        writeln!(
64            output,
65            "\n\n  def handle_cast(message, state) do\n    Logger.debug(\"handle_cast: #{{inspect(message)}}\")\n    {{\n      :noreply,\n      state\n    }}\n  end"
66        )
67        .map_err(|e| e.to_string())?;
68
69        // Closing
70        writeln!(output, "\nend").map_err(|e| e.to_string())?;
71
72        Ok(output)
73    }
74
75    /// Generate a supervision tree for a list of services
76    ///
77    /// Creates a Supervisor module with children list and one_for_one strategy.
78    /// Each service module is configured with restart: :permanent.
79    pub fn generate_supervision_tree(services: &[ServiceSpec]) -> Result<String, String> {
80        let mut output = String::new();
81
82        writeln!(
83            output,
84            "defmodule Supervisor.Services {{\n  @moduledoc \"\"\"\n  Supervision tree for all microservices\n  \"\"\"\n\n  use Supervisor\n  require Logger"
85        )
86        .map_err(|e| e.to_string())?;
87
88        writeln!(
89            output,
90            "\n\n  def start_link(opts) do\n    Supervisor.start_link(__MODULE__, opts, name: __MODULE__)\n  end"
91        )
92        .map_err(|e| e.to_string())?;
93
94        writeln!(
95            output,
96            "\n\n  def init(_opts) do\n    Logger.info(\"Starting service supervision tree\")\n\n    children = ["
97        )
98        .map_err(|e| e.to_string())?;
99
100        for service in services {
101            writeln!(
102                output,
103                "\n      {{{}, [], restart: :permanent}}  # {}",
104                service.module_name,
105                service.description.as_deref().unwrap_or(&service.name)
106            )
107            .map_err(|e| e.to_string())?;
108        }
109
110        writeln!(
111            output,
112            "\n    ]\n\n    Supervisor.init(children, strategy: :one_for_one)\n  end\nend"
113        )
114        .map_err(|e| e.to_string())?;
115
116        Ok(output)
117    }
118
119    /// Generate a config.exs configuration file
120    ///
121    /// Creates configuration blocks for the application with import of runtime.exs.
122    pub fn generate_config(
123        module_prefix: &str, config_spec: &Option<String>,
124    ) -> Result<String, String> {
125        let mut output = String::new();
126
127        writeln!(
128            output,
129            "import Config\n\n# Application configuration for {}\n",
130            module_prefix
131        )
132        .map_err(|e| e.to_string())?;
133
134        writeln!(
135            output,
136            "config :{}, {}.\n  modules: [],\n  timeouts: %{{\n    default: 5000,\n    long: 30000\n  }}\n",
137            module_prefix.to_lowercase(),
138            module_prefix
139        )
140        .map_err(|e| e.to_string())?;
141
142        if let Some(spec) = config_spec {
143            writeln!(output, "\n# Custom configuration\n{}", spec).map_err(|e| e.to_string())?;
144        }
145
146        writeln!(
147            output,
148            "\n# Import runtime configuration (e.g., from environment variables)\nimport_config \"runtime.exs\""
149        )
150        .map_err(|e| e.to_string())?;
151
152        Ok(output)
153    }
154
155    /// Generate a test file scaffold for a module
156    ///
157    /// Creates an ExUnit test module with test "service starts" assertion.
158    pub fn generate_tests(module_name: &str) -> Result<String, String> {
159        let mut output = String::new();
160
161        let test_module = format!("{}Test", module_name.replace('.', ""));
162
163        writeln!(
164            output,
165            "defmodule {} {{\n  use ExUnit.Case, async: true\n  require Logger",
166            test_module
167        )
168        .map_err(|e| e.to_string())?;
169
170        writeln!(
171            output,
172            "\n\n  setup do\n    # Start the module under test\n    {{\n      :ok,\n      pid: GenServer.whereis({})\n    }}\n  end",
173            module_name
174        )
175        .map_err(|e| e.to_string())?;
176
177        writeln!(
178            output,
179            "\n\n  test \"service starts and is running\" do\n    assert is_pid(GenServer.whereis({}))\n  end",
180            module_name
181        )
182        .map_err(|e| e.to_string())?;
183
184        writeln!(
185            output,
186            "\n\n  test \"service responds to health check\" do\n    # Placeholder for service health verification\n    assert true\n  end"
187        )
188        .map_err(|e| e.to_string())?;
189
190        writeln!(output, "\nend").map_err(|e| e.to_string())?;
191
192        Ok(output)
193    }
194
195    /// Generate a supervision tree test
196    pub fn generate_supervision_test() -> Result<String, String> {
197        let mut output = String::new();
198
199        writeln!(
200            output,
201            "defmodule Supervisor.ServicesTest {{\n  use ExUnit.Case, async: false\n  require Logger"
202        )
203        .map_err(|e| e.to_string())?;
204
205        writeln!(
206            output,
207            "\n\n  test \"supervision tree starts all children\" do\n    {{\n      :ok,\n      _pid\n    }} = Supervisor.Services.start_link([])\n\n    # Give children time to start\n    Process.sleep(100)\n\n    # Verify supervisor is running\n    assert is_pid(GenServer.whereis(Supervisor.Services))\n  end"
208        )
209        .map_err(|e| e.to_string())?;
210
211        writeln!(
212            output,
213            "\n\n  test \"supervision tree recovers from child crashes\" do\n    {{\n      :ok,\n      _pid\n    }} = Supervisor.Services.start_link([])\n\n    # Supervisor should be able to restart crashed children\n    assert is_pid(GenServer.whereis(Supervisor.Services))\n  end"
214        )
215        .map_err(|e| e.to_string())?;
216
217        writeln!(output, "\nend").map_err(|e| e.to_string())?;
218
219        Ok(output)
220    }
221
222    /// Generate a runtime.exs configuration file for environment-specific config
223    pub fn generate_runtime_config(env: &str) -> Result<String, String> {
224        let mut output = String::new();
225
226        writeln!(
227            output,
228            "import Config\n\n# Runtime configuration for {} environment\n",
229            env
230        )
231        .map_err(|e| e.to_string())?;
232
233        writeln!(
234            output,
235            "# Logger configuration\nconfig :logger, level: :info"
236        )
237        .map_err(|e| e.to_string())?;
238
239        writeln!(
240            output,
241            "\n\n# Service timeouts (override config.exs defaults)\nif config_env() == :test do\n  config :logger, level: :debug\nend"
242        )
243        .map_err(|e| e.to_string())?;
244
245        writeln!(
246            output,
247            "\n\n# OpenTelemetry OTLP exporter\nconfig :opentelemetry, :processors, [\n  {{\n    OpenTelemetry.Processors.BatchSampler,\n    {{\n      OpenTelemetry.Exporter.OTLP,\n      endpoint: System.get_env(\"OTEL_EXPORTER_OTLP_ENDPOINT\", \"http://localhost:4318\"),\n      protocol: :http_protobuf\n    }}\n  }}\n]"
248        )
249        .map_err(|e| e.to_string())?;
250
251        Ok(output)
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258
259    fn create_test_service() -> ServiceSpec {
260        ServiceSpec {
261            name: "OrderService".to_string(),
262            module_name: "MyApp.OrderService".to_string(),
263            description: Some("Service for managing orders".to_string()),
264            supervisor: Some("MyApp.Supervisor".to_string()),
265            config: Some("port: 8080".to_string()),
266        }
267    }
268
269    #[test]
270    fn test_generate_module() {
271        let spec = create_test_service();
272        let result = ElixirGenerator::generate_module(&spec);
273        assert!(result.is_ok());
274        let code = result.unwrap();
275        assert!(code.contains("defmodule MyApp.OrderService"));
276        assert!(code.contains("use GenServer"));
277        assert!(code.contains("require Logger"));
278        assert!(code.contains("def start_link(opts)"));
279        assert!(code.contains("def init(opts)"));
280        assert!(code.contains("def handle_call"));
281        assert!(code.contains("def handle_cast"));
282    }
283
284    #[test]
285    fn test_generate_supervision_tree() {
286        let services = vec![
287            create_test_service(),
288            ServiceSpec {
289                name: "PaymentService".to_string(),
290                module_name: "MyApp.PaymentService".to_string(),
291                description: Some("Payment processing".to_string()),
292                supervisor: None,
293                config: None,
294            },
295        ];
296        let result = ElixirGenerator::generate_supervision_tree(&services);
297        assert!(result.is_ok());
298        let code = result.unwrap();
299        assert!(code.contains("defmodule Supervisor.Services"));
300        assert!(code.contains("use Supervisor"));
301        assert!(code.contains("MyApp.OrderService"));
302        assert!(code.contains("MyApp.PaymentService"));
303        assert!(code.contains("strategy: :one_for_one"));
304        assert!(code.contains("restart: :permanent"));
305    }
306
307    #[test]
308    fn test_generate_config() {
309        let spec = Some("log_level: :debug".to_string());
310        let result = ElixirGenerator::generate_config("MyApp", &spec);
311        assert!(result.is_ok());
312        let code = result.unwrap();
313        assert!(code.contains("import Config"));
314        assert!(code.contains("config :myapp, MyApp"));
315        assert!(code.contains("import_config \"runtime.exs\""));
316    }
317
318    #[test]
319    fn test_generate_tests() {
320        let result = ElixirGenerator::generate_tests("MyApp.OrderService");
321        assert!(result.is_ok());
322        let code = result.unwrap();
323        assert!(code.contains("defmodule"));
324        assert!(code.contains("use ExUnit.Case"));
325        assert!(code.contains("async: true"));
326        assert!(code.contains("test \"service starts"));
327    }
328
329    #[test]
330    fn test_generate_supervision_test() {
331        let result = ElixirGenerator::generate_supervision_test();
332        assert!(result.is_ok());
333        let code = result.unwrap();
334        assert!(code.contains("defmodule Supervisor.ServicesTest"));
335        assert!(code.contains("use ExUnit.Case"));
336        assert!(code.contains("test \"supervision tree"));
337    }
338
339    #[test]
340    fn test_generate_runtime_config() {
341        let result = ElixirGenerator::generate_runtime_config("dev");
342        assert!(result.is_ok());
343        let code = result.unwrap();
344        assert!(code.contains("import Config"));
345        assert!(code.contains("Logger configuration"));
346        assert!(code.contains("OpenTelemetry"));
347        assert!(code.contains("http_protobuf"));
348    }
349
350    #[test]
351    fn test_module_generation_structure() {
352        let spec = ServiceSpec {
353            name: "TestService".to_string(),
354            module_name: "Test.Service".to_string(),
355            description: Some("Test description".to_string()),
356            supervisor: None,
357            config: None,
358        };
359        let result = ElixirGenerator::generate_module(&spec);
360        assert!(result.is_ok());
361        let code = result.unwrap();
362
363        // Verify correct structure: module -> use GenServer -> init -> handle_call -> handle_cast
364        let lines: Vec<&str> = code.lines().collect();
365        let defmodule_idx = lines.iter().position(|l| l.contains("defmodule"));
366        let use_genserver_idx = lines.iter().position(|l| l.contains("use GenServer"));
367        let init_idx = lines.iter().position(|l| l.contains("def init"));
368        let handle_call_idx = lines.iter().position(|l| l.contains("def handle_call"));
369        let handle_cast_idx = lines.iter().position(|l| l.contains("def handle_cast"));
370
371        assert!(defmodule_idx < use_genserver_idx);
372        assert!(use_genserver_idx < init_idx);
373        assert!(init_idx < handle_call_idx);
374        assert!(handle_call_idx < handle_cast_idx);
375    }
376}