Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/local-profile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ on:
- 'src/Civ13/AccessFileSync.php'
- 'src/Civ13/AccessListProjection.php'
- 'src/Civ13/PortableProfile.php'
- 'src/Civ13/LogLevelSetting.php'
- 'src/Civ13/HostedVerificationSource.php'
- 'src/Civ13/HostedVerificationSnapshot.php'
- 'src/Civ13/Verifier.php'
Expand Down Expand Up @@ -65,6 +66,7 @@ jobs:
extensions: sodium
coverage: none
- run: php tests/local/run.php
- run: php tests/local/log-level.php
- run: php tests/local/admin-sync-projection.php
- run: php tests/local/admin-file-sync-profile.php
- run: php tests/local/admin-file-writer.php
Expand Down
10 changes: 8 additions & 2 deletions bot.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ function loadEnv(string $filePath, bool $explicit = false): array
require_once __DIR__.'/src/Civ13/PortableProfile.php';
require_once __DIR__.'/src/Civ13/PortableProcess.php';
require_once __DIR__.'/src/Civ13/DefaultBranchGuard.php';
require_once __DIR__.'/src/Civ13/LogLevelSetting.php';
$portable = null;
$portableLock = null;
$portablePath = getenv('CIVILIZATIONBOT_PROFILE');
Expand Down Expand Up @@ -142,10 +143,15 @@ function loadEnv(string $filePath, bool $explicit = false): array
if ($portable !== null && (!in_array('TOKEN', $loadedNames, true) || !getenv('TOKEN'))) { throw new \RuntimeException('Separate profile environment must explicitly supply TOKEN'); }

if ($portable === null) { file_put_contents($baseDir.'/output.log', ''); } // Clear the contents of 'output.log'
$fileHandler = (new StreamHandler(($portable['state_dir'] ?? $baseDir).'/output.log', Level::Debug))->setFormatter(new LineFormatter(null, null, true, true, true));
$stdoutHandler = (new StreamHandler('php://stdout', Level::Debug))->setFormatter(new LineFormatter(null, null, true, true, true));
// Profile log_level (set from the launcher's Civilizationbot tab), else LOG_LEVEL, else info. Never blocks boot.
[$logLevelName, $logLevelWarning] = \Civ13\LogLevelSetting::resolve($portable['log_level'] ?? null, getenv('LOG_LEVEL'));
$logLevel = Level::fromName($logLevelName);
$fileHandler = (new StreamHandler(($portable['state_dir'] ?? $baseDir).'/output.log', $logLevel))->setFormatter(new LineFormatter(null, null, true, true, true));
$stdoutHandler = (new StreamHandler('php://stdout', $logLevel))->setFormatter(new LineFormatter(null, null, true, true, true));
$logger = new Logger('Civ13', [$fileHandler, $stdoutHandler]);
Loop::addPeriodicTimer(60 * 10, fn () => $logger->reset()); // Flush all buffers every 10 minutes
if ($logLevelWarning !== null) { $logger->warning($logLevelWarning); }
$logger->notice('Log level: '.$logLevelName);
$logger->info('Loading configurations for the bot...');
set_rejection_handler(function (\Throwable $e) use ($logger) {
if ($e->getMessage() !== 'Cannot resume a fiber that is not suspended') {
Expand Down
5 changes: 5 additions & 0 deletions docs/windows-test1714.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ start never refuses because of the source check: it prints "Source check warning
(starting anyway): ..." and boots the current checkout, so a guard problem can always
be fixed from the launcher with Update or Repair and update.

Logging defaults to info. The optional top-level profile key `log_level` (debug, info,
notice, warning or error; the Civ13 launcher's Civilizationbot tab sets it) or the
`LOG_LEVEL` environment value changes it at the next start. An unknown value logs a
warning and uses info; it never stops the bot from starting.

status reports whether the state lock is held (running), any pending stop or
reload marker, and the stdout/stderr log paths. check-update fetches origin/main
like start does and reports current, available, behind, can_update and reason;
Expand Down
4 changes: 2 additions & 2 deletions src/Civ13/Civ13.php
Original file line number Diff line number Diff line change
Expand Up @@ -670,7 +670,7 @@ private function resolveOptions(array &$options = []): array
$this->welcome_message = $options['welcome_message'];

if (! $options['logger']) {
$streamHandler = new StreamHandler('php://stdout', Level::Debug);
$streamHandler = new StreamHandler('php://stdout', Level::Info);
$streamHandler->setFormatter(new LineFormatter(null, null, true, true));
$options['logger'] = new Logger(self::class, [$streamHandler]);
}
Expand Down Expand Up @@ -867,7 +867,7 @@ private static function initialLogger(array $options): LoggerInterface
return $logger;
}

return new Logger(self::class, [new StreamHandler('php://stdout', Level::Debug)]);
return new Logger(self::class, [new StreamHandler('php://stdout', Level::Info)]);
}

/** The command prefix `$content` starts with (bot mention or `command_symbol`), or null. */
Expand Down
26 changes: 26 additions & 0 deletions src/Civ13/LogLevelSetting.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Civ13;

/**
* The bot's log level: the portable profile's `log_level`, else the LOG_LEVEL environment value, else info.
* An unknown value falls back to info with a warning; it never stops the bot from starting.
*/
final class LogLevelSetting
{
public const DEFAULT = 'info';
/** The levels the launcher offers, quietest last. */
public const NAMES = ['debug', 'info', 'notice', 'warning', 'error'];

/** @return array{0: string, 1: ?string} the level name and a warning for an ignored value, or null. */
public static function resolve(mixed $profileValue, mixed $environmentValue): array
{
foreach (['profile log_level' => $profileValue, 'LOG_LEVEL' => $environmentValue] as $source => $value) {
if ($value === null || $value === false || $value === '') { continue; }
$name = is_string($value) ? strtolower(trim($value)) : '';
if (in_array($name, self::NAMES, true)) { return [$name, null]; }
return [self::DEFAULT, 'Unknown '.$source.' '.json_encode($value).'; using '.self::DEFAULT.' (expected one of '.implode(', ', self::NAMES).')'];
}
return [self::DEFAULT, null];
}
}
21 changes: 21 additions & 0 deletions tests/local/log-level.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
// Offline: the log level never blocks boot and defaults to info.
require __DIR__.'/../../src/Civ13/LogLevelSetting.php';
use Civ13\LogLevelSetting;
function check(bool $ok, string $name): void { if (!$ok) { throw new RuntimeException($name); } }
check(LogLevelSetting::resolve(null, false) === ['info', null], 'default is info');
check(LogLevelSetting::resolve(null, '') === ['info', null], 'empty env is info');
foreach (LogLevelSetting::NAMES as $name) {
check(LogLevelSetting::resolve($name, false) === [$name, null], 'profile '.$name);
check(LogLevelSetting::resolve(null, strtoupper($name)) === [$name, null], 'env '.$name);
}
check(LogLevelSetting::resolve('warning', 'debug') === ['warning', null], 'profile wins over env');
check(LogLevelSetting::resolve(' Error ', false) === ['error', null], 'trim and case');
foreach (['verbose', 7, true, ['debug']] as $bad) {
[$level, $warning] = LogLevelSetting::resolve($bad, 'debug');
check($level === 'info' && is_string($warning) && str_contains($warning, 'profile log_level'), 'bad profile falls back to info');
}
[$level, $warning] = LogLevelSetting::resolve(null, 'loud');
check($level === 'info' && str_contains((string) $warning, 'LOG_LEVEL'), 'bad env falls back to info');
echo "log level: ok\n";
4 changes: 2 additions & 2 deletions tests/windows/bootstrap.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?php
declare(strict_types=1);
// Real bootstrap through final options assembly; only external-effect dependencies are inert fixtures.
namespace Monolog { class Level { public const Debug=100; } class Logger { public function __construct(...$args) {} public function info(...$args):void {} } }
namespace Monolog { class Level { public const Debug=100; public static function fromName(string $name): string { return $name; } } class Logger { public function __construct(...$args) {} public function info(...$args):void {} public function notice(...$args):void {} public function warning(...$args):void {} } }
namespace Monolog\Formatter { class LineFormatter { public function __construct(...$args) {} } }
namespace Monolog\Handler { class StreamHandler { public function __construct(...$args) {} public function setFormatter($formatter) { return $this; } } }
namespace Discord { class Discord { public function __construct(array $options) {} } class Stats { public static function new($discord) { return new self(); } } }
Expand Down Expand Up @@ -35,7 +35,7 @@ function check(bool $ok): void { if (!$ok) { throw new RuntimeException('Bootstr
$previous=getcwd();$previousProfile=getenv('CIVILIZATIONBOT_PROFILE');
try {
file_put_contents($root.'/vendor/autoload.php','<?php return 1;');
foreach(['PortableProfile','PortableProcess'] as $class) { copy(__DIR__.'/../../src/Civ13/'.$class.'.php',$root.'/src/Civ13/'.$class.'.php'); }
foreach(['PortableProfile','PortableProcess','LogLevelSetting'] as $class) { copy(__DIR__.'/../../src/Civ13/'.$class.'.php',$root.'/src/Civ13/'.$class.'.php'); }
// Git/network admission is covered by default-branch.php; this fixture
// isolates subsequent bootstrap option assembly with synthetic inputs.
file_put_contents($root.'/src/Civ13/DefaultBranchGuard.php', '<?php namespace Civ13; final class DefaultBranchGuard { public static function verify(string $root): array { $GLOBALS["bootstrap_guard_seen"] = true; return []; } }');
Expand Down
2 changes: 1 addition & 1 deletion tests/windows/default-branch.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ function refused(callable $call):void { try{$call();}catch(RuntimeException $err

// Real control/direct bootstrap refuses detached source before credentials, Composer, spawn or network.
$app=$root.'/app';$state=$root.'/state';mkdir($app);mkdir($state);mkdir($app.'/vendor');mkdir($app.'/scripts');mkdir($app.'/scripts/windows');mkdir($app.'/src');mkdir($app.'/src/Civ13');
foreach(['DefaultBranchGuard','PortableProfile','PortableProcess'] as $class){copy(__DIR__.'/../../src/Civ13/'.$class.'.php',$app.'/src/Civ13/'.$class.'.php');}
foreach(['DefaultBranchGuard','PortableProfile','PortableProcess','LogLevelSetting'] as $class){copy(__DIR__.'/../../src/Civ13/'.$class.'.php',$app.'/src/Civ13/'.$class.'.php');}
copy(__DIR__.'/../../scripts/windows/control.php',$app.'/scripts/windows/control.php');copy(__DIR__.'/../../bot.php',$app.'/bot.php');file_put_contents($app.'/vendor/autoload.php','<?php throw new RuntimeException("Composer must not load");');
file_put_contents($root.'/separate.env','invalid fixture; must never load');
$server=['basedir'=>$app,'ip'=>'127.0.0.1','port'=>1714,'name'=>'fixture','host'=>'fixture','enabled'=>false];foreach(['discussion','playercount','ooc','lobby','asay','ic','transit','adminlog','debug','garbage','runtime','attack']as$key){$server[$key]='';}
Expand Down
Loading