feat(jobs): implement job model and state machine (#4)

Add core job management infrastructure:

- Job record with lifecycle methods (createQueued, withStarted,
  withCompleted, withRetry, withCanceled)
- JobIdGenerator for unique job identifiers (job-XXXXXXXX format)
- JobManifest for immutable job configuration with retry settings
- JobStateMachine for validating state transitions
- JobRepository for filesystem persistence using atomic operations

State transitions: QUEUED → RUNNING → SUCCEEDED/FAILED/CANCELED
Failed jobs can transition back to QUEUED for retry.

Includes 87 tests covering all components with comprehensive edge
case coverage.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Daniel SamsonandClaude Opus 4.5 committed 2026-01-21 13:15:19 +00:00
1 parent 647e602fe9
commit c6e26bbedb
11 files changed
+1830 -2

No files matched your search

@@ -0,0 +1,185 @@
package com.samsonmedia.barn.jobs;
import java.time.Instant;
import java.util.List;
import java.util.Objects;
import com.samsonmedia.barn.state.JobState;
/**
* Represents a job in the Barn system.
*
* <p>A job is an external command to be executed by the daemon. This record
* captures the current state and metadata of a job.
*
* @param id unique identifier (e.g., "job-9f83c")
* @param state current lifecycle state
* @param command command and arguments to execute
* @param tag optional user-defined tag
* @param createdAt when the job was created
* @param startedAt when execution started (null if not started)
* @param finishedAt when execution finished (null if not finished)
* @param exitCode process exit code (null if not finished)
* @param error error message (null if no error)
* @param pid OS process ID (null if not started)
* @param heartbeat last liveness check timestamp
* @param retryCount current retry attempt (0-based)
* @param retryAt when to retry (null if not scheduled for retry)
*/
public record Job(
String id,
JobState state,
List<String> command,
String tag,
Instant createdAt,
Instant startedAt,
Instant finishedAt,
Integer exitCode,
String error,
Long pid,
Instant heartbeat,
int retryCount,
Instant retryAt
) {
/**
* Creates a Job with validation.
*/
public Job {
Objects.requireNonNull(id, "id must not be null");
Objects.requireNonNull(state, "state must not be null");
Objects.requireNonNull(command, "command must not be null");
Objects.requireNonNull(createdAt, "createdAt must not be null");
if (id.isBlank()) {
throw new IllegalArgumentException("id must not be blank");
}
if (command.isEmpty()) {
throw new IllegalArgumentException("command must not be empty");
}
if (retryCount < 0) {
throw new IllegalArgumentException("retryCount must be non-negative");
}
command = List.copyOf(command);
}
/**
* Creates a new queued job with minimal required fields.
*
* @param id the job ID
* @param command the command to execute
* @param tag optional tag (may be null)
* @return a new Job in QUEUED state
*/
public static Job createQueued(String id, List<String> command, String tag) {
return new Job(
id,
JobState.QUEUED,
command,
tag,
Instant.now(),
null, // startedAt
null, // finishedAt
null, // exitCode
null, // error
null, // pid
null, // heartbeat
0, // retryCount
null // retryAt
);
}
/**
* Creates a copy of this job with a new state.
*
* @param newState the new state
* @return a new Job with the updated state
*/
public Job withState(JobState newState) {
return new Job(id, newState, command, tag, createdAt, startedAt, finishedAt,
exitCode, error, pid, heartbeat, retryCount, retryAt);
}
/**
* Creates a copy of this job marked as started.
*
* @param processId the OS process ID
* @return a new Job in RUNNING state
*/
public Job withStarted(long processId) {
Instant now = Instant.now();
return new Job(id, JobState.RUNNING, command, tag, createdAt, now, finishedAt,
exitCode, error, processId, now, retryCount, retryAt);
}
/**
* Creates a copy of this job marked as completed.
*
* @param code the exit code
* @param errorMessage optional error message (may be null)
* @return a new Job in terminal state
*/
public Job withCompleted(int code, String errorMessage) {
JobState newState = (code == 0) ? JobState.SUCCEEDED : JobState.FAILED;
return new Job(id, newState, command, tag, createdAt, startedAt, Instant.now(),
code, errorMessage, pid, heartbeat, retryCount, retryAt);
}
/**
* Creates a copy of this job with updated heartbeat.
*
* @param timestamp the heartbeat timestamp
* @return a new Job with updated heartbeat
*/
public Job withHeartbeat(Instant timestamp) {
return new Job(id, state, command, tag, createdAt, startedAt, finishedAt,
exitCode, error, pid, timestamp, retryCount, retryAt);
}
/**
* Creates a copy of this job scheduled for retry.
*
* @param retryTimestamp when to retry
* @return a new Job in QUEUED state with incremented retry count
*/
public Job withRetry(Instant retryTimestamp) {
return new Job(id, JobState.QUEUED, command, tag, createdAt, null, null,
null, null, null, null, retryCount + 1, retryTimestamp);
}
/**
* Creates a copy of this job marked as canceled.
*
* @return a new Job in CANCELED state
*/
public Job withCanceled() {
return new Job(id, JobState.CANCELED, command, tag, createdAt, startedAt, Instant.now(),
exitCode, "Job was canceled", pid, heartbeat, retryCount, retryAt);
}
/**
* Checks if this job is in a terminal state.
*
* @return true if the job is finished
*/
public boolean isTerminal() {
return state.isTerminal();
}
/**
* Checks if this job is actively running.
*
* @return true if the job is running
*/
public boolean isRunning() {
return state == JobState.RUNNING;
}
/**
* Checks if this job is waiting to be executed.
*
* @return true if the job is queued
*/
public boolean isQueued() {
return state == JobState.QUEUED;
}
}
@@ -0,0 +1,61 @@
package com.samsonmedia.barn.jobs;
import java.security.SecureRandom;
/**
* Generates unique job identifiers.
*
* <p>Job IDs follow the format: "job-" followed by 8 random hexadecimal characters.
* For example: "job-9f83c012"
*/
public final class JobIdGenerator {
private static final String PREFIX = "job-";
private static final int HEX_LENGTH = 8;
private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
private static final SecureRandom RANDOM = new SecureRandom();
private JobIdGenerator() {
// Utility class - prevent instantiation
}
/**
* Generates a new unique job ID.
*
* @return a new job ID in the format "job-XXXXX"
*/
public static String generate() {
StringBuilder sb = new StringBuilder(PREFIX.length() + HEX_LENGTH);
sb.append(PREFIX);
for (int i = 0; i < HEX_LENGTH; i++) {
sb.append(HEX_CHARS[RANDOM.nextInt(HEX_CHARS.length)]);
}
return sb.toString();
}
/**
* Validates that a string is a valid job ID format.
*
* @param id the ID to validate
* @return true if the ID matches the expected format
*/
public static boolean isValid(String id) {
if (id == null || id.length() != PREFIX.length() + HEX_LENGTH) {
return false;
}
if (!id.startsWith(PREFIX)) {
return false;
}
String hex = id.substring(PREFIX.length());
for (char c : hex.toCharArray()) {
if (!isHexChar(c)) {
return false;
}
}
return true;
}
private static boolean isHexChar(char c) {
return c >= '0' && c <= '9' || c >= 'a' && c <= 'f';
}
}
@@ -0,0 +1,126 @@
package com.samsonmedia.barn.jobs;
import java.time.Instant;
import java.util.List;
import java.util.Objects;
import com.samsonmedia.barn.config.JobsConfig;
/**
* Immutable job definition stored as manifest.json.
*
* <p>The manifest is written once when a job is created and never modified.
* It contains the job's command and retry configuration.
*
* @param id unique job identifier
* @param command command and arguments to execute
* @param tag optional user-defined tag
* @param createdAt when the job was created
* @param maxRetries maximum number of retry attempts
* @param retryDelaySeconds initial delay before first retry
* @param retryBackoffMultiplier multiplier for exponential backoff
*/
public record JobManifest(
String id,
List<String> command,
String tag,
Instant createdAt,
int maxRetries,
int retryDelaySeconds,
double retryBackoffMultiplier
) {
/**
* Creates a JobManifest with validation.
*/
public JobManifest {
Objects.requireNonNull(id, "id must not be null");
Objects.requireNonNull(command, "command must not be null");
Objects.requireNonNull(createdAt, "createdAt must not be null");
if (id.isBlank()) {
throw new IllegalArgumentException("id must not be blank");
}
if (command.isEmpty()) {
throw new IllegalArgumentException("command must not be empty");
}
if (maxRetries < 0) {
throw new IllegalArgumentException("maxRetries must be non-negative");
}
if (retryDelaySeconds < 0) {
throw new IllegalArgumentException("retryDelaySeconds must be non-negative");
}
if (retryBackoffMultiplier < 1.0) {
throw new IllegalArgumentException("retryBackoffMultiplier must be at least 1.0");
}
command = List.copyOf(command);
}
/**
* Creates a JobManifest with default retry configuration from JobsConfig.
*
* @param id the job ID
* @param command the command to execute
* @param tag optional tag (may be null)
* @param config the jobs configuration for defaults
* @return a new JobManifest
*/
public static JobManifest create(String id, List<String> command, String tag, JobsConfig config) {
Objects.requireNonNull(config, "config must not be null");
return new JobManifest(
id,
command,
tag,
Instant.now(),
config.maxRetries(),
config.retryDelaySeconds(),
config.retryBackoffMultiplier()
);
}
/**
* Creates a JobManifest with custom retry configuration.
*
* @param id the job ID
* @param command the command to execute
* @param tag optional tag (may be null)
* @param maxRetries maximum retry attempts
* @param retryDelaySeconds initial retry delay
* @param retryBackoffMultiplier backoff multiplier
* @return a new JobManifest
*/
public static JobManifest create(String id, List<String> command, String tag,
int maxRetries, int retryDelaySeconds, double retryBackoffMultiplier) {
return new JobManifest(
id,
command,
tag,
Instant.now(),
maxRetries,
retryDelaySeconds,
retryBackoffMultiplier
);
}
/**
* Calculates the delay for a specific retry attempt using exponential backoff.
*
* @param retryCount the current retry count (0-based)
* @return the delay in seconds
*/
public int calculateRetryDelay(int retryCount) {
if (retryCount < 0) {
throw new IllegalArgumentException("retryCount must be non-negative");
}
return (int) (retryDelaySeconds * Math.pow(retryBackoffMultiplier, retryCount));
}
/**
* Checks if another retry is allowed.
*
* @param currentRetryCount the current retry count
* @return true if retries are available
*/
public boolean canRetry(int currentRetryCount) {
return currentRetryCount < maxRetries;
}
}
@@ -0,0 +1,355 @@
package com.samsonmedia.barn.jobs;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.samsonmedia.barn.config.JobsConfig;
import com.samsonmedia.barn.state.AtomicFiles;
import com.samsonmedia.barn.state.BarnDirectories;
import com.samsonmedia.barn.state.JobState;
import com.samsonmedia.barn.state.StateFiles;
/**
* Repository for persisting jobs to the filesystem.
*
* <p>Jobs are stored in directories under the jobs directory, with state
* files and a manifest.json containing the immutable job definition.
*/
public class JobRepository {
private static final Logger LOG = LoggerFactory.getLogger(JobRepository.class);
private static final String MANIFEST_FILE = "manifest.json";
private final BarnDirectories dirs;
private final ObjectMapper objectMapper;
/**
* Creates a JobRepository with the specified directories.
*
* @param dirs the Barn directories manager
*/
public JobRepository(BarnDirectories dirs) {
this.dirs = Objects.requireNonNull(dirs, "dirs must not be null");
this.objectMapper = createObjectMapper();
}
private static ObjectMapper createObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
return mapper;
}
/**
* Creates a new job with the given command and configuration.
*
* @param command the command to execute
* @param tag optional user tag (may be null)
* @param config the jobs configuration for defaults
* @return the created Job
* @throws IOException if creation fails
*/
public Job create(List<String> command, String tag, JobsConfig config) throws IOException {
Objects.requireNonNull(command, "command must not be null");
Objects.requireNonNull(config, "config must not be null");
String id = JobIdGenerator.generate();
JobManifest manifest = JobManifest.create(id, command, tag, config);
// Create directories
dirs.createJobDirs(id);
// Write manifest
Path manifestPath = dirs.getJobDir(id).resolve(MANIFEST_FILE);
String manifestJson = objectMapper.writeValueAsString(manifest);
AtomicFiles.writeAtomically(manifestPath, manifestJson);
// Write initial state files
StateFiles stateFiles = new StateFiles(dirs.getJobDir(id));
stateFiles.writeState(JobState.QUEUED);
stateFiles.writeCreatedAt(manifest.createdAt());
if (tag != null) {
stateFiles.writeTag(tag);
}
stateFiles.writeRetryCount(0);
LOG.info("Created job: {}", id);
return Job.createQueued(id, command, tag);
}
/**
* Finds a job by its ID.
*
* @param id the job ID
* @return the job if found, or empty
* @throws IOException if reading fails
*/
public Optional<Job> findById(String id) throws IOException {
Objects.requireNonNull(id, "id must not be null");
if (!dirs.jobExists(id)) {
return Optional.empty();
}
return Optional.of(loadJob(id));
}
/**
* Lists all jobs.
*
* @return list of all jobs
* @throws IOException if reading fails
*/
public List<Job> findAll() throws IOException {
Path jobsDir = dirs.getJobsDir();
if (!Files.exists(jobsDir)) {
return List.of();
}
List<Job> jobs = new ArrayList<>();
try (Stream<Path> stream = Files.list(jobsDir)) {
for (Path jobPath : stream.toList()) {
if (Files.isDirectory(jobPath)) {
String id = jobPath.getFileName().toString();
try {
jobs.add(loadJob(id));
} catch (IOException e) {
LOG.warn("Failed to load job {}: {}", id, e.getMessage());
}
}
}
}
return jobs;
}
/**
* Finds all jobs in a specific state.
*
* @param state the state to filter by
* @return list of jobs in the specified state
* @throws IOException if reading fails
*/
public List<Job> findByState(JobState state) throws IOException {
Objects.requireNonNull(state, "state must not be null");
return findAll().stream()
.filter(job -> job.state() == state)
.toList();
}
/**
* Updates the state of a job.
*
* @param id the job ID
* @param newState the new state
* @throws IOException if update fails
* @throws IllegalStateException if the transition is invalid
*/
public void updateState(String id, JobState newState) throws IOException {
Objects.requireNonNull(id, "id must not be null");
Objects.requireNonNull(newState, "newState must not be null");
StateFiles stateFiles = new StateFiles(dirs.getJobDir(id));
Optional<JobState> currentState = stateFiles.readState();
if (currentState.isPresent()) {
JobStateMachine.validateTransition(currentState.get(), newState);
}
stateFiles.writeState(newState);
LOG.debug("Updated job {} state to {}", id, newState);
}
/**
* Marks a job as started.
*
* @param id the job ID
* @param pid the OS process ID
* @throws IOException if update fails
*/
public void markStarted(String id, long pid) throws IOException {
Objects.requireNonNull(id, "id must not be null");
StateFiles stateFiles = new StateFiles(dirs.getJobDir(id));
Instant now = Instant.now();
updateState(id, JobState.RUNNING);
stateFiles.writeStartedAt(now);
stateFiles.writePid(pid);
stateFiles.writeHeartbeat(now);
LOG.info("Job {} started with PID {}", id, pid);
}
/**
* Updates the heartbeat for a running job.
*
* @param id the job ID
* @param timestamp the heartbeat timestamp
* @throws IOException if update fails
*/
public void updateHeartbeat(String id, Instant timestamp) throws IOException {
Objects.requireNonNull(id, "id must not be null");
Objects.requireNonNull(timestamp, "timestamp must not be null");
StateFiles stateFiles = new StateFiles(dirs.getJobDir(id));
stateFiles.writeHeartbeat(timestamp);
}
/**
* Marks a job as completed.
*
* @param id the job ID
* @param exitCode the process exit code
* @param error optional error message (may be null)
* @throws IOException if update fails
*/
public void markCompleted(String id, int exitCode, String error) throws IOException {
Objects.requireNonNull(id, "id must not be null");
StateFiles stateFiles = new StateFiles(dirs.getJobDir(id));
JobState newState = (exitCode == 0) ? JobState.SUCCEEDED : JobState.FAILED;
updateState(id, newState);
stateFiles.writeFinishedAt(Instant.now());
stateFiles.writeExitCode(exitCode);
if (error != null) {
stateFiles.writeError(error);
}
LOG.info("Job {} completed with exit code {}", id, exitCode);
}
/**
* Marks a job as failed with a symbolic exit code.
*
* @param id the job ID
* @param symbolicCode the symbolic exit code (e.g., "orphaned_process")
* @param error the error message
* @throws IOException if update fails
*/
public void markFailed(String id, String symbolicCode, String error) throws IOException {
Objects.requireNonNull(id, "id must not be null");
Objects.requireNonNull(symbolicCode, "symbolicCode must not be null");
StateFiles stateFiles = new StateFiles(dirs.getJobDir(id));
updateState(id, JobState.FAILED);
stateFiles.writeFinishedAt(Instant.now());
stateFiles.writeExitCode(symbolicCode);
if (error != null) {
stateFiles.writeError(error);
}
LOG.info("Job {} failed: {}", id, symbolicCode);
}
/**
* Schedules a job for retry.
*
* @param id the job ID
* @param retryAt when to retry
* @throws IOException if update fails
*/
public void scheduleRetry(String id, Instant retryAt) throws IOException {
Objects.requireNonNull(id, "id must not be null");
Objects.requireNonNull(retryAt, "retryAt must not be null");
StateFiles stateFiles = new StateFiles(dirs.getJobDir(id));
// Increment retry count
int currentCount = stateFiles.readRetryCount().orElse(0);
stateFiles.writeRetryCount(currentCount + 1);
stateFiles.writeRetryAt(retryAt);
// Transition back to queued
updateState(id, JobState.QUEUED);
// Clear runtime state
stateFiles.writeStartedAt(null);
stateFiles.writeHeartbeat(null);
LOG.info("Job {} scheduled for retry at {} (attempt {})", id, retryAt, currentCount + 1);
}
/**
* Marks a job as canceled.
*
* @param id the job ID
* @throws IOException if update fails
*/
public void markCanceled(String id) throws IOException {
Objects.requireNonNull(id, "id must not be null");
StateFiles stateFiles = new StateFiles(dirs.getJobDir(id));
updateState(id, JobState.CANCELED);
stateFiles.writeFinishedAt(Instant.now());
stateFiles.writeError("Job was canceled");
LOG.info("Job {} canceled", id);
}
/**
* Deletes a job and its directory.
*
* @param id the job ID
* @throws IOException if deletion fails
*/
public void delete(String id) throws IOException {
Objects.requireNonNull(id, "id must not be null");
dirs.deleteJobDir(id);
LOG.info("Deleted job: {}", id);
}
/**
* Loads the manifest for a job.
*
* @param id the job ID
* @return the job manifest
* @throws IOException if loading fails
*/
public JobManifest loadManifest(String id) throws IOException {
Objects.requireNonNull(id, "id must not be null");
Path manifestPath = dirs.getJobDir(id).resolve(MANIFEST_FILE);
String json = Files.readString(manifestPath);
return objectMapper.readValue(json, JobManifest.class);
}
private Job loadJob(String id) throws IOException {
Path jobDir = dirs.getJobDir(id);
StateFiles stateFiles = new StateFiles(jobDir);
JobManifest manifest = loadManifest(id);
return new Job(
id,
stateFiles.readState().orElse(JobState.QUEUED),
manifest.command(),
stateFiles.readTag().orElse(null),
stateFiles.readCreatedAt().orElse(manifest.createdAt()),
stateFiles.readStartedAt().orElse(null),
stateFiles.readFinishedAt().orElse(null),
stateFiles.readExitCode().isPresent() ? stateFiles.readExitCode().getAsInt() : null,
stateFiles.readError().orElse(null),
stateFiles.readPid().isPresent() ? stateFiles.readPid().getAsLong() : null,
stateFiles.readHeartbeat().orElse(null),
stateFiles.readRetryCount().orElse(0),
stateFiles.readRetryAt().orElse(null)
);
}
}
@@ -0,0 +1,114 @@
package com.samsonmedia.barn.jobs;
import java.time.Instant;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import com.samsonmedia.barn.state.JobState;
/**
* Enforces valid state transitions for jobs.
*
* <p>Valid transitions:
* <ul>
* <li>QUEUED → RUNNING, CANCELED</li>
* <li>RUNNING → SUCCEEDED, FAILED, CANCELED</li>
* <li>FAILED → QUEUED (for retry)</li>
* <li>SUCCEEDED → (none, terminal)</li>
* <li>CANCELED → (none, terminal)</li>
* </ul>
*/
public final class JobStateMachine {
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()
);
private JobStateMachine() {
// Utility class - prevent instantiation
}
/**
* Validates that a state transition is allowed.
*
* @param from the current state
* @param to the target state
* @throws IllegalStateException if the transition is not valid
*/
public static void validateTransition(JobState from, JobState to) {
Objects.requireNonNull(from, "from state must not be null");
Objects.requireNonNull(to, "to state must not be null");
Set<JobState> validTargets = VALID_TRANSITIONS.get(from);
if (!validTargets.contains(to)) {
throw new IllegalStateException(
"Invalid state transition: " + from + " -> " + to);
}
}
/**
* Checks if a state transition is valid.
*
* @param from the current state
* @param to the target state
* @return true if the transition is valid
*/
public static boolean isValidTransition(JobState from, JobState to) {
if (from == null || to == null) {
return false;
}
return VALID_TRANSITIONS.get(from).contains(to);
}
/**
* Gets the valid target states for a given state.
*
* @param state the current state
* @return the set of valid target states
*/
public static Set<JobState> getValidTransitions(JobState state) {
Objects.requireNonNull(state, "state must not be null");
return VALID_TRANSITIONS.get(state);
}
/**
* Record representing a state transition event.
*
* @param from the previous state
* @param to the new state
* @param timestamp when the transition occurred
* @param reason optional reason for the transition
*/
public record Transition(
JobState from,
JobState to,
Instant timestamp,
String reason
) {
/**
* Creates a Transition with validation.
*/
public Transition {
Objects.requireNonNull(from, "from must not be null");
Objects.requireNonNull(to, "to must not be null");
Objects.requireNonNull(timestamp, "timestamp must not be null");
}
/**
* Creates a Transition with the current timestamp.
*
* @param from the previous state
* @param to the new state
* @param reason optional reason
* @return a new Transition
*/
public static Transition now(JobState from, JobState to, String reason) {
return new Transition(from, to, Instant.now(), reason);
}
}
}
@@ -232,8 +232,12 @@ public final class StateFiles {
}
private void writeTimestamp(String filename, Instant timestamp) throws IOException {
Objects.requireNonNull(timestamp, "timestamp must not be null");
AtomicFiles.writeAtomically(jobDir.resolve(filename), timestamp.toString());
Path file = jobDir.resolve(filename);
if (timestamp == null) {
AtomicFiles.deleteIfExists(file);
} else {
AtomicFiles.writeAtomically(file, timestamp.toString());
}
}
private Optional<Instant> readTimestamp(String filename) throws IOException {