2
0

ReadingCacheTest.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. <?php
  2. use App\Facades\RedisCache;
  3. use App\Models\Discussion;
  4. use App\Models\PaliText;
  5. use App\Services\PaliContentService;
  6. use App\Services\ReadingIndexService;
  7. use App\Services\V3\PaliTextService;
  8. use Illuminate\Foundation\Testing\RefreshDatabase;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Str;
  11. uses(RefreshDatabase::class);
  12. /**
  13. * 阅读缓存(api-v13/documents/reading-cache-plan.html):
  14. * L0 pali_texts 按书缓存、A1 整块批量渲染、L1 段落成品、L2 段号 / 书号索引。
  15. */
  16. function makePaliRow(int $book, int $para, int $level, int $chapterLen = 0, string $class = 'bodytext', string $toc = ''): void
  17. {
  18. (new PaliText)->forceFill([
  19. 'book' => $book,
  20. 'paragraph' => $para,
  21. 'level' => $level,
  22. 'class' => $class,
  23. 'toc' => $toc,
  24. 'text' => '',
  25. 'html' => '',
  26. 'lenght' => 10 * $para,
  27. 'chapter_len' => $chapterLen,
  28. 'chapter_strlen' => 100,
  29. 'parent' => 0,
  30. 'pcd_book_id' => 0,
  31. 'uid' => (string) Str::uuid(),
  32. ])->save();
  33. }
  34. function makeReadingNote(string $sentenceUid, string $type, string $content, ?int $score = null): Discussion
  35. {
  36. $discussion = new Discussion;
  37. $discussion->forceFill([
  38. 'res_id' => $sentenceUid,
  39. 'res_type' => 'sentence',
  40. 'type' => $type,
  41. 'title' => $content,
  42. 'content' => $content,
  43. 'content_type' => 'markdown',
  44. 'editor_uid' => makeStudio('note-'.Str::random(6)),
  45. 'score' => $score,
  46. 'pos_start' => 0,
  47. 'pos_end' => 1,
  48. ])->save();
  49. return $discussion;
  50. }
  51. /**
  52. * 计数这段代码查了几次库。
  53. */
  54. function countQueries(Closure $callback): int
  55. {
  56. DB::flushQueryLog();
  57. DB::enableQueryLog();
  58. $callback();
  59. $count = count(DB::getQueryLog());
  60. DB::disableQueryLog();
  61. return $count;
  62. }
  63. it('caches pali_texts per book and serves headings, levels and classes without queries', function () {
  64. makePaliRow(9301, 1, 1, 5, 'book', 'Book');
  65. makePaliRow(9301, 2, 2, 4, 'chapter', 'Chapter');
  66. makePaliRow(9301, 3, 100, 0, 'gatha1');
  67. app(PaliTextService::class)->headings(9301);
  68. app(PaliTextService::class)->paragraphs(9301, 1, 3);
  69. // 新实例(没有进程内记忆)也只读缓存
  70. $service = new PaliTextService;
  71. expect(countQueries(function () use ($service) {
  72. expect($service->headingLevel(9301, 2))->toBe(2)
  73. ->and($service->headingLevel(9301, 3))->toBe(0)
  74. ->and($service->paragraph(9301, 3))->toBe(['level' => 100, 'class' => 'gatha1', 'length' => 30])
  75. ->and($service->chapterRange(9301, 2))->toBe([2, 5])
  76. ->and($service->chapterRange(9301, 3))->toBe([3, 3])
  77. ->and($service->bookStart(9301, 3))->toMatchArray(['para' => 1, 'toc' => 'Book']);
  78. }))->toBe(0);
  79. expect($service->chapterRange(9301, 99))->toBeNull();
  80. });
  81. it('renders a block exactly like rendering each paragraph alone', function () {
  82. $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
  83. makePaliRow(9302, 1, 2, 3, 'chapter');
  84. foreach ([1, 2, 3] as $para) {
  85. $sentence = makeSentence($channel, 9302, $para, 1, "first of {$para}");
  86. makeSentence($channel, 9302, $para, 2, "second of {$para}");
  87. makeReadingNote($sentence->uid, 'note', "note of {$para}");
  88. }
  89. // 只有第 2 段有评估:第 2 段的另一句补灰色对勾,别的段不补(按段算,不是按整块)
  90. $assessed = makeSentence($channel, 9302, 2, 3, 'assessed');
  91. makeReadingNote($assessed->uid, 'assessment', 'ok', 90);
  92. $service = app(PaliContentService::class);
  93. $block = $service->readParagraphs(9302, [1, 2, 3], $channel);
  94. foreach ([1, 2, 3] as $para) {
  95. PaliContentService::forgetParagraph(9302, $para, $channel);
  96. }
  97. foreach ([1, 2, 3] as $para) {
  98. expect($service->readParagraph(9302, $para, $channel))->toBe($block[$para]);
  99. }
  100. expect($block[1]['display'])->toContain('<h2>')->toContain('note of 1')->toContain('anno-footnotes')
  101. ->and($block[2]['display'])->toContain('anno-assessment')
  102. ->and($block[1]['display'])->not->toContain('anno-assessment')
  103. ->and($block[3]['display'])->not->toContain('anno-assessment');
  104. });
  105. it('renders a block with a fixed number of queries however many paragraphs it has', function () {
  106. $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
  107. $render = function (int $book, int $count) use ($channel) {
  108. foreach (range(1, $count) as $para) {
  109. $sentence = makeSentence($channel, $book, $para, 1, "text {$para}");
  110. makeReadingNote($sentence->uid, 'note', "note {$para}");
  111. }
  112. app(PaliTextService::class)->headings($book);
  113. app(PaliTextService::class)->paragraphs($book, 1, $count);
  114. return countQueries(fn () => app(PaliContentService::class)->readParagraphs($book, range(1, $count), $channel));
  115. };
  116. expect($render(9303, 20))->toBe($render(9304, 2));
  117. });
  118. it('serves cached paragraphs without touching the database', function () {
  119. $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
  120. makeSentence($channel, 9305, 1, 1, 'cached');
  121. $url = "/api/v3/tipitaka-reading/{$channel}?book=9305";
  122. $first = $this->getJson($url)->assertOk()->json();
  123. // 鉴权中间件等外围查询之外,正文、候选、进度都不查库
  124. $queries = countQueries(fn () => expect($this->getJson($url)->assertOk()->json())->toBe($first));
  125. $baseline = countQueries(fn () => $this->getJson("/api/v3/tipitaka-reading/{$channel}?book=9305&para=999")->assertOk());
  126. expect($queries)->toBe($baseline);
  127. });
  128. it('refreshes the paragraph index only when the set of translated paragraphs changes', function () {
  129. $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
  130. $first = makeSentence($channel, 9306, 1, 1, 'one');
  131. $index = fn () => new ReadingIndexService;
  132. expect($index()->paragraphs($channel, 9306))->toBe([1]);
  133. $sentence = makeSentence($channel, 9306, 3, 1, 'three');
  134. expect($index()->paragraphs($channel, 9306))->toBe([1, 3]);
  135. // 只改内容:段落成品删掉,索引不动(不重建)
  136. app(PaliContentService::class)->readParagraph(9306, 1, $channel);
  137. $first->forceFill(['content' => 'one again', 'strlen' => 9])->save();
  138. expect(RedisCache::has(PaliContentService::paragraphCacheKey(9306, 1, $channel, 'html')))->toBeFalse()
  139. ->and(countQueries(fn () => expect($index()->paragraphs($channel, 9306))->toBe([1, 3])))->toBe(0);
  140. // strlen 变成 0 就不算有译文
  141. $sentence->forceFill(['content' => '', 'strlen' => 0])->save();
  142. expect($index()->paragraphs($channel, 9306))->toBe([1]);
  143. // 批注不碰索引
  144. makeReadingNote($first->uid, 'note', 'n');
  145. expect(countQueries(fn () => $index()->paragraphs($channel, 9306)))->toBe(0);
  146. });
  147. it('keeps the book index in step with books gaining or losing translations', function () {
  148. $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
  149. makeSentence($channel, 9307, 1, 1, 'a');
  150. expect((new ReadingIndexService)->books($channel))->toBe([9307]);
  151. $other = makeSentence($channel, 9308, 1, 1, 'b');
  152. expect((new ReadingIndexService)->books($channel))->toBe([9307, 9308]);
  153. // 搬去别的书:旧书少了、新书多了
  154. $other->forceFill(['book_id' => 9309])->save();
  155. expect((new ReadingIndexService)->books($channel))->toBe([9307, 9309]);
  156. $other->delete();
  157. expect((new ReadingIndexService)->books($channel))->toBe([9307]);
  158. });
  159. it('walks a whole channel across books with the cursor', function () {
  160. $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
  161. makeSentence($channel, 9310, 1, 1, 'a');
  162. makeSentence($channel, 9310, 2, 1, 'b');
  163. makeSentence($channel, 9311, 5, 1, 'c');
  164. $page = $this->getJson("/api/v3/tipitaka-reading/{$channel}?page_size=2")->assertOk();
  165. expect(array_column($page->json('data'), 'para'))->toBe([1, 2])
  166. ->and($page->json('meta.next_cursor'))->toBe('9310-2');
  167. $page = $this->getJson("/api/v3/tipitaka-reading/{$channel}?page_size=2&after=9310-2")->assertOk();
  168. expect($page->json('data.0'))->toMatchArray(['book' => 9311, 'para' => 5])
  169. ->and($page->json('meta.next_cursor'))->toBeNull();
  170. });
  171. it('clears the paragraph cache only after the transaction commits', function () {
  172. $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
  173. $sentence = makeSentence($channel, 9313, 1, 1, 'before');
  174. app(PaliContentService::class)->readParagraph(9313, 1, $channel);
  175. $key = PaliContentService::paragraphCacheKey(9313, 1, $channel, 'html');
  176. DB::transaction(function () use ($sentence, $key) {
  177. $sentence->forceFill(['content' => 'after'])->save();
  178. expect(RedisCache::has($key))->toBeTrue();
  179. });
  180. expect(RedisCache::has($key))->toBeFalse();
  181. });
  182. it('splits a book into flat chapters, each running up to the next heading', function () {
  183. makePaliRow(9320, 1, 1, 10);
  184. makePaliRow(9320, 2, 2, 5);
  185. makePaliRow(9320, 4, 3, 3);
  186. makePaliRow(9320, 7, 2, 4);
  187. $service = app(PaliTextService::class);
  188. expect($service->flatChapters(9320))->toBe([1 => 1, 2 => 3, 4 => 6, 7 => 10])
  189. ->and($service->flatChapterOf(9320, 5))->toBe(4)
  190. ->and($service->flatChapterOf(9320, 10))->toBe(7)
  191. ->and($service->flatChapterOf(9320, 11))->toBeNull();
  192. });
  193. it('caches the reader chapters and drops only the chapter whose sentence changed', function () {
  194. $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
  195. makePaliRow(9321, 1, 2, 2);
  196. makePaliRow(9321, 3, 2, 2);
  197. makeSentence($channel, 9321, 1, 1, 'chapter one');
  198. $changed = makeSentence($channel, 9321, 4, 1, 'chapter two');
  199. $service = app(PaliContentService::class);
  200. $display = $service->readChapters(9321, 1, 4, $channel);
  201. expect($display)->toContain('chapter one')->toContain('chapter two')
  202. ->and($display)->toBe(implode('', array_column($service->readParagraphs(9321, [1, 2, 3, 4], $channel), 'display')))
  203. ->and(countQueries(fn () => $service->readChapters(9321, 1, 4, $channel)))->toBe(0);
  204. $changed->forceFill(['content' => 'chapter two edited'])->save();
  205. expect(RedisCache::has(PaliContentService::chapterCacheKey(9321, 1, $channel, 'html')))->toBeTrue()
  206. ->and(RedisCache::has(PaliContentService::chapterCacheKey(9321, 3, $channel, 'html')))->toBeFalse()
  207. ->and($service->readChapters(9321, 1, 4, $channel))->toContain('chapter two edited');
  208. });