Spector.Integrity (Spector v0.6.0)

View Source

Integrity verification for Spector event logs.

This module provides functions to verify the integrity of event logs, including savepoint validation and hash chain verification.

Summary

Functions

Verify the hash chain integrity of an entire events table.

Verify all savepoints for a record match the expected state at that point.

Functions

verify_hash_chain(events_module)

@spec verify_hash_chain(module()) ::
  :ok | {:error, Spector.Integrity.HashMismatch.t()}

Verify the hash chain integrity of an entire events table.

Iterates through all events in the table ordered by id and verifies that each event's hash correctly chains from the previous event.

Returns :ok if the hash chain is valid, or {:error, exception} where exception is a Spector.Integrity.HashMismatch.

Raises if the events module doesn't have hash chain integrity enabled.

Examples

# Verify the hash chain for an events table
:ok = Spector.Integrity.verify_hash_chain(MyApp.Events)

# Handle verification failures
case Spector.Integrity.verify_hash_chain(MyApp.Events) do
  :ok -> :verified
  {:error, %Spector.Integrity.HashMismatch{} = failure} ->
    Logger.error(Exception.message(failure))
end

verify_savepoints(schema, parent_id)

@spec verify_savepoints(module(), String.t()) ::
  :ok | {:error, Spector.Integrity.SavepointFailure.t()}

Verify all savepoints for a record match the expected state at that point.

Replays events from the beginning up to each savepoint and verifies that all replay paths (skipping different combinations of savepoints) converge to the same state. This catches bugs in savepoint/2 implementations that omit fields.

Returns :ok if all savepoints are valid, or {:error, exception} where exception is a Spector.Integrity.SavepointFailure.

Raises if the schema doesn't implement the savepoint/2 callback.

Examples

# Verify all savepoints for a record
:ok = Spector.Integrity.verify_savepoints(MyApp.User, user_id)

# Handle verification failures
case Spector.Integrity.verify_savepoints(MyApp.User, user_id) do
  :ok -> :verified
  {:error, %Spector.Integrity.SavepointFailure{} = failure} ->
    Logger.error(Exception.message(failure))
end