Implement Job model and state machine #4

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

Imported from GitHub samson-media/barn#4 — opened by @daniel-samson on 2026-01-21 12:35:56 UTC

Overview

Implement the Job domain model with proper state machine transitions.

Context

  • Read first: docs/jobs.md (job lifecycle), README.md (job fields)
  • Depends on: #3 (filesystem state management)

Requirements

1. Job State Enum

com.samsonmedia.barn.jobs.JobState.java:

public enum JobState {
    QUEUED,     // Created, waiting to run
    RUNNING,    // Currently executing
    SUCCEEDED,  // Completed with exit code 0
    FAILED,     // Completed with non-zero exit or error
    CANCELED;   // Manually stopped
    
    public boolean isTerminal() {
        return this == SUCCEEDED || this == FAILED || this == CANCELED;
    }
}

2. Job Record

com.samsonmedia.barn.jobs.Job.java:

public record Job(
    String id,              // Unique identifier (e.g., "job-9f83c")
    JobState state,
    List<String> command,   // Command and arguments
    String tag,             // Optional user tag
    Instant createdAt,
    Instant startedAt,      // null if not started
    Instant finishedAt,     // null if not finished
    Integer exitCode,       // null if not finished
    String error,           // null if no error
    Long pid,               // OS process ID, null if not started
    Instant heartbeat,      // Last liveness check
    int retryCount,         // Current retry attempt (0-based)
    Instant retryAt         // When to retry, null if not scheduled
) {
    // Compact constructor with validation
    public Job {
        Objects.requireNonNull(id, "id");
        Objects.requireNonNull(state, "state");
        Objects.requireNonNull(command, "command");
        Objects.requireNonNull(createdAt, "createdAt");
        if (command.isEmpty()) {
            throw new IllegalArgumentException("command must not be empty");
        }
    }
}

3. Job ID Generator

com.samsonmedia.barn.jobs.JobIdGenerator.java:

public final class JobIdGenerator {
    // Generate unique ID: "job-" + 5 random hex chars
    public static String generate() {
        // Use SecureRandom for uniqueness
        return "job-" + randomHex(5);
    }
}

4. Job Manifest (Immutable Definition)

com.samsonmedia.barn.jobs.JobManifest.java:

// Written as manifest.json, never modified after creation
public record JobManifest(
    String id,
    List<String> command,
    String tag,
    Instant createdAt,
    // Retry configuration (per-job override)
    int maxRetries,
    int retryDelaySeconds,
    double retryBackoffMultiplier
) { }

5. Job State Machine

com.samsonmedia.barn.jobs.JobStateMachine.java:

public final class JobStateMachine {
    // Valid transitions
    private static final Map<JobState, Set<JobState>> VALID_TRANSITIONS = Map.of(
        JobState.QUEUED, Set.of(JobState.RUNNING, JobState.CANCELED),
        JobState.RUNNING, Set.of(JobState.SUCCEEDED, JobState.FAILED, JobState.CANCELED),
        JobState.FAILED, Set.of(JobState.QUEUED),  // For retry
        JobState.SUCCEEDED, Set.of(),
        JobState.CANCELED, Set.of()
    );
    
    public static void validateTransition(JobState from, JobState to) {
        if (!VALID_TRANSITIONS.get(from).contains(to)) {
            throw new IllegalStateException(
                "Invalid transition: " + from + " -> " + to
            );
        }
    }
    
    // Create state transition record for logging
    public record Transition(JobState from, JobState to, Instant timestamp, String reason) { }
}

6. Job Repository (Filesystem Persistence)

com.samsonmedia.barn.jobs.JobRepository.java:

public class JobRepository {
    private final BarnDirectories dirs;
    private final ObjectMapper json;
    
    // Create new job directory and files
    public Job create(List<String> command, String tag, JobsConfig config);
    
    // Load job from filesystem
    public Optional<Job> findById(String id);
    
    // List all jobs
    public List<Job> findAll();
    
    // Update job state
    public void updateState(String id, JobState state);
    
    // Update heartbeat
    public void updateHeartbeat(String id, Instant timestamp);
    
    // Update on completion
    public void complete(String id, int exitCode, String error);
    
    // Delete job directory
    public void delete(String id);
}

7. Tests Required

  • JobStateTest.java: Test isTerminal(), all state values
  • JobTest.java: Test record validation, builder patterns
  • JobIdGeneratorTest.java: Test uniqueness, format
  • JobStateMachineTest.java: Test all valid transitions, reject invalid
  • JobRepositoryTest.java: Test CRUD operations, filesystem interaction

Acceptance Criteria

  • Job state machine enforces valid transitions only
  • Job IDs are unique and URL-safe
  • JobManifest is immutable after creation
  • JobRepository persists to filesystem correctly
  • All operations are atomic (no corrupt state)
  • mvn verify passes
  • Tests have 80%+ coverage

Implementation Notes

Job ID format: job-[a-f0-9]{5} (e.g., job-9f83c)

Manifest written as JSON:

{
  "id": "job-9f83c",
  "command": ["ffmpeg", "-i", "input.mp4", "output.mp4"],
  "tag": "transcode",
  "createdAt": "2026-01-21T18:40:01Z",
  "maxRetries": 3,
  "retryDelaySeconds": 30,
  "retryBackoffMultiplier": 2.0
}

Definition of Done

  • Job model complete with all fields
  • State machine enforces valid transitions
  • Repository reads/writes filesystem correctly
  • All tests pass
<!-- github-import:issue:4 --> _Imported from GitHub samson-media/barn#4 — opened by **@daniel-samson** on 2026-01-21 12:35:56 UTC_ ## Overview Implement the Job domain model with proper state machine transitions. ## Context - **Read first**: `docs/jobs.md` (job lifecycle), `README.md` (job fields) - **Depends on**: #3 (filesystem state management) ## Requirements ### 1. Job State Enum `com.samsonmedia.barn.jobs.JobState.java`: ```java public enum JobState { QUEUED, // Created, waiting to run RUNNING, // Currently executing SUCCEEDED, // Completed with exit code 0 FAILED, // Completed with non-zero exit or error CANCELED; // Manually stopped public boolean isTerminal() { return this == SUCCEEDED || this == FAILED || this == CANCELED; } } ``` ### 2. Job Record `com.samsonmedia.barn.jobs.Job.java`: ```java public record Job( String id, // Unique identifier (e.g., "job-9f83c") JobState state, List<String> command, // Command and arguments String tag, // Optional user tag Instant createdAt, Instant startedAt, // null if not started Instant finishedAt, // null if not finished Integer exitCode, // null if not finished String error, // null if no error Long pid, // OS process ID, null if not started Instant heartbeat, // Last liveness check int retryCount, // Current retry attempt (0-based) Instant retryAt // When to retry, null if not scheduled ) { // Compact constructor with validation public Job { Objects.requireNonNull(id, "id"); Objects.requireNonNull(state, "state"); Objects.requireNonNull(command, "command"); Objects.requireNonNull(createdAt, "createdAt"); if (command.isEmpty()) { throw new IllegalArgumentException("command must not be empty"); } } } ``` ### 3. Job ID Generator `com.samsonmedia.barn.jobs.JobIdGenerator.java`: ```java public final class JobIdGenerator { // Generate unique ID: "job-" + 5 random hex chars public static String generate() { // Use SecureRandom for uniqueness return "job-" + randomHex(5); } } ``` ### 4. Job Manifest (Immutable Definition) `com.samsonmedia.barn.jobs.JobManifest.java`: ```java // Written as manifest.json, never modified after creation public record JobManifest( String id, List<String> command, String tag, Instant createdAt, // Retry configuration (per-job override) int maxRetries, int retryDelaySeconds, double retryBackoffMultiplier ) { } ``` ### 5. Job State Machine `com.samsonmedia.barn.jobs.JobStateMachine.java`: ```java public final class JobStateMachine { // Valid transitions private static final Map<JobState, Set<JobState>> VALID_TRANSITIONS = Map.of( JobState.QUEUED, Set.of(JobState.RUNNING, JobState.CANCELED), JobState.RUNNING, Set.of(JobState.SUCCEEDED, JobState.FAILED, JobState.CANCELED), JobState.FAILED, Set.of(JobState.QUEUED), // For retry JobState.SUCCEEDED, Set.of(), JobState.CANCELED, Set.of() ); public static void validateTransition(JobState from, JobState to) { if (!VALID_TRANSITIONS.get(from).contains(to)) { throw new IllegalStateException( "Invalid transition: " + from + " -> " + to ); } } // Create state transition record for logging public record Transition(JobState from, JobState to, Instant timestamp, String reason) { } } ``` ### 6. Job Repository (Filesystem Persistence) `com.samsonmedia.barn.jobs.JobRepository.java`: ```java public class JobRepository { private final BarnDirectories dirs; private final ObjectMapper json; // Create new job directory and files public Job create(List<String> command, String tag, JobsConfig config); // Load job from filesystem public Optional<Job> findById(String id); // List all jobs public List<Job> findAll(); // Update job state public void updateState(String id, JobState state); // Update heartbeat public void updateHeartbeat(String id, Instant timestamp); // Update on completion public void complete(String id, int exitCode, String error); // Delete job directory public void delete(String id); } ``` ### 7. Tests Required - `JobStateTest.java`: Test isTerminal(), all state values - `JobTest.java`: Test record validation, builder patterns - `JobIdGeneratorTest.java`: Test uniqueness, format - `JobStateMachineTest.java`: Test all valid transitions, reject invalid - `JobRepositoryTest.java`: Test CRUD operations, filesystem interaction ## Acceptance Criteria - [ ] Job state machine enforces valid transitions only - [ ] Job IDs are unique and URL-safe - [ ] JobManifest is immutable after creation - [ ] JobRepository persists to filesystem correctly - [ ] All operations are atomic (no corrupt state) - [ ] `mvn verify` passes - [ ] Tests have 80%+ coverage ## Implementation Notes Job ID format: `job-[a-f0-9]{5}` (e.g., `job-9f83c`) Manifest written as JSON: ```json { "id": "job-9f83c", "command": ["ffmpeg", "-i", "input.mp4", "output.mp4"], "tag": "transcode", "createdAt": "2026-01-21T18:40:01Z", "maxRetries": 3, "retryDelaySeconds": 30, "retryBackoffMultiplier": 2.0 } ``` ## Definition of Done - Job model complete with all fields - State machine enforces valid transitions - Repository reads/writes filesystem correctly - All tests pass
daniel added this to the M1: Foundation milestone 2026-10-04 19:27:56 +00:00
daniel added the foundation label 2026-10-04 19:27:56 +00:00
Author
Owner

@daniel-samson commented on 2026-01-21 13:15:31 UTC:

Implemented in commit c6e26bb:

Implementation complete:

  • Job record with full lifecycle methods
  • JobIdGenerator for unique 8-hex character IDs
  • JobManifest for immutable configuration
  • JobStateMachine for state transition validation
  • JobRepository for filesystem persistence

Test coverage: 87 new tests, 298 total tests passing

<!-- github-import:comment:3778086085 --> _**@daniel-samson** commented on 2026-01-21 13:15:31 UTC:_ Implemented in commit c6e26bb: **Implementation complete:** - Job record with full lifecycle methods - JobIdGenerator for unique 8-hex character IDs - JobManifest for immutable configuration - JobStateMachine for state transition validation - JobRepository for filesystem persistence **Test coverage:** 87 new tests, 298 total tests passing
This repo is archived. You cannot comment on issues.