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
@@ -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; });
}
}