WIP: AI: #485 タグ広場 V1 /posts/changes の非 admin アクセス時 503 を修正 #489

ドラフト
テツノニジカ が feature/485 から main への 11 コミットのマージを希望しています
14個のファイルの変更、658行の追加、44行の削除
+13 -8
ファイルの表示
@@ -16,7 +16,7 @@ class PostVersionsController < ApplicationController
q = HistoryAccess.visible(PostVersion.all)
q = q.where('post_versions.post_id = ?', post_id) if post_id
q = q.with_previous_version if tag_id || external_tag_id
q = q.merge(version_scope) if tag_id || external_tag_id
if external_tag_id || (tag_id && !(Tag.exists?(id: tag_id)))
q = q.where('JSON_CONTAINS(post_versions.tags_json,' +
"JSON_OBJECT('external_tag_id', #{ external_tag_id || tag_id })) " +
@@ -29,14 +29,19 @@ class PostVersionsController < ApplicationController
count = q.except(:select, :order, :limit, :offset).count
ids = q.order(Arel.sql('post_versions.created_at DESC, post_versions.id DESC'))
.limit(limit)
.offset(offset)
.pluck('post_versions.id')
versions = version_scope.merge(q).where(id: ids)
.order(Arel.sql('post_versions.created_at DESC, post_versions.id DESC'))
# Reuse the authorised previous snapshot when it is needed for filtering.
page_scope = q.order(Arel.sql('post_versions.created_at DESC, post_versions.id DESC'))
.limit(limit).offset(offset)
versions =
if tag_id || external_tag_id
page_scope
else
version_scope.from(page_scope.select('post_versions.*'), :post_versions)
.order(Arel.sql('post_versions.created_at DESC, post_versions.id DESC'))
end
render json: { versions: serialise_versions(versions, locale.language_code), count:, population_count: HistoryAccess.population_count(PostVersion) }
render json: { versions: serialise_versions(versions, locale.language_code),
count:, population_count: HistoryAccess.population_count(PostVersion) }
end
private
+11 -13
ファイルの表示
@@ -41,10 +41,9 @@ class HistoryAccess < ActiveSupport::CurrentAttributes
table = model.table_name
keys = KEYS.fetch(table)
matches = keys.map { "boundary.#{ _1 } = #{ row }.#{ _1 }" }.join(' AND ')
boundaries = "SELECT #{ keys.join(', ') }, MAX(version_no) AS version_no FROM #{ table } " +
"WHERE event_type = 'discard' GROUP BY #{ keys.join(', ') }"
clauses = ["NOT EXISTS (SELECT 1 FROM (#{ boundaries }) boundary WHERE #{ matches } " +
"AND boundary.version_no >= #{ row }.version_no)"]
# Any discard at or after this version hides it, including after a restore.
clauses = ["NOT EXISTS (SELECT 1 FROM #{ table } boundary WHERE #{ matches } " +
"AND boundary.version_no >= #{ row }.version_no AND boundary.event_type = 'discard')"]
clauses += reference_sql(table, row) if references
clauses.map { "(#{ _1 })" }.join(' AND ')
end
@@ -62,8 +61,8 @@ class HistoryAccess < ActiveSupport::CurrentAttributes
# A scalar lookup avoids MySQL's semijoin rewrite losing the JSON row correlation.
"(SELECT 1 FROM JSON_TABLE(COALESCE(#{ document }, JSON_ARRAY()), " +
"'$[*]' COLUMNS (reference_id BIGINT PATH '$' NULL ON EMPTY)) reference_entry " +
"JOIN (#{ discarded_keys(table, key) }) blocked " +
"ON reference_entry.reference_id = blocked.#{ key } LIMIT 1) IS NULL"
"JOIN #{ table } blocked ON reference_entry.reference_id = blocked.#{ key } " +
"WHERE blocked.event_type = 'discard' LIMIT 1) IS NULL"
end
def self.list_reference(table, key, document)
@@ -83,17 +82,16 @@ class HistoryAccess < ActiveSupport::CurrentAttributes
"tag_id BIGINT PATH '$.#{ key }', version_no INT PATH '$.version_no')) tag_reference"
match = 'reference_version.tag_id = tag_reference.tag_id'
if external
match += " AND reference_version.created_at <= #{ row }.created_at"
latest = "AND NOT EXISTS (SELECT 1 FROM #{ table } later_reference " +
'WHERE later_reference.tag_id = reference_version.tag_id ' +
"AND later_reference.created_at <= #{ row }.created_at " +
'AND later_reference.version_no > reference_version.version_no)'
# Select the recorded version before evaluating its reference privacy.
match += ' AND reference_version.version_no = ' +
"(SELECT MAX(candidate.version_no) FROM #{ table } candidate " +
'WHERE candidate.tag_id = tag_reference.tag_id ' +
"AND candidate.created_at <= #{ row }.created_at)"
else
match += ' AND reference_version.version_no = tag_reference.version_no'
latest = ''
end
"(SELECT 1 FROM #{ source } JOIN #{ table } reference_version ON #{ match } " +
"WHERE NOT (#{ sql(model, 'reference_version') }) #{ latest } LIMIT 1) IS NULL"
"WHERE NOT (#{ sql(model, 'reference_version') }) LIMIT 1) IS NULL"
end
def self.reference_sql(table, row)
+238 -2
ファイルの表示
@@ -8,7 +8,12 @@ RSpec.describe 'Post history privacy', type: :request do
let!(:other_post) do
create(:post, created_at: origin, updated_at: origin + 3.days + 1.hour)
end
let!(:tag) { create(:tag, primary_name: 'private-history-tag') }
let!(:tag) do
# Locale completion in the tag factory can create its own version 1.
create(:tag, primary_tag_name: nil).tap do |record|
create(:tag_name, tag: record, name: 'private-history-tag')
end
end
let!(:external) { create(:external_tag, name: 'external-history-tag') }
before do
@@ -33,6 +38,9 @@ RSpec.describe 'Post history privacy', type: :request do
end
PostVersion.create!(post: post_record, version_no: index + 1, event_type: event,
title: "version #{ index + 1 }", url: post_record.url, tags: '',
thumbnail_base: "history-#{ index + 1 }", video_ms: (index + 1) * 1000,
original_created_from: origin - 1.year + index.days,
original_created_before: origin - 1.year + (index + 1).days,
tags_json: snapshots, parent_post_ids: '', created_at: origin + (index + 1).days)
end
end
@@ -63,7 +71,7 @@ RSpec.describe 'Post history privacy', type: :request do
expect(response.parsed_body.fetch('versions').first.fetch('title').fetch('prev')).to be_nil
end
['anonymous', 'member', 'admin'].each do |role|
['anonymous', 'guest', 'member', 'admin'].each do |role|
context "as #{ role }" do
before do
sign_in_as(create(:user, role.to_sym)) unless role == 'anonymous'
@@ -115,6 +123,15 @@ RSpec.describe 'Post history privacy', type: :request do
expect(body.fetch('versions').pluck('version_no')).to eq(expected)
restored = body.fetch('versions').find { _1.fetch('version_no') == 3 }
expect(restored.fetch('title').fetch('prev')).to eq(role == 'admin' ? 'version 2' : nil)
unless role == 'admin'
fields = [
'url', 'thumbnail_base', 'video_ms',
'original_created_from', 'original_created_before']
fields.each do |field|
expect(restored.fetch(field).fetch('prev')).to be_nil
end
expect(restored.fetch('tags')).to eq([])
end
end
it 'uses only an authorised previous version for tag filtering' do
@@ -124,6 +141,225 @@ RSpec.describe 'Post history privacy', type: :request do
expect(response.parsed_body.fetch('versions').pluck('version_no')).to eq(expected)
expect(response.parsed_body.fetch('count')).to eq(expected.length)
end
it 'paginates public tag additions and removals using the same exact count' do
public_tag = create(:tag, primary_tag_name: nil).tap do |record|
create(:tag_name, tag: record, name: 'public-history-tag')
end
public_external = create(:external_tag)
TagVersion.create!(tag: public_tag, version_no: 1, event_type: 'create',
name: 'public-history-tag', category: 'general', aliases: '', parent_tag_ids: '',
names: { ja: { name: 'public-history-tag', script_code: 'Jpan',
auto_generated: false, aliases: [] } },
created_at: origin)
NicoTagVersion.create!(external_tag: public_external, version_no: 1,
event_type: 'create', linked_tag_ids: '', created_at: origin)
snapshots = [
[{ tag_id: public_tag.id, version_no: 1, sections: [] },
{ external_tag_id: public_external.id }], []]
snapshots.each_with_index do |tags, index|
PostVersion.create!(post: post_record, version_no: index + 5, event_type: 'update',
title: "public snapshot #{ index }", url: post_record.url, tags: '',
tags_json: tags, parent_post_ids: '', created_at: origin + (index + 5).days)
end
{ tag: public_tag.id, external_tag: public_external.id }.each do |parameter, id|
[6, 5].each_with_index do |number, index|
get '/posts/versions', params: {
post: post_record.id, parameter => id, page: index + 1, limit: 1 }
expect(response).to have_http_status(:ok)
body = response.parsed_body
expect(body.fetch('count')).to eq(2)
expect(body.fetch('versions').pluck('version_no')).to eq([number])
snapshot = body.fetch('versions').first
type = index.zero? ? 'removed' : 'added'
expect(snapshot.fetch('tags')).to include(
a_hash_including('name' => 'public-history-tag', 'type' => type),
a_hash_including('name' => "nico:#{ public_external.name }", 'type' => type))
previous =
if index.zero?
'public snapshot 0'
elsif role == 'admin'
'version 4'
end
expect(snapshot.fetch('title').fetch('prev')).to eq(previous)
end
end
end
it 'returns an empty history with an exact count' do
get '/posts/versions', params: { post: other_post.id }
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to include('versions' => [], 'count' => 0,
'population_count' => 4)
end
it 'keeps counts and timestamp ties consistent across history pages' do
rows = 25.times.map do |index|
PostVersion.create!(post: post_record, version_no: index + 5, event_type: 'update',
title: 'page snapshot', url: post_record.url, tags: '', tags_json: [],
parent_post_ids: '', created_at: origin + 5.days)
end
rows << PostVersion.create!(post: other_post, version_no: 1, event_type: 'create',
title: 'another post', url: other_post.url, tags: '', tags_json: [],
parent_post_ids: '', created_at: origin + 5.days)
earlier = role == 'admin' ? [4, 3, 2, 1] : [3]
expected = rows.reverse.map { [_1.post_id, _1.version_no] } +
earlier.map { [post_record.id, _1] }
expected.each_slice(7).with_index do |page_rows, index|
get '/posts/versions', params: { page: index + 1, limit: 7 }
expect(response).to have_http_status(:ok)
body = response.parsed_body
expect(body.fetch('count')).to eq(expected.length)
expect(body.fetch('population_count')).to eq(30)
expect(body.fetch('versions').map { [_1.fetch('post_id'), _1.fetch('version_no')] })
.to eq(page_rows)
end
get '/posts/versions', params: { page: 10, limit: 7 }
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to include('versions' => [], 'count' => expected.length)
end
it 'loads each page with one authorised previous-snapshot join' do
[{ }, { tag: tag.id }, { external_tag: external.id }].each do |filters|
statements = []
listener = lambda do |_name, _started_at, _finished_at, _id, payload|
next if ['SCHEMA', 'TRANSACTION'].include?(payload[:name])
statements << payload[:sql] if payload[:sql].match?(/\ASELECT/i)
end
ActiveSupport::Notifications.subscribed(listener, 'sql.active_record') do
get '/posts/versions', params: { post: post_record.id, limit: 1 }.merge(filters)
end
expect(response).to have_http_status(:ok)
history_queries = statements.select { _1.include?('post_versions') }
counts, details = history_queries.partition { _1.match?(/\ASELECT COUNT\(/i) }
expect(counts.length).to eq(2)
joins = counts.join(' ').scan('LEFT JOIN post_versions prev')
expect(joins.length).to eq(filters.empty? ? 0 : 1)
expect(details.length).to eq(1)
expect(details.first.scan('LEFT JOIN post_versions prev').length).to eq(1)
end
end
it 'hides references to a discarded parent even after its restore' do
['discard', 'restore'].each_with_index do |event, index|
PostVersion.create!(post: other_post, version_no: index + 1, event_type: event,
title: 'parent snapshot', url: other_post.url, tags: '', tags_json: [],
parent_post_ids: '', created_at: origin + index.hours)
end
[other_post.id.to_s, ''].each_with_index do |parents, index|
PostVersion.create!(post: post_record, version_no: index + 5, event_type: 'update',
title: 'parent reference', url: post_record.url, tags: '', tags_json: [],
parent_post_ids: parents, created_at: origin + (index + 5).days)
end
get '/posts/versions', params: { post: post_record.id }
expect(response).to have_http_status(:ok)
body = response.parsed_body
expected = role == 'admin' ? [6, 5, 4, 3, 2, 1] : [6, 3]
expect(body.fetch('versions').pluck('version_no')).to eq(expected)
expect(body.fetch('count')).to eq(expected.length)
previous = body.fetch('versions').first.fetch('title').fetch('prev')
expect(previous).to eq(role == 'admin' ? 'parent reference' : nil)
end
it 'keeps restored tag references private' do
TagVersion.create!(tag:, version_no: 3, event_type: 'restore',
name: 'private-history-tag', category: 'general', aliases: '', parent_tag_ids: '',
names: { ja: { name: 'private-history-tag', script_code: 'Jpan',
auto_generated: false, aliases: [] } },
created_at: origin + 2.hours)
PostVersion.create!(post: post_record, version_no: 5, event_type: 'update',
title: 'restored tag reference', url: post_record.url, tags: '',
tags_json: [{ tag_id: tag.id, version_no: 3, sections: [] }],
parent_post_ids: '', created_at: origin + 5.days)
get '/posts/versions', params: { post: post_record.id }
expect(response).to have_http_status(:ok)
expected = role == 'admin' ? [5, 4, 3, 2, 1] : [3]
expect(response.parsed_body.fetch('versions').pluck('version_no')).to eq(expected)
expect(response.parsed_body.fetch('count')).to eq(expected.length)
end
it 'uses the external linkage recorded at the post snapshot time' do
NicoTagVersion.create!(external_tag: external, version_no: 2, event_type: 'update',
linked_tag_ids: '', created_at: origin + 5.days)
PostVersion.create!(post: post_record, version_no: 5, event_type: 'update',
title: 'public external reference', url: post_record.url, tags: '',
tags_json: [{ external_tag_id: external.id }], parent_post_ids: '',
created_at: origin + 6.days)
get '/posts/versions', params: { post: post_record.id, external_tag: external.id }
expect(response).to have_http_status(:ok)
body = response.parsed_body
expected = role == 'admin' ? [5, 4] : [5]
expect(body.fetch('versions').pluck('version_no')).to eq(expected)
expect(body.fetch('count')).to eq(expected.length)
latest = body.fetch('versions').first
previous = latest.fetch('title').fetch('prev')
expect(previous).to eq(role == 'admin' ? 'version 4' : nil)
expect(latest.fetch('tags')).to contain_exactly(a_hash_including(
'name' => 'nico:external-history-tag',
'type' => role == 'admin' ? 'context' : 'added'))
end
it 'hides references to historical external discard events after restore' do
public_external = create(:external_tag)
# Discard/restore events can remain in history despite current event validation.
snapshots = ['create', 'discard', 'restore'].each_with_index.map do |event, index|
{ tag_id: public_external.id, version_no: index + 1, event_type: event,
linked_tag_ids: '', created_at: origin + index.days }
end
NicoTagVersion.insert_all!(snapshots)
[5, 6].each do |number|
PostVersion.create!(post: post_record, version_no: number, event_type: 'update',
title: 'external discard reference', url: post_record.url, tags: '',
tags_json: [{ external_tag_id: public_external.id }], parent_post_ids: '',
created_at: origin + number.days)
end
get '/posts/versions', params: { post: post_record.id, external_tag: public_external.id }
expect(response).to have_http_status(:ok)
expected = role == 'admin' ? [6, 5] : []
expect(response.parsed_body.fetch('versions').pluck('version_no')).to eq(expected)
expect(response.parsed_body.fetch('count')).to eq(expected.length)
end
it 'selects the highest external version within each post timestamp' do
# Equal and out-of-order timestamps must still use version order.
snapshots = [
[2, 2.hours, tag.id.to_s], [3, 2.hours, tag.id.to_s],
[4, 1.hour, ''], [5, 8.days, tag.id.to_s]]
snapshots.each do |number, time, linked|
NicoTagVersion.create!(external_tag: external, version_no: number,
event_type: 'update', linked_tag_ids: linked, created_at: origin + time)
end
[6, 9].each_with_index do |days, index|
PostVersion.create!(post: post_record, version_no: index + 5,
event_type: 'update', title: 'external version selection',
url: post_record.url, tags: '', tags_json: [{ external_tag_id: external.id }],
parent_post_ids: '', created_at: origin + days.days)
end
get '/posts/versions', params: { post: post_record.id, external_tag: external.id }
expect(response).to have_http_status(:ok)
body = response.parsed_body
expected = role == 'admin' ? [6, 5, 4] : [5, 4]
expect(body.fetch('versions').pluck('version_no')).to eq(expected)
expect(body.fetch('count')).to eq(expected.length)
end
end
end
end
+116
ファイルの表示
@@ -0,0 +1,116 @@
# Issue #485: V1 投稿履歴の非 admin アクセス時 HTTP 503
## PR #489 レビューの遅延ログへの対応
レビューで提示されたログでは、履歴本文の SELECT が31249.2ms、API 全体が
64588ms、ActiveRecord が64396msかかっている。従来の変更で障害が解消したとは
言えない。変更前の同条件の計測値がないため、悪化率も算出できない。
提示範囲には公開件数の count の所要時間がなく、その負荷は別途確認が必要。
今回の変更は `HistoryAccess.snapshot_reference` の外部タグ参照だけに限定する。
従来は投稿時点以前の外部タグ履歴を結合し、各候補の公開判定と、より大きい版番号の
有無を評価する SQL だった。変更後は同じタグ ID・投稿時点の条件で
`MAX(candidate.version_no)` を求め、既存の `(tag_id, version_no)` unique index に
対応する1版へ結合してから公開判定する。最新の版が非公開でも過去の公開版へ
遡らない。時刻順が版番号順と異なる場合や同時刻でも、従来どおり最大版番号を使う。
除票境界、参照先の公開判定、正確な count、直前版の認可は変更しない。
回帰テストには、同時刻・時刻と版番号の順序不一致・投稿より未来の版を組み合わせ、
anonymous・guest・member・admin の件数と履歴の確認を追加した。
担当エージェントはテスト・lint・build・DB 操作を実行していない。
管理側で `post_history_privacy_spec.rb` と `history_access_spec.rb`、共有認可を使う
Counts・各履歴の回帰を確認する。許可された非本番の同一データで、変更前後の
count と本文 SELECT の実行計画・所要時間を個別に比較する必要がある。
特に外部タグ参照が複合キーで1版へ絞られるか、過去の各版に対して公開判定を
繰り返さないかを確認し、SSR の10秒 timeout 内で応答できるかも計測する。
この変更での速度改善量と503解消は未確認であり、他の相関条件や全件 count の
負荷も残る。実行計画未取得のため、本番遅延の根本原因の確定ではない。
対象は V1 の `/posts/changes`(locale prefix 付き URL を含む)。
Issue では admin は表示でき、member・guest では HTTP 503 が発生すると報告されている。
本番の根本原因、503 の解消、SQL の性能改善量は未確定。
既存の `feature/485`(引継ぎ時点 `6329958`)の成果を以下に整理する。
文書の整理に加え、管理側ゲートで判明した MDX テスト補助コードの設定読取を修正する。
## コードから確認できる経路と未確定事項
- [HistoryAccess](../backend/app/models/history_access.rb) は admin に `TRUE` を返す。
非 admin には除票境界、タグ・外部タグ・親投稿の参照公開判定を適用する。
- [PostVersionsController](../backend/app/controllers/post_versions_controller.rb) は
公開条件と検索条件を適用して全件 count を取得する。
count が主なボトルネックかどうかは、実行計画・計測がなく未判定。
- [api.ts](../frontend/src/lib/api.ts) の SSR API timeout は10秒。
[entry-server.tsx](../frontend/src/entry-server.tsx) はデータ準備中の API timeout 等を再送出し、
[server.mjs](../frontend/server.mjs) は SSR 例外に対して原則503を返す。
API 遅延が503につながる経路はあるが、本番でこの経路が発生した証拠は未取得。
- シリアライズはユーザー名・タグ名・外部タグ名をページ内の ID で一括取得する構造。
本番の照会回数・所要時間の計測結果はない。
## 引継ぎ済みの修正
- `backend/app/models/history_access.rb`:除票境界の集約を、同じリソースキーと
`version_no` による後続除票の `NOT EXISTS` 判定に変更。
JSON 参照の除票照会も履歴テーブルへの直接 JOIN に変更。
- `backend/app/controllers/post_versions_controller.rb`:タグ条件なしでは、公開条件による
ページ選択後に直前版を結合。タグ条件ありでは、絞込に使う認可済み直前版を差分にも再利用。
正確な count と `created_at DESC, id DESC` の順序は維持する構造。
- [prefetchers.ts](../frontend/src/lib/prefetchers.ts):URL の `id` を
`fetchPostChanges` の `post` 引数と `postsKeys.changes` の `post` に対応させる。
[PostHistoryPage.tsx](../frontend/src/pages/posts/PostHistoryPage.tsx) の取得条件と一致させる修正。
- [vite.config.ts](../frontend/vite.config.ts) と
[vitest.config.ts](../frontend/vitest.config.ts):既存成果には build 時の `jsxDev: false` と、
関数形式の Vite 設定を Vitest から読み込む変更も含まれる。
### SQL 構造の比較
比較元は引継ぎ済み修正の直前 `dda3d87`。実行計画・実測値の比較ではない。
| 対象 | 修正前 | 引継ぎ済みの構造 |
| --- | --- | --- |
| 除票境界 | リソースキーごとの `GROUP BY / MAX(version_no)` | 同一キーで対象版以降の除票を `NOT EXISTS` で照会 |
| JSON 参照の除票判定 | 除票キーを集約した派生表へ JOIN | 履歴テーブルへ直接 JOIN し、除票を1件検出すれば終了 |
| ページ取得 | ID の `pluck` 後に公開条件付きで本文を再取得 | ページ選択と差分取得を一つの SQL にまとめ、認可済み直前版を再利用 |
| count | 公開・検索条件適用後の正確な全件集計 | 同じ契約を維持。集計自体は残る |
[schema.rb](../backend/db/schema.rb) には `post_versions(post_id, version_no)`、
`tag_versions(tag_id, version_no)`、`nico_tag_versions(tag_id, version_no)` の
複合 unique index がある。新しい照会での利用状況は EXPLAIN による確認が必要。
migration・schema・index の追加変更は行っていない。
## 引継ぎ済みの回帰テスト
- [post_history_privacy_spec.rb](../backend/spec/requests/post_history_privacy_spec.rb):
anonymous・guest・member・admin の可視性、除票と恢復、タグ・外部タグ・親投稿参照、
非公開直前版の旧値と差分、認可済み直前版によるタグ追加・削除の絞込、空履歴、
複数ページの正確な件数・同時刻の表示順序、履歴 SELECT と直前版 JOIN の回数を確認する内容。
タグ factory のロカール補完で第1版が重複しないためのデータ修正も含む。
- [prefetchers.test.ts](../frontend/src/lib/prefetchers.test.ts):locale prefix の有無と
`ain-Kana`、投稿 ID とタグ・外部タグ条件、query key と取得条件の一致、
同じ QueryClient における投稿別履歴と全件履歴のキャッシュ分離を確認する内容。
- [server.ssr.test.mjs](../frontend/server.ssr.test.mjs):ロカールと権限ごとの HTTP 200、
履歴テーブルの SSR、API の投稿・ページ条件と取得回数を確認する内容。
API スタブを用いるため、Rails SQL の性能や公開判定の実証にはならない。
## 検証状況と残る確認
管理側ゲートは frontend の578件を実行し、571件合格・7件不合格だった。
不合格はすべて `mdx-components.test.tsx` で、関数形式の Vite 設定から直接
`plugins` を読んだために発生した。ログは `validation-step-57_7ge7z.log`。
[compileMdx.ts](../frontend/src/test/compileMdx.ts) を、Vitest の設定と同様に
`viteConfig` に `command: 'serve', mode: 'test'` を渡してからプラグインを読む形に修正。
GFM の表、見出し・段落・一覧、長いセル、raw・url の変換除外、内部リンクの
既存回帰テストは維持する。
同じ検証では `frontend/help/.git` の権限修復エラーも別途報告されている。
担当エージェントはテスト・lint・build・DB 操作を実行していない。
修正後の固定スイートによる再検証と合否判定は管理側に委ねる。
この文書は修正後の合格記録ではない。
本番サービス・DB・外部認証情報にはアクセスしていない。
EXPLAIN、実データ規模での前後比較、実画面での503解消確認は行っていない。
全件 count、残る参照集約、`JSON_TABLE`・`snapshot_reference`、ソートの負荷は残る。
共有の `HistoryAccess` を使う他の履歴経路についても回帰確認が必要。
除票以前の版と参照履歴の秘匿、恢復後も解除しない規則、非公開直前版の差分遮断は
性能を理由に緩和せず、権限別の回帰テストと実行計画の両方で確認する。
+31
ファイルの表示
@@ -418,6 +418,37 @@ test ('YouTube posts return HTTP 200 with the embed rendered by SSR', async t =>
}
})
test ('post history HTTP requests preserve filters for every role', async t => {
const accounts = [
{ role: 'guest', cookie: null },
{ role: 'member', cookie: await authenticatedCookie ('second-recovery-secret') },
{ role: 'admin', cookie: await authenticatedCookie () }]
for (const account of accounts) {
for (const prefix of ['', '/ja', '/ain-Kana']) {
await t.test (`${account.role} ${prefix || 'no locale prefix'}`, async () => {
for (const query of ['', '?id=1&page=2&limit=5']) {
const start = requests.length
const response = await fetch (
`${httpOrigin}${prefix}/posts/changes${query}`, {
headers: account.cookie == null ? {} : { Cookie: account.cookie } })
assert.equal (response.status, 200)
const html = await response.text ()
assert.match (html, /<table/)
assert.doesNotMatch (html, /Switched to client rendering|template id="B:/)
const calls = requests.slice (start).map (request => new URL (request.url, apiURL))
.filter (url => url.pathname === '/posts/versions')
assert.equal (calls.length, 1)
assert.equal (calls[0].searchParams.get ('post'), query ? '1' : null)
assert.equal (calls[0].searchParams.get ('page'), query ? '2' : '1')
assert.equal (calls[0].searchParams.get ('limit'), query ? '5' : '20')
assert.equal (calls[0].searchParams.get ('locale'), prefix === '/ain-Kana'
? 'ain-Kana' : 'ja')
}
})
}
}
})
test ('parallel localized requests keep list data isolated', async () => {
const start = requests.length
const pages = await Promise.all (['ja', 'ain-Kana', 'ja', 'ain-Kana'].map (locale =>
+10 -1
ファイルの表示
@@ -110,8 +110,17 @@ export default forwardRef<HTMLAnchorElement, Props> (({
setOverlay (false)
})
if (!(ok) && cancelOnError)
if (!ok)
{
if (!cancelOnError)
{
if (replace)
location.replace (path)
else
location.assign (path)
}
return
}
navigate (path, { replace, ...(state && { state }) })
}
+35 -5
ファイルの表示
@@ -1,7 +1,7 @@
import { QueryClient } from '@tanstack/react-query'
import { fireEvent, screen, waitFor } from '@testing-library/react'
import { Route, Routes, useLocation } from 'react-router-dom'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import PrefetchLink from '@/components/PrefetchLink'
import * as prefetchers from '@/lib/prefetchers'
@@ -23,6 +23,10 @@ const Location = () => {
describe ('Help prefetch integration', () => {
afterEach (() => {
vi.unstubAllGlobals ()
})
beforeEach (() => {
helpFixture.reset ()
settings.linkPreload = 'intent'
@@ -115,12 +119,38 @@ describe ('Help prefetch integration', () => {
expect (run).toHaveBeenCalledTimes (mode === 'intent' ? 3 : 1)
})
it ('continues navigation after prefetch failure', async () => {
it.each ([false, true]) ('uses document navigation after failure with replace=%s',
async replacement => {
const assign = vi.fn ()
const replace = vi.fn ()
vi.stubGlobal ('location', { origin: window.location.origin, assign, replace })
vi.spyOn (console, 'error').mockImplementation (() => {})
vi.spyOn (prefetchers, 'prefetchForURL').mockRejectedValue (new Error ('offline'))
renderWithProviders (<>
<Location/>
<PrefetchLink to="/help/guide" replace={replacement}>Help</PrefetchLink>
</>)
fireEvent.click (screen.getByRole ('link', { name: 'Help' }))
await waitFor (() => expect (replacement ? replace : assign)
.toHaveBeenCalledWith ('/ja/help/guide'))
expect (replacement ? assign : replace).not.toHaveBeenCalled ()
expect (screen.getByTestId ('location')).toHaveTextContent ('/')
})
it ('keeps the current page when cancelOnError is requested', async () => {
const assign = vi.fn ()
const replace = vi.fn ()
vi.stubGlobal ('location', { origin: window.location.origin, assign, replace })
vi.spyOn (console, 'error').mockImplementation (() => {})
vi.spyOn (prefetchers, 'prefetchForURL').mockRejectedValue (new Error ('offline'))
renderWithProviders (<><Location/><PrefetchLink to="/help/guide">Help</PrefetchLink></>)
renderWithProviders (<>
<Location/>
<PrefetchLink to="/help/guide" cancelOnError>Help</PrefetchLink>
</>)
fireEvent.click (screen.getByRole ('link', { name: 'Help' }))
await waitFor (() => expect (screen.getByTestId ('location'))
.toHaveTextContent ('/help/guide'))
await waitFor (() => expect (console.error).toHaveBeenCalled ())
expect (assign).not.toHaveBeenCalled ()
expect (replace).not.toHaveBeenCalled ()
expect (screen.getByTestId ('location')).toHaveTextContent ('/')
})
})
+69
ファイルの表示
@@ -2,6 +2,7 @@ import { QueryClient } from '@tanstack/react-query'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { prefetchForURL } from '@/lib/prefetchers'
import { postsKeys } from '@/lib/queryKeys'
const postsApi = vi.hoisted (() => ({
fetchPost: vi.fn (),
@@ -88,6 +89,74 @@ describe ('prefetchForURL', () => {
expect (postsApi.fetchPost).toHaveBeenCalledWith ('12', 'ja')
})
it.each ([
['/posts/changes', 'ja'], ['/ja/posts/changes', 'ja'],
['/ain-Kana/posts/changes', 'ain-Kana']] as const) (
'matches post history filters and cache key at %s', async (path, locale) => {
const client = qc ()
const params = { post: '12', page: 2, limit: 5 }
const history = { versions: [], count: 7 }
postsApi.fetchPostChanges.mockResolvedValueOnce (history)
await prefetchForURL (client, `${path}?id=12&page=2&limit=5`)
expect (postsApi.fetchPostChanges).toHaveBeenCalledExactlyOnceWith (params, locale)
expect (client.getQueryData (postsKeys.changes (params, locale))).toEqual (history)
expect (client.getQueryCache ().getAll ()).toHaveLength (1)
})
it ('preserves a tag filter when prefetching one post history', async () => {
const client = qc ()
const params = { post: '12', tag: '7', page: 1, limit: 20 }
await prefetchForURL (client, '/ja/posts/changes?id=12&tag=7')
expect (postsApi.fetchPostChanges).toHaveBeenCalledExactlyOnceWith (params, 'ja')
expect (client.getQueryData (postsKeys.changes (params, 'ja')))
.toEqual ({ versions: [], count: 0 })
})
it ('propagates history prefetch failure to the navigation caller', async () => {
const client = qc ()
const error = new Error ('unavailable')
postsApi.fetchPostChanges.mockRejectedValueOnce (error)
await expect (prefetchForURL (client, '/ja/posts/changes?id=12'))
.rejects.toBe (error)
expect (client.getQueryData (postsKeys.changes (
{ post: '12', page: 1, limit: 20 }, 'ja'))).toBeUndefined ()
})
it ('preserves an external tag filter when prefetching one post history', async () => {
const client = qc ()
const params = { post: '12', externalTag: '7', page: 1, limit: 20 }
await prefetchForURL (client, '/ja/posts/changes?id=12&external_tag=7')
expect (postsApi.fetchPostChanges).toHaveBeenCalledExactlyOnceWith (params, 'ja')
expect (client.getQueryData (postsKeys.changes (params, 'ja')))
.toEqual ({ versions: [], count: 0 })
})
it ('keeps one post history separate from unfiltered history in the cache', async () => {
const client = qc ()
const params = { page: 2, limit: 5 }
const postParams = { ...params, post: '12' }
const history = { versions: [], count: 7 }
postsApi.fetchPostChanges.mockResolvedValueOnce (history)
await prefetchForURL (client, '/ja/posts/changes?id=12&page=2&limit=5')
await prefetchForURL (client, '/ja/posts/changes?page=2&limit=5')
expect (postsApi.fetchPostChanges).toHaveBeenCalledTimes (2)
expect (postsApi.fetchPostChanges).toHaveBeenNthCalledWith (1, postParams, 'ja')
expect (postsApi.fetchPostChanges).toHaveBeenNthCalledWith (2, params, 'ja')
expect (client.getQueryData (postsKeys.changes (postParams, 'ja'))).toEqual (history)
expect (client.getQueryData (postsKeys.changes (params, 'ja')))
.toEqual ({ versions: [], count: 0 })
expect (client.getQueryCache ().getAll ()).toHaveLength (2)
})
it ('prefetches tag indexes from query parameters', async () => {
await prefetchForURL (
qc (),
+3 -3
ファイルの表示
@@ -213,12 +213,12 @@ const prefetchPostChanges: Prefetcher = async (qc, url, locale) => {
queryFn: () => fetchTag (tag, locale) })
}
await qc.prefetchQuery ({
queryKey: postsKeys.changes ({ ...(id && { id }),
await qc.fetchQuery ({
queryKey: postsKeys.changes ({ ...(id && { post: id }),
...(tag && { tag }),
...(externalTag && { externalTag }),
page, limit }, locale),
queryFn: () => fetchPostChanges ({ ...(id && { id }),
queryFn: () => fetchPostChanges ({ ...(id && { post: id }),
...(tag && { tag }),
...(externalTag && { externalTag }),
page, limit }, locale) })
+103
ファイルの表示
@@ -0,0 +1,103 @@
import { QueryClient, dehydrate } from '@tanstack/react-query'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { localesKeys, postsKeys, sessionKeys } from '@/lib/queryKeys'
const bootstrap = vi.hoisted (() => ({
hydrateRoot: vi.fn (), createRoot: vi.fn (), session: vi.fn (),
reload: vi.fn (), preload: vi.fn () }))
vi.mock ('react-dom/client', () => ({
hydrateRoot: bootstrap.hydrateRoot, createRoot: bootstrap.createRoot }))
vi.mock ('@/App', () => ({ default: () => null,
preloadPageRoute: bootstrap.preload, resolvePageRoute: () => null }))
vi.mock ('@/lib/users', () => ({ initialiseUserSession: bootstrap.session }))
vi.mock ('@/lib/i18n', () => ({ createUII18n: () => ({ }) }))
vi.mock ('@/lib/locales', () => ({ currentViewingLocale: () => 'ja' }))
vi.mock ('@/lib/settings', () => ({
applyClientAnimationMode: vi.fn (), getClientAnimationMode: () => 'normal' }))
const user = { id: 1, role: 'guest', name: 'Guest', inheritanceCode: 'code' }
const historyKey = postsKeys.changes ({ page: 1, limit: 20 }, 'ja')
const history = { versions: [], count: 0 }
const prepareDocument = (authority: { id: number; role: string } | null) => {
const client = new QueryClient ()
client.setQueryData (localesKeys.index, { locales: [{ code: 'ja' }] })
client.setQueryData (historyKey, history)
if (authority != null)
client.setQueryData (sessionKeys.current, authority)
document.body.innerHTML = '<div id="root">SSR history</div>'
+ '<script id="ssr-state" type="application/json"></script>'
document.getElementById ('ssr-state')!.textContent = JSON.stringify ({
state: dehydrate (client), status: 200 })
}
describe ('SSR session reconciliation before hydration', () => {
beforeEach (() => {
vi.resetModules ()
vi.clearAllMocks ()
sessionStorage.clear ()
bootstrap.session.mockReset ()
bootstrap.session.mockResolvedValue (user)
bootstrap.preload.mockResolvedValue (undefined)
vi.stubGlobal ('window', {
location: { href: 'http://localhost:3000/ja/posts/changes',
reload: bootstrap.reload },
addEventListener: vi.fn (), removeEventListener: vi.fn () })
})
afterEach (() => {
vi.unstubAllGlobals ()
})
it.each (['guest', 'member', 'admin']) (
'retains SSR history when the confirmed %s identity matches', async role => {
prepareDocument ({ id: user.id, role })
bootstrap.session.mockResolvedValue ({ ...user, role })
await import ('@/main')
await vi.waitFor (() => expect (bootstrap.hydrateRoot).toHaveBeenCalledOnce ())
const client = bootstrap.hydrateRoot.mock.calls[0][1]
.props.children.props.client as QueryClient
expect (client.getQueryData (historyKey)).toEqual (history)
expect (client.getQueryData (sessionKeys.current)).toEqual ({ ...user, role })
expect (bootstrap.reload).not.toHaveBeenCalled ()
expect (bootstrap.createRoot).not.toHaveBeenCalled ()
})
it.each ([null, { id: 2, role: 'guest' }, { id: 1, role: 'admin' }]) (
'requests fresh SSR for a different identity: %s', async authority => {
prepareDocument (authority)
await import ('@/main')
await vi.waitFor (() => expect (bootstrap.reload).toHaveBeenCalledOnce ())
expect (bootstrap.hydrateRoot).not.toHaveBeenCalled ()
expect (bootstrap.createRoot).not.toHaveBeenCalled ()
expect (document.getElementById ('root')!.textContent).toBe ('SSR history')
})
it ('waits for session confirmation before hydrating', async () => {
prepareDocument (user)
let confirmSession!: (value: typeof user) => void
const session = new Promise<typeof user> (resolve => { confirmSession = resolve })
bootstrap.session.mockReturnValue (session)
await import ('@/main')
expect (bootstrap.hydrateRoot).not.toHaveBeenCalled ()
confirmSession (user)
await vi.waitFor (() => expect (bootstrap.hydrateRoot).toHaveBeenCalledOnce ())
expect (bootstrap.reload).not.toHaveBeenCalled ()
})
it ('does not loop when the browser cannot retain the confirmed session', async () => {
prepareDocument (null)
await import ('@/main')
await vi.waitFor (() => expect (bootstrap.reload).toHaveBeenCalledOnce ())
vi.resetModules ()
vi.spyOn (console, 'error').mockImplementation (() => {})
await import ('@/main')
await vi.waitFor (() => expect (console.error).toHaveBeenCalled ())
expect (bootstrap.reload).toHaveBeenCalledOnce ()
expect (bootstrap.hydrateRoot).not.toHaveBeenCalled ()
})
})
+16 -1
ファイルの表示
@@ -7,11 +7,14 @@ import '@/index.css'
import App, { preloadPageRoute, resolvePageRoute } from '@/App'
import { createUII18n } from '@/lib/i18n'
import { currentViewingLocale } from '@/lib/locales'
import { localesKeys } from '@/lib/queryKeys'
import { localesKeys, sessionKeys } from '@/lib/queryKeys'
import { applyClientAnimationMode, getClientAnimationMode } from '@/lib/settings'
import { initialiseUserSession } from '@/lib/users'
import type { DehydratedState } from '@tanstack/react-query'
import type { User } from '@/types'
const helmetContext = { }
const client = new QueryClient ({
@@ -70,6 +73,18 @@ const start = () => {
}
if (client.getQueryData (localesKeys.index) == null)
throw new Error ('Missing SSR locales')
const authority = client.getQueryData<User> (sessionKeys.current)
const user = await initialiseUserSession ()
if (user.id !== authority?.id || user.role !== authority?.role)
{
// Re-render under the confirmed Cookie before hydrating another identity's data.
if (sessionStorage.getItem (storageKey) === identity)
throw new Error ('SSR session identity did not converge')
sessionStorage.setItem (storageKey, identity)
window.location.reload ()
return
}
client.setQueryData (sessionKeys.current, user)
const url = new URL (window.location.href)
const match = resolvePageRoute (url.pathname)
const prepare = match?.route.handle?.prepare
+2 -1
ファイルの表示
@@ -10,7 +10,8 @@ type Transform = (source: string, id: string) => Promise<{ code: string } | null
export const transformMdx = async (source: string, suffix = '.mdx') => {
const plugins = viteConfig.plugins?.flat () as { name: string; transform: Transform }[]
const config = viteConfig ({ command: 'serve', mode: 'test' })
const plugins = config.plugins?.flat () as { name: string; transform: Transform }[]
const plugin = plugins.find (entry => entry.name === '@mdx-js/rollup')
if (plugin == null)
throw new Error ('The application MDX compiler is not registered')
+4 -2
ファイルの表示
@@ -21,7 +21,9 @@ if (typeof originalTransform === 'function')
}
}
export default defineConfig ({
export default defineConfig (({ command }) => ({
// Production React does not provide jsxDEV, regardless of the build environment.
esbuild: command === 'build' ? { jsxDev: false } : undefined,
plugins: [{ name: 'request-render-context', enforce: 'pre',
resolveId (id, _importer, options) {
const contextPath = path.resolve (__dirname, './src/lib/renderContext')
@@ -40,4 +42,4 @@ export default defineConfig ({
rewrite: requestPath => requestPath.replace (/^\/api/, ''),
secure: false } },
watch: { usePolling: true,
interval: 100 } } })
interval: 100 } } }))
+7 -8
ファイルの表示
@@ -3,11 +3,10 @@ import { defineConfig, mergeConfig } from 'vitest/config'
import viteConfig from './vite.config'
export default mergeConfig (
viteConfig,
defineConfig ({
test: { environment: 'jsdom',
testTimeout: 30_000,
exclude: ['**/node_modules/**', '**/dist/**', 'server.ssr.test.mjs'],
setupFiles: './src/test/setup.ts',
globals: false } }))
export default defineConfig (env => mergeConfig (
viteConfig (env),
{ test: { environment: 'jsdom',
testTimeout: 30_000,
exclude: ['**/node_modules/**', '**/dist/**', 'server.ssr.test.mjs'],
setupFiles: './src/test/setup.ts',
globals: false } }))