Skip to content

Service Layer

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);
}

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() {}
}
  1. Configurationconfigure() is called with the parsed config file
  2. Route setupsetupRoutes() registers all CrateRouters and middleware
  3. Before startonBeforeStart() runs any pre-listen setup
  4. Listen — vibe.d HTTP server starts accepting connections
  5. After startonAfterStart() runs post-listen initialization
  6. Shutdown — Signal handlers (SIGINT, SIGTERM) trigger graceful shutdown()

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.

The service module provides a command-line interface for managing the service:

CommandDescription
startStart the service
stopStop a running service (via PID file)
runRun with custom CLI arguments
startCleanStart, then clean up on exit
cleanRun cleanup tasks
recoverAttempt 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
}

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.