Domain Module in Apache Maka: Definition, Interface, and Lifecycle Management

A Domain Module in Apache Maka is a RuntimeHostDomainModule interface that encapsulates a logical domain of operations within the Runtime Host, defining unique identifiers, operation handlers, and lifecycle hooks for state recovery and graceful shutdown.

In the apache/maka repository, the Domain Module serves as the fundamental building block for extending Runtime Host capabilities. Defined in packages/runtime-host/src/server/host-composition.ts, this architectural component allows developers to package related operations, state management, and resource cleanup into discrete, composable units that the host orchestrates during execution.

Core Interface and Responsibilities

The RuntimeHostDomainModule interface in host-composition.ts specifies the contract that every domain module must implement. According to the source code, this interface mandates five core members that govern identity, operation handling, and lifecycle management.

Mandatory Properties

  • id: string – A unique identifier validated against MODULE_ID_PATTERN. The Runtime Host enforces uniqueness across all loaded modules.
  • handlers: Partial<DomainOperationHandlerMap> – A map of operation names to handler functions that implement the domain’s runtime-host API. These handlers process incoming domain requests.

Lifecycle Methods

  • recover(phase: HostRecoveryPhase): Promise<void> – Called during each recovery phase (state, resources, executions, domains, schedulers) to restore module state after interruptions.
  • beginDrain(): void – Invoked when the host initiates shutdown; signals the module to start releasing resources.
  • close(): Promise<void> – Executes final cleanup of the module’s resources. The host aggregates failures across modules and throws a consolidated error if any close operation fails.
  • releaseConnection?(connectionId: string): void – Optional hook to free a specific connection owned by the module.

Declarative Definition and Factory Creation

Developers do not instantiate RuntimeHostDomainModule directly. Instead, they provide a RuntimeHostDomainModuleDefinition to the factory function createRuntimeHostDomainModule, which constructs the concrete module object.

A definition may include:

  • handlers – One or more groups of operation handlers.
  • recovery – Optional callbacks for each recovery phase.
  • drain – Optional functions executed on beginDrain.
  • close – Optional functions executed on close.
  • releaseConnection – Optional callbacks for connection cleanup.
// Define a domain module (e.g. a "file-system" domain)
const fileSystemModule = createRuntimeHostDomainModule({
  id: 'file-system',
  // Handlers that implement the domain's operations
  handlers: [
    {
      readFile: async ({ path }) => await fs.promises.readFile(path, 'utf8'),
      writeFile: async ({ path, content }) => await fs.promises.writeFile(path, content),
    },
  ],
  // Optional recovery hooks (run on each recovery phase)
  recovery: {
    state: async () => console.log('Restoring file-system state…'),
  },
  // Optional shutdown hooks
  drain: [() => console.log('Draining file-system resources…')],
  close: [async () => console.log('Closing file-system module…')],
});

Operation Handlers and Composition

Individual modules expose their functionality through DomainOperationHandlerMap structures. The Runtime Host aggregates these into a unified dispatch table using composition utilities defined in host-composition.ts. This aggregation enforces uniqueness of operation handlers across all domains, preventing collisions.

// Compose several modules into a single handler map
const networkModule = createRuntimeHostDomainModule({
  id: 'network',
  handlers: [{ fetchUrl: async ({ url }) => fetch(url).then(r => r.text()) }],
});

const allHandlers = composeRuntimeHostDomainHandlers([fileSystemModule, networkModule]);

Once composed, the Runtime Host uses this map to route incoming requests to the appropriate domain implementation, as demonstrated in execution-composition.ts.

// Use the composed handlers inside the Runtime Host
await runtimeHost.handleDomainOperation({
  operation: 'readFile',
  args: { path: '/tmp/example.txt' },
}); // dispatched to `fileSystemModule.handlers.readFile`

Lifecycle Management and Recovery Phases

Apache Maka implements a five-phase recovery protocol to ensure state consistency. When the Runtime Host recovers, it iterates through state, resources, executions, domains, and schedulers, invoking each module’s recover method with the current phase. During shutdown, the host coordinates graceful degradation through drain and close sequences.

// Lifecycle management (recovery → drain → close)
await recoverRuntimeHostDomainModules([fileSystemModule, networkModule]); // runs each phase
beginRuntimeHostDomainModuleDrain([fileSystemModule, networkModule]);  // starts drain
await closeRuntimeHostDomainModules([fileSystemModule, networkModule]); // final cleanup

The drain phase allows asynchronous operations to complete before close terminates resources. If multiple modules fail during close, the host aggregates these errors into a single thrown exception.

Module Composition and Uniqueness Constraints

When composing modules via composeRuntimeHostDomainHandlers, the Runtime Host validates that no two modules share the same id and that operation names remain unique across the aggregated DomainOperationHandlerMap. Violations result in runtime errors during composition rather than during request dispatch.

Unit tests demonstrating these constraints and lifecycle behaviors are available in packages/runtime-host/src/__tests__/host-composition.test.ts, which validates creation, draining, and closing semantics.

Summary

  • A Domain Module in Apache Maka implements the RuntimeHostDomainModule interface defined in host-composition.ts.
  • Modules are created using createRuntimeHostDomainModule from declarative definitions containing handlers and optional lifecycle hooks.
  • The five recovery phases (state, resources, executions, domains, schedulers) enable granular state restoration.
  • Composition utilities merge module handlers into a single DomainOperationHandlerMap while enforcing ID and operation uniqueness.
  • Graceful shutdown proceeds through beginDrain() and close() with aggregated error handling across all domains.

Frequently Asked Questions

What is the primary purpose of a Domain Module in Apache Maka?

A Domain Module encapsulates a logical boundary of functionality within the Runtime Host. It packages operation handlers, state recovery logic, and resource management hooks into a single unit that the host can compose with other domains and manage through a standardized lifecycle.

How does the Runtime Host ensure unique identifiers across Domain Modules?

The host validates every module’s id property against MODULE_ID_PATTERN and checks for collisions during composition. If two modules share the same ID or expose identical operation names in their handler maps, the composition utilities throw an error before the host begins processing requests.

What happens if a Domain Module fails to close properly during shutdown?

The Runtime Host captures all errors that occur during the close() phase across every loaded module. Rather than failing on the first error, it aggregates all close failures and throws a consolidated error after attempting to close every module, ensuring comprehensive cleanup reporting.

Where are the unit tests for Domain Module lifecycle management located?

The unit tests covering module creation, composition, recovery phases, and shutdown sequences reside in packages/runtime-host/src/__tests__/host-composition.test.ts. These tests demonstrate how createRuntimeHostDomainModule and the lifecycle helpers (recoverRuntimeHostDomainModules, beginRuntimeHostDomainModuleDrain, closeRuntimeHostDomainModules) behave under various conditions.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →