Implement IPC mechanism (CLI-to-service communication) #14

Closed
opened 2026-10-04 19:28:13 +00:00 by daniel · 1 comment
Owner

Imported from GitHub samson-media/barn#14 — opened by @daniel-samson on 2026-01-21 12:40:15 UTC

Overview

Implement the IPC (Inter-Process Communication) mechanism for CLI-to-service communication.

Context

  • Read first: docs/config.md (ipc_socket setting)
  • Depends on: #2 (configuration)

Requirements

1. IPC Protocol

Simple JSON-over-Unix-socket protocol (Windows uses named pipes).

Request format:

{
  "type": "run_job",
  "payload": {
    "command": ["echo", "hello"],
    "tag": "test"
  }
}

Response format:

{
  "status": "ok",
  "payload": {
    "job_id": "job-9f83c"
  }
}

Error response:

{
  "status": "error",
  "error": {
    "code": "JOB_NOT_FOUND",
    "message": "Job not found: job-xyz"
  }
}

2. Request Types

public sealed interface IpcRequest {
    record RunJob(List<String> command, String tag, JobOptions options) implements IpcRequest {}
    record GetStatus(StatusFilter filter) implements IpcRequest {}
    record GetJob(String jobId) implements IpcRequest {}
    record KillJob(String jobId, boolean force) implements IpcRequest {}
    record CleanJobs(CleanOptions options) implements IpcRequest {}
    record GetServiceStatus() implements IpcRequest {}
    record Shutdown() implements IpcRequest {}
    record Reload() implements IpcRequest {}
}

3. Response Types

public sealed interface IpcResponse {
    record Ok<T>(T payload) implements IpcResponse {}
    record Error(String code, String message) implements IpcResponse {}
}

4. IPC Server (Service Side)

com.samsonmedia.barn.ipc.IpcServer.java:

public class IpcServer {
    private final Path socketPath;
    private final RequestHandler handler;

    public void start();
    public void stop();

    // Handle incoming connections
    private void handleConnection(SocketChannel channel) {
        IpcRequest request = readRequest(channel);
        IpcResponse response = handler.handle(request);
        writeResponse(channel, response);
    }
}

5. IPC Client (CLI Side)

com.samsonmedia.barn.ipc.IpcClient.java:

public class IpcClient implements AutoCloseable {
    private final Path socketPath;

    public IpcClient(Path socketPath) {
        this.socketPath = socketPath;
    }

    public <T> T send(IpcRequest request, Class<T> responseType) throws IpcException {
        // 1. Connect to socket
        // 2. Send request JSON
        // 3. Read response JSON
        // 4. Parse and return
    }

    public void ensureConnected() throws IpcException {
        // Verify service is running
    }
}

6. Platform-Specific Socket Paths

public static Path getDefaultSocketPath() {
    return switch (OS.current()) {
        case LINUX, MACOS -> Path.of("/tmp/barn/barn.sock");
        case WINDOWS -> Path.of("\\\\.\\pipe\\barn");
    };
}

7. Error Codes

Code Description
SERVICE_NOT_RUNNING Service is not running
JOB_NOT_FOUND Job ID doesn't exist
INVALID_REQUEST Malformed request
INTERNAL_ERROR Unexpected server error
JOB_NOT_RUNNING Job is not in running state

8. Tests Required

  • IpcServerTest.java: Test request handling, error responses
  • IpcClientTest.java: Test connection, request/response cycle
  • IpcProtocolTest.java: Test JSON serialization
  • Integration test: Full client-server round trip

Acceptance Criteria

  • Unix socket works on Linux/macOS
  • Named pipe works on Windows
  • All request types handled
  • Error responses are clear
  • Connection timeout handles missing service
  • Concurrent requests don't corrupt state
  • mvn verify passes
  • Tests have 80%+ coverage

Implementation Notes

Unix socket in Java:

UnixDomainSocketAddress address = UnixDomainSocketAddress.of(socketPath);
ServerSocketChannel server = ServerSocketChannel.open(StandardProtocolFamily.UNIX);
server.bind(address);

Named pipe on Windows (requires JNI or library):

// Consider using a cross-platform library or
// fall back to TCP localhost for Windows

For simplicity, consider TCP localhost as fallback:

  • Linux/macOS: Unix socket preferred, TCP localhost fallback
  • Windows: TCP localhost (named pipes need JNI)

Definition of Done

  • IPC works on all platforms
  • All request types implemented
  • Error handling is robust
  • All tests pass
<!-- github-import:issue:14 --> _Imported from GitHub samson-media/barn#14 — opened by **@daniel-samson** on 2026-01-21 12:40:15 UTC_ ## Overview Implement the IPC (Inter-Process Communication) mechanism for CLI-to-service communication. ## Context - **Read first**: `docs/config.md` (ipc_socket setting) - **Depends on**: #2 (configuration) ## Requirements ### 1. IPC Protocol Simple JSON-over-Unix-socket protocol (Windows uses named pipes). Request format: ```json { "type": "run_job", "payload": { "command": ["echo", "hello"], "tag": "test" } } ``` Response format: ```json { "status": "ok", "payload": { "job_id": "job-9f83c" } } ``` Error response: ```json { "status": "error", "error": { "code": "JOB_NOT_FOUND", "message": "Job not found: job-xyz" } } ``` ### 2. Request Types ```java public sealed interface IpcRequest { record RunJob(List<String> command, String tag, JobOptions options) implements IpcRequest {} record GetStatus(StatusFilter filter) implements IpcRequest {} record GetJob(String jobId) implements IpcRequest {} record KillJob(String jobId, boolean force) implements IpcRequest {} record CleanJobs(CleanOptions options) implements IpcRequest {} record GetServiceStatus() implements IpcRequest {} record Shutdown() implements IpcRequest {} record Reload() implements IpcRequest {} } ``` ### 3. Response Types ```java public sealed interface IpcResponse { record Ok<T>(T payload) implements IpcResponse {} record Error(String code, String message) implements IpcResponse {} } ``` ### 4. IPC Server (Service Side) `com.samsonmedia.barn.ipc.IpcServer.java`: ```java public class IpcServer { private final Path socketPath; private final RequestHandler handler; public void start(); public void stop(); // Handle incoming connections private void handleConnection(SocketChannel channel) { IpcRequest request = readRequest(channel); IpcResponse response = handler.handle(request); writeResponse(channel, response); } } ``` ### 5. IPC Client (CLI Side) `com.samsonmedia.barn.ipc.IpcClient.java`: ```java public class IpcClient implements AutoCloseable { private final Path socketPath; public IpcClient(Path socketPath) { this.socketPath = socketPath; } public <T> T send(IpcRequest request, Class<T> responseType) throws IpcException { // 1. Connect to socket // 2. Send request JSON // 3. Read response JSON // 4. Parse and return } public void ensureConnected() throws IpcException { // Verify service is running } } ``` ### 6. Platform-Specific Socket Paths ```java public static Path getDefaultSocketPath() { return switch (OS.current()) { case LINUX, MACOS -> Path.of("/tmp/barn/barn.sock"); case WINDOWS -> Path.of("\\\\.\\pipe\\barn"); }; } ``` ### 7. Error Codes | Code | Description | |------|-------------| | SERVICE_NOT_RUNNING | Service is not running | | JOB_NOT_FOUND | Job ID doesn't exist | | INVALID_REQUEST | Malformed request | | INTERNAL_ERROR | Unexpected server error | | JOB_NOT_RUNNING | Job is not in running state | ### 8. Tests Required - `IpcServerTest.java`: Test request handling, error responses - `IpcClientTest.java`: Test connection, request/response cycle - `IpcProtocolTest.java`: Test JSON serialization - Integration test: Full client-server round trip ## Acceptance Criteria - [ ] Unix socket works on Linux/macOS - [ ] Named pipe works on Windows - [ ] All request types handled - [ ] Error responses are clear - [ ] Connection timeout handles missing service - [ ] Concurrent requests don't corrupt state - [ ] `mvn verify` passes - [ ] Tests have 80%+ coverage ## Implementation Notes Unix socket in Java: ```java UnixDomainSocketAddress address = UnixDomainSocketAddress.of(socketPath); ServerSocketChannel server = ServerSocketChannel.open(StandardProtocolFamily.UNIX); server.bind(address); ``` Named pipe on Windows (requires JNI or library): ```java // Consider using a cross-platform library or // fall back to TCP localhost for Windows ``` For simplicity, consider TCP localhost as fallback: - Linux/macOS: Unix socket preferred, TCP localhost fallback - Windows: TCP localhost (named pipes need JNI) ## Definition of Done - IPC works on all platforms - All request types implemented - Error handling is robust - All tests pass
daniel added this to the M4: Service Infrastructure milestone 2026-10-04 19:28:13 +00:00
daniel added the service label 2026-10-04 19:28:13 +00:00
Author
Owner

@daniel-samson commented on 2026-01-21 14:29:23 UTC:

Implemented IPC mechanism with tests

<!-- github-import:comment:3778429356 --> _**@daniel-samson** commented on 2026-01-21 14:29:23 UTC:_ Implemented IPC mechanism with tests
This repo is archived. You cannot comment on issues.