Class SnapshotManager

java.lang.Object
com.loomcache.server.persistence.SnapshotManager

public class SnapshotManager extends Object
Manages snapshots for WAL log compaction.

Provides:

  • Snapshot creation with CRC32 integrity verification
  • Snapshot loading with corruption detection
  • Metadata-only loading (without full data)
  • Automatic cleanup to maintain bounded snapshot storage

Snapshot format on disk: [lastIncludedIndex(8)][lastIncludedTerm(8)][timestamp(8)][dataLength(4)][data(variable)][checksum(4 CRC32)]

Snapshots are named: snapshot-{nodeId}-{index}.bin

  • Constructor Details

    • SnapshotManager

      public SnapshotManager(String nodeId, Path snapshotDirectory) throws IOException
      Initialize the SnapshotManager.
      Parameters:
      nodeId - The node identifier (must not be null or empty)
      snapshotDirectory - The directory path for snapshot files (must not be null)
      Throws:
      IOException - If directory creation fails
      IllegalArgumentException - If parameters are invalid
  • Method Details

    • createSnapshot

      public void createSnapshot(long lastIncludedIndex, long lastIncludedTerm, byte[] data) throws IOException
      Create a snapshot of the current state.

      The snapshot is written atomically to disk with CRC32 checksum for corruption detection on load.

      Parameters:
      lastIncludedIndex - The index of the last log entry included in this snapshot
      lastIncludedTerm - The term of lastIncludedIndex
      data - The snapshot data (state machine state)
      Throws:
      IOException - If write fails
      IllegalArgumentException - If indices or term are invalid
    • loadLatestSnapshot

      public Optional<SnapshotManager.Snapshot> loadLatestSnapshot() throws IOException
      Load the latest snapshot from disk.

      Validates CRC32 checksum and returns the snapshot if valid. Returns empty if no valid snapshot exists.

      Returns:
      Optional containing the latest snapshot if found and valid
      Throws:
      IOException - If read fails
    • getSnapshotInfo

      public Optional<SnapshotManager.SnapshotInfo> getSnapshotInfo() throws IOException
      Get metadata for the latest snapshot without loading the full data.
      Returns:
      Optional containing snapshot metadata if available
      Throws:
      IOException - If read fails
    • cleanup

      public void cleanup(int maxSnapshots) throws IOException
      Clean up old snapshots, keeping only the latest N.

      Useful for managing disk space by removing snapshots that are no longer needed.

      Parameters:
      maxSnapshots - The maximum number of snapshots to keep
      Throws:
      IOException - If file operations fail
    • deleteSnapshot

      public void deleteSnapshot(long index) throws IOException
      Delete a specific snapshot by index.
      Parameters:
      index - The snapshot index to delete
      Throws:
      IOException - If deletion fails