Просмотр исходного кода

♻️ (export): 三藏下载的文件改存 S3 临时区,不再进 Redis

文件写到默认磁盘的 mint.attachments.bucket_name.temporary/tipitaka-exports/{channel}/{format}/{work-sn|category-id|channel}
(与 ExportDownload / ExportZip 同一做法)。路径按范围固定、不跟内容指纹走:Redis 里的导出状态过期或译文改了,
重新生成时覆盖同一个对象,临时区不积累旧文件;旧 id 的下载链接拿到的是覆盖后的最新文件。

- 下载端点 download_url 不变(mobile、下载页不用改):默认磁盘是 S3 时 302 跳 S3 临时链接(1 小时,
  ResponseContentDisposition 带文件名;ContentType、离线包的 ContentEncoding: gzip 写在对象上),
  Range / 304 由 S3 处理;本地磁盘自己流式读,ETag 改按文件大小 + 修改时间
- 导出状态仍在 Redis 7 天;文件大小按实际文件取
- 测试:S3 跳转、文件被清后 404、状态过期 / 译文改后覆盖同一文件;重生成 spec 与 schema.d.ts
- tasks.md、CLAUDE.md 对照表、config 注释同步

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda 21 часов назад
Родитель
Сommit
16c00e06e3

Разница между файлами не показана из-за своего большого размера
+ 0 - 0
CLAUDE.md


+ 1 - 1
api-v13/app/Console/Commands/MqExportTipitaka.php

@@ -10,7 +10,7 @@ use Illuminate\Console\Attributes\Signature;
 use Illuminate\Console\Command;
 use Illuminate\Console\Command;
 
 
 /**
 /**
- * 三藏下载(`/v3/tipitaka-exports`)的 worker:生成文件存进 Redis。单部作品的队列 `export_tipitaka`
+ * 三藏下载(`/v3/tipitaka-exports`)的 worker:生成文件存进临时区(生产是 S3)。单部作品的队列 `export_tipitaka`
  * 与打包的队列 `export_tipitaka_bulk`(`--bulk`)各跑一个,大打包不会堵住单部作品的下载。
  * 与打包的队列 `export_tipitaka_bulk`(`--bulk`)各跑一个,大打包不会堵住单部作品的下载。
  *
  *
  * 一次只处理一条(prefetch 1),生成完才 ack。最大的 channel 整个打包约 4 分钟(实测 cs6 html 217 秒,2026-11-22),
  * 一次只处理一条(prefetch 1),生成完才 ack。最大的 channel 整个打包约 4 分钟(实测 cs6 html 217 秒,2026-11-22),

+ 3 - 1
api-v13/app/Http/Controllers/V3/TipitakaExportFileController.php

@@ -17,7 +17,8 @@ class TipitakaExportFileController extends Controller
     /**
     /**
      * 下载文件
      * 下载文件
      *
      *
-     * 支持 `Range`(206,断点续传)与 `If-None-Match`(304,ETag 就是导出 id)。
+     * 文件存在 S3 时 302 跳到 S3 的临时链接(1 小时有效,客户端跟随跳转即可);本地开发直接返回文件。
+     * 两种情况都支持 `Range`(206,断点续传)与 `If-None-Match`(304)。
      * 离线包(offline)是 NDJSON,带 `Content-Encoding: gzip`,HTTP 客户端会自动解压。
      * 离线包(offline)是 NDJSON,带 `Content-Encoding: gzip`,HTTP 客户端会自动解压。
      * 签名无效或过期 403,文件已过期 404。
      * 签名无效或过期 403,文件已过期 404。
      *
      *
@@ -30,6 +31,7 @@ class TipitakaExportFileController extends Controller
      *
      *
      * @responseFile application/zip application/epub+zip application/vnd.openxmlformats-officedocument.wordprocessingml.document application/x-ndjson
      * @responseFile application/zip application/epub+zip application/vnd.openxmlformats-officedocument.wordprocessingml.document application/x-ndjson
      *
      *
+     * @responseStatus 302 文件在 S3:跳到临时下载链接
      * @responseStatus 206 Range 请求的部分内容
      * @responseStatus 206 Range 请求的部分内容
      * @responseStatus 304 If-None-Match 命中,本地文件就是最新的
      * @responseStatus 304 If-None-Match 命中,本地文件就是最新的
      * @responseStatus 403 签名无效或已过期
      * @responseStatus 403 签名无效或已过期

+ 40 - 13
api-v13/app/Services/V3/TipitakaExportDownload.php

@@ -2,19 +2,27 @@
 
 
 namespace App\Services\V3;
 namespace App\Services\V3;
 
 
-use App\Facades\RedisCache;
+use Illuminate\Support\Facades\Storage;
 use Symfony\Component\HttpFoundation\HeaderUtils;
 use Symfony\Component\HttpFoundation\HeaderUtils;
 use Symfony\Component\HttpFoundation\Response;
 use Symfony\Component\HttpFoundation\Response;
 use Symfony\Component\HttpFoundation\StreamedResponse;
 use Symfony\Component\HttpFoundation\StreamedResponse;
 
 
 /**
 /**
- * 把 Redis 里的导出文件流给客户端:按 1MB 分块 GETRANGE 读,不把整个文件读进 PHP 内存;
- * 支持单段 `Range`(mobile 断点续传)与 `If-None-Match`(id 即内容指纹,可当强 ETag)。
+ * 把临时区里的导出文件交给客户端。
+ *
+ * - 默认磁盘是 S3(生产):302 跳到 S3 的临时签名链接,流量不经 PHP;文件名由链接参数给,
+ *   类型与离线包的 `Content-Encoding: gzip` 已写在对象上,`Range` / `If-None-Match` 由 S3 处理。
+ * - 其他磁盘(本地开发):自己流式读,按 1MB 分块,不把整个文件读进内存;
+ *   支持单段 `Range`(mobile 断点续传)与 `If-None-Match`。ETag 按文件的大小与修改时间算,不用导出 id:
+ *   同一范围重新生成会覆盖同一个文件,旧 id 的链接拿到的是新文件。
  */
  */
 class TipitakaExportDownload
 class TipitakaExportDownload
 {
 {
     private const CHUNK = 1024 * 1024;
     private const CHUNK = 1024 * 1024;
 
 
+    /** 跳去 S3 的签名链接有效多久(秒)。每次下载现签;给慢速网络下的大文件留足时间。 */
+    private const REDIRECT_TTL = 3600;
+
     public function __construct(private readonly TipitakaExportService $exports) {}
     public function __construct(private readonly TipitakaExportService $exports) {}
 
 
     public function respond(string $id, ?string $range, ?string $ifNoneMatch): Response
     public function respond(string $id, ?string $range, ?string $ifNoneMatch): Response
@@ -23,14 +31,21 @@ class TipitakaExportDownload
         if ($file === null) {
         if ($file === null) {
             abort(404, __('messages.export_not_found'));
             abort(404, __('messages.export_not_found'));
         }
         }
-        $etag = '"'.$id.'"';
+        $disposition = HeaderUtils::makeDisposition(
+            HeaderUtils::DISPOSITION_ATTACHMENT,
+            $file['filename'],
+            $this->asciiFallback($file['filename']),
+        );
+        if (config('filesystems.disks.'.config('filesystems.default').'.driver') === 's3') {
+            return redirect()->away(Storage::temporaryUrl($file['path'], now()->addSeconds(self::REDIRECT_TTL), [
+                'ResponseContentDisposition' => $disposition,
+            ]));
+        }
+
+        $etag = '"'.$file['size'].'-'.Storage::lastModified($file['path']).'"';
         $headers = [
         $headers = [
             'Content-Type' => $file['content_type'],
             'Content-Type' => $file['content_type'],
-            'Content-Disposition' => HeaderUtils::makeDisposition(
-                HeaderUtils::DISPOSITION_ATTACHMENT,
-                $file['filename'],
-                $this->asciiFallback($file['filename']),
-            ),
+            'Content-Disposition' => $disposition,
             'Accept-Ranges' => 'bytes',
             'Accept-Ranges' => 'bytes',
             'ETag' => $etag,
             'ETag' => $etag,
             'Cache-Control' => 'private, max-age=0, must-revalidate',
             'Cache-Control' => 'private, max-age=0, must-revalidate',
@@ -62,13 +77,25 @@ class TipitakaExportDownload
             $headers['Content-Range'] = "bytes {$start}-{$end}/{$size}";
             $headers['Content-Range'] = "bytes {$start}-{$end}/{$size}";
         }
         }
         $headers['Content-Length'] = (string) ($end - $start + 1);
         $headers['Content-Length'] = (string) ($end - $start + 1);
-        $key = $this->exports->fileKey($id);
+        $path = $file['path'];
 
 
-        return new StreamedResponse(function () use ($key, $start, $end) {
-            for ($offset = $start; $offset <= $end; $offset += self::CHUNK) {
-                echo RedisCache::getBinaryRange($key, $offset, min($end, $offset + self::CHUNK - 1));
+        return new StreamedResponse(function () use ($path, $start, $end) {
+            $stream = Storage::readStream($path);
+            if ($stream === null) {
+                return;
+            }
+            fseek($stream, $start);
+            $remaining = $end - $start + 1;
+            while ($remaining > 0 && ! feof($stream)) {
+                $chunk = fread($stream, min(self::CHUNK, $remaining));
+                if ($chunk === false || $chunk === '') {
+                    break;
+                }
+                echo $chunk;
                 flush();
                 flush();
+                $remaining -= strlen($chunk);
             }
             }
+            fclose($stream);
         }, $status, $headers);
         }, $status, $headers);
     }
     }
 
 

+ 43 - 16
api-v13/app/Services/V3/TipitakaExportService.php

@@ -10,8 +10,10 @@ use App\Services\TipitakaCatalogService;
 use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Support\Carbon;
 use Illuminate\Support\Carbon;
 use Illuminate\Support\Facades\Log;
 use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Facades\Storage;
 use Illuminate\Support\Facades\URL;
 use Illuminate\Support\Facades\URL;
 use Illuminate\Validation\ValidationException;
 use Illuminate\Validation\ValidationException;
+use RuntimeException;
 use Throwable;
 use Throwable;
 
 
 /**
 /**
@@ -19,7 +21,11 @@ use Throwable;
  *
  *
  * 流程:请求方 request() → 已有同一份文件就直接给;没有就写一条 queued 状态、投递到 RabbitMQ
  * 流程:请求方 request() → 已有同一份文件就直接给;没有就写一条 queued 状态、投递到 RabbitMQ
  * (TipitakaExportQueue:单部作品与打包分两个队列)→ worker `mq:export.tipitaka` 调 run() 生成(TipitakaExportBuilder)→
  * (TipitakaExportQueue:单部作品与打包分两个队列)→ worker `mq:export.tipitaka` 调 run() 生成(TipitakaExportBuilder)→
- * 文件以二进制存进 Redis 集群(RedisCache::putBinary),保留 `mint.tipitaka_export.ttl`。
+ * 文件存进默认磁盘的临时区(生产是 S3),状态存 Redis,保留 `mint.tipitaka_export.ttl`。
+ *
+ * **文件路径按范围固定,不跟 id 走**({@see self::filePath()}):同一 channel、同一范围、同一格式永远是同一个对象。
+ * Redis 状态过期、或译文改了换了 id,重新生成时覆盖原来那份,临时区不会积累没人读的旧文件。
+ * 旧 id 的下载链接(7 天内)拿到的是覆盖后的最新文件。
  *
  *
  * **id 就是内容指纹**:channel + 范围 + 格式 + 模板版本 + 范围内句子的最后修改时间与条数。
  * **id 就是内容指纹**:channel + 范围 + 格式 + 模板版本 + 范围内句子的最后修改时间与条数。
  * 所以谁先生成谁就给后来的人用;译文一改,指纹就变,自然重新生成,不需要失效逻辑。
  * 所以谁先生成谁就给后来的人用;译文一改,指纹就变,自然重新生成,不需要失效逻辑。
@@ -121,8 +127,8 @@ class TipitakaExportService
             abort(404, __('messages.export_not_found'));
             abort(404, __('messages.export_not_found'));
         }
         }
         $this->abilities->assertReadable($status['channel'], $userUid);
         $this->abilities->assertReadable($status['channel'], $userUid);
-        if ($status['status'] === 'ready' && ! $this->fileExists($id)) {
-            // 文件被 Redis 淘汰了,状态还在:当作没生成过,让客户端重新发起
+        if ($status['status'] === 'ready' && ! $this->fileExists($status)) {
+            // 文件被清掉了,状态还在:当作没生成过,让客户端重新发起
             abort(404, __('messages.export_not_found'));
             abort(404, __('messages.export_not_found'));
         }
         }
 
 
@@ -197,12 +203,12 @@ class TipitakaExportService
     }
     }
 
 
     /**
     /**
-     * worker 入口:生成一份导出并存进 Redis。已经生成好、或状态已过期被清掉的直接跳过。
+     * worker 入口:生成一份导出,文件存进临时区、状态存 Redis。已经生成好、或状态已过期被清掉的直接跳过。
      */
      */
     public function run(string $id): void
     public function run(string $id): void
     {
     {
         $status = $this->find($id);
         $status = $this->find($id);
-        if ($status === null || ($status['status'] === 'ready' && $this->fileExists($id))) {
+        if ($status === null || ($status['status'] === 'ready' && $this->fileExists($status))) {
             return;
             return;
         }
         }
         $status = $this->save(['status' => 'running', 'progress' => 0.0, 'message' => null] + $status);
         $status = $this->save(['status' => 'running', 'progress' => 0.0, 'message' => null] + $status);
@@ -218,7 +224,14 @@ class TipitakaExportService
                 throw new BusinessException(__('messages.export_too_large'), 422, 'export-too-large');
                 throw new BusinessException(__('messages.export_too_large'), 422, 'export-too-large');
             }
             }
             $ttl = (int) config('mint.tipitaka_export.ttl');
             $ttl = (int) config('mint.tipitaka_export.ttl');
-            RedisCache::putBinary($this->fileKey($id), $file, $ttl);
+            // S3 上把类型与传输编码写进对象:下载时直接跳到 S3,离线包靠 Content-Encoding: gzip 让客户端自动解压
+            $stored = Storage::put($this->filePath($status), $file, array_filter([
+                'ContentType' => $status['content_type'],
+                'ContentEncoding' => $status['format'] === 'offline' ? 'gzip' : null,
+            ]));
+            if (! $stored) {
+                throw new RuntimeException('tipitaka-export: cannot store '.$this->filePath($status));
+            }
             $this->save([
             $this->save([
                 'status' => 'ready',
                 'status' => 'ready',
                 'progress' => 1.0,
                 'progress' => 1.0,
@@ -235,31 +248,42 @@ class TipitakaExportService
     }
     }
 
 
     /**
     /**
-     * 文件在 Redis 里的 key。下载接口按它分块读。
+     * 文件在默认磁盘上的路径(临时区):`{temporary}/tipitaka-exports/{channel}/{format}/{work-sn | category-id | channel}`。
+     * 只由 channel、范围、格式决定,与内容指纹(id)、模板版本无关,重新生成时覆盖同一个对象。
+     *
+     * @param  array<string, mixed>  $status  导出状态(spec() 的字段)
      */
      */
-    public function fileKey(string $id): string
+    public function filePath(array $status): string
     {
     {
-        return "/tipitaka-export/file/{$id}";
+        $scope = match ($status['scope']['kind']) {
+            'work' => 'work-'.$status['scope']['work'],
+            'category' => 'category-'.$status['scope']['category'],
+            default => 'channel',
+        };
+
+        return config('mint.attachments.bucket_name.temporary')."/tipitaka-exports/{$status['channel']}/{$status['format']}/{$scope}";
     }
     }
 
 
     /**
     /**
      * 已生成的文件的元数据;没有(或不可下载)返回 null。
      * 已生成的文件的元数据;没有(或不可下载)返回 null。
      *
      *
-     * @return array{filename: string, content_type: string, content_encoding: string|null, size: int}|null
+     * @return array{path: string, filename: string, content_type: string, content_encoding: string|null, size: int}|null
      */
      */
     public function file(string $id): ?array
     public function file(string $id): ?array
     {
     {
         $status = $this->find($id);
         $status = $this->find($id);
-        $size = RedisCache::binaryLength($this->fileKey($id));
-        if ($status === null || $status['status'] !== 'ready' || $size === null) {
+        if ($status === null || $status['status'] !== 'ready' || ! $this->fileExists($status)) {
             return null;
             return null;
         }
         }
+        $path = $this->filePath($status);
 
 
         return [
         return [
+            'path' => $path,
             'filename' => $status['filename'],
             'filename' => $status['filename'],
             'content_type' => $status['content_type'],
             'content_type' => $status['content_type'],
             'content_encoding' => $status['format'] === 'offline' ? 'gzip' : null,
             'content_encoding' => $status['format'] === 'offline' ? 'gzip' : null,
-            'size' => $size,
+            // 按文件实际大小:这个范围后来又生成过的话,旧 id 的状态里记的是旧文件的大小
+            'size' => (int) Storage::size($path),
         ];
         ];
     }
     }
 
 
@@ -357,7 +381,7 @@ class TipitakaExportService
     private function reusable(array $status): bool
     private function reusable(array $status): bool
     {
     {
         return match ($status['status']) {
         return match ($status['status']) {
-            'ready' => $this->fileExists($status['id']),
+            'ready' => $this->fileExists($status),
             'queued', 'running' => now()->diffInSeconds($status['updated_at'], true) < (int) config('mint.tipitaka_export.stale_after'),
             'queued', 'running' => now()->diffInSeconds($status['updated_at'], true) < (int) config('mint.tipitaka_export.stale_after'),
             default => false,
             default => false,
         };
         };
@@ -417,9 +441,12 @@ class TipitakaExportService
         return $status;
         return $status;
     }
     }
 
 
-    private function fileExists(string $id): bool
+    /**
+     * @param  array<string, mixed>  $status
+     */
+    private function fileExists(array $status): bool
     {
     {
-        return RedisCache::binaryLength($this->fileKey($id)) !== null;
+        return Storage::exists($this->filePath($status));
     }
     }
 
 
     private function statusKey(string $id): string
     private function statusKey(string $id): string

+ 3 - 2
api-v13/config/mint.php

@@ -216,9 +216,10 @@ return [
     'tipitaka_export' => [
     'tipitaka_export' => [
         // 生成前按范围内句子的 strlen 之和估算,超过就 422,不排队
         // 生成前按范围内句子的 strlen 之和估算,超过就 422,不排队
         'max_source_chars' => (int) env('TIPITAKA_EXPORT_MAX_SOURCE_CHARS', 160 * 1024 * 1024),
         'max_source_chars' => (int) env('TIPITAKA_EXPORT_MAX_SOURCE_CHARS', 160 * 1024 * 1024),
-        // 生成后的文件超过就判失败、不写 Redis(单个值太大会撑爆从库同步缓冲,见 RedisCache 类注释)
+        // 生成后的文件超过就判失败、不上传(整个文件在 worker 内存里拼好再传,cs6 整个 channel 的 html zip 是 44MB)
         'max_file_bytes' => (int) env('TIPITAKA_EXPORT_MAX_FILE_BYTES', 64 * 1024 * 1024),
         'max_file_bytes' => (int) env('TIPITAKA_EXPORT_MAX_FILE_BYTES', 64 * 1024 * 1024),
-        // 文件与状态在 Redis 里保留多久
+        // 导出状态在 Redis 里保留多久。文件在临时区(mint.attachments.bucket_name.temporary/tipitaka-exports/),
+        // 路径按范围固定:状态过期或译文改了,重新生成时覆盖同一个文件
         'ttl' => 7 * 24 * 3600,
         'ttl' => 7 * 24 * 3600,
         // 排队 / 生成中的状态多久没更新就当作 worker 丢了,下次请求重新排队
         // 排队 / 生成中的状态多久没更新就当作 worker 丢了,下次请求重新排队
         'stale_after' => 1800,
         'stale_after' => 1800,

+ 4 - 1
api-v13/documents/tasks.md

@@ -46,7 +46,10 @@ php artisan mq:export.tipitaka --bulk
 三藏下载的两个 worker 要分开跑,打包才不会堵住单部作品。它们处理完一条才 ack。实测 cs6 整个 channel(282 部作品)的 html 打包 217 秒、zip 43.7 MiB、
 三藏下载的两个 worker 要分开跑,打包才不会堵住单部作品。它们处理完一条才 ack。实测 cs6 整个 channel(282 部作品)的 html 打包 217 秒、zip 43.7 MiB、
 内存峰值 172 MB(2026-11-22,段落缓存全冷;阅读段落冷启动优化之前是 2286 秒)。
 内存峰值 172 MB(2026-11-22,段落缓存全冷;阅读段落冷启动优化之前是 2286 秒)。
 数据库或渲染变慢时仍可能超过 RabbitMQ 的 `consumer_timeout`(默认 30 分钟),建议调大,否则跑到一半被服务端断开(开发机 `rabbitmq.conf` 是 333600000,约 92 小时)。
 数据库或渲染变慢时仍可能超过 RabbitMQ 的 `consumer_timeout`(默认 30 分钟),建议调大,否则跑到一半被服务端断开(开发机 `rabbitmq.conf` 是 333600000,约 92 小时)。
-生成的文件存在 Redis 集群里(7 天,`mint.tipitaka_export`),中间文件在 `storage/app/tmp/tipitaka-export/`,跑完即删。
+生成的文件存在默认磁盘的临时区 `{ATTACHMENTS_TEMPORARY_BUCKET_NAME}/tipitaka-exports/{channel}/{format}/{work-sn|category-id|channel}`
+(生产是 S3,下载时 302 跳到 S3 临时链接)。路径只按范围定,Redis 里的导出状态(7 天,`mint.tipitaka_export`)过期或译文改了,
+重新生成时覆盖同一个文件,不会积累旧文件。
+中间文件在 `storage/app/tmp/tipitaka-export/`,跑完即删。
 epub / docx 依赖服务器上的 `pandoc`(3.x,路径可用 `PANDOC_PATH` 指定)。
 epub / docx 依赖服务器上的 `pandoc`(3.x,路径可用 `PANDOC_PATH` 指定)。
 
 
 `ai_translate_v2`(`rabbitmq:consume`)待第二阶段重构 worker 后补上。`content` 队列已移除(无消费者,发送端已注释,见 `SentenceController@update` 的 FIXME)。
 `ai_translate_v2`(`rabbitmq:consume`)待第二阶段重构 worker 后补上。`content` 队列已移除(无消费者,发送端已注释,见 `SentenceController@update` 的 FIXME)。

+ 56 - 3
api-v13/tests/Feature/TipitakaExportV3Test.php

@@ -1,24 +1,29 @@
 <?php
 <?php
 
 
+use App\Facades\RedisCache;
 use App\Models\BookTitle;
 use App\Models\BookTitle;
 use App\Models\Channel;
 use App\Models\Channel;
 use App\Models\PaliText;
 use App\Models\PaliText;
 use App\Models\ProgressChapter;
 use App\Models\ProgressChapter;
+use App\Models\Sentence;
 use App\Models\Tag;
 use App\Models\Tag;
 use App\Models\TagMap;
 use App\Models\TagMap;
 use App\Services\V3\TipitakaExportQueue;
 use App\Services\V3\TipitakaExportQueue;
 use App\Services\V3\TipitakaExportService;
 use App\Services\V3\TipitakaExportService;
 use Illuminate\Foundation\Testing\RefreshDatabase;
 use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\Storage;
 use Illuminate\Support\Str;
 use Illuminate\Support\Str;
 
 
 /*
 /*
 | 三藏下载 /v3/tipitaka-exports。这里断言的是形状而非契约(spectator 未安装)。
 | 三藏下载 /v3/tipitaka-exports。这里断言的是形状而非契约(spectator 未安装)。
 | 生成在测试里同步调 TipitakaExportService::run(),队列换成 mock,不连 RabbitMQ;
 | 生成在测试里同步调 TipitakaExportService::run(),队列换成 mock,不连 RabbitMQ;
-| 文件进的是 RedisCacheFake(TestCase 已换好)。
+| 文件进的是 Storage::fake() 的默认磁盘(本地磁盘的流式下载);S3 的跳转单独一条测。
 */
 */
 
 
 uses(RefreshDatabase::class);
 uses(RefreshDatabase::class);
 
 
+beforeEach(fn () => Storage::fake());
+
 function exportPaliText(int $book, int $paragraph, int $level, int $chapterLen, string $toc = ''): PaliText
 function exportPaliText(int $book, int $paragraph, int $level, int $chapterLen, string $toc = ''): PaliText
 {
 {
     $row = new PaliText;
     $row = new PaliText;
@@ -155,7 +160,6 @@ it('generates an html work export and serves it through the signed link', functi
     $file = $this->get($data['download_url'])
     $file = $this->get($data['download_url'])
         ->assertOk()
         ->assertOk()
         ->assertHeader('Content-Type', 'application/zip')
         ->assertHeader('Content-Type', 'application/zip')
-        ->assertHeader('ETag', '"'.$data['id'].'"')
         ->assertHeader('Accept-Ranges', 'bytes');
         ->assertHeader('Accept-Ranges', 'bytes');
     expect($file->headers->get('Content-Disposition'))->toContain("filename*=utf-8''");
     expect($file->headers->get('Content-Disposition'))->toContain("filename*=utf-8''");
     $bytes = $file->streamedContent();
     $bytes = $file->streamedContent();
@@ -174,7 +178,56 @@ it('generates an html work export and serves it through the signed link', functi
         ->assertHeader('Content-Range', "bytes 10-19/{$data['size']}");
         ->assertHeader('Content-Range', "bytes 10-19/{$data['size']}");
     expect($part->streamedContent())->toBe(substr($bytes, 10, 10));
     expect($part->streamedContent())->toBe(substr($bytes, 10, 10));
     $this->get($data['download_url'], ['Range' => 'bytes=999999999-'])->assertStatus(416);
     $this->get($data['download_url'], ['Range' => 'bytes=999999999-'])->assertStatus(416);
-    $this->get($data['download_url'], ['If-None-Match' => '"'.$data['id'].'"'])->assertStatus(304);
+    $this->get($data['download_url'], ['If-None-Match' => $file->headers->get('ETag')])->assertStatus(304);
+});
+
+it('stores the file in the temporary area and redirects to a signed S3 link when the disk is S3', function () {
+    config(['filesystems.default' => 's3']);
+    Storage::fake('s3')->buildTemporaryUrlsUsing(
+        fn (string $path, DateTimeInterface $expiration, array $options) => "https://s3.test/{$path}?".http_build_query($options)
+    );
+    fakeExportQueue();
+    ['channel' => $channel, 'sn' => $sn] = exportFixture();
+
+    $data = exportReady(['channel' => $channel, 'work' => $sn, 'format' => 'html']);
+    $path = config('mint.attachments.bucket_name.temporary')."/tipitaka-exports/{$channel}/html/work-{$sn}";
+    Storage::disk('s3')->assertExists($path);
+    expect(Storage::disk('s3')->size($path))->toBe($data['size']);
+
+    $location = $this->get($data['download_url'])->assertRedirect()->headers->get('Location');
+    expect($location)->toStartWith("https://s3.test/{$path}?")
+        ->and(urldecode($location))->toContain('ResponseContentDisposition=attachment;')->toContain("filename*=utf-8''");
+
+    // 文件被生命周期规则清掉了:状态还在也当作没有
+    Storage::disk('s3')->delete($path);
+    $this->get($data['download_url'])->assertNotFound();
+    $this->getJson("/api/v3/tipitaka-exports/{$data['id']}")->assertNotFound();
+});
+
+it('regenerates into the same file once the status expires or the translation changes', function () {
+    fakeExportQueue();
+    ['channel' => $channel, 'sn' => $sn] = exportFixture();
+    $path = config('mint.attachments.bucket_name.temporary')."/tipitaka-exports/{$channel}/html/work-{$sn}";
+
+    $first = exportReady(['channel' => $channel, 'work' => $sn, 'format' => 'html']);
+    expect(Storage::files(dirname($path)))->toBe([$path]);
+
+    // Redis 里的状态过期:重新生成,同一个 id、同一个文件
+    RedisCache::forget("/tipitaka-export/status/{$first['id']}");
+    $again = exportReady(['channel' => $channel, 'work' => $sn, 'format' => 'html']);
+    expect($again['id'])->toBe($first['id'])
+        ->and(Storage::files(dirname($path)))->toBe([$path]);
+
+    // 译文改了:换了 id,仍覆盖同一个文件;旧 id 的链接拿到的是新文件
+    $sentence = Sentence::where('channel_uid', $channel)->orderBy('paragraph')->first();
+    // 范围统计(指纹的来源)缓存 5 分钟;指纹看 max(updated_at),改动要晚于建好的数据
+    $this->travel(6)->minutes();
+    $sentence->forceFill(['content' => '改过的译文', 'strlen' => 5])->save();
+    $changed = exportReady(['channel' => $channel, 'work' => $sn, 'format' => 'html']);
+    expect($changed['id'])->not->toBe($first['id'])
+        ->and(Storage::files(dirname($path)))->toBe([$path]);
+    $files = unzipExport($this->get($first['download_url'])->assertOk()->streamedContent());
+    expect(array_values($files)[0])->toContain('改过的译文');
 });
 });
 
 
 it('rejects the file link without a valid signature', function () {
 it('rejects the file link without a valid signature', function () {

+ 11 - 1
dashboard-v6/src/api/schema.d.ts

@@ -9623,7 +9623,8 @@ export interface paths {
         };
         };
         /**
         /**
          * 下载文件
          * 下载文件
-         * @description 支持 `Range`(206,断点续传)与 `If-None-Match`(304,ETag 就是导出 id)。
+         * @description 文件存在 S3 时 302 跳到 S3 的临时链接(1 小时有效,客户端跟随跳转即可);本地开发直接返回文件。
+         *     两种情况都支持 `Range`(206,断点续传)与 `If-None-Match`(304)。
          *     离线包(offline)是 NDJSON,带 `Content-Encoding: gzip`,HTTP 客户端会自动解压。
          *     离线包(offline)是 NDJSON,带 `Content-Encoding: gzip`,HTTP 客户端会自动解压。
          *     签名无效或过期 403,文件已过期 404。
          *     签名无效或过期 403,文件已过期 404。
          *
          *
@@ -42933,6 +42934,15 @@ export interface operations {
                     "application/x-ndjson": string;
                     "application/x-ndjson": string;
                 };
                 };
             };
             };
+            /** @description 文件在 S3:跳到临时下载链接 */
+            302: {
+                headers: {
+                    [name: string]: unknown;
+                };
+                content: {
+                    "application/problem+json": components["schemas"]["ProblemDetails"];
+                };
+            };
             /** @description If-None-Match 命中,本地文件就是最新的 */
             /** @description If-None-Match 命中,本地文件就是最新的 */
             304: {
             304: {
                 headers: {
                 headers: {

+ 8 - 1
openapi/public/assets/protocol/resources/auto/v3-tipitaka-exports-export-file.yaml

@@ -5,7 +5,8 @@ get:
     - tipitaka-exports
     - tipitaka-exports
   operationId: get_api_v3_tipitaka_exports_export_file
   operationId: get_api_v3_tipitaka_exports_export_file
   description: |-
   description: |-
-    支持 `Range`(206,断点续传)与 `If-None-Match`(304,ETag 就是导出 id)。
+    文件存在 S3 时 302 跳到 S3 的临时链接(1 小时有效,客户端跟随跳转即可);本地开发直接返回文件。
+    两种情况都支持 `Range`(206,断点续传)与 `If-None-Match`(304)。
     离线包(offline)是 NDJSON,带 `Content-Encoding: gzip`,HTTP 客户端会自动解压。
     离线包(offline)是 NDJSON,带 `Content-Encoding: gzip`,HTTP 客户端会自动解压。
     签名无效或过期 403,文件已过期 404。
     签名无效或过期 403,文件已过期 404。
 
 
@@ -75,6 +76,12 @@ get:
           schema:
           schema:
             type: string
             type: string
             format: binary
             format: binary
+    302:
+      description: '文件在 S3:跳到临时下载链接'
+      content:
+        application/problem+json:
+          schema:
+            $ref: '../../main.yaml#/components/schemas/ProblemDetails'
     304:
     304:
       description: 'If-None-Match 命中,本地文件就是最新的'
       description: 'If-None-Match 命中,本地文件就是最新的'
     403:
     403:

Некоторые файлы не были показаны из-за большого количества измененных файлов