TipitakaReadingService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Services\PaliContentService;
  4. use App\Services\ReadingIndexService;
  5. use Illuminate\Validation\ValidationException;
  6. /**
  7. * 三藏译文的阅读与下载:按 channel 取已翻译的段落,游标式分块。
  8. *
  9. * 服务 `GET /v3/tipitaka-reading/{channel}`。控制器只负责把 validated() 传进来、
  10. * 把结果包成 Resource;这里是全部业务逻辑——过滤收窄、章节展开、keyset 游标、
  11. * 字节切块、进度统计、输出裁剪。
  12. *
  13. * 渲染本身交给 {@see PaliContentService}(v2/v3 共享的纯能力),这里不重复实现。
  14. */
  15. class TipitakaReadingService
  16. {
  17. /**
  18. * 字节模式下单块的字节上限。请求超过这个数按这个数算,不报错。
  19. */
  20. public const MAX_BYTES_PER_PAGE = 50000;
  21. /**
  22. * 单块最多返回的段落数,两种单位都受它约束。
  23. *
  24. * 每段要单独渲染一次,块的成本跟段落数成正比而不是跟字节数成正比。段落模式
  25. * 直接把 page_size 压到这个数;字节模式下偈颂体的书平均每段只有 20~30 字节,
  26. * 光靠字节上限仍可能切出几百段,所以累加时两个上限谁先到就在哪断块。
  27. */
  28. public const MAX_PARAGRAPHS_PER_PAGE = 200;
  29. public function __construct(
  30. private readonly PaliContentService $paliService,
  31. private readonly PaliTextService $paliTexts,
  32. private readonly ReadingIndexService $index,
  33. ) {}
  34. /**
  35. * 取一块译文。
  36. *
  37. * 候选段、游标、进度都在「有译文的段号」索引上算({@see ReadingIndexService},命中时不查库),
  38. * 正文按书一次交给 {@see PaliContentService::readParagraphs()}。
  39. *
  40. * @param array<string, mixed> $filters 已经过 FormRequest 校验的查询参数
  41. * @return array{items: array<int, array<string, mixed>>, meta: array<string, mixed>}
  42. */
  43. public function page(string $channel, array $filters): array
  44. {
  45. $unit = $filters['unit'] ?? 'para';
  46. $pageSize = min(
  47. max(1, (int) ($filters['page_size'] ?? 10)),
  48. $unit === 'byte' ? self::MAX_BYTES_PER_PAGE : self::MAX_PARAGRAPHS_PER_PAGE
  49. );
  50. $range = $this->scopeRange($filters);
  51. $after = isset($filters['after']) ? $this->parseCursor((string) $filters['after']) : null;
  52. // 多取一段用来判断后面还有没有
  53. $want = $unit === 'byte'
  54. ? self::MAX_PARAGRAPHS_PER_PAGE
  55. : min($pageSize, self::MAX_PARAGRAPHS_PER_PAGE);
  56. $candidates = $this->candidates($channel, $range, $after, $want + 1);
  57. $hasMoreBeyondWant = count($candidates) > $want;
  58. $candidates = array_slice($candidates, 0, $want);
  59. $slice = $unit === 'byte'
  60. ? $this->sliceByBytes($candidates, $this->paragraphLengths($candidates), $pageSize)
  61. : $candidates;
  62. $hasMore = $hasMoreBeyondWant || count($slice) < count($candidates);
  63. $format = $filters['format'] ?? 'html';
  64. $include = $filters['include'] ?? 'display';
  65. // 结果可以跨书:按书分组,一本书一次批量取
  66. $byBook = [];
  67. foreach ($slice as $coord) {
  68. $byBook[$coord['book']][] = $coord['para'];
  69. }
  70. $rendered = [];
  71. foreach ($byBook as $book => $paras) {
  72. $rendered[$book] = $this->paliService->readParagraphs($book, $paras, $channel, $format);
  73. }
  74. $items = [];
  75. foreach ($slice as $coord) {
  76. $paragraph = $rendered[$coord['book']][$coord['para']];
  77. if (empty($paragraph['display'])) {
  78. continue;
  79. }
  80. // 结果可以跨书,所以每条都要带 book——只给 para 在跨书时不唯一
  81. $items[] = ['book' => $coord['book']] + $this->filterInclude($paragraph, $include);
  82. }
  83. $last = $slice === [] ? null : $slice[count($slice) - 1];
  84. return [
  85. 'items' => $items,
  86. 'meta' => [
  87. 'page_size' => $pageSize,
  88. 'page_size_unit' => $unit,
  89. // 本块覆盖的最后一段。渲染为空的段落会被剔出 data 但仍算在块内,
  90. // 所以游标按 slice 推进而不是按 data 推进,否则会卡在那一段上打转
  91. 'next_cursor' => $hasMore && $last ? "{$last['book']}-{$last['para']}" : null,
  92. ] + $this->progressMeta($channel, $range, $last),
  93. ];
  94. }
  95. /**
  96. * 按 filter 收窄的范围:不带 book 是整个 channel(null),带 book 是这本书里的段落闭区间。
  97. *
  98. * @param array<string, mixed> $filters
  99. * @return array{book: int, from: int, to: int}|null
  100. */
  101. private function scopeRange(array $filters): ?array
  102. {
  103. if (! isset($filters['book'])) {
  104. return null;
  105. }
  106. $book = (int) $filters['book'];
  107. if (isset($filters['chapter'])) {
  108. [$from, $to] = $this->chapterRange($book, (int) $filters['chapter']);
  109. return ['book' => $book, 'from' => $from, 'to' => $to];
  110. }
  111. if (isset($filters['para'])) {
  112. $from = (int) $filters['para'];
  113. $to = (int) ($filters['to'] ?? $from);
  114. if ($to < $from) {
  115. throw ValidationException::withMessages(['to' => __('site.invalid_parameter')]);
  116. }
  117. return ['book' => $book, 'from' => $from, 'to' => $to];
  118. }
  119. return ['book' => $book, 'from' => PHP_INT_MIN, 'to' => PHP_INT_MAX];
  120. }
  121. /**
  122. * 范围内有译文的段(句子 strlen > 0),按 (book, para) 升序,排在游标之后,最多 $limit 段。
  123. *
  124. * @param array{book: int, from: int, to: int}|null $range
  125. * @param array{int, int}|null $after
  126. * @return list<array{book: int, para: int}>
  127. */
  128. private function candidates(string $channel, ?array $range, ?array $after, int $limit): array
  129. {
  130. $books = $range === null ? $this->index->books($channel) : [$range['book']];
  131. $result = [];
  132. foreach ($books as $book) {
  133. if ($after !== null && $book < $after[0]) {
  134. continue;
  135. }
  136. foreach ($this->paragraphsIn($channel, $book, $range) as $para) {
  137. if ($after !== null && $book === $after[0] && $para <= $after[1]) {
  138. continue;
  139. }
  140. $result[] = ['book' => $book, 'para' => $para];
  141. if (count($result) >= $limit) {
  142. return $result;
  143. }
  144. }
  145. }
  146. return $result;
  147. }
  148. /**
  149. * 这本书里有译文、且在范围内的段号,升序。
  150. *
  151. * @param array{book: int, from: int, to: int}|null $range
  152. * @return list<int>
  153. */
  154. private function paragraphsIn(string $channel, int $book, ?array $range): array
  155. {
  156. $paras = $this->index->paragraphs($channel, $book);
  157. if ($range === null) {
  158. return $paras;
  159. }
  160. return array_values(array_filter($paras, fn (int $para) => $para >= $range['from'] && $para <= $range['to']));
  161. }
  162. /**
  163. * 章节起始段落号 → 段落闭区间,长度取 pali_texts 那一行的 chapter_len。章节不存在 404。
  164. *
  165. * 公开给按章节取别的东西的 v3 端点共用(`tipitaka-discussions`),口径一致。
  166. *
  167. * @return array{int, int}
  168. */
  169. public function chapterRange(int $book, int $chapter): array
  170. {
  171. $range = $this->paliTexts->chapterRange($book, $chapter);
  172. if ($range === null) {
  173. abort(404, __('site.not_found'));
  174. }
  175. return $range;
  176. }
  177. /**
  178. * 游标 `{book}-{para}` → [book, para]。
  179. *
  180. * @return array{int, int}
  181. */
  182. private function parseCursor(string $after): array
  183. {
  184. [$book, $para] = array_map('intval', explode('-', $after, 2)) + [0, 0];
  185. return [$book, $para];
  186. }
  187. /**
  188. * 按原文字节数累加切块,到上限或到 200 段为止,每块至少一段。
  189. *
  190. * 纯函数:长度由调用方查好传进来,这里不碰数据库。段落数上限要造上千段才看得
  191. * 出来,走 HTTP 会真的去渲染每一段,所以单元测试直接对着它测。
  192. *
  193. * @param array<int, array{book: int, para: int}> $candidates
  194. * @param array<int, array<int, int>> $lengths book => (para => 字节数)
  195. * @return array<int, array{book: int, para: int}>
  196. */
  197. public function sliceByBytes(array $candidates, array $lengths, int $limit): array
  198. {
  199. $bytes = 0;
  200. $take = 0;
  201. foreach ($candidates as $coord) {
  202. $bytes += (int) ($lengths[$coord['book']][$coord['para']] ?? 0);
  203. $take++;
  204. if ($bytes >= $limit || $take >= self::MAX_PARAGRAPHS_PER_PAGE) {
  205. break;
  206. }
  207. }
  208. return array_slice($candidates, 0, $take);
  209. }
  210. /**
  211. * 取这些段落的原文字节数({@see PaliTextService},缓存的经文静态数据)。
  212. *
  213. * @param array<int, array{book: int, para: int}> $candidates
  214. * @return array<int, array<int, int>> book => (para => 字节数)
  215. */
  216. private function paragraphLengths(array $candidates): array
  217. {
  218. $byBook = [];
  219. foreach ($candidates as $coord) {
  220. $byBook[$coord['book']][] = $coord['para'];
  221. }
  222. $lengths = [];
  223. foreach ($byBook as $book => $paras) {
  224. $lengths[$book] = array_map(
  225. fn (array $row) => $row['length'],
  226. $this->paliTexts->paragraphs($book, min($paras), max($paras))
  227. );
  228. }
  229. return $lengths;
  230. }
  231. /**
  232. * 进度用的 total / remaining,**只在带了 book 过滤时给**。
  233. *
  234. * 不带过滤时结果集是整个 channel(实测最大的 52 万段),要把每本书的段号索引都读一遍,
  235. * 不值得。那种场景用 next_cursor 判断结束。
  236. *
  237. * @param array{book: int, from: int, to: int}|null $range
  238. * @param array{book: int, para: int}|null $last
  239. * @return array<string, int>
  240. */
  241. private function progressMeta(string $channel, ?array $range, ?array $last): array
  242. {
  243. if ($range === null) {
  244. return [];
  245. }
  246. $paras = $this->paragraphsIn($channel, $range['book'], $range);
  247. $remaining = 0;
  248. if ($last !== null) {
  249. foreach ($paras as $para) {
  250. if ($para > $last['para']) {
  251. $remaining++;
  252. }
  253. }
  254. }
  255. return ['total' => count($paras), 'remaining' => $remaining];
  256. }
  257. /**
  258. * 按 include 裁剪输出。display 只要段落 html,sentences 只要句子列表,all 两者都要。
  259. *
  260. * @param array{para: int, display: string, sentences: array} $paragraph
  261. * @return array<string, mixed>
  262. */
  263. private function filterInclude(array $paragraph, string $include): array
  264. {
  265. return match ($include) {
  266. 'sentences' => ['para' => $paragraph['para'], 'sentences' => $paragraph['sentences']],
  267. 'all' => $paragraph,
  268. default => ['para' => $paragraph['para'], 'display' => $paragraph['display']],
  269. };
  270. }
  271. }