This commit is contained in:
Your Name
2026-12-03 09:54:46 +08:00
parent 4e0c2daf5c
commit 25070a4889
55 changed files with 8040 additions and 536 deletions
+28 -2
View File
@@ -4,11 +4,13 @@ declare(strict_types=1);
namespace app\command;
use app\common\service\prescriptionai\PrescriptionAiLaneGuard;
use app\common\service\prescriptionai\PrescriptionAiStore;
use app\common\service\prescriptionai\PrescriptionAiWorker;
use think\console\Command;
use think\facade\Config;
use think\facade\Db;
use think\facade\Log;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
@@ -19,16 +21,26 @@ final class PrescriptionAiWork extends Command
{
$this->setName('prescription-ai:work')->setDescription('处方AI独立后台任务;分别运行prepare/qwen/openai')
->addOption('lane', null, Option::VALUE_REQUIRED, 'prepare、qwen、openai', 'prepare')
->addOption('once', null, Option::VALUE_NONE, '只处理一轮');
->addOption('once', null, Option::VALUE_NONE, '只处理一轮')
->addOption('scheduled', null, Option::VALUE_NONE, '定时任务单轮接管,当前队列已占用时跳过');
}
protected function execute(Input $input, Output $output): int
{
$lane = (string) $input->getOption('lane');
if (!in_array($lane, ['prepare', 'qwen', 'openai'], true)) {
if (!in_array($lane, PrescriptionAiLaneGuard::LANES, true)) {
$output->writeln('Invalid lane');
return 1;
}
$scheduled = $input->getOption('scheduled');
if ($scheduled && !$input->getOption('once')) {
$output->writeln('--scheduled requires --once');
return 1;
}
// This handle stays open until execute() returns. Process exit also releases it after a crash.
$laneLock = PrescriptionAiLaneGuard::acquire($this->app->getRuntimePath(), $lane,
$scheduled ? LOCK_EX | LOCK_NB : LOCK_SH);
if ($laneLock === null) { return 0; }
$running = true;
if (function_exists('pcntl_async_signals')) {
pcntl_async_signals(true);
@@ -48,6 +60,11 @@ final class PrescriptionAiWork extends Command
$sweepAt = 0;
$sourceCursor = 0;
$rxCursor = 0;
if ($scheduled && $lane === 'prepare') {
$saved = json_decode((string) stream_get_contents($laneLock), true);
$sourceCursor = (int) ($saved['source'] ?? 0);
$rxCursor = (int) ($saved['prescription'] ?? 0);
}
do {
$worked = false;
try {
@@ -60,6 +77,12 @@ final class PrescriptionAiWork extends Command
$sourceCursor = $sweep['selected'] > 0 ? $sweep['last_id'] : 0;
$rx = $worker->reconcile($rxCursor);
$rxCursor = $rx['selected'] > 0 ? $rx['last_id'] : 0;
if ($scheduled) {
rewind($laneLock);
ftruncate($laneLock, 0);
fwrite($laneLock, json_encode(['source' => $sourceCursor, 'prescription' => $rxCursor]));
fflush($laneLock);
}
$sweepAt = time() + 60;
}
}
@@ -73,6 +96,9 @@ final class PrescriptionAiWork extends Command
$detail .= ' ' . $sqlState[0];
}
$output->writeln('PRESCRIPTION_AI storage_or_configuration_error ' . $detail);
if ($scheduled) {
Log::write('PRESCRIPTION_AI ' . $lane . ' storage_or_configuration_error ' . $detail, 'error');
}
// Drop a possibly dead connection so the next round reconnects instead of looping.
try {
Db::connect()->close();