Implement filesystem state management #3

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

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

Overview

Implement the filesystem-based state management system for job directories and metadata files.

Context

  • Read first: docs/jobs.md (defines directory layout)
  • Depends on: #2 (configuration for base_dir)

Requirements

1. Directory Structure Manager

com.samsonmedia.barn.state.BarnDirectories.java:

public final class BarnDirectories {
    private final Path baseDir;  // e.g., /tmp/barn
    
    // Top-level directories
    public Path getJobsDir()  { return baseDir.resolve("jobs"); }
    public Path getLocksDir() { return baseDir.resolve("locks"); }
    public Path getLogsDir()  { return baseDir.resolve("logs"); }
    
    // Per-job directories
    public Path getJobDir(String jobId) { 
        return getJobsDir().resolve(jobId); 
    }
    public Path getJobWorkDir(String jobId) { 
        return getJobDir(jobId).resolve("work"); 
    }
    public Path getJobLogsDir(String jobId) { 
        return getJobDir(jobId).resolve("logs"); 
    }
    
    // Create all directories atomically
    public void initialize() throws IOException;
    
    // Create job directory structure
    public void createJobDirs(String jobId) throws IOException;
}

2. State File Manager

com.samsonmedia.barn.state.StateFiles.java:

Handles reading/writing the plain-text state files:

File Type Description
state JobState enum queued, running, succeeded, failed, canceled
tag String User-defined tag
created_at Instant ISO-8601 timestamp
started_at Instant ISO-8601 timestamp
finished_at Instant ISO-8601 timestamp
exit_code Integer or String 0, 1, or symbolic like "orphaned_process"
error String Human-readable error
pid Long OS process ID
heartbeat Instant Last liveness update
retry_count Integer Current retry attempt
retry_at Instant Next retry timestamp
public final class StateFiles {
    private final Path jobDir;
    
    // Atomic write (write to .tmp, then rename)
    public void writeState(JobState state) throws IOException;
    public void writeHeartbeat(Instant timestamp) throws IOException;
    public void writeExitCode(int code) throws IOException;
    // ... etc for each file
    
    // Read with Optional for missing files
    public Optional<JobState> readState();
    public Optional<Instant> readHeartbeat();
    public Optional<Integer> readExitCode();
    // ... etc
}

3. Atomic File Operations

com.samsonmedia.barn.state.AtomicFiles.java:

public final class AtomicFiles {
    // Write atomically: write to .tmp, then atomic rename
    public static void writeAtomically(Path target, String content) throws IOException {
        Path temp = target.resolveSibling(target.getFileName() + ".tmp");
        Files.writeString(temp, content, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
        Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
    }
    
    // Read safely
    public static Optional<String> readSafely(Path path) {
        try {
            return Optional.of(Files.readString(path).trim());
        } catch (NoSuchFileException e) {
            return Optional.empty();
        }
    }
}

4. File Locking

com.samsonmedia.barn.state.FileLock.java:

public final class FileLock implements AutoCloseable {
    // Acquire lock (create lock file atomically)
    public static Optional<FileLock> tryAcquire(Path lockFile);
    
    // Release lock (delete lock file)
    @Override
    public void close();
    
    // Check if lock is held by another process
    public static boolean isLocked(Path lockFile);
}

5. Tests Required

  • BarnDirectoriesTest.java: Test directory creation, path resolution
  • StateFilesTest.java: Test read/write of all state files, atomic operations
  • AtomicFilesTest.java: Test atomic write doesn't corrupt on partial write
  • FileLockTest.java: Test lock acquisition, release, contention

Acceptance Criteria

  • Directory structure matches docs/jobs.md exactly
  • All state files readable as plain text
  • Atomic writes never leave corrupted files
  • File locks prevent concurrent access
  • Works on Windows, macOS, Linux (path separators, temp dirs)
  • mvn verify passes
  • Tests have 80%+ coverage

Implementation Notes

Timestamps should be ISO-8601: 2026-01-21T18:42:10Z

Cross-platform considerations:

  • Use System.getProperty("java.io.tmpdir") for temp
  • Use Path APIs, not string concatenation
  • File locks use FileChannel.tryLock() or lock files

Definition of Done

  • Can create/read job directories
  • State files written atomically
  • Lock files work correctly
  • All tests pass
<!-- github-import:issue:3 --> _Imported from GitHub samson-media/barn#3 — opened by **@daniel-samson** on 2026-01-21 12:35:30 UTC_ ## Overview Implement the filesystem-based state management system for job directories and metadata files. ## Context - **Read first**: `docs/jobs.md` (defines directory layout) - **Depends on**: #2 (configuration for base_dir) ## Requirements ### 1. Directory Structure Manager `com.samsonmedia.barn.state.BarnDirectories.java`: ```java public final class BarnDirectories { private final Path baseDir; // e.g., /tmp/barn // Top-level directories public Path getJobsDir() { return baseDir.resolve("jobs"); } public Path getLocksDir() { return baseDir.resolve("locks"); } public Path getLogsDir() { return baseDir.resolve("logs"); } // Per-job directories public Path getJobDir(String jobId) { return getJobsDir().resolve(jobId); } public Path getJobWorkDir(String jobId) { return getJobDir(jobId).resolve("work"); } public Path getJobLogsDir(String jobId) { return getJobDir(jobId).resolve("logs"); } // Create all directories atomically public void initialize() throws IOException; // Create job directory structure public void createJobDirs(String jobId) throws IOException; } ``` ### 2. State File Manager `com.samsonmedia.barn.state.StateFiles.java`: Handles reading/writing the plain-text state files: | File | Type | Description | |------|------|-------------| | `state` | JobState enum | queued, running, succeeded, failed, canceled | | `tag` | String | User-defined tag | | `created_at` | Instant | ISO-8601 timestamp | | `started_at` | Instant | ISO-8601 timestamp | | `finished_at` | Instant | ISO-8601 timestamp | | `exit_code` | Integer or String | 0, 1, or symbolic like "orphaned_process" | | `error` | String | Human-readable error | | `pid` | Long | OS process ID | | `heartbeat` | Instant | Last liveness update | | `retry_count` | Integer | Current retry attempt | | `retry_at` | Instant | Next retry timestamp | ```java public final class StateFiles { private final Path jobDir; // Atomic write (write to .tmp, then rename) public void writeState(JobState state) throws IOException; public void writeHeartbeat(Instant timestamp) throws IOException; public void writeExitCode(int code) throws IOException; // ... etc for each file // Read with Optional for missing files public Optional<JobState> readState(); public Optional<Instant> readHeartbeat(); public Optional<Integer> readExitCode(); // ... etc } ``` ### 3. Atomic File Operations `com.samsonmedia.barn.state.AtomicFiles.java`: ```java public final class AtomicFiles { // Write atomically: write to .tmp, then atomic rename public static void writeAtomically(Path target, String content) throws IOException { Path temp = target.resolveSibling(target.getFileName() + ".tmp"); Files.writeString(temp, content, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } // Read safely public static Optional<String> readSafely(Path path) { try { return Optional.of(Files.readString(path).trim()); } catch (NoSuchFileException e) { return Optional.empty(); } } } ``` ### 4. File Locking `com.samsonmedia.barn.state.FileLock.java`: ```java public final class FileLock implements AutoCloseable { // Acquire lock (create lock file atomically) public static Optional<FileLock> tryAcquire(Path lockFile); // Release lock (delete lock file) @Override public void close(); // Check if lock is held by another process public static boolean isLocked(Path lockFile); } ``` ### 5. Tests Required - `BarnDirectoriesTest.java`: Test directory creation, path resolution - `StateFilesTest.java`: Test read/write of all state files, atomic operations - `AtomicFilesTest.java`: Test atomic write doesn't corrupt on partial write - `FileLockTest.java`: Test lock acquisition, release, contention ## Acceptance Criteria - [ ] Directory structure matches docs/jobs.md exactly - [ ] All state files readable as plain text - [ ] Atomic writes never leave corrupted files - [ ] File locks prevent concurrent access - [ ] Works on Windows, macOS, Linux (path separators, temp dirs) - [ ] `mvn verify` passes - [ ] Tests have 80%+ coverage ## Implementation Notes Timestamps should be ISO-8601: `2026-01-21T18:42:10Z` Cross-platform considerations: - Use `System.getProperty("java.io.tmpdir")` for temp - Use `Path` APIs, not string concatenation - File locks use `FileChannel.tryLock()` or lock files ## Definition of Done - Can create/read job directories - State files written atomically - Lock files work correctly - All tests pass
daniel added this to the M1: Foundation milestone 2026-10-04 19:27:54 +00:00
daniel added the foundation label 2026-10-04 19:27:54 +00:00
Author
Owner

@daniel-samson commented on 2026-01-21 13:04:11 UTC:

Completed implementation:

Deliverables:

  • ✅ AtomicFiles utility for atomic file operations
  • ✅ JobState enum with terminal/active state helpers
  • ✅ BarnDirectories for directory structure management
  • ✅ StateFiles for all job metadata files (state, timestamps, exit codes, etc.)
  • ✅ FileLock for cross-process file locking
  • ✅ All state files are plain-text and human-readable
  • ✅ 92 new tests (211 total), 80%+ coverage
  • ✅ mvn verify passes

Commit: 647e602

<!-- github-import:comment:3778039034 --> _**@daniel-samson** commented on 2026-01-21 13:04:11 UTC:_ Completed implementation: **Deliverables:** - ✅ AtomicFiles utility for atomic file operations - ✅ JobState enum with terminal/active state helpers - ✅ BarnDirectories for directory structure management - ✅ StateFiles for all job metadata files (state, timestamps, exit codes, etc.) - ✅ FileLock for cross-process file locking - ✅ All state files are plain-text and human-readable - ✅ 92 new tests (211 total), 80%+ coverage - ✅ mvn verify passes **Commit:** 647e602
This repo is archived. You cannot comment on issues.