config-central/src/State.psm1

97 lines
4.0 KiB
PowerShell

Set-StrictMode -Version Latest
function Get-ConfigCentralPaths {
param([string]$DataRoot)
if ([string]::IsNullOrWhiteSpace($DataRoot)) {
if ([string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) { throw 'LOCALAPPDATA is unavailable; pass -DataRoot.' }
$DataRoot = Join-Path $env:LOCALAPPDATA 'ConfigCentral'
}
[pscustomobject]@{
Root = $DataRoot
State = Join-Path $DataRoot 'state.json'
Settings = Join-Path $DataRoot 'settings.json'
Logs = Join-Path $DataRoot 'logs'
Backups = Join-Path $DataRoot 'backups'
Snapshots = Join-Path $DataRoot 'snapshots'
Lock = Join-Path $DataRoot 'apply.lock'
}
}
function Initialize-ConfigCentralData {
param($Paths)
foreach ($path in @($Paths.Root, $Paths.Logs, $Paths.Backups, $Paths.Snapshots)) {
[void](New-Item -ItemType Directory -Path $path -Force)
}
}
function Read-JsonState {
param([string]$Path, $Default)
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $Default }
try { return Get-Content -LiteralPath $Path -Raw | ConvertFrom-Json -AsHashtable -Depth 32 }
catch { throw "Cannot read state '$Path': $($_.Exception.Message)" }
}
function Write-JsonAtomic {
param([Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)]$Value)
$directory = Split-Path -Parent $Path
[void](New-Item -ItemType Directory -Path $directory -Force)
$temporary = "$Path.$([guid]::NewGuid().ToString('N')).tmp"
try {
$Value | ConvertTo-Json -Depth 32 | Set-Content -LiteralPath $temporary -Encoding utf8NoBOM
[System.IO.File]::Move($temporary, $Path, $true)
}
finally { if (Test-Path -LiteralPath $temporary) { Remove-Item -LiteralPath $temporary -Force } }
}
function Enter-ApplyLock {
param($Paths)
Initialize-ConfigCentralData $Paths
try {
$stream = [System.IO.File]::Open($Paths.Lock, 'OpenOrCreate', 'ReadWrite', 'None')
$writer = [System.IO.StreamWriter]::new($stream, [System.Text.Encoding]::UTF8, 1024, $true)
$stream.SetLength(0)
$writer.Write("pid=$PID started=$([DateTimeOffset]::UtcNow.ToString('o'))")
$writer.Flush()
return $stream
}
catch { throw "Another Config Central apply appears to be running: $($_.Exception.Message)" }
}
function Exit-ApplyLock {
param($Lock, $Paths)
if ($null -ne $Lock) { $Lock.Dispose() }
Remove-Item -LiteralPath $Paths.Lock -Force -ErrorAction SilentlyContinue
}
function New-RunContext {
param($Paths, [string]$Command, [string]$Revision)
Initialize-ConfigCentralData $Paths
$runId = [DateTimeOffset]::UtcNow.ToString('yyyyMMddTHHmmssfffZ')
[pscustomobject]@{
id = $runId
command = $Command
revision = $Revision
startedAt = [DateTimeOffset]::UtcNow.ToString('o')
logPath = Join-Path $Paths.Logs "$runId.log"
results = [System.Collections.Generic.List[object]]::new()
}
}
function Add-RunResult {
param($Run, [string]$Kind, [string]$Name, [string]$Status, [string]$Message)
$result = [pscustomobject]@{ kind = $Kind; name = $Name; status = $Status; message = $Message }
$Run.results.Add($result)
"[$([DateTimeOffset]::UtcNow.ToString('o'))] $Kind $Name $Status $Message" | Add-Content -LiteralPath $Run.logPath -Encoding utf8
return $result
}
function Complete-Run {
param($Run, $Paths, $State, [bool]$Succeeded)
$Run | Add-Member -NotePropertyName completedAt -NotePropertyValue ([DateTimeOffset]::UtcNow.ToString('o')) -Force
$Run | Add-Member -NotePropertyName succeeded -NotePropertyValue $Succeeded -Force
$State.lastRun = [ordered]@{ id = $Run.id; command = $Run.command; revision = $Run.revision; completedAt = $Run.completedAt; succeeded = $Succeeded }
Write-JsonAtomic -Path $Paths.State -Value $State
}
Export-ModuleMember -Function Get-ConfigCentralPaths, Initialize-ConfigCentralData, Read-JsonState, Write-JsonAtomic, Enter-ApplyLock, Exit-ApplyLock, New-RunContext, Add-RunResult, Complete-Run