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,88 @@
package com.samsonmedia.barn.jobs;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
/**
* Tests for JobIdGenerator.
*/
class JobIdGeneratorTest {
@Test
void generate_shouldReturnIdWithCorrectPrefix() {
String id = JobIdGenerator.generate();
assertThat(id).startsWith("job-");
}
@Test
void generate_shouldReturnIdWithCorrectLength() {
String id = JobIdGenerator.generate();
assertThat(id).hasSize(12); // "job-" (4) + 8 hex chars
}
@Test
void generate_shouldReturnIdWithHexSuffix() {
String id = JobIdGenerator.generate();
String suffix = id.substring(4);
assertThat(suffix).matches("[0-9a-f]{8}");
}
@Test
void generate_shouldProduceUniqueIds() {
Set<String> ids = new HashSet<>();
for (int i = 0; i < 1000; i++) {
ids.add(JobIdGenerator.generate());
}
assertThat(ids).hasSize(1000);
}
@Test
void isValid_withValidId_shouldReturnTrue() {
assertThat(JobIdGenerator.isValid("job-12345678")).isTrue();
assertThat(JobIdGenerator.isValid("job-abcdef01")).isTrue();
assertThat(JobIdGenerator.isValid("job-9f83c012")).isTrue();
}
@Test
void isValid_withNull_shouldReturnFalse() {
assertThat(JobIdGenerator.isValid(null)).isFalse();
}
@Test
void isValid_withWrongPrefix_shouldReturnFalse() {
assertThat(JobIdGenerator.isValid("task-12345678")).isFalse();
assertThat(JobIdGenerator.isValid("12345678")).isFalse();
}
@Test
void isValid_withWrongLength_shouldReturnFalse() {
assertThat(JobIdGenerator.isValid("job-1234567")).isFalse();
assertThat(JobIdGenerator.isValid("job-123456789")).isFalse();
}
@Test
void isValid_withInvalidHexChars_shouldReturnFalse() {
assertThat(JobIdGenerator.isValid("job-ABCDEF01")).isFalse();
assertThat(JobIdGenerator.isValid("job-ghijklmn")).isFalse();
assertThat(JobIdGenerator.isValid("job-12-45678")).isFalse();
}
@Test
void generate_shouldPassOwnValidation() {
for (int i = 0; i < 100; i++) {
String id = JobIdGenerator.generate();
assertThat(JobIdGenerator.isValid(id))
.as("Generated ID '%s' should be valid", id)
.isTrue();
}
}
}
@@ -0,0 +1,152 @@
package com.samsonmedia.barn.jobs;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.time.Instant;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.samsonmedia.barn.config.JobsConfig;
/**
* Tests for JobManifest record.
*/
class JobManifestTest {
@Test
void constructor_withValidValues_shouldCreateManifest() {
Instant now = Instant.now();
JobManifest manifest = new JobManifest(
"job-12345",
List.of("echo", "hello"),
"test-tag",
now,
3, 30, 2.0
);
assertThat(manifest.id()).isEqualTo("job-12345");
assertThat(manifest.command()).containsExactly("echo", "hello");
assertThat(manifest.tag()).isEqualTo("test-tag");
assertThat(manifest.createdAt()).isEqualTo(now);
assertThat(manifest.maxRetries()).isEqualTo(3);
assertThat(manifest.retryDelaySeconds()).isEqualTo(30);
assertThat(manifest.retryBackoffMultiplier()).isEqualTo(2.0);
}
@Test
void constructor_withNullId_shouldThrowException() {
assertThatThrownBy(() -> new JobManifest(
null, List.of("echo"), null, Instant.now(), 3, 30, 2.0))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("id");
}
@Test
void constructor_withBlankId_shouldThrowException() {
assertThatThrownBy(() -> new JobManifest(
" ", List.of("echo"), null, Instant.now(), 3, 30, 2.0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("blank");
}
@Test
void constructor_withEmptyCommand_shouldThrowException() {
assertThatThrownBy(() -> new JobManifest(
"job-12345", List.of(), null, Instant.now(), 3, 30, 2.0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("empty");
}
@Test
void constructor_withNegativeMaxRetries_shouldThrowException() {
assertThatThrownBy(() -> new JobManifest(
"job-12345", List.of("echo"), null, Instant.now(), -1, 30, 2.0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("maxRetries");
}
@Test
void constructor_withNegativeRetryDelay_shouldThrowException() {
assertThatThrownBy(() -> new JobManifest(
"job-12345", List.of("echo"), null, Instant.now(), 3, -1, 2.0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("retryDelaySeconds");
}
@Test
void constructor_withBackoffMultiplierLessThanOne_shouldThrowException() {
assertThatThrownBy(() -> new JobManifest(
"job-12345", List.of("echo"), null, Instant.now(), 3, 30, 0.5))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("retryBackoffMultiplier");
}
@Test
void create_withConfig_shouldUseConfigDefaults() {
JobsConfig config = JobsConfig.withDefaults();
JobManifest manifest = JobManifest.create("job-12345", List.of("echo"), "tag", config);
assertThat(manifest.maxRetries()).isEqualTo(config.maxRetries());
assertThat(manifest.retryDelaySeconds()).isEqualTo(config.retryDelaySeconds());
assertThat(manifest.retryBackoffMultiplier()).isEqualTo(config.retryBackoffMultiplier());
}
@Test
void create_withCustomValues_shouldUseCustomValues() {
JobManifest manifest = JobManifest.create(
"job-12345", List.of("echo"), "tag", 5, 60, 3.0);
assertThat(manifest.maxRetries()).isEqualTo(5);
assertThat(manifest.retryDelaySeconds()).isEqualTo(60);
assertThat(manifest.retryBackoffMultiplier()).isEqualTo(3.0);
}
@Test
void calculateRetryDelay_shouldUseExponentialBackoff() {
JobManifest manifest = new JobManifest(
"job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0);
assertThat(manifest.calculateRetryDelay(0)).isEqualTo(30); // 30 * 2^0
assertThat(manifest.calculateRetryDelay(1)).isEqualTo(60); // 30 * 2^1
assertThat(manifest.calculateRetryDelay(2)).isEqualTo(120); // 30 * 2^2
}
@Test
void calculateRetryDelay_withNegativeCount_shouldThrowException() {
JobManifest manifest = new JobManifest(
"job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0);
assertThatThrownBy(() -> manifest.calculateRetryDelay(-1))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void canRetry_withRetriesAvailable_shouldReturnTrue() {
JobManifest manifest = new JobManifest(
"job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0);
assertThat(manifest.canRetry(0)).isTrue();
assertThat(manifest.canRetry(1)).isTrue();
assertThat(manifest.canRetry(2)).isTrue();
}
@Test
void canRetry_withNoRetriesLeft_shouldReturnFalse() {
JobManifest manifest = new JobManifest(
"job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0);
assertThat(manifest.canRetry(3)).isFalse();
assertThat(manifest.canRetry(4)).isFalse();
}
@Test
void canRetry_withZeroMaxRetries_shouldAlwaysReturnFalse() {
JobManifest manifest = new JobManifest(
"job-12345", List.of("echo"), null, Instant.now(), 0, 30, 2.0);
assertThat(manifest.canRetry(0)).isFalse();
}
}
@@ -0,0 +1,306 @@
package com.samsonmedia.barn.jobs;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import com.samsonmedia.barn.config.JobsConfig;
import com.samsonmedia.barn.state.BarnDirectories;
import com.samsonmedia.barn.state.JobState;
/**
* Tests for JobRepository.
*/
class JobRepositoryTest {
@TempDir
private Path tempDir;
private BarnDirectories dirs;
private JobRepository repository;
private JobsConfig config;
@BeforeEach
void setUp() throws IOException {
dirs = new BarnDirectories(tempDir);
dirs.initialize();
repository = new JobRepository(dirs);
config = JobsConfig.withDefaults();
}
@Nested
class Create {
@Test
void create_shouldCreateJobDirectory() throws IOException {
Job job = repository.create(List.of("echo", "hello"), "test-tag", config);
assertThat(Files.isDirectory(dirs.getJobDir(job.id()))).isTrue();
}
@Test
void create_shouldWriteManifest() throws IOException {
Job job = repository.create(List.of("echo", "hello"), "test-tag", config);
Path manifestPath = dirs.getJobDir(job.id()).resolve("manifest.json");
assertThat(Files.exists(manifestPath)).isTrue();
String content = Files.readString(manifestPath);
assertThat(content).contains("echo");
assertThat(content).contains("hello");
}
@Test
void create_shouldWriteInitialState() throws IOException {
Job job = repository.create(List.of("echo", "hello"), "test-tag", config);
Path statePath = dirs.getJobDir(job.id()).resolve("state");
assertThat(Files.readString(statePath).trim()).isEqualTo("queued");
}
@Test
void create_shouldReturnQueuedJob() throws IOException {
Job job = repository.create(List.of("echo", "hello"), "test-tag", config);
assertThat(job.state()).isEqualTo(JobState.QUEUED);
assertThat(job.command()).containsExactly("echo", "hello");
assertThat(job.tag()).isEqualTo("test-tag");
}
@Test
void create_withNullTag_shouldSucceed() throws IOException {
Job job = repository.create(List.of("echo"), null, config);
assertThat(job.tag()).isNull();
}
}
@Nested
class FindById {
@Test
void findById_withExistingJob_shouldReturnJob() throws IOException {
Job created = repository.create(List.of("echo"), "tag", config);
Optional<Job> found = repository.findById(created.id());
assertThat(found).isPresent();
assertThat(found.get().id()).isEqualTo(created.id());
assertThat(found.get().command()).isEqualTo(created.command());
}
@Test
void findById_withNonexistentJob_shouldReturnEmpty() throws IOException {
Optional<Job> found = repository.findById("job-nonexistent");
assertThat(found).isEmpty();
}
}
@Nested
class FindAll {
@Test
void findAll_withNoJobs_shouldReturnEmpty() throws IOException {
List<Job> jobs = repository.findAll();
assertThat(jobs).isEmpty();
}
@Test
void findAll_withMultipleJobs_shouldReturnAll() throws IOException {
repository.create(List.of("echo", "1"), "tag1", config);
repository.create(List.of("echo", "2"), "tag2", config);
repository.create(List.of("echo", "3"), "tag3", config);
List<Job> jobs = repository.findAll();
assertThat(jobs).hasSize(3);
}
}
@Nested
class FindByState {
@Test
void findByState_shouldFilterByState() throws IOException {
Job job1 = repository.create(List.of("echo", "1"), null, config);
Job job2 = repository.create(List.of("echo", "2"), null, config);
repository.markStarted(job1.id(), 12345L);
List<Job> queued = repository.findByState(JobState.QUEUED);
List<Job> running = repository.findByState(JobState.RUNNING);
assertThat(queued).hasSize(1);
assertThat(queued.get(0).id()).isEqualTo(job2.id());
assertThat(running).hasSize(1);
assertThat(running.get(0).id()).isEqualTo(job1.id());
}
}
@Nested
class MarkStarted {
@Test
void markStarted_shouldUpdateState() throws IOException {
Job job = repository.create(List.of("echo"), null, config);
repository.markStarted(job.id(), 12345L);
Job updated = repository.findById(job.id()).orElseThrow();
assertThat(updated.state()).isEqualTo(JobState.RUNNING);
assertThat(updated.pid()).isEqualTo(12345L);
assertThat(updated.startedAt()).isNotNull();
assertThat(updated.heartbeat()).isNotNull();
}
}
@Nested
class UpdateHeartbeat {
@Test
void updateHeartbeat_shouldWriteTimestamp() throws IOException {
Job job = repository.create(List.of("echo"), null, config);
repository.markStarted(job.id(), 12345L);
Instant newHeartbeat = Instant.now().plusSeconds(60);
repository.updateHeartbeat(job.id(), newHeartbeat);
Job updated = repository.findById(job.id()).orElseThrow();
assertThat(updated.heartbeat()).isEqualTo(newHeartbeat);
}
}
@Nested
class MarkCompleted {
@Test
void markCompleted_withZeroExitCode_shouldSetSucceeded() throws IOException {
Job job = repository.create(List.of("echo"), null, config);
repository.markStarted(job.id(), 12345L);
repository.markCompleted(job.id(), 0, null);
Job updated = repository.findById(job.id()).orElseThrow();
assertThat(updated.state()).isEqualTo(JobState.SUCCEEDED);
assertThat(updated.exitCode()).isZero();
assertThat(updated.finishedAt()).isNotNull();
}
@Test
void markCompleted_withNonZeroExitCode_shouldSetFailed() throws IOException {
Job job = repository.create(List.of("echo"), null, config);
repository.markStarted(job.id(), 12345L);
repository.markCompleted(job.id(), 1, "Process failed");
Job updated = repository.findById(job.id()).orElseThrow();
assertThat(updated.state()).isEqualTo(JobState.FAILED);
assertThat(updated.exitCode()).isEqualTo(1);
assertThat(updated.error()).isEqualTo("Process failed");
}
}
@Nested
class MarkFailed {
@Test
void markFailed_withSymbolicCode_shouldSetFailed() throws IOException {
Job job = repository.create(List.of("echo"), null, config);
repository.markStarted(job.id(), 12345L);
repository.markFailed(job.id(), "orphaned_process", "Process was orphaned");
Job updated = repository.findById(job.id()).orElseThrow();
assertThat(updated.state()).isEqualTo(JobState.FAILED);
assertThat(updated.error()).isEqualTo("Process was orphaned");
}
}
@Nested
class ScheduleRetry {
@Test
void scheduleRetry_shouldIncrementCountAndResetState() throws IOException {
Job job = repository.create(List.of("echo"), null, config);
repository.markStarted(job.id(), 12345L);
repository.markCompleted(job.id(), 1, "Failed");
Instant retryAt = Instant.now().plusSeconds(30);
repository.scheduleRetry(job.id(), retryAt);
Job updated = repository.findById(job.id()).orElseThrow();
assertThat(updated.state()).isEqualTo(JobState.QUEUED);
assertThat(updated.retryCount()).isEqualTo(1);
assertThat(updated.retryAt()).isEqualTo(retryAt);
}
}
@Nested
class MarkCanceled {
@Test
void markCanceled_shouldSetCanceledState() throws IOException {
Job job = repository.create(List.of("echo"), null, config);
repository.markCanceled(job.id());
Job updated = repository.findById(job.id()).orElseThrow();
assertThat(updated.state()).isEqualTo(JobState.CANCELED);
assertThat(updated.finishedAt()).isNotNull();
}
}
@Nested
class Delete {
@Test
void delete_shouldRemoveJobDirectory() throws IOException {
Job job = repository.create(List.of("echo"), null, config);
repository.delete(job.id());
assertThat(Files.exists(dirs.getJobDir(job.id()))).isFalse();
assertThat(repository.findById(job.id())).isEmpty();
}
}
@Nested
class LoadManifest {
@Test
void loadManifest_shouldReturnManifest() throws IOException {
Job job = repository.create(List.of("echo", "test"), "my-tag", config);
JobManifest manifest = repository.loadManifest(job.id());
assertThat(manifest.id()).isEqualTo(job.id());
assertThat(manifest.command()).containsExactly("echo", "test");
assertThat(manifest.tag()).isEqualTo("my-tag");
assertThat(manifest.maxRetries()).isEqualTo(config.maxRetries());
}
}
@Nested
class StateTransitionValidation {
@Test
void updateState_withInvalidTransition_shouldThrowException() throws IOException {
Job job = repository.create(List.of("echo"), null, config);
assertThatThrownBy(() -> repository.updateState(job.id(), JobState.SUCCEEDED))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Invalid state transition");
}
}
}
@@ -0,0 +1,203 @@
package com.samsonmedia.barn.jobs;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.time.Instant;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import com.samsonmedia.barn.state.JobState;
/**
* Tests for JobStateMachine.
*/
class JobStateMachineTest {
@Nested
class ValidateTransition {
@Test
void queued_toRunning_shouldBeValid() {
JobStateMachine.validateTransition(JobState.QUEUED, JobState.RUNNING);
// No exception means valid
}
@Test
void queued_toCanceled_shouldBeValid() {
JobStateMachine.validateTransition(JobState.QUEUED, JobState.CANCELED);
}
@Test
void running_toSucceeded_shouldBeValid() {
JobStateMachine.validateTransition(JobState.RUNNING, JobState.SUCCEEDED);
}
@Test
void running_toFailed_shouldBeValid() {
JobStateMachine.validateTransition(JobState.RUNNING, JobState.FAILED);
}
@Test
void running_toCanceled_shouldBeValid() {
JobStateMachine.validateTransition(JobState.RUNNING, JobState.CANCELED);
}
@Test
void failed_toQueued_shouldBeValid() {
JobStateMachine.validateTransition(JobState.FAILED, JobState.QUEUED);
}
@Test
void queued_toSucceeded_shouldThrowException() {
assertThatThrownBy(() ->
JobStateMachine.validateTransition(JobState.QUEUED, JobState.SUCCEEDED))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Invalid state transition")
.hasMessageContaining("QUEUED")
.hasMessageContaining("SUCCEEDED");
}
@Test
void queued_toFailed_shouldThrowException() {
assertThatThrownBy(() ->
JobStateMachine.validateTransition(JobState.QUEUED, JobState.FAILED))
.isInstanceOf(IllegalStateException.class);
}
@Test
void succeeded_toAny_shouldThrowException() {
assertThatThrownBy(() ->
JobStateMachine.validateTransition(JobState.SUCCEEDED, JobState.QUEUED))
.isInstanceOf(IllegalStateException.class);
assertThatThrownBy(() ->
JobStateMachine.validateTransition(JobState.SUCCEEDED, JobState.RUNNING))
.isInstanceOf(IllegalStateException.class);
}
@Test
void canceled_toAny_shouldThrowException() {
assertThatThrownBy(() ->
JobStateMachine.validateTransition(JobState.CANCELED, JobState.QUEUED))
.isInstanceOf(IllegalStateException.class);
assertThatThrownBy(() ->
JobStateMachine.validateTransition(JobState.CANCELED, JobState.RUNNING))
.isInstanceOf(IllegalStateException.class);
}
@Test
void withNullFrom_shouldThrowException() {
assertThatThrownBy(() ->
JobStateMachine.validateTransition(null, JobState.RUNNING))
.isInstanceOf(NullPointerException.class);
}
@Test
void withNullTo_shouldThrowException() {
assertThatThrownBy(() ->
JobStateMachine.validateTransition(JobState.QUEUED, null))
.isInstanceOf(NullPointerException.class);
}
}
@Nested
class IsValidTransition {
@Test
void validTransitions_shouldReturnTrue() {
assertThat(JobStateMachine.isValidTransition(JobState.QUEUED, JobState.RUNNING)).isTrue();
assertThat(JobStateMachine.isValidTransition(JobState.QUEUED, JobState.CANCELED)).isTrue();
assertThat(JobStateMachine.isValidTransition(JobState.RUNNING, JobState.SUCCEEDED)).isTrue();
assertThat(JobStateMachine.isValidTransition(JobState.RUNNING, JobState.FAILED)).isTrue();
assertThat(JobStateMachine.isValidTransition(JobState.RUNNING, JobState.CANCELED)).isTrue();
assertThat(JobStateMachine.isValidTransition(JobState.FAILED, JobState.QUEUED)).isTrue();
}
@Test
void invalidTransitions_shouldReturnFalse() {
assertThat(JobStateMachine.isValidTransition(JobState.QUEUED, JobState.SUCCEEDED)).isFalse();
assertThat(JobStateMachine.isValidTransition(JobState.QUEUED, JobState.FAILED)).isFalse();
assertThat(JobStateMachine.isValidTransition(JobState.SUCCEEDED, JobState.QUEUED)).isFalse();
assertThat(JobStateMachine.isValidTransition(JobState.CANCELED, JobState.RUNNING)).isFalse();
}
@Test
void withNull_shouldReturnFalse() {
assertThat(JobStateMachine.isValidTransition(null, JobState.RUNNING)).isFalse();
assertThat(JobStateMachine.isValidTransition(JobState.QUEUED, null)).isFalse();
}
}
@Nested
class GetValidTransitions {
@Test
void forQueued_shouldReturnRunningAndCanceled() {
assertThat(JobStateMachine.getValidTransitions(JobState.QUEUED))
.containsExactlyInAnyOrder(JobState.RUNNING, JobState.CANCELED);
}
@Test
void forRunning_shouldReturnSucceededFailedCanceled() {
assertThat(JobStateMachine.getValidTransitions(JobState.RUNNING))
.containsExactlyInAnyOrder(JobState.SUCCEEDED, JobState.FAILED, JobState.CANCELED);
}
@Test
void forFailed_shouldReturnQueued() {
assertThat(JobStateMachine.getValidTransitions(JobState.FAILED))
.containsExactly(JobState.QUEUED);
}
@Test
void forSucceeded_shouldReturnEmpty() {
assertThat(JobStateMachine.getValidTransitions(JobState.SUCCEEDED)).isEmpty();
}
@Test
void forCanceled_shouldReturnEmpty() {
assertThat(JobStateMachine.getValidTransitions(JobState.CANCELED)).isEmpty();
}
@Test
void withNull_shouldThrowException() {
assertThatThrownBy(() -> JobStateMachine.getValidTransitions(null))
.isInstanceOf(NullPointerException.class);
}
}
@Nested
class TransitionRecord {
@Test
void constructor_shouldCreateTransition() {
Instant now = Instant.now();
JobStateMachine.Transition transition = new JobStateMachine.Transition(
JobState.QUEUED, JobState.RUNNING, now, "Starting execution");
assertThat(transition.from()).isEqualTo(JobState.QUEUED);
assertThat(transition.to()).isEqualTo(JobState.RUNNING);
assertThat(transition.timestamp()).isEqualTo(now);
assertThat(transition.reason()).isEqualTo("Starting execution");
}
@Test
void constructor_withNullFrom_shouldThrowException() {
assertThatThrownBy(() ->
new JobStateMachine.Transition(null, JobState.RUNNING, Instant.now(), null))
.isInstanceOf(NullPointerException.class);
}
@Test
void now_shouldCreateWithCurrentTimestamp() {
JobStateMachine.Transition transition = JobStateMachine.Transition.now(
JobState.QUEUED, JobState.RUNNING, "Test");
assertThat(transition.from()).isEqualTo(JobState.QUEUED);
assertThat(transition.to()).isEqualTo(JobState.RUNNING);
assertThat(transition.timestamp()).isNotNull();
assertThat(transition.reason()).isEqualTo("Test");
}
}
}
@@ -0,0 +1,234 @@
package com.samsonmedia.barn.jobs;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.time.Instant;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.samsonmedia.barn.state.JobState;
/**
* Tests for Job record.
*/
class JobTest {
@Test
void constructor_withValidValues_shouldCreateJob() {
Job job = new Job(
"job-12345",
JobState.QUEUED,
List.of("echo", "hello"),
"test-tag",
Instant.now(),
null, null, null, null, null, null, 0, null
);
assertThat(job.id()).isEqualTo("job-12345");
assertThat(job.state()).isEqualTo(JobState.QUEUED);
assertThat(job.command()).containsExactly("echo", "hello");
assertThat(job.tag()).isEqualTo("test-tag");
}
@Test
void constructor_withNullId_shouldThrowException() {
assertThatThrownBy(() -> new Job(
null, JobState.QUEUED, List.of("echo"), null,
Instant.now(), null, null, null, null, null, null, 0, null))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("id");
}
@Test
void constructor_withBlankId_shouldThrowException() {
assertThatThrownBy(() -> new Job(
" ", JobState.QUEUED, List.of("echo"), null,
Instant.now(), null, null, null, null, null, null, 0, null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("blank");
}
@Test
void constructor_withNullState_shouldThrowException() {
assertThatThrownBy(() -> new Job(
"job-12345", null, List.of("echo"), null,
Instant.now(), null, null, null, null, null, null, 0, null))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("state");
}
@Test
void constructor_withEmptyCommand_shouldThrowException() {
assertThatThrownBy(() -> new Job(
"job-12345", JobState.QUEUED, List.of(), null,
Instant.now(), null, null, null, null, null, null, 0, null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("empty");
}
@Test
void constructor_withNegativeRetryCount_shouldThrowException() {
assertThatThrownBy(() -> new Job(
"job-12345", JobState.QUEUED, List.of("echo"), null,
Instant.now(), null, null, null, null, null, null, -1, null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("retryCount");
}
@Test
void constructor_shouldMakeDefensiveCopyOfCommand() {
List<String> command = new java.util.ArrayList<>();
command.add("echo");
Job job = Job.createQueued("job-12345", command, null);
command.add("modified");
assertThat(job.command()).containsExactly("echo");
}
@Test
void createQueued_shouldCreateQueuedJob() {
Job job = Job.createQueued("job-12345", List.of("echo", "test"), "my-tag");
assertThat(job.id()).isEqualTo("job-12345");
assertThat(job.state()).isEqualTo(JobState.QUEUED);
assertThat(job.command()).containsExactly("echo", "test");
assertThat(job.tag()).isEqualTo("my-tag");
assertThat(job.createdAt()).isNotNull();
assertThat(job.startedAt()).isNull();
assertThat(job.finishedAt()).isNull();
assertThat(job.exitCode()).isNull();
assertThat(job.retryCount()).isZero();
}
@Test
void withState_shouldCreateCopyWithNewState() {
Job original = Job.createQueued("job-12345", List.of("echo"), null);
Job updated = original.withState(JobState.RUNNING);
assertThat(updated.state()).isEqualTo(JobState.RUNNING);
assertThat(updated.id()).isEqualTo(original.id());
assertThat(updated.command()).isEqualTo(original.command());
assertThat(original.state()).isEqualTo(JobState.QUEUED); // Original unchanged
}
@Test
void withStarted_shouldSetRunningStateAndPid() {
Job original = Job.createQueued("job-12345", List.of("echo"), null);
Job started = original.withStarted(12345L);
assertThat(started.state()).isEqualTo(JobState.RUNNING);
assertThat(started.pid()).isEqualTo(12345L);
assertThat(started.startedAt()).isNotNull();
assertThat(started.heartbeat()).isNotNull();
}
@Test
void withCompleted_withZeroExitCode_shouldSetSucceeded() {
Job running = Job.createQueued("job-12345", List.of("echo"), null)
.withStarted(12345L);
Job completed = running.withCompleted(0, null);
assertThat(completed.state()).isEqualTo(JobState.SUCCEEDED);
assertThat(completed.exitCode()).isZero();
assertThat(completed.finishedAt()).isNotNull();
}
@Test
void withCompleted_withNonZeroExitCode_shouldSetFailed() {
Job running = Job.createQueued("job-12345", List.of("echo"), null)
.withStarted(12345L);
Job completed = running.withCompleted(1, "Process failed");
assertThat(completed.state()).isEqualTo(JobState.FAILED);
assertThat(completed.exitCode()).isEqualTo(1);
assertThat(completed.error()).isEqualTo("Process failed");
}
@Test
void withHeartbeat_shouldUpdateHeartbeat() {
Job running = Job.createQueued("job-12345", List.of("echo"), null)
.withStarted(12345L);
Instant newHeartbeat = Instant.now().plusSeconds(60);
Job updated = running.withHeartbeat(newHeartbeat);
assertThat(updated.heartbeat()).isEqualTo(newHeartbeat);
}
@Test
void withRetry_shouldIncrementRetryCountAndResetState() {
Job failed = Job.createQueued("job-12345", List.of("echo"), null)
.withStarted(12345L)
.withCompleted(1, "Failed");
Instant retryAt = Instant.now().plusSeconds(30);
Job retrying = failed.withRetry(retryAt);
assertThat(retrying.state()).isEqualTo(JobState.QUEUED);
assertThat(retrying.retryCount()).isEqualTo(1);
assertThat(retrying.retryAt()).isEqualTo(retryAt);
assertThat(retrying.startedAt()).isNull();
assertThat(retrying.finishedAt()).isNull();
}
@Test
void withCanceled_shouldSetCanceledState() {
Job running = Job.createQueued("job-12345", List.of("echo"), null)
.withStarted(12345L);
Job canceled = running.withCanceled();
assertThat(canceled.state()).isEqualTo(JobState.CANCELED);
assertThat(canceled.error()).contains("canceled");
assertThat(canceled.finishedAt()).isNotNull();
}
@Test
void isTerminal_forTerminalStates_shouldReturnTrue() {
Job succeeded = Job.createQueued("job-1", List.of("echo"), null)
.withStarted(1L).withCompleted(0, null);
Job failed = Job.createQueued("job-2", List.of("echo"), null)
.withStarted(1L).withCompleted(1, null);
Job canceled = Job.createQueued("job-3", List.of("echo"), null)
.withCanceled();
assertThat(succeeded.isTerminal()).isTrue();
assertThat(failed.isTerminal()).isTrue();
assertThat(canceled.isTerminal()).isTrue();
}
@Test
void isTerminal_forActiveStates_shouldReturnFalse() {
Job queued = Job.createQueued("job-1", List.of("echo"), null);
Job running = queued.withStarted(1L);
assertThat(queued.isTerminal()).isFalse();
assertThat(running.isTerminal()).isFalse();
}
@Test
void isRunning_shouldReturnTrueOnlyForRunning() {
Job queued = Job.createQueued("job-1", List.of("echo"), null);
Job running = queued.withStarted(1L);
Job completed = running.withCompleted(0, null);
assertThat(queued.isRunning()).isFalse();
assertThat(running.isRunning()).isTrue();
assertThat(completed.isRunning()).isFalse();
}
@Test
void isQueued_shouldReturnTrueOnlyForQueued() {
Job queued = Job.createQueued("job-1", List.of("echo"), null);
Job running = queued.withStarted(1L);
assertThat(queued.isQueued()).isTrue();
assertThat(running.isQueued()).isFalse();
}
}