This commit is contained in:
Your Name
2026-11-09 14:51:31 +08:00
parent 01a46ee06f
commit 06afe2c453
20 changed files with 1241 additions and 25 deletions
+7
View File
@@ -0,0 +1,7 @@
<?php
declare(strict_types=1);
// Extends the actual API/ACL/Range suite with COS fault injection. No live service or config is loaded.
define('MOBILE_RECORDING_COS_FAULT_TEST', true);
require __DIR__ . '/MobileRecordingMediaTest.php';
+26 -1
View File
@@ -11,8 +11,13 @@ use app\adminapi\logic\tcm\MobileRecordingMediaLogic as Media;
use app\adminapi\controller\tcm\MobileRecordingMediaController;
use think\Container;
use think\facade\Db;
use app\common\service\mobilerecording\MobileRecordingObjects as Objects;
use app\common\service\mobilerecording\MobileRecordingCos;
$app = new think\App();
require __DIR__ . '/fixtures/FakeMobileRecordingCos.php';
$fakeCloud = new FakeMobileRecordingCos();
Container::getInstance()->instance(MobileRecordingCos::class, $fakeCloud);
$manager = new think\DbManager();
$driver = 'sqlite';
$pdo = null;
@@ -83,6 +88,8 @@ try {
$pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_06_mobile_recording_binding.sql'));
$pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_09_mobile_recording_media.sql'));
$pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_09_mobile_recording_media.sql'));
$pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_09_mobile_recording_cos.sql'));
$pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_09_mobile_recording_cos.sql'));
$expect(true, 'real upgrade migration executes and is idempotent on isolated MySQL');
} else {
Db::execute('CREATE TABLE zyt_mobile_recording_binding (id INTEGER PRIMARY KEY AUTOINCREMENT, admin_id INT NOT NULL,
@@ -168,7 +175,22 @@ try {
$expect(filesize($storage . '/' . $session['upload_id'] . '.bin') === Media::CHUNK_SIZE, 'uncommitted trailing bytes removed');
$last = substr($wav, Media::CHUNK_SIZE);
Media::chunk($upload + ['offset' => Media::CHUNK_SIZE, 'chunk_sha256' => hash('sha256', $last)], $last, 11);
$expect(Media::complete($upload, 11)['state'] === 'complete', 'full size hash and WAV signature validated');
$expect(Media::complete($upload, 11)['state'] === 'complete', 'full size hash and WAV signature validated before confirmed COS publication');
$cosObject = Db::name('mobile_recording_object')->where('upload_id', $session['upload_id'])->find();
$expect($cosObject['state'] === 'ready' && $cosObject['version_id'] !== '', 'COS location and version durably recorded');
$expect(!is_file($storage . '/' . $session['upload_id'] . '.bin'), 'completed COS media clears local plaintext staging');
$expect(!str_starts_with($fakeCloud->objects[$fakeCloud->key($cosObject)]['bytes'], 'RIFF'), 'COS audio is ciphertext rather than playable plaintext');
if ($driver === 'mysql') {
$tables = ['mobile_recording_binding', 'mobile_recording_upload', 'mobile_recording_asset', 'mobile_recording_object', 'mobile_recording_work'];
$beforeUpgrade = [];
foreach ($tables as $table) { $beforeUpgrade[$table] = Db::name($table)->select()->toArray(); }
$pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_09_mobile_recording_cos.sql'));
$pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_09_mobile_recording_cos.sql'));
foreach ($tables as $table) {
$expect(Db::name($table)->select()->toArray() === $beforeUpgrade[$table], 'COS upgrade preserves existing synthetic ' . $table . ' rows');
}
}
$expect(Media::chunk($chunk, $first, 11)['state'] === 'complete', 'duplicate completed chunk validates against COS without recreating local file');
$expect(Media::complete($upload, 11)['state'] === 'complete', 'repeat complete idempotent');
$expect(Media::prepare($prepare, 11)['state'] === 'complete', 'repeat completed prepare reuses object');
$expect(Binding::patientLists(['diagnosis_id' => 101], 11)['lists'][0]['upload_state'] === 'partial', 'audio alone is partial and available');
@@ -245,6 +267,8 @@ try {
$denied(fn () => Media::chunk($chunk, $first, 11), 'unbind immediately revokes pending writes');
$expect(Db::name('mobile_recording_upload')->count() === 0 && Db::name('mobile_recording_asset')->count() === 0, 'unbind removes all media DB references');
$expect((glob($storage . '/*.bin') ?: []) === [], 'unbind removes private files');
$cloudCleanup = Objects::cleanup(100);
$expect($cloudCleanup['errors'] === 0 && $fakeCloud->objects === [], 'revoked COS assets deleted with explicit version IDs');
$orphan = $storage . '/' . str_repeat('f', 32) . '.bin';
file_put_contents($orphan, 'synthetic orphan');
touch($orphan, time() - 90000);
@@ -252,6 +276,7 @@ try {
$expect($cleanup['eligible'] === 1 && is_file($orphan), 'orphan cleanup dry run preserves files');
$cleanup = \app\common\service\mobilerecording\MobileRecordingStorage::cleanupOrphans(false);
$expect($cleanup['deleted'] === 1 && !is_file($orphan), 'orphan cleanup removes only aged unreferenced objects');
if (defined('MOBILE_RECORDING_COS_FAULT_TEST')) { require __DIR__ . '/fixtures/mobile_recording_cos_cases.php'; }
Binding::bind($input, 11);
Db::execute('DROP TABLE zyt_mobile_recording_upload');
$missingSchema = $controller('prepare', $prepare)->getData();
+85
View File
@@ -0,0 +1,85 @@
<?php
declare(strict_types=1);
use app\common\service\mobilerecording\MobileRecordingCos;
/** In-memory synthetic COS. No configuration, credentials, SDK or network access. */
final class FakeMobileRecordingCos extends MobileRecordingCos
{
public array $current = ['bucket' => 'synthetic-1250000000', 'region' => 'ap-guangzhou'];
public array $objects = [];
public array $multipart = [];
public array $calls = [];
public int $losePartAck = 0;
public int $loseFinishAck = 0;
public int $failHead = 0;
public int $denyHead = 0;
public int $failDelete = 0;
public int $loseCreateAck = 0;
public int $partWrites = 0;
public int $finishes = 0;
public array $deletedVersions = [];
public $onPart = null;
public function location(): array { return $this->current; }
public function key(array $o): string { return $o['bucket'] . '|' . $o['region'] . '|' . $o['object_key']; }
public function initiate(array $o): string
{
$id = 'fake-' . (count($this->multipart) + 1);
$this->multipart[$id] = ['object' => $o, 'parts' => []];
$this->calls[] = 'initiate';
if ($this->loseCreateAck-- > 0) { throw new RuntimeException('synthetic create acknowledgement lost'); }
return $id;
}
public function part(array $o, int $number, string $cipher): string
{
if (!isset($this->multipart[$o['multipart_id']])) { throw new RuntimeException('synthetic session missing'); }
$this->multipart[$o['multipart_id']]['parts'][$number] = $cipher;
$this->partWrites++; $this->calls[] = 'part';
if ($this->onPart !== null) { $callback = $this->onPart; $this->onPart = null; $callback(); }
if ($this->losePartAck-- > 0) { throw new RuntimeException('synthetic part acknowledgement lost'); }
return md5($cipher);
}
public function finish(array $o, array $parts): void
{
$session = $this->multipart[$o['multipart_id']] ?? null;
if (!$session) { throw new RuntimeException('synthetic multipart absent'); }
$bytes = '';
foreach ($parts as $part) {
$body = $session['parts'][$part['PartNumber']] ?? '';
if (md5($body) !== $part['ETag']) { throw new RuntimeException('synthetic part mismatch'); }
$bytes .= $body;
}
$this->objects[$this->key($o)] = ['bytes' => $bytes, 'context' => $o['context_hash'], 'version_id' => 'version-' . (++$this->finishes)];
unset($this->multipart[$o['multipart_id']]);
$this->calls[] = 'finish';
if ($this->loseFinishAck-- > 0) { throw new RuntimeException('synthetic finish acknowledgement lost'); }
}
public function head(array $o, bool $pinned = false): ?array
{
$this->calls[] = 'head';
if ($this->denyHead-- > 0) { throw new DomainException('云端存储授权不可用,请联系管理员检查配置'); }
if ($this->failHead-- > 0) { throw new RuntimeException('synthetic COS down'); }
$object = $this->objects[$this->key($o)] ?? null;
if (!$object || ($pinned && $o['version_id'] !== '' && $o['version_id'] !== $object['version_id'])) { return null; }
return ['size' => strlen($object['bytes']), 'context' => $object['context'], 'version_id' => $object['version_id']];
}
public function range(array $o, int $start, int $end): string
{
$object = $this->objects[$this->key($o)] ?? null;
if (!$object || $o['version_id'] !== $object['version_id']) { throw new RuntimeException('synthetic pinned object absent'); }
if ($end - $start + 1 > 1048592) { throw new RuntimeException('unbounded cloud read'); }
$this->calls[] = 'range:' . $start . '-' . $end;
return substr($object['bytes'], $start, $end - $start + 1);
}
public function delete(array $o): void
{
if ($this->failDelete-- > 0) { throw new RuntimeException('synthetic delete failed'); }
$object = $this->objects[$this->key($o)] ?? null;
if ($object && $object['version_id'] !== $o['version_id']) { throw new RuntimeException('unversioned delete forbidden in fixture'); }
$this->deletedVersions[] = $o['version_id'];
unset($this->objects[$this->key($o)]);
$this->calls[] = 'delete';
}
public function abort(array $o): void { unset($this->multipart[$o['multipart_id']]); $this->calls[] = 'abort'; }
}
+134
View File
@@ -0,0 +1,134 @@
<?php
use app\adminapi\logic\tcm\MobileRecordingLogic as CosBinding;
use app\adminapi\logic\tcm\MobileRecordingMediaLogic as CosMedia;
use app\common\service\mobilerecording\MobileRecordingObjects as CosObjects;
use think\facade\Db as CosDb;
(static function () use ($fakeCloud, $expect, $controller, $input, $identity, $target, $prepare, $wav, $storage, $driver, $capture): void {
$binding = CosBinding::bind($input, 11)['binding'];
$bindingId = $binding['id'];
$send = static function (string $text) use ($target): array {
$p = CosMedia::prepare($target + ['kind' => 'transcript', 'size_bytes' => strlen($text),
'sha256' => hash('sha256', $text), 'media_type' => 'text/plain'], 11);
$request = ['upload_id' => $p['upload_id'], 'diagnosis_id' => 101];
if ($text !== '') { CosMedia::chunk($request + ['offset' => 0, 'chunk_sha256' => hash('sha256', $text)], $text, 11); }
return $request;
};
$read = static fn (): array => CosMedia::transcript(['binding_id' => $bindingId, 'diagnosis_id' => 101], 11);
$legacy = $send('synthetic legacy plaintext');
CosDb::name('mobile_recording_upload')->where('upload_id', $legacy['upload_id'])->update(['state' => 'complete']);
CosDb::name('mobile_recording_asset')->insert(['binding_id' => $bindingId, 'kind' => 'transcript', 'upload_id' => $legacy['upload_id'], 'updated_at' => time()]);
$calls = count($fakeCloud->calls);
$expect($read()['text'] === 'synthetic legacy plaintext' && count($fakeCloud->calls) === $calls, 'legacy local completion reads without COS or config');
$expect(!CosObjects::ready(CosDb::name('mobile_recording_upload')->where('upload_id', $legacy['upload_id'])->find()), 'legacy remains local until explicit migration');
$output = new \think\console\Output('buffer');
$exit = (new \app\command\MobileRecordingCosMigrate())->run(new \think\console\Input(['--dry-run', '--limit=1']), $output);
$expect($exit === 0 && count($fakeCloud->calls) === $calls && is_file($storage . '/' . $legacy['upload_id'] . '.bin'), 'actual migration CLI dry-run reads no media or cloud and writes no object');
$expect(str_contains($output->fetch(), '"selected":1'), 'migration dry-run reports bounded batch count');
CosMedia::migrateLocal($legacy['upload_id']);
$expect($read()['text'] === 'synthetic legacy plaintext', 'explicit migration preserves exact text');
$expect(!is_file($storage . '/' . $legacy['upload_id'] . '.bin'), 'migration removes local plaintext only after ready commit');
$replacementText = 'synthetic replacement secret UTF8 中文';
$replacement = $send($replacementText);
$fakeCloud->failHead = 1;
$failure = $controller('complete', $replacement)->getData();
$expect($failure['code'] === 0 && $failure['data'] === ['error_code' => 'temporarily_unavailable', 'retryable' => true], 'COS outage uses unchanged dev26 retryable machine envelope');
$ledger = CosDb::name('mobile_recording_object')->where('upload_id', $replacement['upload_id'])->find();
$expect(strlen($ledger['encryption_key']) === 64 && $ledger['state'] === 'pending', 'intent and crypto key committed before remote calls');
$expect(CosMedia::status($target, 11)['transcript']['received_bytes'] === strlen($replacementText), 'COS failure preserves confirmed phone cursor');
$expect($read()['text'] === 'synthetic legacy plaintext' && is_file($storage . '/' . $replacement['upload_id'] . '.bin'), 'COS failure keeps old publication and new local staging');
$calls = count($fakeCloud->calls);
$output = new \think\console\Output('buffer');
$exit = (new \app\command\MobileRecordingCosWork())->run(new \think\console\Input(['--dry-run', '--limit=1', '--seconds=1']), $output);
$expect($exit === 0 && count($fakeCloud->calls) === $calls && str_contains($output->fetch(), '"uploads_selected":1'), 'actual worker dry-run reports pending upload without remote calls');
$fakeCloud->loseCreateAck = 1;
$failure = $controller('complete', $replacement)->getData();
$orphanIds = array_keys($fakeCloud->multipart);
$orphan = end($orphanIds);
$afterCreate = CosDb::name('mobile_recording_object')->where('upload_id', $replacement['upload_id'])->find();
$expect($failure['code'] === 0 && $afterCreate['multipart_id'] === '' && $fakeCloud->multipart[$orphan]['parts'] === [],
'lost create acknowledgement sends no patient parts before durable multipart checkpoint');
// COS lifecycle for this dedicated prefix must abort stale incomplete uploads; simulate that cleanup only.
unset($fakeCloud->multipart[$orphan]);
$fakeCloud->losePartAck = 1;
$failure = $controller('complete', $replacement)->getData();
$ledger = CosDb::name('mobile_recording_object')->where('upload_id', $replacement['upload_id'])->find();
$expect($failure['code'] === 0 && $ledger['multipart_id'] !== '' && json_decode($ledger['part_etags'], true) === [], 'lost part acknowledgement keeps durable multipart ID without false checkpoint');
$fakeCloud->loseFinishAck = 1;
$failure = $controller('complete', $replacement)->getData();
$expect($failure['code'] === 0 && isset($fakeCloud->objects[$fakeCloud->key($ledger)]), 'lost remote completion acknowledgement leaves tracked ciphertext');
$finishes = $fakeCloud->finishes;
$output = new \think\console\Output('buffer');
$exit = (new \app\command\MobileRecordingCosWork())->run(new \think\console\Input(['--limit=1', '--seconds=20']), $output);
$expect($exit === 0 && str_contains($output->fetch(), '"uploads_completed":1'), 'actual worker resumes and publishes checkpointed upload without the phone');
$expect($fakeCloud->finishes === $finishes && $read()['text'] === $replacementText, 'HEAD recovers lost finish acknowledgement without duplicate completion');
$ledger = CosDb::name('mobile_recording_object')->where('upload_id', $replacement['upload_id'])->find();
$cipher = $fakeCloud->objects[$fakeCloud->key($ledger)]['bytes'];
$expect(!str_contains($cipher, $replacementText) && strlen($cipher) === strlen($replacementText) + 16, 'COS text contains only authenticated ciphertext');
$publicDto = json_encode(CosMedia::status($target, 11));
$expect(!str_contains($publicDto, $ledger['encryption_key']) && !str_contains($publicDto, $ledger['bucket'])
&& !str_contains($publicDto, $ledger['object_key']), 'protocol never returns crypto key bucket or object key');
$fakeCloud->current = ['bucket' => 'new-synthetic-1250000000', 'region' => 'ap-shanghai'];
$expect($read()['text'] === $replacementText, 'configuration change reads original persisted location');
$next = $send('new config content');
if ($driver === 'sqlite') {
CosDb::execute("CREATE TRIGGER synthetic_publish_failure BEFORE UPDATE ON zyt_mobile_recording_upload WHEN NEW.state='complete' BEGIN SELECT RAISE(ABORT,'synthetic publication failure'); END");
$failure = $controller('complete', $next)->getData();
$ready = CosDb::name('mobile_recording_object')->where('upload_id', $next['upload_id'])->find();
$expect($failure['code'] === 0 && $ready['state'] === 'ready', 'remote ready survives separate DB publication failure');
$expect($read()['text'] === $replacementText, 'failed publication preserves previously completed asset');
$expect(is_file($storage . '/' . $next['upload_id'] . '.bin'), 'failed publication does not clear source staging');
CosDb::execute('DROP TRIGGER synthetic_publish_failure');
$finishes = $fakeCloud->finishes;
CosMedia::complete($next, 11);
$expect($fakeCloud->finishes === $finishes, 'publication retry does not reupload already ready COS object');
} else { CosMedia::complete($next, 11); }
$ready = CosDb::name('mobile_recording_object')->where('upload_id', $next['upload_id'])->find();
$expect($ready['bucket'] === $fakeCloud->current['bucket'] && $ledger['bucket'] !== $ready['bucket'], 'new uploads use new config while old ledger is immutable');
$key = $fakeCloud->key($ready); $untampered = $fakeCloud->objects[$key]['bytes'];
$fakeCloud->objects[$key]['bytes'][0] = chr(ord($untampered[0]) ^ 1);
$failure = $controller('transcript', ['binding_id' => $bindingId, 'diagnosis_id' => 101], false)->getData();
$expect($failure['code'] === 0 && !str_contains(json_encode($failure), 'new config content'), 'GCM tampering fails closed before returning text');
$fakeCloud->objects[$key]['bytes'] = $untampered;
CosBinding::bind(array_replace($input, ['diagnosis_id' => 102]), 11);
$expect(CosMedia::transcript(['binding_id' => $bindingId, 'diagnosis_id' => 102], 11)['text'] === 'new config content', 'immutable AAD permits authorized rebind');
CosBinding::bind($input, 11);
$audio = CosMedia::prepare($prepare, 11);
$ap = ['upload_id' => $audio['upload_id'], 'diagnosis_id' => 101];
for ($offset = 0; $offset < strlen($wav); $offset += CosMedia::CHUNK_SIZE) {
$part = substr($wav, $offset, CosMedia::CHUNK_SIZE);
CosMedia::chunk($ap + ['offset' => $offset, 'chunk_sha256' => hash('sha256', $part)], $part, 11);
}
CosMedia::complete($ap, 11);
$range = 'bytes=' . (CosMedia::CHUNK_SIZE - 5) . '-' . (CosMedia::CHUNK_SIZE + 5);
$expect($capture(CosMedia::audio(['binding_id' => $bindingId], 11, $range)) === substr($wav, CosMedia::CHUNK_SIZE - 5, 11), 'plaintext Range crossing two authenticated frames is exact');
$empty = $send(''); CosMedia::complete($empty, 11);
$emptyObject = CosDb::name('mobile_recording_object')->where('upload_id', $empty['upload_id'])->find();
$expect(strlen($fakeCloud->objects[$fakeCloud->key($emptyObject)]['bytes']) === 16 && $read()['text'] === '', 'empty transcript is a verified GCM tag rather than unprotected empty object');
CosBinding::unbind($identity, 11);
$fakeCloud->failDelete = 1;
$clean = CosObjects::cleanup(100);
$expect($clean['errors'] === 1 && CosDb::name('mobile_recording_object')->where('state', 'deleting')->count() === 1, 'delete failure retains durable location and retry outbox');
$denial = $controller('transcript', ['binding_id' => $bindingId], false)->getData();
$expect($denial['code'] === 0 && $denial['data']['retryable'] === false, 'access revoked before remote deletion retry');
CosDb::name('mobile_recording_object')->where('state', 'deleting')->update(['next_retry_at' => 0]);
$clean = CosObjects::cleanup(100);
$expect($clean['errors'] === 0 && $fakeCloud->objects === [], 'delete retries remove objects from their original buckets');
$expect(!in_array('', $fakeCloud->deletedVersions, true), 'versioned objects are deleted by explicit version ID');
$expect(CosDb::name('mobile_recording_object')->where('state', 'deleted')->where('encryption_key', '<>', '')->count() === 0, 'successful cleanup erases per-object decryption keys');
// Mutation during a fake remote callback stresses the revalidation boundary (not a claim of concurrent InnoDB testing).
CosBinding::bind($input, 11);
$revoked = $send('revoked while part in flight');
$fakeCloud->onPart = static function () use ($identity): void { CosBinding::unbind($identity, 11); };
$failure = $controller('complete', $revoked)->getData();
$expect($failure['code'] === 0 && CosDb::name('mobile_recording_asset')->count() === 0, 'revoked binding cannot publish after remote callback');
$expect(CosDb::name('mobile_recording_object')->where('upload_id', $revoked['upload_id'])->value('state') === 'deleting', 'revoked in-flight multipart remains tracked for abort');
$clean = CosObjects::cleanup(100);
$expect($clean['errors'] === 0 && $fakeCloud->multipart === [], 'queued cleanup aborts in-flight multipart');
require __DIR__ . '/mobile_recording_cos_sdk.php';
require __DIR__ . '/mobile_recording_cos_final_cases.php';
})();
@@ -0,0 +1,182 @@
<?php
use app\adminapi\logic\tcm\MobileRecordingLogic as FinalBinding;
use app\adminapi\logic\tcm\MobileRecordingMediaLogic as FinalMedia;
use app\common\service\mobilerecording\MobileRecordingObjects as FinalObjects;
use think\facade\Db as FinalDb;
// Regressions for COS-FINAL-001/002/003. Runs with both SQLite and the isolated real MySQL schema.
(static function () use ($fakeCloud, $expect, $controller, $input, $storage): void {
$send = static function (string $label, string $text, int $actor = 11) use ($input): array {
$identity = ['installation_id' => $input['installation_id'], 'recording_key' => hash('sha256', 'cos-final-' . $label)];
$binding = FinalBinding::bind(array_replace($input, $identity), $actor)['binding'];
$prepare = $identity + ['diagnosis_id' => 101, 'kind' => 'transcript', 'size_bytes' => strlen($text),
'sha256' => hash('sha256', $text), 'media_type' => 'text/plain'];
$upload = FinalMedia::prepare($prepare, $actor);
$request = ['upload_id' => $upload['upload_id'], 'diagnosis_id' => 101];
if ($text !== '') { FinalMedia::chunk($request + ['offset' => 0, 'chunk_sha256' => hash('sha256', $text)], $text, $actor); }
return ['id' => $upload['upload_id'], 'request' => $request, 'prepare' => $prepare,
'binding' => $binding['id'], 'identity' => $identity, 'actor' => $actor, 'text' => $text];
};
$legacy = static function (array $case): void {
FinalDb::name('mobile_recording_upload')->where('upload_id', $case['id'])->update(['state' => 'complete']);
FinalDb::name('mobile_recording_asset')->insert(['binding_id' => $case['binding'], 'kind' => 'transcript',
'upload_id' => $case['id'], 'updated_at' => time()]);
};
$advanceOnly = static function (array $case): void {
$guard = static fn (): array => FinalDb::name('mobile_recording_upload')->where('upload_id', $case['id'])->lock(true)->find();
FinalDb::transaction(static fn (): array => FinalObjects::ensure($guard()));
FinalObjects::advance($case['id'], $guard);
};
$worker = static function (bool $dry = false): array {
$output = new \think\console\Output('buffer');
$options = ['--limit=1', '--seconds=20'];
if ($dry) { $options[] = '--dry-run'; }
$exit = (new \app\command\MobileRecordingCosWork())->run(new \think\console\Input($options), $output);
$text = trim($output->fetch());
return ['exit' => $exit, 'counts' => json_decode(substr($text, strlen('MOBILE_RECORDING_COS_WORK ')), true, 512, JSON_THROW_ON_ERROR)];
};
$forget = static function (array $case): void { FinalBinding::unbind($case['identity'], $case['actor']); };
$published = $send('authorization', 'synthetic durable publication');
FinalMedia::complete($published['request'], 11);
$beforeUpload = FinalDb::name('mobile_recording_upload')->where('upload_id', $published['id'])->find();
$beforeAsset = FinalDb::name('mobile_recording_asset')->where('upload_id', $published['id'])->find();
$beforeObject = FinalDb::name('mobile_recording_object')->where('upload_id', $published['id'])->find();
$fakeCloud->denyHead = 1;
$denial = $controller('prepare', $published['prepare'])->getData();
$expect($denial['code'] === 0 && $denial['data'] === ['error_code' => 'request_rejected', 'retryable' => false],
'COS-FINAL-001 cloud authorization failure keeps non-retryable API envelope');
$expect(FinalDb::name('mobile_recording_upload')->where('upload_id', $published['id'])->find() === $beforeUpload
&& FinalDb::name('mobile_recording_asset')->where('upload_id', $published['id'])->find() === $beforeAsset
&& FinalDb::name('mobile_recording_object')->where('upload_id', $published['id'])->find() === $beforeObject,
'COS-FINAL-001 cloud authorization failure preserves published asset upload cursor and ready ledger');
$fakeCloud->failHead = 1;
$failure = $controller('prepare', $published['prepare'])->getData();
$expect($failure['code'] === 0 && $failure['data']['retryable'] === true
&& FinalDb::name('mobile_recording_asset')->where('upload_id', $published['id'])->find() === $beforeAsset,
'COS-FINAL-001 transient cloud outage also preserves publication');
$expect(FinalMedia::transcript(['binding_id' => $published['binding']], 11)['text'] === $published['text'],
'COS-FINAL-001 published transcript remains readable after cloud authorization recovers');
$forget($published);
$missing = $send('missing-local', 'synthetic missing legacy');
$legacy($missing);
unlink($storage . '/' . $missing['id'] . '.bin');
$calls = count($fakeCloud->calls);
$reset = FinalMedia::prepare($missing['prepare'], 11);
$expect($reset['state'] === 'uploading' && $reset['received_bytes'] === 0
&& FinalDb::name('mobile_recording_asset')->where('upload_id', $missing['id'])->count() === 0
&& count($fakeCloud->calls) === $calls, 'COS-FINAL-001 explicit missing legacy source still resets for reupload without COS');
$forget($missing);
$crash = $send('publication-window', 'synthetic publication window');
FinalMedia::complete($crash['request'], 11);
$path = $storage . '/' . $crash['id'] . '.bin';
// Reconstruct exactly the committed publication before its cleanup acknowledgement exists.
file_put_contents($path, $crash['text']);
FinalDb::name('mobile_recording_work')->where('upload_id', $crash['id'])->delete();
$finishes = $fakeCloud->finishes;
$repeat = FinalMedia::complete($crash['request'], 11);
$expect($repeat['state'] === 'complete' && !is_file($path) && $fakeCloud->finishes === $finishes
&& FinalDb::name('mobile_recording_work')->where('upload_id', $crash['id'])->value('staging_cleaned') == 1,
'COS-FINAL-002 repeat complete recovers publication-to-unlink crash without reupload');
file_put_contents($path, $crash['text']);
FinalDb::name('mobile_recording_work')->where('upload_id', $crash['id'])->delete();
$calls = count($fakeCloud->calls);
$preview = $worker(true);
$expect($preview['exit'] === 0 && $preview['counts']['uploads_selected'] === 1 && is_file($path)
&& count($fakeCloud->calls) === $calls && FinalDb::name('mobile_recording_work')->where('upload_id', $crash['id'])->count() === 0,
'COS-FINAL-002 worker dry-run reports staging recovery without remote or local writes');
$run = $worker();
$expect($run['exit'] === 0 && $run['counts']['staging_cleaned'] === 1 && !is_file($path) && $fakeCloud->finishes === $finishes,
'COS-FINAL-002 worker recovers committed publication staging without phone or reupload');
// The file is already absent, but a process died before recording that fact in the work table.
FinalDb::name('mobile_recording_work')->where('upload_id', $crash['id'])->delete();
$run = $worker();
$expect($run['exit'] === 0 && $run['counts']['staging_cleaned'] === 1
&& FinalDb::name('mobile_recording_work')->where('upload_id', $crash['id'])->value('staging_cleaned') == 1,
'COS-FINAL-002 worker idempotently acknowledges unlink-to-DB crash with missing file');
file_put_contents($path, $crash['text']);
FinalMedia::complete($crash['request'], 11);
$expect(!is_file($path), 'COS-FINAL-002 repeat complete also removes unexpectedly restored staging');
$forget($crash);
$migration = $send('migration-window', 'synthetic migration window');
$legacy($migration);
$calls = count($fakeCloud->calls);
$expect(!FinalObjects::cleanupStaging($migration['id']) && is_file($storage . '/' . $migration['id'] . '.bin')
&& count($fakeCloud->calls) === $calls, 'COS-FINAL-002 cleanup preserves published legacy source without COS ledger');
$advanceOnly($migration); // The real ready checkpoint is committed; explicit migration has not unlinked yet.
$finishes = $fakeCloud->finishes;
$run = $worker();
$expect($run['exit'] === 0 && $run['counts']['staging_cleaned'] === 1
&& !is_file($storage . '/' . $migration['id'] . '.bin') && $fakeCloud->finishes === $finishes,
'COS-FINAL-002 worker recovers legacy migration ready-to-unlink crash');
FinalMedia::migrateLocal($migration['id']);
$expect(FinalMedia::transcript(['binding_id' => $migration['binding']], 11)['text'] === $migration['text'],
'COS-FINAL-002 explicit migration remains idempotent after recovered cleanup');
$forget($migration);
$unpublished = $send('unpublished-ready', 'synthetic not yet published');
$advanceOnly($unpublished);
$calls = count($fakeCloud->calls);
$expect(!FinalObjects::cleanupStaging($unpublished['id']) && is_file($storage . '/' . $unpublished['id'] . '.bin')
&& count($fakeCloud->calls) === $calls, 'COS-FINAL-002 cleanup never removes ready but unpublished staging');
$forget($unpublished);
$unlink = $send('unlink-failure', 'synthetic unlink failure');
FinalMedia::complete($unlink['request'], 11);
$path = $storage . '/' . $unlink['id'] . '.bin';
// A directory at the owned synthetic filename deterministically makes unlink fail on both test platforms.
mkdir($path, 0700);
file_put_contents($path . '/synthetic', 'owned fixture');
FinalDb::name('mobile_recording_work')->where('upload_id', $unlink['id'])->delete();
try {
$repeat = FinalMedia::complete($unlink['request'], 11);
$run = $worker();
$work = FinalDb::name('mobile_recording_work')->where('upload_id', $unlink['id'])->find();
$expect($repeat['state'] === 'complete' && $run['exit'] === 1 && $run['counts']['uploads_deferred'] === 1
&& $work['staging_cleaned'] == 0 && $work['next_retry_at'] > time()
&& FinalDb::name('mobile_recording_asset')->where('upload_id', $unlink['id'])->count() === 1,
'COS-FINAL-002 unlink failure retains publication and durable cleanup retry');
} finally { unlink($path . '/synthetic'); rmdir($path); }
file_put_contents($path, $unlink['text']);
FinalDb::name('mobile_recording_work')->where('upload_id', $unlink['id'])->update(['next_retry_at' => 0]);
$run = $worker();
$expect($run['exit'] === 0 && !is_file($path)
&& FinalDb::name('mobile_recording_work')->where('upload_id', $unlink['id'])->value('staging_cleaned') == 1,
'COS-FINAL-002 next due worker removes staging after unlink failure clears');
$forget($unlink);
$blocked = $send('blocked-owner', 'synthetic disabled owner');
$healthy = $send('healthy-owner', 'synthetic healthy owner', 1);
FinalDb::name('mobile_recording_upload')->where('upload_id', $blocked['id'])->update(['updated_at' => 1]);
FinalDb::name('mobile_recording_upload')->where('upload_id', $healthy['id'])->update(['updated_at' => 2]);
FinalDb::name('admin')->where('id', 11)->update(['disable' => 1]);
try {
$first = $worker();
$work = FinalDb::name('mobile_recording_work')->where('upload_id', $blocked['id'])->find();
$expect($first['exit'] === 1 && $first['counts']['uploads_denied'] === 1 && $work['attempts'] == 1
&& $work['last_result'] === 'denied' && $work['next_retry_at'] >= time() + 29,
'COS-FINAL-003 denied oldest upload persists bounded retry classification and time before COS intent');
$second = $worker();
$expect($second['exit'] === 0 && $second['counts']['uploads_completed'] === 1
&& FinalDb::name('mobile_recording_upload')->where('upload_id', $healthy['id'])->value('state') === 'complete',
'COS-FINAL-003 limit one worker reaches healthy upload behind denied owner');
$third = $worker();
$expect($third['counts']['uploads_selected'] === 0
&& FinalDb::name('mobile_recording_object')->where('upload_id', $blocked['id'])->count() === 0
&& FinalDb::name('mobile_recording_asset')->where('upload_id', $blocked['id'])->count() === 0,
'COS-FINAL-003 denied owner stays unpublished and is not immediately retried');
} finally { FinalDb::name('admin')->where('id', 11)->update(['disable' => 0]); }
FinalDb::name('mobile_recording_work')->where('upload_id', $blocked['id'])->update(['next_retry_at' => 0]);
$run = $worker();
$work = FinalDb::name('mobile_recording_work')->where('upload_id', $blocked['id'])->find();
$expect($run['exit'] === 0 && $run['counts']['uploads_completed'] === 1 && $work['attempts'] == 0
&& $work['next_retry_at'] == 0 && $work['last_result'] === 'completed',
'COS-FINAL-003 due retry rechecks restored ACL and clears failure backoff after success');
$forget($blocked); $forget($healthy);
$expect(FinalDb::name('mobile_recording_work')->count() === 0, 'COS-FINAL-003 binding revocation removes obsolete maintenance rows');
FinalObjects::cleanup(100);
})();
+66
View File
@@ -0,0 +1,66 @@
<?php
/** Exercise the actual adapter and installed SDK with a transport that cannot reach the network. */
class ProbeMobileRecordingCos extends \app\common\service\mobilerecording\MobileRecordingCos
{
public array $responses = [];
public array $requests = [];
protected function settings(): array
{
return ['bucket' => 'synthetic-1250000000', 'region' => 'ap-guangzhou',
'access_key' => 'SYNTHETIC_NOT_REAL', 'secret_key' => 'SYNTHETIC_NOT_REAL_SECRET', 'domain' => 'https://unused.invalid'];
}
protected function client(array $object): \Qcloud\Cos\Client
{
$client = parent::client($object);
$client->httpClient->getConfig('handler')->setHandler(function ($request, $options) {
$this->requests[] = ['scheme' => $request->getUri()->getScheme(), 'host' => $request->getUri()->getHost(),
'query' => $request->getUri()->getQuery(), 'acl' => $request->getHeaderLine('x-cos-acl'),
'range' => $request->getHeaderLine('Range'), 'md5' => $request->getHeaderLine('Content-MD5'),
'content_type' => $request->getHeaderLine('Content-Type'), 'options' => $options,
'authorized' => $request->hasHeader('Authorization')];
if (!$this->responses) { throw new RuntimeException('No synthetic response; network forbidden'); }
return \GuzzleHttp\Promise\Create::promiseFor(array_shift($this->responses));
});
return $client;
}
}
$probe = new ProbeMobileRecordingCos();
$po = ['bucket' => 'synthetic-1250000000', 'region' => 'ap-guangzhou',
'object_key' => 'private/mobile-recording/v1/' . str_repeat('a', 32) . '.enc', 'context_hash' => str_repeat('b', 64),
'multipart_id' => 'synthetic-multipart', 'version_id' => 'synthetic-version', 'cipher_size' => 8];
$probe->responses[] = new \GuzzleHttp\Psr7\Response(200, [], '<InitiateMultipartUploadResult><UploadId>synthetic-multipart</UploadId></InitiateMultipartUploadResult>');
$expect($probe->initiate($po) === 'synthetic-multipart', 'actual SDK parses persisted multipart ID');
$r = $probe->requests[0];
$expect($r['scheme'] === 'https' && $r['acl'] === 'private', 'actual adapter serializes HTTPS schema and explicit private ACL');
$expect($r['content_type'] === 'application/octet-stream' && !str_contains($r['host'], 'unused.invalid'), 'ciphertext never uses configured public CDN domain');
$expect($r['options']['connect_timeout'] === 3 && $r['options']['timeout'] === 10 && $r['options']['allow_redirects'] === false,
'actual SDK receives bounded per-command connection request timeouts and no redirects');
$probe->responses[] = new \GuzzleHttp\Psr7\Response(200, ['ETag' => '"' . md5('synthetic-cipher') . '"']);
$expect($probe->part($po, 1, 'synthetic-cipher') === md5('synthetic-cipher'), 'part acknowledgement validates expected MD5');
$expect($probe->requests[1]['md5'] === base64_encode(md5('synthetic-cipher', true)), 'bounded ciphertext part sends Content-MD5');
$probe->responses[] = new \GuzzleHttp\Psr7\Response(200, ['Content-Length' => '8', 'x-cos-meta-mr-context' => str_repeat('b', 64), 'x-cos-version-id' => 'synthetic-version']);
$head = $probe->head($po, true);
$expect($head === ['size' => 8, 'context' => str_repeat('b', 64), 'version_id' => 'synthetic-version'], 'actual SDK HEAD confirms context size and version');
$probe->responses[] = new \GuzzleHttp\Psr7\Response(206, ['Content-Length' => '4', 'Content-Range' => 'bytes 2-5/8'],
new \GuzzleHttp\Psr7\NoSeekStream(\GuzzleHttp\Psr7\Utils::streamFor('2345')));
$expect($probe->range($po, 2, 5) === '2345', 'actual SDK nonseekable body reads from range response position zero');
$r = $probe->requests[3];
$expect($r['range'] === 'bytes=2-5' && $r['options']['stream'] === true && str_contains($r['query'], 'versionId=synthetic-version'),
'actual adapter pins version and enables bounded Range transport streaming');
$expect($r['authorized'] && !str_contains($r['query'], 'q-sign-'), 'SDK authentication uses headers rather than signed public URLs');
$probe->responses[] = new \GuzzleHttp\Psr7\Response(204);
$probe->delete($po);
$expect(str_contains($probe->requests[4]['query'], 'versionId=synthetic-version'), 'actual SDK deletion targets recorded version rather than delete marker');
$probe->responses[] = new \GuzzleHttp\Psr7\Response(404, [], '<Error><Code>NoSuchKey</Code><Message>synthetic-provider-path</Message></Error>');
$expect($probe->head($po) === null, 'actual SDK missing object is a recoverable absent HEAD result');
$probe->responses[] = new \GuzzleHttp\Psr7\Response(403, [], '<Error><Code>AccessDenied</Code><Message>synthetic-provider-path</Message></Error>');
$permanent = false;
try { $probe->initiate($po); }
catch (\DomainException $e) { $permanent = $e->getPrevious() === null && !str_contains($e->getMessage(), 'synthetic-provider-path'); }
$expect($permanent, 'actual SDK permanent cloud denial is non-retryable and strips provider details');
$probe->responses[] = new \GuzzleHttp\Psr7\Response(503, [], '<Error><Code>ServiceUnavailable</Code><Message>synthetic-provider-path</Message></Error>');
$temporary = false;
try { $probe->initiate($po); }
catch (\RuntimeException $e) { $temporary = $e->getPrevious() === null && !str_contains($e->getMessage(), 'synthetic-provider-path'); }
$expect($temporary, 'actual SDK transient cloud failure retains retryable sanitized exception type');
+10
View File
@@ -8,3 +8,13 @@
\think\facade\Db::execute('CREATE TABLE zyt_mobile_recording_asset (
binding_id INTEGER NOT NULL, kind TEXT NOT NULL, upload_id TEXT NOT NULL UNIQUE,
updated_at INTEGER NOT NULL, PRIMARY KEY(binding_id,kind))');
\think\facade\Db::execute('CREATE TABLE zyt_mobile_recording_object (
upload_id TEXT PRIMARY KEY, backend TEXT NOT NULL, bucket TEXT NOT NULL, region TEXT NOT NULL, object_key TEXT NOT NULL,
version_id TEXT NOT NULL, encryption_key TEXT NOT NULL, nonce_prefix TEXT NOT NULL, cipher_format TEXT NOT NULL,
context_hash TEXT NOT NULL, kind TEXT NOT NULL, plain_size INTEGER NOT NULL, plain_sha256 TEXT NOT NULL, cipher_size INTEGER NOT NULL,
multipart_id TEXT NOT NULL, part_etags TEXT NOT NULL, state TEXT NOT NULL, attempts INTEGER NOT NULL,
next_retry_at INTEGER NOT NULL, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL,
UNIQUE(bucket,region,object_key))');
\think\facade\Db::execute('CREATE TABLE zyt_mobile_recording_work (
upload_id TEXT PRIMARY KEY, attempts INTEGER NOT NULL DEFAULT 0, next_retry_at INTEGER NOT NULL DEFAULT 0,
last_attempt_at INTEGER NOT NULL DEFAULT 0, last_result TEXT NOT NULL DEFAULT "", staging_cleaned INTEGER NOT NULL DEFAULT 0)');