382 lines
23 KiB
PHP
382 lines
23 KiB
PHP
<?php
|
||
|
||
declare(strict_types=1);
|
||
|
||
namespace app\common\service\assistantservice;
|
||
|
||
use app\adminapi\logic\tcm\AssistantServiceLogic;
|
||
use DomainException;
|
||
use RuntimeException;
|
||
use think\facade\Db;
|
||
|
||
/** 单机自动调度:只发现已归档来源;模型调用仍由原持久队列消费者执行。 */
|
||
final class AssistantServiceAutomation
|
||
{
|
||
private const CHANNELS = ['im', 'manual', 'tracking'];
|
||
private const DAYS = 30;
|
||
private string $directory;
|
||
private \Closure $clock;
|
||
|
||
public function __construct(?string $directory = null, ?callable $clock = null)
|
||
{
|
||
// CLI 与 adminapi 必须读取同一目录;不能使用分应用的 runtime_path()。
|
||
$this->directory = rtrim($directory ?? root_path('runtime') . 'assistant_service_automation', '/\\');
|
||
$this->clock = $clock === null ? static fn (): int => time() : \Closure::fromCallable($clock);
|
||
}
|
||
|
||
/** 只读状态,不建任务、不触发同步或模型,也不公开运行账号与队列内容。 */
|
||
public static function status(?string $directory = null, ?int $now = null): array
|
||
{
|
||
$self = new self($directory);
|
||
$now = $now ?? time();
|
||
$interval = self::interval();
|
||
$result = ['enabled' => (bool) config('assistant_service.auto_enabled', false), 'state' => 'disabled',
|
||
'last_scan_at' => 0, 'next_scan_at' => 0, 'interval_seconds' => $interval,
|
||
'quiet_seconds' => self::quiet(), 'days' => self::DAYS, 'reason' => '自动分析尚未启用'];
|
||
if (!$result['enabled']) { return $result; }
|
||
$result['state'] = 'waiting';
|
||
try {
|
||
$scan = $self->read('scan.json');
|
||
$result['last_scan_at'] = (int) ($scan['last_scan_at'] ?? 0);
|
||
$result['next_scan_at'] = (int) ($scan['next_scan_at'] ?? 0);
|
||
$actorId = (int) config('assistant_service.auto_actor_id', 0);
|
||
if ($actorId <= 0) { return array_replace($result, ['state' => 'error', 'reason' => '自动分析尚未绑定有效的主管账号']); }
|
||
if (!config('assistant_service.enabled', false)) {
|
||
return array_replace($result, ['state' => 'error', 'reason' => 'AI 分析尚未启用']);
|
||
}
|
||
if (!$scan || (int) ($scan['actor_id'] ?? 0) !== $actorId) {
|
||
return array_replace($result, ['last_scan_at' => 0, 'next_scan_at' => 0, 'reason' => '等待自动检查进程首次运行']);
|
||
}
|
||
if (($scan['state'] ?? '') === 'error') {
|
||
return array_replace($result, ['state' => 'error', 'reason' => self::reason((string) ($scan['reason_code'] ?? 'storage'))]);
|
||
}
|
||
if ($result['last_scan_at'] <= 0 || $result['last_scan_at'] < $now - max(120, $interval * 3)) {
|
||
return array_replace($result, ['reason' => '自动检查心跳已过期,等待检查进程恢复']);
|
||
}
|
||
if (($scan['reason_code'] ?? '') === 'daily_limit') {
|
||
return array_replace($result, ['reason' => self::reason('daily_limit')]);
|
||
}
|
||
$health = $self->read('workers.json');
|
||
$active = false;
|
||
foreach ($health['workers'] ?? [] as $worker) {
|
||
$ttl = ($worker['phase'] ?? '') === 'working'
|
||
? max(90, (int) config('assistant_service.timeout', 120) + 60) : 90;
|
||
if (in_array($worker['phase'] ?? '', ['working', 'idle'], true)
|
||
&& (int) ($worker['at'] ?? 0) >= $now - $ttl) { $active = true; break; }
|
||
}
|
||
return array_replace($result, $active
|
||
? ['state' => 'running', 'reason' => self::scanReason($scan['summary'] ?? [])]
|
||
: ['reason' => '自动检查已运行,等待分析处理进程恢复;' . self::scanReason($scan['summary'] ?? [])]);
|
||
} catch (\Throwable $e) {
|
||
return array_replace($result, ['state' => 'error', 'reason' => self::reason('storage')]);
|
||
}
|
||
}
|
||
|
||
/** 每轮实际工作前后调用;不改变消费者的认领、生成或提交语义。 */
|
||
public static function workerHeartbeat(string $phase, ?string $directory = null, ?int $now = null): void
|
||
{
|
||
if (!in_array($phase, ['working', 'idle', 'error', 'stopped'], true)) { throw new \InvalidArgumentException('Invalid worker phase'); }
|
||
$self = new self($directory);
|
||
$self->ensureDirectory();
|
||
$lock = $self->lock('workers.lock', false);
|
||
try {
|
||
$now = $now ?? time();
|
||
$health = $self->read('workers.json');
|
||
$workers = array_filter($health['workers'] ?? [], static fn (array $row): bool => (int) ($row['at'] ?? 0) > $now - 3600);
|
||
$workers[(string) getmypid()] = ['phase' => $phase, 'at' => $now];
|
||
uasort($workers, static fn (array $a, array $b): int => $b['at'] <=> $a['at']);
|
||
$self->write('workers.json', ['workers' => array_slice($workers, 0, 64, true)]);
|
||
} finally { flock($lock, LOCK_UN); fclose($lock); }
|
||
}
|
||
|
||
public function tick(): array
|
||
{
|
||
$counts = ['scanned' => 0, 'enqueued' => 0, 'skipped' => 0, 'quiet' => 0, 'no_sources' => 0,
|
||
'source_limit' => 0, 'unavailable_channels' => 0, 'history_limit' => 0, 'invalid_or_changed' => 0];
|
||
if (!config('assistant_service.auto_enabled', false)) { return $counts + ['state' => 'disabled', 'reason' => self::reason('disabled')]; }
|
||
$lock = null;
|
||
$state = [];
|
||
try {
|
||
$this->ensureDirectory();
|
||
$lock = $this->lock('scan.lock', true);
|
||
if ($lock === null) { return $counts + ['state' => 'waiting', 'reason' => '另一自动检查进程正在运行']; }
|
||
$state = $this->read('scan.json');
|
||
$now = ($this->clock)();
|
||
$actorId = (int) config('assistant_service.auto_actor_id', 0);
|
||
if ((int) ($state['actor_id'] ?? 0) !== $actorId) { $state = []; }
|
||
$state['actor_id'] = $actorId;
|
||
if ($actorId <= 0) { return $this->finish($state, $counts, 'error', 'actor'); }
|
||
try {
|
||
$actor = AssistantServiceAccess::actor($actorId, 'analyze');
|
||
if (!(int) $actor['root'] && !array_intersect($actor['role_id'], [3, 7, 8])) { throw new DomainException('manager required'); }
|
||
} catch (DomainException $e) { return $this->finish($state, $counts, 'error', 'actor'); }
|
||
if (!AssistantServiceLogic::automationReady()) { return $this->finish($state, $counts, 'error', 'configuration'); }
|
||
if ((int) ($state['next_scan_at'] ?? 0) > $now && ($state['state'] ?? '') !== 'error') {
|
||
return $counts + ['state' => 'waiting', 'reason' => '等待下次自动检查'];
|
||
}
|
||
|
||
$staffIds = array_column(AssistantServiceAccess::assistantRows($actorId, $actor), 'id');
|
||
$batch = max(1, min(10, (int) config('assistant_service.auto_batch_size', 10)));
|
||
$scanLimit = max(30, min(300, $batch * 10));
|
||
$perChannel = (int) ceil($scanLimit / count(self::CHANNELS));
|
||
$available = $this->availableChannels();
|
||
$counts['unavailable_channels'] = count(array_filter($available, static fn (bool $ready): bool => !$ready));
|
||
// 保留最近发现的资料问题,避免游标经过空页时把尚未解决的问题隐藏。
|
||
$problems = array_filter($state['problems'] ?? [], static fn (array $problem): bool => (int) ($problem['at'] ?? 0) >= $now - 3600);
|
||
$pages = []; $positions = []; $cursors = $state['cursors'] ?? [];
|
||
foreach (self::CHANNELS as $channel) {
|
||
$pages[$channel] = $staffIds && $available[$channel]
|
||
? $this->candidates($channel, $actorId, $actor, $staffIds, $cursors[$channel] ?? [0, 0], $perChannel, $now) : [];
|
||
$positions[$channel] = 0;
|
||
// 到末尾后下一轮回到起点;安静期、额度、权限变更后仍会再检查。
|
||
if (!$pages[$channel]) { $cursors[$channel] = [0, 0]; }
|
||
}
|
||
$turn = (int) ($state['channel_next'] ?? 0) % count(self::CHANNELS);
|
||
$seen = []; $empty = 0; $quota = false;
|
||
while ($counts['scanned'] < $scanLimit && $counts['enqueued'] < $batch && $empty < count(self::CHANNELS)) {
|
||
$channel = self::CHANNELS[$turn];
|
||
$turn = ($turn + 1) % count(self::CHANNELS);
|
||
$candidate = $pages[$channel][$positions[$channel]++] ?? null;
|
||
if ($candidate === null) { $empty++; continue; }
|
||
$empty = 0;
|
||
$counts['scanned']++;
|
||
$previous = $cursors[$channel] ?? [0, 0];
|
||
$cursors[$channel] = [(int) $candidate['source_id'], (int) $candidate['diagnosis_id']];
|
||
$assistantId = $this->candidateAssistant($channel, $candidate, $staffIds);
|
||
$key = $assistantId . ':' . $candidate['diagnosis_id'];
|
||
if ($assistantId <= 0 || isset($seen[$key])) { $counts['skipped']++; continue; }
|
||
$seen[$key] = true;
|
||
unset($problems[$key]);
|
||
try {
|
||
$context = AssistantServiceContext::build((int) $candidate['diagnosis_id'], $actorId, self::DAYS, $assistantId);
|
||
if (!$context['sources']) { $counts['no_sources']++; $counts['skipped']++; continue; }
|
||
if (!$this->quietContext($context, $now)) { $counts['quiet']++; $counts['skipped']++; continue; }
|
||
$decision = $this->analysisDecision($context, $assistantId);
|
||
if ($decision !== 'new') {
|
||
if ($decision === 'history_limit') {
|
||
$counts['history_limit']++;
|
||
$problems[$key] = ['code' => 'history_limit', 'at' => $now];
|
||
}
|
||
$counts['skipped']++; continue;
|
||
}
|
||
if ($this->dailyLimit($actorId)) { $quota = true; $cursors[$channel] = $previous; break; }
|
||
AssistantServiceLogic::analyzeAutomatic(['diagnosis_id' => (int) $candidate['diagnosis_id'],
|
||
'assistant_id' => $assistantId, 'days' => self::DAYS, 'scenario' => 'followup'], $actorId);
|
||
$counts['enqueued']++;
|
||
} catch (DomainException $e) {
|
||
// 入队事务内也检查额度;并发人工任务可能正好用完剩余额度。
|
||
if ($this->dailyLimit($actorId)) { $quota = true; $cursors[$channel] = $previous; break; }
|
||
$problem = $e->getCode() === 413 ? 'source_limit' : 'invalid_or_changed';
|
||
$counts[$problem]++;
|
||
if ($problem === 'source_limit') { $problems[$key] = ['code' => $problem, 'at' => $now]; }
|
||
$counts['skipped']++;
|
||
}
|
||
}
|
||
$state['cursors'] = $cursors;
|
||
$state['problems'] = array_slice($problems, -300, null, true);
|
||
$state['channel_next'] = $turn;
|
||
$state['last_scan_at'] = $now;
|
||
return $this->finish($state, $counts, $quota ? 'waiting' : 'running', $quota ? 'daily_limit' : 'ok');
|
||
} catch (\Throwable $e) {
|
||
// 错误文本可能包含患者资料、SQL 或凭据,只记录稳定原因码。
|
||
try { return $this->finish($state, $counts, 'error', 'storage'); }
|
||
catch (\Throwable $ignored) { return $counts + ['state' => 'error', 'reason' => self::reason('storage')]; }
|
||
} finally {
|
||
if (is_resource($lock)) { flock($lock, LOCK_UN); fclose($lock); }
|
||
}
|
||
}
|
||
|
||
private function candidates(string $channel, int $actorId, array $actor, array $staff, array $cursor, int $limit, int $now): array
|
||
{
|
||
$query = AssistantServiceAccess::patientQuery($actorId, $actor);
|
||
$fields = 's.id AS source_id,d.id AS diagnosis_id,d.patient_id';
|
||
if ($channel === 'im') {
|
||
// 同一患者聊天仅自动落到当前有权可见的最新有效诊单,避免多诊单重复调用模型。
|
||
// 人工登记与跟踪备注仍使用其自身绑定的诊单。
|
||
$latest = AssistantServiceAccess::patientQuery($actorId, $actor)->field('MAX(d.id)')->group('d.patient_id')->buildSql();
|
||
$query->whereRaw('d.id IN ' . $latest);
|
||
$peers = array_map(static fn (int $id): string => 'doctor_' . $id, $staff);
|
||
$query->join('tcm_im_chat_message s', 's.patient_id = d.patient_id')->where('s.msg_type', 'text')
|
||
->where('s.msg_time', '>=', $now - self::DAYS * 86400)->where('s.text', '<>', '')
|
||
->where(static function ($q) use ($peers): void { $q->whereIn('s.from_account', $peers)->whereOr('s.to_account', 'in', $peers); });
|
||
$fields .= ',s.from_account,s.to_account';
|
||
} elseif ($channel === 'manual') {
|
||
$query->join('assistant_service_record s', 's.diagnosis_id = d.id AND s.patient_id = d.patient_id')
|
||
->whereNull('s.delete_time')->whereIn('s.actor_id', $staff)->where('s.occurred_at', '>=', $now - self::DAYS * 86400)
|
||
->where('s.content', '<>', '');
|
||
$fields .= ',s.actor_id AS assistant_id';
|
||
} else {
|
||
$query->join('tracking_note s', 's.diagnosis_id = d.id')->whereNull('s.delete_time')->whereIn('s.admin_id', $staff)
|
||
->where('s.note_date', '>=', date('Y-m-d', $now - self::DAYS * 86400))->where('s.content', '<>', '');
|
||
$fields .= ',s.admin_id AS assistant_id';
|
||
}
|
||
$sourceId = (int) ($cursor[0] ?? 0); $diagnosisId = (int) ($cursor[1] ?? 0);
|
||
$query->where(static function ($q) use ($sourceId, $diagnosisId): void {
|
||
$q->where('s.id', '>', $sourceId)->whereOr(static function ($q) use ($sourceId, $diagnosisId): void {
|
||
$q->where('s.id', $sourceId)->where('d.id', '>', $diagnosisId);
|
||
});
|
||
});
|
||
return $query->field($fields)->order('s.id', 'asc')->order('d.id', 'asc')->limit($limit)->select()->toArray();
|
||
}
|
||
|
||
private function candidateAssistant(string $channel, array $row, array $staff): int
|
||
{
|
||
if ($channel !== 'im') { return (int) $row['assistant_id']; }
|
||
$patient = 'patient_' . (int) $row['patient_id'];
|
||
if ((int) $row['patient_id'] <= 0) { return 0; }
|
||
$peer = $row['from_account'] === $patient ? $row['to_account'] : ($row['to_account'] === $patient ? $row['from_account'] : '');
|
||
$id = preg_match('/^doctor_([1-9][0-9]*)$/D', $peer, $match) === 1 ? (int) $match[1] : 0;
|
||
return in_array($id, $staff, true) ? $id : 0;
|
||
}
|
||
|
||
private function quietContext(array $context, int $now): bool
|
||
{
|
||
$cutoff = $now - self::quiet();
|
||
$ids = ['im' => [], 'manual' => [], 'tracking' => []];
|
||
foreach ($context['sources'] as $source) {
|
||
if ((int) $source['occurred_at'] > $cutoff) { return false; }
|
||
[$channel, $id] = explode(':', $source['id'], 2);
|
||
$ids[$channel][] = (int) $id;
|
||
}
|
||
// 补录历史日期、当天追加跟踪备注也必须先等安静期。
|
||
foreach (['manual' => ['assistant_service_record', ['created_at']], 'tracking' => ['tracking_note', ['create_time', 'update_time']],
|
||
'im' => ['tcm_im_chat_message', ['create_time']]] as $channel => [$table, $timestamps]) {
|
||
if (!$ids[$channel]) { continue; }
|
||
$fields = Db::name($table)->getFields();
|
||
foreach ($timestamps as $timestamp) {
|
||
if (isset($fields[$timestamp]) && (int) Db::name($table)->whereIn('id', $ids[$channel])->max($timestamp) > $cutoff) { return false; }
|
||
}
|
||
}
|
||
return true;
|
||
}
|
||
|
||
private function analysisDecision(array $context, int $assistantId): string
|
||
{
|
||
$query = Db::name('assistant_service_job')->where('patient_id', $context['patient']['patient_id'])->where('type', 'analysis');
|
||
$imOnly = count(array_filter($context['sources'], static fn (array $source): bool => $source['channel'] !== 'im')) === 0;
|
||
// 新建诊单可能改变 IM 的最新诊单映射;没有新增聊天时仍不能为同一患者重复生成。
|
||
if (!$imOnly) { $query->where('diagnosis_id', $context['patient']['diagnosis_id']); }
|
||
// 跨创建人、场景和时间范围保护正在执行或结果未知的同一目标任务。
|
||
// 有界检查遇到过多历史时保守跳过,避免把未知结果当成可重试。
|
||
$active = (clone $query)->whereIn('status', ['queued', 'running', 'needs_reconciliation'])->limit(101)->select()->toArray();
|
||
if (count($active) > 100) { return 'history_limit'; }
|
||
foreach ($active as $job) {
|
||
$payload = json_decode((string) $job['payload_json'], true);
|
||
if ((int) ($payload['context']['subject_admin_id'] ?? 0) === $assistantId) { return 'existing'; }
|
||
}
|
||
$history = $query->order('id', 'desc')->limit(101)->select()->toArray();
|
||
foreach ($history as $job) {
|
||
$payload = json_decode((string) $job['payload_json'], true);
|
||
if ((int) ($payload['context']['subject_admin_id'] ?? 0) !== $assistantId) { continue; }
|
||
$previous = [];
|
||
foreach ($payload['context']['sources'] ?? [] as $source) { $previous[$source['id']] = $source; }
|
||
if (!$previous) { return 'history_limit'; }
|
||
foreach ($context['sources'] as $source) {
|
||
if (!isset($previous[$source['id']]) || $previous[$source['id']] !== $source) { return 'new'; }
|
||
}
|
||
// 没有新增或变更文字;来源过期、权限/知识变化不触发重复生成。
|
||
return 'existing';
|
||
}
|
||
return count($history) <= 100 ? 'new' : 'history_limit';
|
||
}
|
||
|
||
private function availableChannels(): array
|
||
{
|
||
$available = ['manual' => true];
|
||
foreach (['im' => ['tcm_im_chat_message', 'id,patient_id,from_account,to_account,msg_type,msg_time,text'],
|
||
'tracking' => ['tracking_note', 'id,diagnosis_id,admin_id,note_date,content,delete_time']] as $channel => [$table, $fields]) {
|
||
try { Db::name($table)->field($fields)->limit(1)->select(); $available[$channel] = true; }
|
||
catch (\Throwable $e) { $available[$channel] = false; }
|
||
}
|
||
return $available;
|
||
}
|
||
|
||
private function dailyLimit(int $actorId): bool
|
||
{
|
||
return (int) Db::name('assistant_service_job')->where('actor_id', $actorId)->where('created_at', '>=', strtotime('today'))->count()
|
||
>= max(1, (int) config('assistant_service.daily_job_limit', 100));
|
||
}
|
||
|
||
private function finish(array $state, array $counts, string $status, string $reason): array
|
||
{
|
||
$state['state'] = $status; $state['reason_code'] = $reason;
|
||
$state['summary'] = $counts;
|
||
foreach ($state['problems'] ?? [] as $problem) {
|
||
if (in_array($problem['code'] ?? '', ['source_limit', 'history_limit'], true)) { $state['summary'][$problem['code']] = 1; }
|
||
}
|
||
$state['last_attempt_at'] = ($this->clock)();
|
||
$state['next_scan_at'] = $state['last_attempt_at'] + self::interval();
|
||
$this->write('scan.json', $state);
|
||
return $counts + ['state' => $status, 'reason' => $reason === 'ok' ? self::scanReason($counts) : self::reason($reason)];
|
||
}
|
||
|
||
private static function interval(): int { return max(5, min(3600, (int) config('assistant_service.auto_interval_seconds', 60))); }
|
||
private static function quiet(): int { return max(0, min(86400, (int) config('assistant_service.auto_quiet_seconds', 300))); }
|
||
|
||
private static function reason(string $code): string
|
||
{
|
||
return ['disabled' => '自动分析尚未启用', 'actor' => '自动分析主管账号或权限不可用,请联系管理员',
|
||
'configuration' => '自动分析所需的数据结构或模型配置尚未就绪', 'storage' => '自动检查暂不可用,请检查运行环境',
|
||
'daily_limit' => '今日分析任务已达上限,未处理来源将在后续检查中继续', 'ok' => '自动检查已完成'][$code] ?? '自动检查暂不可用';
|
||
}
|
||
|
||
private static function scanReason(array $summary): string
|
||
{
|
||
$notes = [];
|
||
foreach (['source_limit' => '部分资料超出分析上限,需人工缩小范围', 'history_limit' => '部分记录的历史任务需人工核对',
|
||
'unavailable_channels' => '部分来源暂不可用', 'invalid_or_changed' => '部分记录因权限或资料变化已跳过',
|
||
'quiet' => '部分沟通尚在等待安静期'] as $key => $message) {
|
||
// 状态供不同团队读取,不能公开调度账号全域的任务或来源数量。
|
||
if ((int) ($summary[$key] ?? 0) > 0) { $notes[] = $message; }
|
||
}
|
||
if (!$notes) {
|
||
$notes[] = (int) ($summary['enqueued'] ?? 0) > 0 ? '新来源已进入分析队列'
|
||
: '本轮没有新增待分析来源,继续等待新来源';
|
||
}
|
||
return implode(';', $notes);
|
||
}
|
||
|
||
private function ensureDirectory(): void
|
||
{
|
||
if (!is_dir($this->directory) && !@mkdir($this->directory, 0700, true) && !is_dir($this->directory)) { throw new RuntimeException('AUTOMATION_STORAGE'); }
|
||
}
|
||
|
||
private function lock(string $name, bool $nonblocking)
|
||
{
|
||
$handle = @fopen($this->directory . DIRECTORY_SEPARATOR . $name, 'c+b');
|
||
if (!$handle) { throw new RuntimeException('AUTOMATION_STORAGE'); }
|
||
if (!flock($handle, LOCK_EX | ($nonblocking ? LOCK_NB : 0))) {
|
||
fclose($handle);
|
||
if ($nonblocking) { return null; }
|
||
throw new RuntimeException('AUTOMATION_STORAGE');
|
||
}
|
||
return $handle;
|
||
}
|
||
|
||
private function read(string $name): array
|
||
{
|
||
$path = $this->directory . DIRECTORY_SEPARATOR . $name;
|
||
if (!is_file($path)) { return []; }
|
||
$file = @fopen($path, 'rb');
|
||
if (!$file) { throw new RuntimeException('AUTOMATION_STORAGE'); }
|
||
try {
|
||
if (!flock($file, LOCK_SH)) { throw new RuntimeException('AUTOMATION_STORAGE'); }
|
||
$text = stream_get_contents($file, 65537);
|
||
if (!is_string($text) || strlen($text) > 65536) { throw new RuntimeException('AUTOMATION_STORAGE'); }
|
||
$data = json_decode($text, true, 32, JSON_THROW_ON_ERROR);
|
||
if (!is_array($data)) { throw new RuntimeException('AUTOMATION_STORAGE'); }
|
||
return $data;
|
||
} finally { flock($file, LOCK_UN); fclose($file); }
|
||
}
|
||
|
||
private function write(string $name, array $value): void
|
||
{
|
||
$file = $this->lock($name, false);
|
||
try {
|
||
$json = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
|
||
if (!ftruncate($file, 0) || fwrite($file, $json) !== strlen($json) || !fflush($file)) { throw new RuntimeException('AUTOMATION_STORAGE'); }
|
||
@chmod($this->directory . DIRECTORY_SEPARATOR . $name, 0600);
|
||
} finally { flock($file, LOCK_UN); fclose($file); }
|
||
}
|
||
}
|