Files
zyt/server/app/common/service/assistantservice/AssistantServiceWorker.php
T
2026-11-12 09:07:07 +08:00

133 lines
8.1 KiB
PHP

<?php
declare(strict_types=1);
namespace app\common\service\assistantservice;
use DomainException;
use think\facade\Db;
/** 持久队列消费者:过期租约不重发;只有持有有效 token 的消费者能提交。 */
final class AssistantServiceWorker
{
public function runOnce(?callable $generator = null): bool
{
if (!config('assistant_service.enabled', false)) { return false; }
$job = $this->claim();
if ($job === null) { return false; }
$started = false;
try {
$payload = json_decode((string) $job['payload_json'], true, 64, JSON_THROW_ON_ERROR);
if (!is_array($payload) || !is_array($payload['context'] ?? null) || !is_array($payload['knowledge'] ?? null)
|| !is_string($payload['question'] ?? null)) { throw new DomainException('PAYLOAD_INVALID'); }
$this->assertFresh($job, $payload);
if (!$this->ownsLease($job)) { return true; }
$started = true;
$call = $generator ?? [AssistantServiceEngine::class, 'generate'];
try {
$answer = $call((string) $job['type'], (string) $job['scenario'], $payload['context'], $payload['knowledge'], $payload['question']);
} catch (\Throwable $e) {
$this->finish($job, 'needs_reconciliation', 'UPSTREAM_UNCERTAIN', '执行状态待核对,不能自动重试');
return true;
}
if (!is_array($answer) || ($answer['ok'] ?? null) !== true) {
$code = is_array($answer) ? (string) ($answer['error_code'] ?? '') : '';
$uncertain = !in_array($code, ['DISABLED', 'CONFIG_INVALID', 'NO_SOURCES', 'KNOWLEDGE_REQUIRED',
'INPUT_INVALID', 'UPSTREAM_REJECTED', 'RESULT_INVALID'], true);
$this->finish($job, $uncertain ? 'needs_reconciliation' : 'failed',
$uncertain ? 'UPSTREAM_UNCERTAIN' : $code, $uncertain
? '模型执行结果尚未确认,需人工核对,不能自动重试' : '任务未通过模型配置、来源或结果校验,请人工处理');
return true;
}
// 即使是注入的生成器也不得绕过服务端结果约束。
if (!is_array($answer['result'] ?? null)) { throw new DomainException('RESULT_INVALID'); }
$validated = AssistantServiceEngine::validateResult((string) $job['type'], $answer['result'], $payload['context'], $payload['knowledge']);
Db::transaction(function () use ($job, $payload, $validated, $answer): void {
if (!$this->ownsLease($job, true)) { return; }
// 新事务内重读,防止生成期间转交患者、撤权、来源变化或知识撤回。
$this->assertFresh($job, $payload, true);
$id = $answer['message_id'] ?? '';
$this->finish($job, 'ready', '', '', [
'result_json' => json_encode($validated, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
'upstream_id' => is_string($id) && preg_match('/^[A-Za-z0-9._:-]{1,191}$/D', $id) ? $id : '',
]);
});
} catch (DomainException $e) {
$code = $e->getMessage();
if (in_array($code, ['ACCESS_REVOKED', 'SOURCE_CHANGED', 'KNOWLEDGE_CHANGED', 'DISABLED'], true)) {
$this->finish($job, 'stale', $code, '权限、来源或服务知识已变化,请重新查看当前资料');
} else {
$this->finish($job, 'failed', 'RESULT_INVALID', '任务未通过资料或结果校验,请人工处理');
}
} catch (\Throwable $e) {
// 异常原文可能含 SQL、患者内容或凭证,禁止记录或返回。
$this->finish($job, $started ? 'needs_reconciliation' : 'failed', $started ? 'UPSTREAM_UNCERTAIN' : 'INTERNAL_ERROR',
$started ? '执行状态待核对,不能自动重试' : '服务任务执行异常,请联系管理员');
}
return true;
}
private function claim(): ?array
{
$now = time();
// 宕机后的 running 可能已向上游提交,禁止重新入队或抢占后重发。
Db::name('assistant_service_job')->where('status', 'running')->where('lease_until', '<=', $now)->update([
'status' => 'needs_reconciliation', 'error_code' => 'LEASE_EXPIRED', 'error_message' => '执行租约已过期,需人工核对上游状态',
'claim_token' => '', 'lease_until' => 0, 'updated_at' => $now, 'finished_at' => $now,
]);
return Db::transaction(function () use ($now): ?array {
$row = Db::name('assistant_service_job')->where('status', 'queued')->order('id', 'asc')->lock(true)->find();
if (!$row) { return null; }
$lease = max(60, (int) config('assistant_service.lease_seconds', 300), (int) config('assistant_service.timeout', 120) + 60);
$fields = ['status' => 'running', 'claim_token' => bin2hex(random_bytes(24)), 'lease_until' => $now + $lease, 'updated_at' => $now];
$changed = Db::name('assistant_service_job')->where('id', $row['id'])->where('status', 'queued')->update($fields);
return $changed === 1 ? array_replace($row, $fields) : null;
});
}
private function ownsLease(array $job, bool $lock = false): bool
{
return (bool) Db::name('assistant_service_job')->where('id', (int) $job['id'])->where('status', 'running')
->where('claim_token', (string) $job['claim_token'])->where('lease_until', '>', time())->lock($lock)->find();
}
private function assertFresh(array $job, array $payload, bool $lock = false): void
{
if (!config('assistant_service.enabled', false)) { throw new DomainException('DISABLED'); }
try {
$diagnosis = AssistantServiceAccess::diagnosis((int) $job['diagnosis_id'], (int) $job['actor_id'],
$job['type'] === 'reply' ? 'draftReply' : 'analyze', $lock);
if ((int) ($diagnosis['patient_id'] ?? 0) !== (int) $job['patient_id']) { throw new DomainException('ACCESS_REVOKED'); }
} catch (DomainException $e) { throw new DomainException('ACCESS_REVOKED'); }
try {
$context = AssistantServiceContext::build((int) $job['diagnosis_id'], (int) $job['actor_id'], (int) $job['days'],
(int) ($payload['context']['subject_admin_id'] ?? 0));
} catch (DomainException $e) { throw new DomainException('SOURCE_CHANGED'); }
foreach (['source_hash', 'scope_hash'] as $key) {
if (!is_string($context[$key] ?? null) || !is_string($payload['context'][$key] ?? null)
|| !hash_equals((string) $job[$key], $context[$key]) || !hash_equals((string) $job[$key], $payload['context'][$key])) {
throw new DomainException('SOURCE_CHANGED');
}
}
foreach ($payload['knowledge'] as $entry) {
if (!is_array($entry) || empty($entry['id']) || empty($entry['version'])) { throw new DomainException('KNOWLEDGE_CHANGED'); }
$current = Db::name('assistant_service_knowledge')->where('id', (int) $entry['id'])->lock($lock)->find();
if (!$current || $current['status'] !== 'published' || (int) $current['version'] !== (int) $entry['version']) {
throw new DomainException('KNOWLEDGE_CHANGED');
}
foreach (['question', 'answer', 'category', 'source_note'] as $field) {
if ((string) ($entry[$field] ?? '') !== (string) $current[$field]) { throw new DomainException('KNOWLEDGE_CHANGED'); }
}
}
}
private function finish(array $job, string $status, string $code, string $message, array $fields = []): void
{
Db::name('assistant_service_job')->where('id', (int) $job['id'])->where('status', 'running')
->where('claim_token', (string) $job['claim_token'])->where('lease_until', '>', time())->update(array_replace([
'status' => $status, 'error_code' => $code, 'error_message' => $message, 'result_json' => null,
'claim_token' => '', 'lease_until' => 0, 'updated_at' => time(), 'finished_at' => time(),
], $fields));
}
}