Service Layer
The Service Interface
Section titled “The Service Interface”Crate provides a service abstraction for running HTTP applications with proper lifecycle management:
interface Service { ServiceInfo info(); string pidFile(); void log(string message); void error(string message); bool recover(); int main(); void shutdown() nothrow;}For applications that need configuration files:
interface ConfigurableService(C) : Service { alias Configuration = C; string defaultConfigFile(); void configure(Configuration config);}WebService
Section titled “WebService”Most applications extend WebService, which handles HTTP server setup, signal handling, and graceful shutdown:
abstract class WebService( Configuration, string serviceName = null, string serviceVersion = null, string serviceDescription = null,) : ConfigurableService!Configuration {
/// Define your routes here abstract void setupRoutes(URLRouter router);
/// Called before the HTTP server starts listening void onBeforeStart(URLRouter router) {}
/// Called after the server is running void onAfterStart() {}}Lifecycle
Section titled “Lifecycle”- Configuration —
configure()is called with the parsed config file - Route setup —
setupRoutes()registers all CrateRouters and middleware - Before start —
onBeforeStart()runs any pre-listen setup - Listen — vibe.d HTTP server starts accepting connections
- After start —
onAfterStart()runs post-listen initialization - Shutdown — Signal handlers (SIGINT, SIGTERM) trigger graceful
shutdown()
Signal Handling
Section titled “Signal Handling”WebService installs signal handlers automatically:
- SIGINT (Ctrl+C) — triggers graceful shutdown
- SIGTERM — triggers graceful shutdown
The shutdown sequence stops the HTTP listener and cleans up resources.
CLI Commands
Section titled “CLI Commands”The service module provides a command-line interface for managing the service:
| Command | Description |
|---|---|
start | Start the service |
stop | Stop a running service (via PID file) |
run | Run with custom CLI arguments |
startClean | Start, then clean up on exit |
clean | Run cleanup tasks |
recover | Attempt crash recovery |
class MyApp : WebService!(MyConfig, "myapp", "1.0.0", "My API") { override void setupRoutes(URLRouter router) { auto crateRouter = router.crateSetup!RestApi; crateRouter.add(userCrate); }}
void main(string[] args) { auto service = new MyApp(); service.run(args); // Handles start/stop/recover commands}Configuration
Section titled “Configuration”WebService expects a configuration struct that’s deserialized from a JSON file:
struct MyConfig { string mongoUri = "mongodb://localhost"; ushort port = 8080; string bindAddress = "0.0.0.0";}The default config file path is returned by defaultConfigFile(). Override this to customize where your service looks for configuration.