更新
This commit is contained in:
@@ -7,6 +7,8 @@ namespace app\adminapi\logic\tcm;
|
||||
use app\common\service\mobilerecording\MobileRecordingStorage as Storage;
|
||||
use app\common\service\mobilerecording\MobileRecordingStream;
|
||||
use app\common\service\mobilerecording\MobileRecordingResyncException;
|
||||
use app\common\service\mobilerecording\MobileRecordingLocalUnavailableException;
|
||||
use app\common\service\mobilerecording\MobileRecordingObjects as Objects;
|
||||
use DomainException;
|
||||
use think\facade\Db;
|
||||
|
||||
@@ -45,8 +47,8 @@ final class MobileRecordingMediaLogic
|
||||
self::deleteUploads($obsolete, $garbage);
|
||||
if ($existing) {
|
||||
if ($existing['state'] === 'complete') {
|
||||
try { $file = Storage::open($existing); fclose($file); }
|
||||
catch (DomainException $e) {
|
||||
try { Objects::verifyAvailable($existing); }
|
||||
catch (MobileRecordingLocalUnavailableException $e) {
|
||||
Db::name('mobile_recording_asset')->where('upload_id', $existing['upload_id'])->delete();
|
||||
$existing['state'] = 'uploading'; $existing['received_bytes'] = 0;
|
||||
Db::name('mobile_recording_upload')->where('upload_id', $existing['upload_id'])
|
||||
@@ -76,6 +78,14 @@ final class MobileRecordingMediaLogic
|
||||
if (!hash_equals($sha, hash('sha256', $bytes))) { throw new DomainException('分片摘要校验失败'); }
|
||||
return self::mutate(static function (array &$garbage) use ($uploadId, $diagnosis, $offset, $bytes, $length, $actor): array {
|
||||
$row = self::session($uploadId, $diagnosis, $actor);
|
||||
if ($row['state'] === 'complete') {
|
||||
if ($offset + $length > (int) $row['size_bytes']) { throw new DomainException('分片超出声明的文件大小'); }
|
||||
$source = Objects::source($row);
|
||||
try { $existing = is_callable($source) ? $source($offset, $length) : Storage::bytes($source, $offset, $length); }
|
||||
finally { if (is_resource($source)) { fclose($source); } }
|
||||
if (!hash_equals($bytes, $existing)) { throw new MobileRecordingResyncException('分片与已接收内容冲突,请查询上传状态'); }
|
||||
return self::dto($row);
|
||||
}
|
||||
return Storage::locked($uploadId, static function ($file) use ($row, $offset, $bytes, $length): array {
|
||||
$received = Storage::reconcile($file, (int) $row['received_bytes']);
|
||||
if ($offset + $length > (int) $row['size_bytes']) { throw new DomainException('分片超出声明的文件大小'); }
|
||||
@@ -99,14 +109,16 @@ final class MobileRecordingMediaLogic
|
||||
MobileRecordingLogic::only($p, ['upload_id', 'diagnosis_id']);
|
||||
$uploadId = self::uploadId($p['upload_id'] ?? null);
|
||||
$diagnosis = self::diagnosisId($p);
|
||||
return self::mutate(static function (array &$garbage) use ($uploadId, $diagnosis, $actor): array {
|
||||
$row = self::synchronize(self::session($uploadId, $diagnosis, $actor));
|
||||
// Persist the object location and encryption key before the first COS call.
|
||||
$prepared = self::mutate(static function (array &$garbage) use ($uploadId, $diagnosis, $actor): array {
|
||||
$row = self::session($uploadId, $diagnosis, $actor);
|
||||
if ($row['state'] === 'complete') { return self::dto($row); }
|
||||
if (Objects::ready($row)) { return ['prepared' => true]; }
|
||||
$row = self::synchronize($row);
|
||||
if ((int) $row['received_bytes'] !== (int) $row['size_bytes']) { throw new MobileRecordingResyncException('文件尚未上传完整'); }
|
||||
$error = Storage::locked($uploadId, static function ($file) use ($row): ?string {
|
||||
try { Storage::validate($file, $row); return null; }
|
||||
catch (DomainException $e) {
|
||||
// Persist a reset before returning a validation error, so same-hash retry is recoverable.
|
||||
catch (\DomainException $e) {
|
||||
if (!ftruncate($file, 0) || !fflush($file)) { throw new \RuntimeException('Upload reset failed'); }
|
||||
return $e->getMessage();
|
||||
}
|
||||
@@ -115,15 +127,61 @@ final class MobileRecordingMediaLogic
|
||||
Db::name('mobile_recording_upload')->where('upload_id', $uploadId)->update(['received_bytes' => 0, 'updated_at' => time()]);
|
||||
return ['validation_error' => $error];
|
||||
}
|
||||
Db::name('mobile_recording_upload')->where('upload_id', $uploadId)->update(['state' => 'complete', 'updated_at' => time()]);
|
||||
$asset = ['binding_id' => $row['binding_id'], 'kind' => $row['kind'], 'upload_id' => $uploadId, 'updated_at' => time()];
|
||||
$query = Db::name('mobile_recording_asset')->where('binding_id', $row['binding_id'])->where('kind', $row['kind']);
|
||||
if ((clone $query)->find()) { $query->update($asset); } else { Db::name('mobile_recording_asset')->insert($asset); }
|
||||
$oldIds = Db::name('mobile_recording_upload')->where('binding_id', $row['binding_id'])->where('kind', $row['kind'])
|
||||
->where('upload_id', '<>', $uploadId)->column('upload_id');
|
||||
self::deleteUploads($oldIds, $garbage);
|
||||
return self::dto(array_replace($row, ['state' => 'complete']));
|
||||
Objects::ensure($row);
|
||||
return ['prepared' => true];
|
||||
});
|
||||
if (!isset($prepared['prepared'])) {
|
||||
if (($prepared['state'] ?? '') === 'complete') { self::tryCleanupStaging($uploadId); }
|
||||
return $prepared;
|
||||
}
|
||||
Objects::advance($uploadId, static fn (): array => self::session($uploadId, $diagnosis, $actor));
|
||||
$result = self::mutate(static function (array &$garbage) use ($uploadId, $diagnosis, $actor): array {
|
||||
$row = self::session($uploadId, $diagnosis, $actor);
|
||||
if (!Objects::ready($row)) { throw new \RuntimeException('Private cloud confirmation pending'); }
|
||||
if ($row['state'] !== 'complete') { self::publish($row, $garbage); }
|
||||
return self::dto(array_replace($row, ['state' => 'complete', 'received_bytes' => (int) $row['size_bytes']]));
|
||||
});
|
||||
self::tryCleanupStaging($uploadId);
|
||||
return $result;
|
||||
}
|
||||
|
||||
private static function tryCleanupStaging(string $id): void
|
||||
{
|
||||
// Publication is already durable; failure must not unpublish it. The worker retries this task.
|
||||
try { Objects::cleanupStaging($id); } catch (\Throwable $ignored) {}
|
||||
}
|
||||
|
||||
private static function publish(array $row, array &$garbage): void
|
||||
{
|
||||
$uploadId = $row['upload_id'];
|
||||
Db::name('mobile_recording_upload')->where('upload_id', $uploadId)
|
||||
->update(['state' => 'complete', 'received_bytes' => $row['size_bytes'], 'updated_at' => time()]);
|
||||
$asset = ['binding_id' => $row['binding_id'], 'kind' => $row['kind'], 'upload_id' => $uploadId, 'updated_at' => time()];
|
||||
$query = Db::name('mobile_recording_asset')->where('binding_id', $row['binding_id'])->where('kind', $row['kind']);
|
||||
if ((clone $query)->find()) { $query->update($asset); } else { Db::name('mobile_recording_asset')->insert($asset); }
|
||||
$oldIds = Db::name('mobile_recording_upload')->where('binding_id', $row['binding_id'])->where('kind', $row['kind'])
|
||||
->where('upload_id', '<>', $uploadId)->column('upload_id');
|
||||
self::deleteUploads($oldIds, $garbage);
|
||||
}
|
||||
|
||||
/** Privileged maintenance only, never routed by the HTTP controller. */
|
||||
public static function migrateLocal(string $id): void
|
||||
{
|
||||
$guard = static function () use ($id): array {
|
||||
$peek = Db::name('mobile_recording_upload')->where('upload_id', $id)->find();
|
||||
$binding = $peek ? Db::name('mobile_recording_binding')->where('id', $peek['binding_id'])->lock(true)->find() : null;
|
||||
$row = Db::name('mobile_recording_upload')->where('upload_id', $id)->where('state', 'complete')->lock(true)->find();
|
||||
if (!$binding || !$row) { throw new \DomainException('Legacy media reference no longer active'); }
|
||||
return $row;
|
||||
};
|
||||
Db::transaction(static function () use ($id, $guard): void {
|
||||
$row = $guard();
|
||||
if (Objects::ready($row)) { return; }
|
||||
Storage::locked($id, static fn ($file) => Storage::validate($file, $row));
|
||||
Objects::ensure($row);
|
||||
});
|
||||
Objects::advance($id, $guard);
|
||||
Objects::cleanupStaging($id);
|
||||
}
|
||||
|
||||
public static function status(array $p, int $actor): array
|
||||
@@ -149,16 +207,17 @@ final class MobileRecordingMediaLogic
|
||||
public static function audio(array $p, int $actor, string $range = ''): MobileRecordingStream
|
||||
{
|
||||
return self::read($p, $actor, 'audio', static function (array $row) use ($range): MobileRecordingStream {
|
||||
return new MobileRecordingStream(Storage::open($row), (int) $row['size_bytes'], $row['media_type'], $range);
|
||||
return new MobileRecordingStream(Objects::source($row), (int) $row['size_bytes'], $row['media_type'], $range);
|
||||
});
|
||||
}
|
||||
|
||||
public static function transcript(array $p, int $actor): array
|
||||
{
|
||||
return self::read($p, $actor, 'transcript', static function (array $row): array {
|
||||
$file = Storage::open($row);
|
||||
try { $text = Storage::bytes($file, 0, (int) $row['size_bytes']); }
|
||||
finally { fclose($file); }
|
||||
$source = Objects::source($row);
|
||||
try { $text = is_callable($source) ? $source(0, (int) $row['size_bytes']) : Storage::bytes($source, 0, (int) $row['size_bytes']); }
|
||||
finally { if (is_resource($source)) { fclose($source); } }
|
||||
if (!hash_equals($row['sha256'], hash('sha256', $text))) { throw new \RuntimeException('Transcript integrity mismatch'); }
|
||||
return ['text' => $text, 'sha256' => $row['sha256'], 'size_bytes' => (int) $row['size_bytes']];
|
||||
});
|
||||
}
|
||||
@@ -187,6 +246,7 @@ final class MobileRecordingMediaLogic
|
||||
public static function bindingMoved(int $id, int $diagnosisId): array
|
||||
{
|
||||
$garbage = Db::name('mobile_recording_upload')->where('binding_id', $id)->where('state', 'uploading')->column('upload_id');
|
||||
Objects::queueDelete($garbage);
|
||||
if ($garbage) { Db::name('mobile_recording_upload')->whereIn('upload_id', $garbage)->delete(); }
|
||||
Db::name('mobile_recording_upload')->where('binding_id', $id)->where('state', 'complete')
|
||||
->update(['diagnosis_id' => $diagnosisId, 'updated_at' => time()]);
|
||||
@@ -197,6 +257,7 @@ final class MobileRecordingMediaLogic
|
||||
public static function bindingRemoved(int $id): array
|
||||
{
|
||||
$garbage = Db::name('mobile_recording_upload')->where('binding_id', $id)->column('upload_id');
|
||||
Objects::queueDelete($garbage);
|
||||
Db::name('mobile_recording_asset')->where('binding_id', $id)->delete();
|
||||
Db::name('mobile_recording_upload')->where('binding_id', $id)->delete();
|
||||
return $garbage;
|
||||
@@ -247,6 +308,7 @@ final class MobileRecordingMediaLogic
|
||||
|
||||
private static function synchronize(array $row): array
|
||||
{
|
||||
if ($row['state'] === 'uploading' && Objects::ready($row)) { return $row; }
|
||||
if ($row['state'] === 'uploading') {
|
||||
$received = Storage::locked($row['upload_id'], static fn ($file): int => Storage::reconcile($file, (int) $row['received_bytes']));
|
||||
if ($received !== (int) $row['received_bytes']) {
|
||||
@@ -269,6 +331,7 @@ final class MobileRecordingMediaLogic
|
||||
private static function deleteUploads(array $ids, array &$garbage): void
|
||||
{
|
||||
if (!$ids) { return; }
|
||||
Objects::queueDelete($ids);
|
||||
Db::name('mobile_recording_upload')->whereIn('upload_id', $ids)->delete();
|
||||
$garbage = array_merge($garbage, $ids);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\command;
|
||||
|
||||
use app\adminapi\logic\tcm\MobileRecordingMediaLogic;
|
||||
use think\console\Command;
|
||||
use think\console\Input;
|
||||
use think\console\Output;
|
||||
use think\console\input\Option;
|
||||
use think\facade\Db;
|
||||
|
||||
/** Explicit privileged migration. Never implicitly moves all legacy patient media on deployment. */
|
||||
final class MobileRecordingCosMigrate extends Command
|
||||
{
|
||||
protected function configure()
|
||||
{
|
||||
$this->setName('mobile-recording:cos-migrate')->setDescription('分批迁移历史本地完整录音/文字至COS')
|
||||
->addOption('dry-run', null, Option::VALUE_NONE, '只统计,不读取内容、不调用COS')
|
||||
->addOption('limit', null, Option::VALUE_REQUIRED, '每批1至100条', '20')
|
||||
->addOption('after', null, Option::VALUE_REQUIRED, '上一批输出的32位不透明cursor', '');
|
||||
}
|
||||
protected function execute(Input $input, Output $output): int
|
||||
{
|
||||
try {
|
||||
$after = (string) $input->getOption('after');
|
||||
if ($after !== '' && !preg_match('/^[a-f0-9]{32}$/D', $after)) { throw new \InvalidArgumentException('Invalid cursor'); }
|
||||
$query = Db::name('mobile_recording_upload')->alias('u')
|
||||
->leftJoin([Db::name('mobile_recording_object')->getTable() => 'o'], 'o.upload_id=u.upload_id')
|
||||
->where('u.state', 'complete')->whereRaw('(o.upload_id IS NULL OR o.state IN (\'pending\',\'finalizing\',\'verifying\'))');
|
||||
if ($after !== '') { $query->where('u.upload_id', '>', $after); }
|
||||
$ids = $query->order('u.upload_id')->limit(max(1, min(100, (int) $input->getOption('limit'))))->column('u.upload_id');
|
||||
$counts = ['selected' => count($ids), 'migrated' => 0, 'deferred' => 0, 'next_cursor' => $ids ? end($ids) : ''];
|
||||
if (!$input->getOption('dry-run')) {
|
||||
foreach ($ids as $id) {
|
||||
try { MobileRecordingMediaLogic::migrateLocal($id); $counts['migrated']++; }
|
||||
catch (\Throwable $e) { $counts['deferred']++; }
|
||||
}
|
||||
}
|
||||
$output->writeln('MOBILE_RECORDING_COS_MIGRATE ' . json_encode($counts));
|
||||
return 0;
|
||||
} catch (\Throwable $e) { $output->writeln('MOBILE_RECORDING_COS_MIGRATE storage_or_configuration_error'); return 1; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\command;
|
||||
|
||||
use app\adminapi\logic\tcm\MobileRecordingMediaLogic;
|
||||
use app\common\service\mobilerecording\MobileRecordingObjects;
|
||||
use app\common\service\mobilerecording\MobileRecordingWork;
|
||||
use think\console\Command;
|
||||
use think\console\Input;
|
||||
use think\console\Output;
|
||||
use think\console\input\Option;
|
||||
use think\facade\Db;
|
||||
|
||||
/** Schedule once per minute with a non-overlap lock; contains no cloud credentials in arguments. */
|
||||
final class MobileRecordingCosWork extends Command
|
||||
{
|
||||
protected function configure()
|
||||
{
|
||||
$this->setName('mobile-recording:cos-work')->setDescription('推进手机录音COS提交及私有对象删除重试')
|
||||
->addOption('dry-run', null, Option::VALUE_NONE, '只统计,不调用COS')
|
||||
->addOption('limit', null, Option::VALUE_REQUIRED, '最多处理的上传数,1至100', '5')
|
||||
->addOption('seconds', null, Option::VALUE_REQUIRED, '上传调度时间预算,1至300秒;单个COS请求仍有10秒超时', '20');
|
||||
}
|
||||
protected function execute(Input $input, Output $output): int
|
||||
{
|
||||
try {
|
||||
$limit = max(1, min(100, (int) $input->getOption('limit')));
|
||||
$seconds = max(1, min(300, (int) $input->getOption('seconds')));
|
||||
$dry = (bool) $input->getOption('dry-run');
|
||||
$deadline = microtime(true) + $seconds;
|
||||
$counts = MobileRecordingObjects::cleanup(1, $dry);
|
||||
$counts += ['uploads_selected' => 0, 'uploads_completed' => 0, 'uploads_deferred' => 0,
|
||||
'uploads_denied' => 0, 'staging_cleaned' => 0];
|
||||
$rows = Db::name('mobile_recording_upload')->alias('u')
|
||||
->join([Db::name('mobile_recording_binding')->getTable() => 'b'], 'b.id=u.binding_id')
|
||||
->leftJoin([Db::name('mobile_recording_object')->getTable() => 'o'], 'o.upload_id=u.upload_id')
|
||||
->leftJoin([Db::name('mobile_recording_asset')->getTable() => 'a'], 'a.upload_id=u.upload_id AND a.binding_id=u.binding_id AND a.kind=u.kind')
|
||||
->leftJoin([Db::name('mobile_recording_work')->getTable() => 'w'], 'w.upload_id=u.upload_id')
|
||||
->whereRaw("((u.state='uploading' AND u.received_bytes=u.size_bytes) OR (u.state='complete' AND o.state IN ('pending','finalizing','verifying')) OR (u.state='complete' AND o.state='ready' AND a.upload_id IS NOT NULL AND COALESCE(w.staging_cleaned,0)=0))")
|
||||
->whereRaw('COALESCE(w.next_retry_at,0) <= ' . time())
|
||||
->field('u.upload_id,u.state,o.state AS object_state,b.admin_id,b.diagnosis_id')
|
||||
->orderRaw('COALESCE(w.last_attempt_at,0),u.updated_at,u.upload_id')->limit($limit)->select()->toArray();
|
||||
$counts['uploads_selected'] = count($rows);
|
||||
if (!$dry) {
|
||||
foreach ($rows as $row) {
|
||||
if (microtime(true) >= $deadline) { break; }
|
||||
try {
|
||||
if ($row['state'] === 'complete' && $row['object_state'] === 'ready') {
|
||||
if (!MobileRecordingObjects::cleanupStaging($row['upload_id'], true)) { throw new \DomainException('Media publication no longer active'); }
|
||||
$counts['staging_cleaned']++;
|
||||
} elseif ($row['state'] === 'complete') { MobileRecordingMediaLogic::migrateLocal($row['upload_id']); $counts['uploads_completed']++; }
|
||||
else { MobileRecordingMediaLogic::complete(['upload_id' => $row['upload_id'], 'diagnosis_id' => (int) $row['diagnosis_id']], (int) $row['admin_id']); }
|
||||
if ($row['state'] === 'uploading') {
|
||||
// complete may publish successfully while best-effort unlink failed. Keep that task retryable.
|
||||
if (!MobileRecordingObjects::cleanupStaging($row['upload_id'], true)) { throw new \DomainException('Media publication no longer active'); }
|
||||
$counts['uploads_completed']++;
|
||||
}
|
||||
MobileRecordingWork::attempted($row['upload_id']);
|
||||
} catch (\Throwable $e) {
|
||||
MobileRecordingWork::attempted($row['upload_id'], $e);
|
||||
$counts['uploads_deferred']++;
|
||||
if ($e instanceof \DomainException) { $counts['uploads_denied']++; }
|
||||
}
|
||||
}
|
||||
}
|
||||
$output->writeln('MOBILE_RECORDING_COS_WORK ' . json_encode($counts));
|
||||
return $counts['errors'] > 0 || $counts['uploads_deferred'] > 0 ? 1 : 0;
|
||||
} catch (\Throwable $e) { $output->writeln('MOBILE_RECORDING_COS_WORK storage_or_configuration_error'); return 1; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\mobilerecording;
|
||||
|
||||
/** Independent authenticated frames permit bounded-memory plaintext Range playback. */
|
||||
final class MobileRecordingCipher
|
||||
{
|
||||
public const FRAME = 1048576;
|
||||
public const TAG = 16;
|
||||
public const FORMAT = 'aes256gcm-frame-v1';
|
||||
|
||||
public static function frames(int $size): int { return max(1, (int) ceil($size / self::FRAME)); }
|
||||
public static function cipherSize(int $size): int { return $size + self::frames($size) * self::TAG; }
|
||||
public static function plainLength(array $object, int $index): int
|
||||
{
|
||||
if ($index < 0 || $index >= self::frames((int) $object['plain_size'])) { throw new \RuntimeException('Invalid media frame'); }
|
||||
return min(self::FRAME, max(0, (int) $object['plain_size'] - $index * self::FRAME));
|
||||
}
|
||||
private static function aad(array $object, int $index): string
|
||||
{
|
||||
// Diagnosis and owner assignments may change. Only immutable content identity is authenticated.
|
||||
return implode('|', [self::FORMAT, $object['upload_id'], $object['kind'], $object['plain_size'], $object['plain_sha256'], $index]);
|
||||
}
|
||||
private static function key(array $object): string
|
||||
{
|
||||
if (!preg_match('/^[0-9a-f]{64}$/D', (string) $object['encryption_key'])) { throw new \RuntimeException('Media key unavailable'); }
|
||||
return hex2bin($object['encryption_key']);
|
||||
}
|
||||
private static function nonce(array $object, int $index): string
|
||||
{
|
||||
if (!preg_match('/^[0-9a-f]{16}$/D', (string) $object['nonce_prefix'])) { throw new \RuntimeException('Media nonce unavailable'); }
|
||||
return hex2bin($object['nonce_prefix']) . pack('N', $index);
|
||||
}
|
||||
public static function encrypt(array $object, int $index, string $plain): string
|
||||
{
|
||||
if (strlen($plain) !== self::plainLength($object, $index)) { throw new \RuntimeException('Invalid media frame length'); }
|
||||
$tag = '';
|
||||
$cipher = openssl_encrypt($plain, 'aes-256-gcm', self::key($object), OPENSSL_RAW_DATA,
|
||||
self::nonce($object, $index), $tag, self::aad($object, $index), self::TAG);
|
||||
if ($cipher === false || strlen($tag) !== self::TAG) { throw new \RuntimeException('Media encryption unavailable'); }
|
||||
return $cipher . $tag;
|
||||
}
|
||||
public static function decrypt(array $object, int $index, string $cipher): string
|
||||
{
|
||||
if (strlen($cipher) !== self::plainLength($object, $index) + self::TAG) { throw new \RuntimeException('Media frame length mismatch'); }
|
||||
$plain = openssl_decrypt(substr($cipher, 0, -self::TAG), 'aes-256-gcm', self::key($object), OPENSSL_RAW_DATA,
|
||||
self::nonce($object, $index), substr($cipher, -self::TAG), self::aad($object, $index));
|
||||
if ($plain === false) { throw new \RuntimeException('Media frame authentication failed'); }
|
||||
return $plain;
|
||||
}
|
||||
public static function context(array $object): string
|
||||
{
|
||||
return hash_hmac('sha256', self::aad($object, 0), self::key($object));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\mobilerecording;
|
||||
|
||||
/** One decrypted frame cache, never a public URL or whole-file buffer. */
|
||||
final class MobileRecordingCloudReader
|
||||
{
|
||||
private int $index = -1;
|
||||
private string $plain = '';
|
||||
public function __construct(private array $object, private MobileRecordingCos $cloud) {}
|
||||
public function __invoke(int $offset, int $length): string
|
||||
{
|
||||
if ($offset < 0 || $length < 0 || $offset + $length > (int) $this->object['plain_size']) { throw new \RuntimeException('Media read range invalid'); }
|
||||
// Empty text still authenticates its one zero-length GCM frame.
|
||||
if ((int) $this->object['plain_size'] === 0) { $this->frame(0); return ''; }
|
||||
$result = '';
|
||||
while (strlen($result) < $length) {
|
||||
$at = $offset + strlen($result);
|
||||
$index = intdiv($at, MobileRecordingCipher::FRAME);
|
||||
$this->frame($index);
|
||||
$part = substr($this->plain, $at % MobileRecordingCipher::FRAME, min($length - strlen($result), MobileRecordingCipher::FRAME));
|
||||
if ($part === '') { throw new \RuntimeException('Media frame incomplete'); }
|
||||
$result .= $part;
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
private function frame(int $index): void
|
||||
{
|
||||
if ($this->index === $index) { return; }
|
||||
$start = $index * (MobileRecordingCipher::FRAME + MobileRecordingCipher::TAG);
|
||||
$end = $start + MobileRecordingCipher::plainLength($this->object, $index) + MobileRecordingCipher::TAG - 1;
|
||||
$this->plain = MobileRecordingCipher::decrypt($this->object, $index, $this->cloud->range($this->object, $start, $end));
|
||||
$this->index = $index;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\mobilerecording;
|
||||
|
||||
use app\common\service\ConfigService;
|
||||
use Qcloud\Cos\Client;
|
||||
|
||||
/** Dedicated private adapter. Never uses FileService/CDN or the general-purpose upload engine. */
|
||||
class MobileRecordingCos
|
||||
{
|
||||
protected function settings(): array
|
||||
{
|
||||
$config = ConfigService::get('storage', 'qcloud', []);
|
||||
if (!is_array($config) || empty($config['access_key']) || empty($config['secret_key'])) {
|
||||
throw new \RuntimeException('Private cloud configuration unavailable');
|
||||
}
|
||||
return $config;
|
||||
}
|
||||
public function location(): array
|
||||
{
|
||||
$config = $this->settings();
|
||||
$location = ['bucket' => (string) ($config['bucket'] ?? ''), 'region' => (string) ($config['region'] ?? '')];
|
||||
self::validateLocation($location);
|
||||
return $location;
|
||||
}
|
||||
private static function validateLocation(array $object): void
|
||||
{
|
||||
if (!preg_match('/^[a-z0-9][a-z0-9-]{1,62}-[0-9]{5,20}$/D', (string) $object['bucket'])
|
||||
|| !preg_match('/^[a-z]{2}-[a-z0-9-]{2,40}$/D', (string) $object['region'])) {
|
||||
throw new \RuntimeException('Private cloud location invalid');
|
||||
}
|
||||
}
|
||||
protected function client(array $object): Client
|
||||
{
|
||||
self::validateLocation($object);
|
||||
$config = $this->settings();
|
||||
// Installed SDK 2.6.5 requires "schema", not "scheme". Region is the object's durable snapshot.
|
||||
return new Client(['schema' => 'https', 'region' => $object['region'], 'retry' => 0,
|
||||
'timeout' => 10, 'connect_timeout' => 3, 'allow_redirects' => false,
|
||||
'credentials' => ['secretId' => $config['access_key'], 'secretKey' => $config['secret_key']]]);
|
||||
}
|
||||
protected function invoke(string $method, array $object, array $params = [], bool $missingIsNull = false)
|
||||
{
|
||||
if (!preg_match('#^private/mobile-recording/v1/[a-f0-9]{32}\.enc$#D', (string) $object['object_key'])) {
|
||||
throw new \RuntimeException('Private cloud object invalid');
|
||||
}
|
||||
$args = ['Bucket' => $object['bucket'], 'Key' => $object['object_key'],
|
||||
'@http' => ['connect_timeout' => 3, 'timeout' => 10, 'read_timeout' => 10, 'allow_redirects' => false]] + $params;
|
||||
if ($method === 'getObject') { $args['@http']['stream'] = true; }
|
||||
try { return $this->client($object)->$method($args); }
|
||||
catch (\Throwable $e) {
|
||||
$status = method_exists($e, 'getStatusCode') ? (int) $e->getStatusCode() : 0;
|
||||
if ($missingIsNull && $status === 404) { return null; }
|
||||
if ($status === 401 || $status === 403) {
|
||||
// Permanent cloud authorization/configuration errors must not trigger a phone retry storm.
|
||||
throw new \DomainException('云端存储授权不可用,请联系管理员检查配置');
|
||||
}
|
||||
// Do not retain the provider exception as previous: URLs, signatures and settings stay private.
|
||||
throw new \RuntimeException('Private cloud temporarily unavailable');
|
||||
}
|
||||
}
|
||||
public function initiate(array $object): string
|
||||
{
|
||||
$result = $this->invoke('createMultipartUpload', $object, ['ACL' => 'private',
|
||||
'ContentType' => 'application/octet-stream', 'CacheControl' => 'private, no-store, max-age=0',
|
||||
'ContentDisposition' => 'attachment; filename="encrypted-recording"',
|
||||
'Metadata' => ['mr-context' => $object['context_hash'], 'mr-format' => MobileRecordingCipher::FORMAT]]);
|
||||
$id = (string) ($result['UploadId'] ?? '');
|
||||
if ($id === '' || strlen($id) > 1024) { throw new \RuntimeException('Private cloud session unavailable'); }
|
||||
return $id;
|
||||
}
|
||||
public function part(array $object, int $number, string $cipher): string
|
||||
{
|
||||
$result = $this->invoke('uploadPart', $object, ['UploadId' => $object['multipart_id'], 'PartNumber' => $number,
|
||||
'Body' => $cipher, 'Headers' => ['Content-MD5' => base64_encode(md5($cipher, true))]]);
|
||||
$etag = trim((string) ($result['ETag'] ?? ''), '"');
|
||||
if (!hash_equals(md5($cipher), strtolower($etag))) { throw new \RuntimeException('Private cloud part integrity failed'); }
|
||||
return $etag;
|
||||
}
|
||||
public function finish(array $object, array $parts): void
|
||||
{
|
||||
$this->invoke('completeMultipartUpload', $object, ['UploadId' => $object['multipart_id'], 'Parts' => $parts]);
|
||||
}
|
||||
public function head(array $object, bool $pinned = false): ?array
|
||||
{
|
||||
$version = $pinned && !empty($object['version_id']) ? ['VersionId' => $object['version_id']] : [];
|
||||
$result = $this->invoke('headObject', $object, $version, true);
|
||||
return $result === null ? null : ['size' => (int) ($result['ContentLength'] ?? -1),
|
||||
'context' => (string) ($result['Metadata']['mr-context'] ?? ''),
|
||||
'version_id' => (string) ($result['VersionId'] ?? '')];
|
||||
}
|
||||
public function range(array $object, int $start, int $end): string
|
||||
{
|
||||
$params = ['Range' => "bytes={$start}-{$end}"];
|
||||
if ($object['version_id'] !== '') { $params['VersionId'] = $object['version_id']; }
|
||||
$result = $this->invoke('getObject', $object, $params);
|
||||
$body = $result['Body'] ?? null;
|
||||
try {
|
||||
$length = $end - $start + 1;
|
||||
if ((int) ($result['ContentLength'] ?? -1) !== $length
|
||||
|| ($result['ContentRange'] ?? '') !== "bytes {$start}-{$end}/" . $object['cipher_size']
|
||||
|| !$body instanceof \Psr\Http\Message\StreamInterface) { throw new \RuntimeException('Private cloud range invalid'); }
|
||||
$bytes = '';
|
||||
while (strlen($bytes) < $length) {
|
||||
$chunk = $body->read(min(65536, $length - strlen($bytes)));
|
||||
if ($chunk === '') { throw new \RuntimeException('Private cloud range incomplete'); }
|
||||
$bytes .= $chunk;
|
||||
}
|
||||
return $bytes;
|
||||
} catch (\Throwable $e) { throw new \RuntimeException('Private cloud read unavailable'); }
|
||||
finally { if ($body instanceof \Psr\Http\Message\StreamInterface) { $body->close(); } }
|
||||
}
|
||||
public function delete(array $object): void
|
||||
{
|
||||
$params = $object['version_id'] !== '' ? ['VersionId' => $object['version_id']] : [];
|
||||
$this->invoke('deleteObject', $object, $params, true);
|
||||
}
|
||||
public function abort(array $object): void
|
||||
{
|
||||
if ($object['multipart_id'] !== '') { $this->invoke('abortMultipartUpload', $object, ['UploadId' => $object['multipart_id']], true); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\mobilerecording;
|
||||
|
||||
/** Only a missing/corrupt legacy local source permits prepare to reset a published local upload. */
|
||||
final class MobileRecordingLocalUnavailableException extends \DomainException {}
|
||||
@@ -0,0 +1,193 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\mobilerecording;
|
||||
|
||||
use think\facade\Db;
|
||||
|
||||
/** Durable intent, resumable COS parts and a transactional deletion outbox. */
|
||||
final class MobileRecordingObjects
|
||||
{
|
||||
public static function cloud(): MobileRecordingCos { return app(MobileRecordingCos::class); }
|
||||
|
||||
/** Caller holds authorized actor/binding/upload locks. Commit this before any remote write. */
|
||||
public static function ensure(array $upload): array
|
||||
{
|
||||
$existing = Db::name('mobile_recording_object')->where('upload_id', $upload['upload_id'])->lock(true)->find();
|
||||
if ($existing) { return $existing; }
|
||||
$object = self::cloud()->location() + ['upload_id' => $upload['upload_id'], 'backend' => 'cos',
|
||||
'object_key' => 'private/mobile-recording/v1/' . $upload['upload_id'] . '.enc', 'version_id' => '',
|
||||
'encryption_key' => bin2hex(random_bytes(32)), 'nonce_prefix' => bin2hex(random_bytes(8)),
|
||||
'cipher_format' => MobileRecordingCipher::FORMAT, 'kind' => $upload['kind'],
|
||||
'plain_size' => (int) $upload['size_bytes'], 'plain_sha256' => $upload['sha256'],
|
||||
'cipher_size' => MobileRecordingCipher::cipherSize((int) $upload['size_bytes']),
|
||||
'multipart_id' => '', 'part_etags' => '[]', 'state' => 'pending', 'attempts' => 0, 'next_retry_at' => 0,
|
||||
'created_at' => time(), 'updated_at' => time()];
|
||||
$object['context_hash'] = MobileRecordingCipher::context($object);
|
||||
Db::name('mobile_recording_object')->insert($object);
|
||||
return $object;
|
||||
}
|
||||
|
||||
private static function confirm(array $object, ?array $head): bool
|
||||
{
|
||||
if ($head === null) { return false; }
|
||||
if ($head['size'] !== (int) $object['cipher_size'] || !hash_equals($object['context_hash'], (string) $head['context'])) {
|
||||
throw new \RuntimeException('Private cloud object integrity mismatch');
|
||||
}
|
||||
if (strlen($head['version_id']) > 256) { throw new \RuntimeException('Private cloud version invalid'); }
|
||||
Db::name('mobile_recording_object')->where('upload_id', $object['upload_id'])->update([
|
||||
'state' => 'ready', 'version_id' => $head['version_id'], 'attempts' => 0, 'next_retry_at' => 0, 'updated_at' => time()]);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Each bounded cloud operation has its own committed checkpoint. A retry never restarts all parts. */
|
||||
public static function advance(string $id, callable $guard, float $seconds = 20): void
|
||||
{
|
||||
$deadline = microtime(true) + max(0.01, min(20, $seconds));
|
||||
$probe = true;
|
||||
do {
|
||||
$ready = Db::transaction(static function () use ($id, $guard, &$probe): bool {
|
||||
$upload = $guard(); // Lock current binding and recheck ACL before each remote operation.
|
||||
$object = Db::name('mobile_recording_object')->where('upload_id', $id)->lock(true)->find();
|
||||
if (!$object || !in_array($object['state'], ['pending', 'finalizing', 'verifying', 'ready'], true)) {
|
||||
throw new \DomainException('上传会话已失效,请重新准备上传');
|
||||
}
|
||||
if ($object['state'] === 'ready') { return true; }
|
||||
$cloud = self::cloud();
|
||||
if ($probe || $object['state'] === 'verifying') {
|
||||
$probe = false;
|
||||
if (self::confirm($object, $cloud->head($object))) { return true; }
|
||||
if ($object['state'] === 'verifying') { throw new \RuntimeException('Private cloud confirmation pending'); }
|
||||
return false;
|
||||
}
|
||||
if ($object['multipart_id'] === '') {
|
||||
$multipart = $cloud->initiate($object);
|
||||
Db::name('mobile_recording_object')->where('upload_id', $id)->update(['multipart_id' => $multipart, 'updated_at' => time()]);
|
||||
return false;
|
||||
}
|
||||
$parts = json_decode($object['part_etags'], true, 512, JSON_THROW_ON_ERROR);
|
||||
$count = count($parts);
|
||||
$frames = MobileRecordingCipher::frames((int) $object['plain_size']);
|
||||
if ($count < $frames) {
|
||||
$cipher = MobileRecordingStorage::locked($id, static function ($file) use ($object, $count): string {
|
||||
$plain = MobileRecordingStorage::bytes($file, $count * MobileRecordingCipher::FRAME, MobileRecordingCipher::plainLength($object, $count));
|
||||
return MobileRecordingCipher::encrypt($object, $count, $plain);
|
||||
});
|
||||
$etag = $cloud->part($object, $count + 1, $cipher);
|
||||
$parts[] = ['PartNumber' => $count + 1, 'ETag' => $etag];
|
||||
Db::name('mobile_recording_object')->where('upload_id', $id)->update(['part_etags' => json_encode($parts), 'updated_at' => time()]);
|
||||
return false;
|
||||
}
|
||||
if ($object['state'] === 'pending') {
|
||||
// This checkpoint survives a lost CompleteMultipartUpload acknowledgement.
|
||||
Db::name('mobile_recording_object')->where('upload_id', $id)->update(['state' => 'finalizing', 'updated_at' => time()]);
|
||||
return false;
|
||||
}
|
||||
$cloud->finish($object, $parts);
|
||||
Db::name('mobile_recording_object')->where('upload_id', $id)->update(['state' => 'verifying', 'updated_at' => time()]);
|
||||
return false;
|
||||
});
|
||||
if ($ready) { return; }
|
||||
} while (microtime(true) < $deadline);
|
||||
// Existing dev26 machine code temporarily_unavailable drives bounded prepare/complete retries.
|
||||
throw new \RuntimeException('Private cloud upload checkpointed; continue on retry');
|
||||
}
|
||||
|
||||
public static function ready(array $upload): bool
|
||||
{
|
||||
return Db::name('mobile_recording_object')->where('upload_id', $upload['upload_id'])->where('state', 'ready')->count() > 0;
|
||||
}
|
||||
|
||||
public static function source(array $upload)
|
||||
{
|
||||
$object = Db::name('mobile_recording_object')->where('upload_id', $upload['upload_id'])->find();
|
||||
if (!$object || in_array($object['state'], ['pending', 'finalizing', 'verifying'], true)) {
|
||||
// Only an already-published legacy local upload can take this path.
|
||||
return MobileRecordingStorage::open($upload);
|
||||
}
|
||||
if ($object['state'] !== 'ready' || $object['cipher_format'] !== MobileRecordingCipher::FORMAT
|
||||
|| $object['kind'] !== $upload['kind'] || (int) $object['plain_size'] !== (int) $upload['size_bytes']
|
||||
|| !hash_equals($object['plain_sha256'], $upload['sha256'])) { throw new \RuntimeException('Private cloud reference invalid'); }
|
||||
return new MobileRecordingCloudReader($object, self::cloud());
|
||||
}
|
||||
|
||||
public static function verifyAvailable(array $upload): void
|
||||
{
|
||||
$object = Db::name('mobile_recording_object')->where('upload_id', $upload['upload_id'])->where('state', 'ready')->find();
|
||||
if (!$object) { $file = MobileRecordingStorage::open($upload); fclose($file); return; }
|
||||
$head = self::cloud()->head($object, true);
|
||||
if (!$head || $head['size'] !== (int) $object['cipher_size'] || !hash_equals($object['context_hash'], $head['context'])) {
|
||||
throw new \RuntimeException('Private cloud completed object unavailable');
|
||||
}
|
||||
}
|
||||
|
||||
/** Recover the commit-to-unlink window. Never delete legacy or un-published source bytes. */
|
||||
public static function cleanupStaging(string $id, bool $onlyPending = false): bool
|
||||
{
|
||||
return Db::transaction(static function () use ($id, $onlyPending): bool {
|
||||
$peek = Db::name('mobile_recording_upload')->where('upload_id', $id)->find();
|
||||
$binding = $peek ? Db::name('mobile_recording_binding')->where('id', $peek['binding_id'])->lock(true)->find() : null;
|
||||
$upload = Db::name('mobile_recording_upload')->where('upload_id', $id)->where('state', 'complete')->lock(true)->find();
|
||||
if (!$binding || !$upload) { return false; }
|
||||
$object = Db::name('mobile_recording_object')->where('upload_id', $id)->where('state', 'ready')->lock(true)->find();
|
||||
if (!$object || !Db::name('mobile_recording_asset')->where('binding_id', $upload['binding_id'])
|
||||
->where('kind', $upload['kind'])->where('upload_id', $id)->count()) { return false; }
|
||||
if ($onlyPending && Db::name('mobile_recording_work')->where('upload_id', $id)->value('staging_cleaned') == 1) { return true; }
|
||||
self::verifyAvailable($upload); // Pin the recorded version before deleting the fallback source.
|
||||
MobileRecordingStorage::removeStaging($id); // Missing file is success; unlink failure is retryable.
|
||||
MobileRecordingWork::stagingCleaned($id); // Commit after unlink; a crash can only cause a safe repeat.
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/** Same transaction as reference removal. Location/crypto ledger survives for reliable cleanup. */
|
||||
public static function queueDelete(array $ids): void
|
||||
{
|
||||
if (!$ids) { return; }
|
||||
Db::name('mobile_recording_object')->whereIn('upload_id', $ids)->where('state', '<>', 'deleted')
|
||||
->update(['state' => 'deleting', 'next_retry_at' => 0, 'updated_at' => time()]);
|
||||
Db::name('mobile_recording_work')->whereIn('upload_id', $ids)->delete();
|
||||
}
|
||||
|
||||
public static function cleanup(int $limit = 10, bool $dryRun = false): array
|
||||
{
|
||||
$ids = Db::name('mobile_recording_object')->where('state', 'deleting')->where('next_retry_at', '<=', time())
|
||||
->order('updated_at')->limit(max(1, min(100, $limit)))->column('upload_id');
|
||||
$counts = ['eligible' => count($ids), 'deleted' => 0, 'errors' => 0];
|
||||
if ($dryRun) { return $counts; }
|
||||
foreach ($ids as $id) {
|
||||
try {
|
||||
$deleted = Db::transaction(static function () use ($id): bool {
|
||||
$object = Db::name('mobile_recording_object')->where('upload_id', $id)->lock(true)->find();
|
||||
if (!$object || $object['state'] !== 'deleting') { return false; }
|
||||
if (Db::name('mobile_recording_upload')->where('upload_id', $id)->count()
|
||||
|| Db::name('mobile_recording_asset')->where('upload_id', $id)->count()) { throw new \RuntimeException('Media reference still live'); }
|
||||
$cloud = self::cloud();
|
||||
$cloud->abort($object);
|
||||
$head = $cloud->head($object, $object['version_id'] !== '');
|
||||
if ($head) {
|
||||
if (!hash_equals($object['context_hash'], $head['context'])) { throw new \RuntimeException('Cleanup context mismatch'); }
|
||||
$object['version_id'] = $head['version_id'];
|
||||
$cloud->delete($object); // Explicit VersionId when enabled; no mere delete marker.
|
||||
if ($cloud->head($object, true) !== null) { throw new \RuntimeException('Cleanup confirmation pending'); }
|
||||
}
|
||||
Db::name('mobile_recording_object')->where('upload_id', $id)->update(['state' => 'deleted',
|
||||
'version_id' => $object['version_id'], 'encryption_key' => '', 'nonce_prefix' => '', 'plain_sha256' => '',
|
||||
'part_etags' => '[]', 'multipart_id' => '', 'next_retry_at' => 0, 'updated_at' => time()]);
|
||||
return true;
|
||||
});
|
||||
if ($deleted) { $counts['deleted']++; }
|
||||
} catch (\Throwable $e) {
|
||||
$counts['errors']++;
|
||||
$row = Db::name('mobile_recording_object')->where('upload_id', $id)->find();
|
||||
if ($row && $row['state'] === 'deleting') {
|
||||
$attempts = min(10000, (int) $row['attempts'] + 1);
|
||||
Db::name('mobile_recording_object')->where('upload_id', $id)->update(['attempts' => $attempts,
|
||||
'next_retry_at' => time() + min(3600, 30 * (2 ** min(7, $attempts - 1))), 'updated_at' => time()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return $counts;
|
||||
}
|
||||
}
|
||||
@@ -194,10 +194,10 @@ final class MobileRecordingStorage
|
||||
public static function open(array $upload)
|
||||
{
|
||||
$file = @fopen(self::path((string) $upload['upload_id']), 'rb');
|
||||
if (!$file) { throw new DomainException('已上传文件暂不可读取,请重新上传'); }
|
||||
if (!$file) { throw new MobileRecordingLocalUnavailableException('已上传文件暂不可读取,请重新上传'); }
|
||||
if ((int) fstat($file)['size'] !== (int) $upload['size_bytes']) {
|
||||
fclose($file);
|
||||
throw new DomainException('已上传文件暂不可读取,请重新上传');
|
||||
throw new MobileRecordingLocalUnavailableException('已上传文件暂不可读取,请重新上传');
|
||||
}
|
||||
return $file;
|
||||
}
|
||||
@@ -211,6 +211,14 @@ final class MobileRecordingStorage
|
||||
}
|
||||
}
|
||||
|
||||
/** Confirmed COS publication only. A failed unlink must leave its durable cleanup task pending. */
|
||||
public static function removeStaging(string $id): void
|
||||
{
|
||||
$path = self::path($id);
|
||||
clearstatcache(true, $path);
|
||||
if (file_exists($path) && !@unlink($path)) { throw new RuntimeException('Private recording cleanup pending'); }
|
||||
}
|
||||
|
||||
/** CLI housekeeping only. Never expires referenced uploads or completed patient assets. */
|
||||
public static function cleanupOrphans(bool $dryRun = true): array
|
||||
{
|
||||
|
||||
@@ -10,6 +10,7 @@ final class MobileRecordingStream extends \think\Response
|
||||
private $file;
|
||||
private int $start = 0;
|
||||
private int $length = 0;
|
||||
private string $prefetched = '';
|
||||
|
||||
public function __construct($file, int $size, string $mime, string $range = '')
|
||||
{
|
||||
@@ -39,20 +40,29 @@ final class MobileRecordingStream extends \think\Response
|
||||
}
|
||||
$this->header(['Content-Length' => (string) $this->length]);
|
||||
$this->allowCache(false);
|
||||
// Fetch/authenticate the first cloud frame before HTTP headers are sent, so failure is still JSON.
|
||||
if (is_callable($this->file) && $this->length > 0) {
|
||||
$this->prefetched = ($this->file)($this->start, min(65536, $this->length));
|
||||
}
|
||||
}
|
||||
|
||||
protected function sendData(string $data): void
|
||||
{
|
||||
if (!is_resource($this->file) || fseek($this->file, $this->start) !== 0) { return; }
|
||||
$remote = is_callable($this->file);
|
||||
if (!$remote && (!is_resource($this->file) || fseek($this->file, $this->start) !== 0)) { return; }
|
||||
try {
|
||||
$remaining = $this->length;
|
||||
$offset = $this->start;
|
||||
while ($remaining > 0 && !connection_aborted()) {
|
||||
$chunk = fread($this->file, min(65536, $remaining));
|
||||
if ($this->prefetched !== '') { $chunk = $this->prefetched; $this->prefetched = ''; }
|
||||
else { $chunk = $remote ? ($this->file)($offset, min(65536, $remaining)) : fread($this->file, min(65536, $remaining)); }
|
||||
if ($chunk === false || $chunk === '') { break; }
|
||||
echo $chunk;
|
||||
$remaining -= strlen($chunk);
|
||||
$remaining -= strlen($chunk); $offset += strlen($chunk);
|
||||
}
|
||||
} finally { fclose($this->file); $this->file = null; }
|
||||
} catch (\Throwable $e) {
|
||||
// A short body fails Content-Length at the client; never append provider errors to audio.
|
||||
} finally { if (is_resource($this->file)) { fclose($this->file); } $this->file = null; }
|
||||
}
|
||||
|
||||
public function __destruct()
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\mobilerecording;
|
||||
|
||||
use think\facade\Db;
|
||||
|
||||
/** Durable scheduling even when ACL/configuration fails before a COS object intent exists. */
|
||||
final class MobileRecordingWork
|
||||
{
|
||||
private static function update(string $id, callable $change): void
|
||||
{
|
||||
Db::transaction(static function () use ($id, $change): void {
|
||||
// Share the API's binding lock before upload/work locks. Unbind and replacement
|
||||
// remove work before upload; skipping this boundary would invert their lock order.
|
||||
$peek = Db::name('mobile_recording_upload')->where('upload_id', $id)->find();
|
||||
if (!$peek || !Db::name('mobile_recording_binding')->where('id', $peek['binding_id'])->lock(true)->find()) { return; }
|
||||
$upload = Db::name('mobile_recording_upload')->where('upload_id', $id)->lock(true)->find();
|
||||
if (!$upload || (int) $upload['binding_id'] !== (int) $peek['binding_id']) { return; }
|
||||
$current = Db::name('mobile_recording_work')->where('upload_id', $id)->lock(true)->find();
|
||||
$row = $current ?: ['upload_id' => $id, 'attempts' => 0, 'next_retry_at' => 0,
|
||||
'last_attempt_at' => 0, 'last_result' => '', 'staging_cleaned' => 0];
|
||||
$row = $change($row);
|
||||
if ($current) { Db::name('mobile_recording_work')->where('upload_id', $id)->update($row); }
|
||||
else { Db::name('mobile_recording_work')->insert($row); }
|
||||
});
|
||||
}
|
||||
|
||||
public static function attempted(string $id, ?\Throwable $error = null): void
|
||||
{
|
||||
self::update($id, static function (array $row) use ($error): array {
|
||||
$row['attempts'] = $error === null ? 0 : min(10000, (int) $row['attempts'] + 1);
|
||||
$row['next_retry_at'] = $error === null ? 0 : time() + min(3600, 30 * (2 ** min(7, $row['attempts'] - 1)));
|
||||
$row['last_attempt_at'] = time();
|
||||
// Store only a bounded classification, never exception text, URLs or credentials.
|
||||
$row['last_result'] = $error === null ? 'completed' : ($error instanceof \DomainException ? 'denied' : 'deferred');
|
||||
return $row;
|
||||
});
|
||||
}
|
||||
|
||||
public static function stagingCleaned(string $id): void
|
||||
{
|
||||
self::update($id, static function (array $row): array { $row['staging_cleaned'] = 1; return $row; });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user