publicenumJobState{QUEUED,// Created, waiting to runRUNNING,// Currently executingSUCCEEDED,// Completed with exit code 0FAILED,// Completed with non-zero exit or errorCANCELED;// Manually stoppedpublicbooleanisTerminal(){returnthis==SUCCEEDED||this==FAILED||this==CANCELED;}}
2. Job Record
com.samsonmedia.barn.jobs.Job.java:
publicrecordJob(Stringid,// Unique identifier (e.g., "job-9f83c")JobStatestate,List<String>command,// Command and argumentsStringtag,// Optional user tagInstantcreatedAt,InstantstartedAt,// null if not startedInstantfinishedAt,// null if not finishedIntegerexitCode,// null if not finishedStringerror,// null if no errorLongpid,// OS process ID, null if not startedInstantheartbeat,// Last liveness checkintretryCount,// Current retry attempt (0-based)InstantretryAt// When to retry, null if not scheduled){// Compact constructor with validationpublicJob{Objects.requireNonNull(id,"id");Objects.requireNonNull(state,"state");Objects.requireNonNull(command,"command");Objects.requireNonNull(createdAt,"createdAt");if(command.isEmpty()){thrownewIllegalArgumentException("command must not be empty");}}}
3. Job ID Generator
com.samsonmedia.barn.jobs.JobIdGenerator.java:
publicfinalclassJobIdGenerator{// Generate unique ID: "job-" + 5 random hex charspublicstaticStringgenerate(){// Use SecureRandom for uniquenessreturn"job-"+randomHex(5);}}
4. Job Manifest (Immutable Definition)
com.samsonmedia.barn.jobs.JobManifest.java:
// Written as manifest.json, never modified after creationpublicrecordJobManifest(Stringid,List<String>command,Stringtag,InstantcreatedAt,// Retry configuration (per-job override)intmaxRetries,intretryDelaySeconds,doubleretryBackoffMultiplier){}
5. Job State Machine
com.samsonmedia.barn.jobs.JobStateMachine.java:
publicfinalclassJobStateMachine{// Valid transitionsprivatestaticfinalMap<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 retryJobState.SUCCEEDED,Set.of(),JobState.CANCELED,Set.of());publicstaticvoidvalidateTransition(JobStatefrom,JobStateto){if(!VALID_TRANSITIONS.get(from).contains(to)){thrownewIllegalStateException("Invalid transition: "+from+" -> "+to);}}// Create state transition record for loggingpublicrecordTransition(JobStatefrom,JobStateto,Instanttimestamp,Stringreason){}}
6. Job Repository (Filesystem Persistence)
com.samsonmedia.barn.jobs.JobRepository.java:
publicclassJobRepository{privatefinalBarnDirectoriesdirs;privatefinalObjectMapperjson;// Create new job directory and filespublicJobcreate(List<String>command,Stringtag,JobsConfigconfig);// Load job from filesystempublicOptional<Job>findById(Stringid);// List all jobspublicList<Job>findAll();// Update job statepublicvoidupdateState(Stringid,JobStatestate);// Update heartbeatpublicvoidupdateHeartbeat(Stringid,Instanttimestamp);// Update on completionpublicvoidcomplete(Stringid,intexitCode,Stringerror);// Delete job directorypublicvoiddelete(Stringid);}
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
<!-- 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
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
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.
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
docs/jobs.md(job lifecycle),README.md(job fields)Requirements
1. Job State Enum
com.samsonmedia.barn.jobs.JobState.java:2. Job Record
com.samsonmedia.barn.jobs.Job.java:3. Job ID Generator
com.samsonmedia.barn.jobs.JobIdGenerator.java:4. Job Manifest (Immutable Definition)
com.samsonmedia.barn.jobs.JobManifest.java:5. Job State Machine
com.samsonmedia.barn.jobs.JobStateMachine.java:6. Job Repository (Filesystem Persistence)
com.samsonmedia.barn.jobs.JobRepository.java:7. Tests Required
JobStateTest.java: Test isTerminal(), all state valuesJobTest.java: Test record validation, builder patternsJobIdGeneratorTest.java: Test uniqueness, formatJobStateMachineTest.java: Test all valid transitions, reject invalidJobRepositoryTest.java: Test CRUD operations, filesystem interactionAcceptance Criteria
mvn verifypassesImplementation Notes
Job ID format:
job-[a-f0-9]{5}(e.g.,job-9f83c)Manifest written as JSON:
Definition of Done
@daniel-samson commented on 2026-01-21 13:15:31 UTC:
Implemented in commit
c6e26bb:Implementation complete:
Test coverage: 87 new tests, 298 total tests passing