netgescon-day0/app/Services/GesconImport/ImportProgressLogger.php

108 lines
3.2 KiB
PHP

<?php
namespace App\Services\GesconImport;
class ImportProgressLogger
{
private string $baseDir;
private string $logDir;
private string $key;
public function __construct(?string $baseDir = null)
{
$this->baseDir = $baseDir ?: '/home/michele/netgescon/docs/logs';
$this->logDir = rtrim($this->baseDir, DIRECTORY_SEPARATOR);
if (!is_dir($this->logDir)) {
@mkdir($this->logDir, 0775, true);
}
$this->key = '';
}
public function begin(string $task, array $context = []): string
{
$this->key = $this->makeKey($task, $context);
$this->writeState('started', $context);
$this->appendJsonl(['event' => 'begin', 'context' => $context]);
return $this->key;
}
public function checkpoint(string $step, array $data = []): void
{
$this->appendJsonl(['event' => 'checkpoint', 'step' => $step, 'data' => $data]);
$this->writeState('running', ['last_step' => $step, 'data' => $data]);
}
public function stdout(string $chunk): void
{
$this->appendText($chunk);
}
public function error(string $message, array $data = []): void
{
$this->appendJsonl(['event' => 'error', 'message' => $message, 'data' => $data]);
$this->writeState('error', ['message' => $message] + $data);
}
public function finish(array $summary = []): void
{
$this->appendJsonl(['event' => 'finish', 'summary' => $summary]);
$this->writeState('finished', $summary);
}
public function getStatePath(): string
{
return $this->filePath('state.json');
}
public function getLogPath(): string
{
return $this->filePath('progress.jsonl');
}
public function getStdoutPath(): string
{
return $this->filePath('stdout.log');
}
private function writeState(string $status, array $data): void
{
$payload = [
'status' => $status,
'updated_at' => date('c'),
'task_key' => $this->key,
] + $data;
@file_put_contents($this->getStatePath(), json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
}
private function appendJsonl(array $row): void
{
$row['ts'] = date('c');
@file_put_contents($this->getLogPath(), json_encode($row, JSON_UNESCAPED_UNICODE) . "\n", FILE_APPEND);
}
private function appendText(string $text): void
{
@file_put_contents($this->getStdoutPath(), $text, FILE_APPEND);
}
private function filePath(string $name): string
{
$dir = $this->logDir . DIRECTORY_SEPARATOR . $this->key;
if (!is_dir($dir)) @mkdir($dir, 0775, true);
return $dir . DIRECTORY_SEPARATOR . $name;
}
private function makeKey(string $task, array $ctx): string
{
$parts = [
'gescon',
preg_replace('/[^a-z0-9_-]/i', '-', $task),
];
foreach (['legacy_code', 'stabile_id', 'amministratore_id', 'anno', 'solo'] as $k) {
if (isset($ctx[$k]) && $ctx[$k] !== null && $ctx[$k] !== '') {
$parts[] = $k . '-' . preg_replace('/[^a-z0-9_-]/i', '-', (string)$ctx[$k]);
}
}
$parts[] = date('Ymd-His');
return implode('_', $parts);
}
}