wal.go
wal.go - Overview
This file defines an abstract WAL (Write-Ahead Logging) interface and provides functionality for periodic WAL rotation in the background.
Detailed Documentation
AbstractWAL
Interface
type AbstractWAL interface {
LogCommand([]byte) error
Close() error
Init(t time.Time) error
Replay(c func(*WALEntry) error) error
ForEachCommand(e *WALEntry, c func(*WALEntry) error) error
}
- Purpose: Defines the interface for a Write-Ahead Log (WAL) implementation.
LogCommand
: Writes a command to the log.- Parameters:
[]byte
: The command to be logged.
- Returns:
error
: An error if the command could not be logged.
- Parameters:
Close
: Closes the WAL.- Parameters: None
- Returns:
error
: An error if the WAL could not be closed.
Init
: Initializes the WAL.- Parameters:
t time.Time
: The initialization time.
- Returns:
error
: An error if the WAL could not be initialized.
- Parameters:
Replay
: Replays the WAL entries.- Parameters:
c func(*WALEntry) error
: A callback function to be executed for each WAL entry.
- Returns:
error
: An error if there was an issue replaying the WAL.
- Parameters:
ForEachCommand
: Iterates through each command in the WAL- Parameters:
e *WALEntry
: WAL Entryc func(*WALEntry) error
: A callback function to be executed for each WAL entry.
- Returns:
error
: An error if there was an issue iterating through the WAL.
- Parameters:
Variables
ticker
: Atime.Ticker
used for periodic WAL rotation. Initialized to tick every 1 minute.stopCh
: A channel used to signal the background WAL rotation goroutine to stop.mu
: Async.Mutex
to protect concurrent access to the WAL during rotation.
init
Function
func init() {
ticker = time.NewTicker(1 * time.Minute)
stopCh = make(chan struct{})
}
- Purpose: Initializes the
ticker
andstopCh
variables when the package is initialized.
rotateWAL
Function
func rotateWAL(wl AbstractWAL) {
mu.Lock()
defer mu.Unlock()
if err := wl.Close(); err != nil {
slog.Warn("error closing the WAL", slog.Any("error", err))
}
if err := wl.Init(time.Now()); err != nil {
slog.Warn("error creating a new WAL", slog.Any("error", err))
}
}
- Purpose: Closes the current WAL and initializes a new one.
- Parameters:
wl AbstractWAL
: The WAL to be rotated.
- Returns: None
- Parameters:
periodicRotate
Function
func periodicRotate(wl AbstractWAL) {
for {
select {
case <-ticker.C:
rotateWAL(wl)
case <-stopCh:
return
}
}
}
- Purpose: Periodically rotates the WAL in the background.
- Parameters:
wl AbstractWAL
: The WAL to be rotated.
- Returns: None
- Parameters:
InitBG
Function
func InitBG(wl AbstractWAL) {
go periodicRotate(wl)
}
- Purpose: Initializes the background WAL rotation goroutine.
- Parameters:
wl AbstractWAL
: The WAL to be rotated.
- Returns: None
- Parameters:
ShutdownBG
Function
func ShutdownBG() {
close(stopCh)
ticker.Stop()
}
- Purpose: Shuts down the background WAL rotation goroutine.
- Parameters: None
- Returns: None