AI: address issue #483

このコミットが含まれているのは:
Codex Night Worker
2026-11-17 04:09:38 +09:00
コミット 9c71a9fc02
7個のファイルの変更、358行の追加、46行の削除
+1 -2
ファイルの表示
@@ -18,8 +18,7 @@ class StaticMirrorsController < ApplicationController
locale = resolve_locale!
session[:static_mirror_owner] ||= SecureRandom.hex(32)
job = StaticMirrorJob.start(owner: session[:static_mirror_owner], locale: locale.code,
origin: request.base_url)
job = StaticMirrorJob.start(owner: session[:static_mirror_owner], locale: locale.code)
render json: { job: }, status: :accepted
rescue StaticMirrorJob::Busy
response.headers['Retry-After'] = StaticMirrorJob::COOLDOWN.to_s
+19 -11
ファイルの表示
@@ -8,6 +8,7 @@ class StaticMirrorJob < ApplicationJob
EXPIRY = 10.minutes
COOLDOWN = 60
MAX_SECONDS = 60
ACTIVE = ['queued', 'running'].freeze
class Busy < StandardError; end
def self.directory = Rails.root.join('tmp/static_mirror')
@@ -36,9 +37,19 @@ class StaticMirrorJob < ApplicationJob
File.unlink(path) if path&.exist?
end
def self.start(owner:, locale:, origin:)
def self.expire_stalled(value)
return unless value && ACTIVE.include?(value['status'])
return unless Time.current.to_f - value.fetch('created_at') > MAX_SECONDS + 15
value.merge!('status' => 'failed', 'error' => 'worker_stopped')
write(value)
end
def self.start(owner:, locale:)
id = synchronise do
previous = state
expire_stalled(previous)
raise Busy if previous && ACTIVE.include?(previous['status'])
if previous && Time.current.to_f - previous.fetch('created_at') < COOLDOWN
raise Busy
end
@@ -48,7 +59,7 @@ class StaticMirrorJob < ApplicationJob
FileUtils.rm_f(directory.join('archive.zip'))
FileUtils.rm_f(directory.join('archive.part'))
identifier = SecureRandom.hex(24)
write({ 'id' => identifier, 'owner' => owner, 'locale' => locale, 'origin' => origin,
write({ 'id' => identifier, 'owner' => owner, 'locale' => locale,
'created_at' => Time.current.to_f, 'expiry_at' => (Time.current + EXPIRY).to_f,
'status' => 'queued', 'processed' => 0, 'total' => nil, 'data_at' => nil })
identifier
@@ -66,13 +77,9 @@ class StaticMirrorJob < ApplicationJob
return unless owner.present? && value && value['id'] == id && value['owner'] == owner
return unless value['expiry_at'] > Time.current.to_f
if (['queued', 'running'].include?(value['status']) &&
Time.current.to_f - value['created_at'] > MAX_SECONDS + 15)
value.merge!('status' => 'failed', 'error' => 'worker_stopped')
write(value)
end
expire_stalled(value)
if value['status'] == 'ready'
permitted = HistoryAccess.set(user: nil) { HistoryAccess.authorised_artifact?(value) }
permitted = StaticMirror.authorised_artifact?(value)
return unless permitted && directory.join('archive.zip').file?
end
value
@@ -91,7 +98,7 @@ class StaticMirrorJob < ApplicationJob
bytes = directory.join('archive.zip').binread
# Revalidate after reading; send_data avoids delayed sendfile reuse of a stale path.
permitted = HistoryAccess.set(user: nil) { HistoryAccess.authorised_artifact?(value) }
permitted = StaticMirror.authorised_artifact?(value)
permitted ? bytes : nil
end
end
@@ -109,7 +116,8 @@ class StaticMirrorJob < ApplicationJob
def perform(id)
File.open(self.class.directory.join('.generation.lock'), File::RDWR) do |lock|
return unless lock.flock(File::LOCK_EX | File::LOCK_NB)
# Intake briefly owns this lock. A queued worker must wait, never disappear.
lock.flock(File::LOCK_EX)
value = self.class.state
return unless value && value['id'] == id && value['status'] == 'queued'
@@ -127,7 +135,7 @@ class StaticMirrorJob < ApplicationJob
Timeout.timeout(remaining) do
locale = Locale.find_by!(code: value.fetch('locale'), deprecated_at: nil)
mirror = StaticMirror.new(locale:, origin: value.fetch('origin'))
mirror = StaticMirror.new(locale:)
bytes = mirror.export do |processed, total|
self.class.update(id) do |metadata|
metadata.merge!('processed' => processed, 'total' => total, 'data_at' => mirror.data_at)
+77 -23
ファイルの表示
@@ -6,6 +6,9 @@ require 'uri'
# A deliberately small current-state projection, always under public authority.
class StaticMirror
ORIGIN = 'https://hub.nizika.monster'.freeze
PUBLICATION_POLICY = 'static-mirror-public-projection-1'.freeze
DATA_AT_BASIS = 'capture_started_at'.freeze
RESOURCE_LIMIT = 100
NAME_LIMIT = 2_000
MAX_BYTES = 8.megabytes
@@ -18,7 +21,7 @@ class StaticMirror
attr_reader :data_at, :authority, :counts
def initialize(locale:, origin:)
def initialize(locale:, origin: ORIGIN)
@locale = locale
@origin = validated_url(origin).sub(%r{/+\z}, '')
end
@@ -30,11 +33,12 @@ class StaticMirror
capture
progress&.call(0, @posts.length + @tags.length)
generate_pages(&progress)
raise HistoryAccess::Forbidden unless HistoryAccess.authorised_artifact?(authority)
raise HistoryAccess::Forbidden unless self.class.authorised_artifact?(authority)
generated_at = Time.current.utc
manifest = { format_version: 1, generated_at: generated_at.iso8601(6),
data_at:, locale: @locale.code, resources: counts, exclusions: EXCLUSIONS,
data_at:, data_at_basis: DATA_AT_BASIS,
locale: @locale.code, resources: counts, exclusions: EXCLUSIONS,
fields: { posts: ['id', 'title', 'url', 'tags'], tags: ['id', 'category', 'names'] },
limits: { posts: RESOURCE_LIMIT, tags: RESOURCE_LIMIT, names: NAME_LIMIT,
bytes: MAX_BYTES },
@@ -51,33 +55,80 @@ class StaticMirror
end
end
# Static distribution has no admin mode or Counts aggregate exception.
# Recheck the exact public projection, including edits without a new discard.
def self.authorised_artifact?(metadata)
return false unless metadata['publication_policy'] == PUBLICATION_POLICY
ids = metadata.values_at('post_ids', 'tag_ids')
unless ids.all? { |values|
values.is_a?(Array) && values.length <= RESOURCE_LIMIT &&
values.all? { _1.is_a?(Integer) && _1.positive? }
}
return false
end
HistoryAccess.set(user: nil) do
ApplicationRecord.uncached do
CountsExporter.with_read_snapshot do
Locale.where(code: metadata['locale'], deprecated_at: nil).exists? &&
metadata['history_revision'] == HistoryAccess.revision &&
metadata['content_digest'] == projection_digest(
read_projection(post_ids: ids[0], tag_ids: ids[1]))
end
end
end
rescue TooLarge
false
end
def self.read_projection(post_ids: nil, tag_ids: nil)
posts = confirmed(Post, PostVersion, :post_versions)
tags = confirmed(Tag, TagVersion, :tag_versions).where(deprecated_at: nil)
posts = posts.where(id: post_ids) unless post_ids.nil?
tags = tags.where(id: tag_ids) unless tag_ids.nil?
posts = posts.order(:id).limit(RESOURCE_LIMIT).select(:id, :version_no, :title, :url).to_a
tags = tags.order(:id).limit(RESOURCE_LIMIT).select(:id, :version_no, :category).to_a
names = TagName.where(tag_id: tags.map(&:id)).order(:tag_id, :language_code, :id)
.limit(NAME_LIMIT + 1).pluck(:tag_id, :language_code, :script_code, :name, :primary_flg)
raise TooLarge if names.length > NAME_LIMIT
relations = PostTag.where(post_id: posts.map(&:id), tag_id: tags.map(&:id))
.order(:post_id, :tag_id).pluck(:post_id, :tag_id)
[posts, tags, names, relations]
end
def self.confirmed(model, version_model, association)
# Requiring a matching immutable revision closes the legacy unversioned gap.
HistoryAccess.current(model.all, version_model).joins(association)
.where("#{ version_model.table_name }.version_no = #{ model.table_name }.version_no")
end
def self.projection_digest(projection)
posts, tags, names, relations = projection
Digest::SHA256.hexdigest(JSON.generate(
[posts.map(&:attributes), tags.map(&:attributes), names, relations]))
end
private_class_method :confirmed
private
def capture
# Server clock at capture entry; MySQL establishes the read view later.
@data_at = Time.current.utc.iso8601(6)
CountsExporter.with_read_snapshot do
@data_at = Time.current.utc.iso8601(6)
@authority = HistoryAccess.authority
# Requiring a matching immutable revision closes the legacy unversioned gap.
@posts = confirmed(Post, PostVersion, :post_versions).order(:id)
.limit(RESOURCE_LIMIT).select(:id, :title, :url).to_a
@tags = confirmed(Tag, TagVersion, :tag_versions).where(deprecated_at: nil)
.order(:id).limit(RESOURCE_LIMIT).select(:id, :category).to_a
@names = TagName.where(tag_id: @tags.map(&:id)).order(:tag_id, :language_code, :id)
.limit(NAME_LIMIT + 1).pluck(:tag_id, :language_code, :script_code, :name, :primary_flg)
raise TooLarge if @names.length > NAME_LIMIT
@names = @names.group_by(&:first)
@relations = PostTag.where(post_id: @posts.map(&:id), tag_id: @tags.map(&:id))
.order(:post_id, :tag_id).pluck(:post_id, :tag_id)
projection = self.class.read_projection
@posts, @tags, names, @relations = projection
@authority = { 'publication_policy' => PUBLICATION_POLICY,
'locale' => @locale.code,
'history_revision' => HistoryAccess.revision,
'post_ids' => @posts.map(&:id), 'tag_ids' => @tags.map(&:id),
'content_digest' => self.class.projection_digest(projection) }
@names = names.group_by(&:first)
@counts = { posts: @posts.length, tags: @tags.length }
end
end
def confirmed(model, version_model, association)
HistoryAccess.current(model.all, version_model).joins(association)
.where("#{ version_model.table_name }.version_no = #{ model.table_name }.version_no")
end
def generate_pages
assets = Rails.root.join('app/views/static_mirror')
['archive.css', 'archive.js'].each do |name|
@@ -108,7 +159,10 @@ class StaticMirror
yield(processed, @posts.length + @tags.length) if block_given?
end
index = @posts.map { |post|
{ path: resource_path('posts', post.id), title: post.title.presence || post.id.to_s }
tag_ids = @relations.filter_map { |post_id, tag_id| tag_id if post_id == post.id }
names = tag_ids.flat_map { |id| @names.fetch(id, []).map { _1[3] } }.uniq
{ path: resource_path('posts', post.id), title: post.title.presence || post.id.to_s,
names: }
} + @tags.map { |tag|
{ path: resource_path('tags', tag.id), title: tag_name(tag),
names: @names.fetch(tag.id, []).map { _1[3] } }
+91 -3
ファイルの表示
@@ -38,7 +38,8 @@ RSpec.describe 'Static Mirror API', type: :request do
get "/static_mirror/jobs/#{ id }"
expect(json).to include('status' => 'ready', 'processed' => 1, 'total' => 1)
expect(json.fetch('data_at')).to be_present
expect(json.keys).not_to include('owner', 'origin', 'actor_id', 'policy_revision')
expect(json.keys).not_to include('owner', 'origin', 'actor_id', 'policy_revision',
'publication_policy', 'history_revision', 'post_ids', 'tag_ids', 'content_digest')
get "/static_mirror/files/#{ id }"
expect(response).to have_http_status(:ok)
expect(response.media_type).to eq('application/zip')
@@ -47,6 +48,21 @@ RSpec.describe 'Static Mirror API', type: :request do
expect(response.headers['Cache-Control']).to include('no-store')
end
it 'bakes the canonical source origin regardless of request and forwarded hosts' do
host! 'mirror-intake.test'
post '/static_mirror/jobs', params: { locale: 'ja' }, as: :json,
headers: { 'X-Forwarded-Host' => 'untrusted-source.test',
'X-Forwarded-Proto' => 'https' }
expect(response).to have_http_status(:accepted)
id = json.fetch('job')
expect(StaticMirrorJob.state).not_to have_key('origin')
StaticMirrorJob.perform_now(id)
get "/static_mirror/files/#{ id }"
expect(response).to have_http_status(:ok)
expect(response.body).to include('https://hub.nizika.monster/ja')
expect(response.body).not_to include('mirror-intake.test', 'untrusted-source.test')
end
it 'rejects historical and unknown input instead of pretending to restore it' do
['at', 'data_at', 'admin', 'limit'].each do |key|
post '/static_mirror/jobs', params: { locale: 'ja', key => '2020-01-01' }, as: :json
@@ -87,6 +103,21 @@ RSpec.describe 'Static Mirror API', type: :request do
expect(response).to have_http_status(:not_found)
end
it 'rechecks ready ZIPs after a non-discard content change' do
record = create(:post, title: 'mirror-withdrawn-title')
PostVersion.create!(post: record, version_no: 1, event_type: 'create',
title: record.title, url: record.url, tags: '', tags_json: [], parent_post_ids: '',
created_at: Time.current)
id = create_job
StaticMirrorJob.perform_now(id)
record.update!(title: 'mirror-corrected-title')
get "/static_mirror/jobs/#{ id }"
expect(response).to have_http_status(:not_found)
get "/static_mirror/files/#{ id }"
expect(response).to have_http_status(:not_found)
expect(response.body).not_to include('mirror-withdrawn-title')
end
it 'fails lost jobs and rejects expired downloads' do
id = create_job
travel 80.seconds do
@@ -110,11 +141,68 @@ RSpec.describe 'Static Mirror API', type: :request do
end
end
it 'keeps simultaneous generation bounded after the cooldown' do
it 'preserves the queued reservation after the cooldown' do
id = create_job
travel 61.seconds do
post '/static_mirror/jobs', params: { locale: 'ja' }, as: :json
expect(response).to have_http_status(:too_many_requests)
expect(StaticMirrorJob.state).to include('id' => id, 'status' => 'queued')
expect(StaticMirrorJob).to have_received(:perform_later).once
StaticMirrorJob.perform_now(id)
get "/static_mirror/jobs/#{ id }"
expect(json).to include('status' => 'failed', 'error' => 'generation_timeout')
end
end
it 'reclaims a stalled queued reservation without waiting for a status request' do
id = create_job
travel 80.seconds do
second_id = create_job
expect(second_id).not_to eq(id)
StaticMirrorJob.perform_now(id)
expect(StaticMirrorJob.state).to include('id' => second_id, 'status' => 'queued')
StaticMirrorJob.perform_now(second_id)
get "/static_mirror/jobs/#{ second_id }"
expect(json).to include('status' => 'ready')
end
end
it 'waits for brief intake lock contention instead of losing the queued worker' do
id = create_job
path = StaticMirrorJob.directory.join('.generation.lock')
lock = File.open(path, File::RDWR)
lock.flock(File::LOCK_EX)
attempts = Queue.new
worker = StaticMirrorJob.new
allow(worker).to receive(:generate)
allow(File).to receive(:open).and_call_original
allow(File).to receive(:open).with(path, File::RDWR).and_wrap_original do |original, *args, &block|
original.call(*args) do |file|
allow(file).to receive(:flock).and_wrap_original do |flock, mode|
attempts << mode
flock.call(mode)
end
block.call(file)
end
end
thread = Thread.new { worker.perform(id) }
Timeout.timeout(5) do
expect(attempts.pop).to eq(File::LOCK_EX)
lock.close
thread.join
end
expect(worker).to have_received(:generate).with(id, hash_including('status' => 'queued'))
ensure
lock&.close unless lock&.closed?
thread&.kill
thread&.join
end
it 'keeps the generation lock reserved even when stale metadata expires' do
create_job
lock = File.open(StaticMirrorJob.directory.join('.generation.lock'), File::RDWR)
lock.flock(File::LOCK_EX)
travel 61.seconds do
travel 80.seconds do
post '/static_mirror/jobs', params: { locale: 'ja' }, as: :json
expect(response).to have_http_status(:too_many_requests)
end
+93 -2
ファイルの表示
@@ -2,6 +2,7 @@ require 'rails_helper'
RSpec.describe StaticMirror do
include_context 'Ainu locale'
include ActiveSupport::Testing::TimeHelpers
let(:tag) { create(:tag, primary_name: 'mirror-public-tag') }
let(:post) { create(:post, title: '<img src=x onerror=alert(1)>') }
@@ -72,7 +73,8 @@ RSpec.describe StaticMirror do
.to include("../../tags/#{ tag.id }/index.html")
manifest = JSON.parse(files.fetch('manifest.json'))
expect(manifest).to include('format_version' => 1, 'locale' => 'ja',
'data_at' => mirror.data_at, 'resources' => { 'posts' => 1, 'tags' => 1 })
'data_at' => mirror.data_at, 'data_at_basis' => 'capture_started_at',
'resources' => { 'posts' => 1, 'tags' => 1 })
expect(Time.iso8601(manifest.fetch('generated_at'))).to be >= Time.iso8601(mirror.data_at)
expect(manifest.fetch('files').map { _1.fetch('path') })
.to match_array(files.keys - ['manifest.json'])
@@ -101,7 +103,9 @@ RSpec.describe StaticMirror do
expect(files.values.join).not_to include('mirror-secret', legacy.title, private_post.url)
expect(files.keys).not_to include("ja/tags/#{ private_tag.id }/index.html",
"ja/posts/#{ private_post.id }/index.html", "ja/posts/#{ referencing.id }/index.html")
expect(mirror.authority.fetch('admin')).to be(false)
expect(mirror.authority.fetch('publication_policy'))
.to eq('static-mirror-public-projection-1')
expect(mirror.authority.keys).not_to include('admin', 'actor_id', 'artifact_policy')
end
it 'applies later discard boundaries after a restoration' do
@@ -132,6 +136,74 @@ RSpec.describe StaticMirror do
end.to raise_error(HistoryAccess::Forbidden)
end
it 'owns the static publication contract independently of Counts' do
allow(HistoryAccess).to receive(:authority).and_raise('Counts metadata is not applicable')
allow(HistoryAccess).to receive(:authorised_artifact?).and_return(false)
archive_files(mirror.export)
expect(described_class.authorised_artifact?(mirror.authority)).to be(true)
metadata = mirror.authority.except('publication_policy')
.merge('artifact_policy' => HistoryAccess::ARTIFACT_POLICY)
expect(described_class.authorised_artifact?(metadata)).to be(false)
stub_const('HistoryAccess::ARTIFACT_POLICY', 'another-counts-policy')
expect(described_class.authorised_artifact?(mirror.authority)).to be(true)
end
it 'rejects stale projections after edits without discard, including for admins' do
create(:tag_name, :alias, tag:, name: 'mirror-old-alias')
archive_files(mirror.export)
HistoryAccess.set(user: create(:user, :admin)) do
expect(described_class.authorised_artifact?(mirror.authority)).to be(true)
TagName.find_by!(tag:, name: 'mirror-old-alias').update!(name: 'mirror-new-alias')
expect(described_class.authorised_artifact?(mirror.authority)).to be(false)
end
end
it 'rejects a deprecated tag and its names without requiring a discard' do
archive_files(mirror.export)
tag.update!(deprecated_at: Time.current)
expect(described_class.authorised_artifact?(mirror.authority)).to be(false)
files = archive_files(mirror.export)
expect(files.keys).not_to include("ja/tags/#{ tag.id }/index.html")
expect(files.values.join).not_to include('mirror-public-tag')
end
it 'rejects stale post content and relations without a discard' do
archive_files(mirror.export)
post.update!(title: 'mirror-corrected-title')
expect(described_class.authorised_artifact?(mirror.authority)).to be(false)
archive_files(mirror.export)
PostTag.where(post:, tag:).delete_all
expect(described_class.authorised_artifact?(mirror.authority)).to be(false)
end
it 'rejects an artifact after its locale is deprecated' do
archive_files(mirror.export)
Locale.nipponese.update!(deprecated_at: Time.current)
expect(described_class.authorised_artifact?(mirror.authority)).to be(false)
end
it 'fails if a tag is deprecated during generation' do
expect do
mirror.export do |processed, _total|
tag.update!(deprecated_at: Time.current) if processed.zero?
end
end.to raise_error(HistoryAccess::Forbidden)
end
it 'records capture entry rather than claiming the exact DB read-view time' do
freeze_time do
capture_at = Time.current.utc.iso8601(6)
allow(CountsExporter).to receive(:with_read_snapshot).and_wrap_original do |original, &block|
travel 5.seconds
original.call(&block)
end
files = archive_files(mirror.export)
manifest = JSON.parse(files.fetch('manifest.json'))
expect(manifest).to include('data_at' => capture_at, 'data_at_basis' => 'capture_started_at')
expect(Time.iso8601(manifest.fetch('generated_at'))).to be > Time.iso8601(capture_at)
end
end
it 'bounds output and never reports hidden population counts' do
stub_const('StaticMirror::RESOURCE_LIMIT', 1)
second = create(:post, title: 'mirror-beyond-limit')
@@ -148,6 +220,25 @@ RSpec.describe StaticMirror do
files = archive_files(described_class.new(locale:, origin: 'https://source.test').export)
detail = files.fetch("ain-Kana/tags/#{ tag.id }/index.html")
expect(detail).to include('mirror-public-tag', 'mirror-alias', 'lang="ain"', 'lang="ja"')
index = JSON.parse(files.fetch('search-index.json'))
entry = index.find { _1.fetch('path') == "ain-Kana/posts/#{ post.id }/index.html" }
expect(entry.fetch('names')).to include('mirror-public-tag', 'mirror-alias')
end
it 'indexes only names of public linked tags within the output limit' do
other = create(:tag, primary_name: 'mirror-unlinked-tag')
snapshot_tag(other)
private_tag = create(:tag, primary_name: 'mirror-private-tag')
snapshot_tag(private_tag, event: 'discard')
PostTag.create!(post:, tag: private_tag)
files = archive_files(mirror.export)
index = JSON.parse(files.fetch('search-index.json'))
entry = index.find { _1.fetch('path') == "ja/posts/#{ post.id }/index.html" }
expect(entry.fetch('names')).to include('mirror-public-tag')
expect(entry.fetch('names')).not_to include('mirror-private-tag', 'mirror-unlinked-tag')
stub_const('StaticMirror::RESOURCE_LIMIT', 1)
expect(archive_files(mirror.export).fetch('search-index.json'))
.not_to include('mirror-unlinked-tag', 'mirror-private-tag')
end
it 'fails rather than truncating registered aliases at the name limit' do
+61 -5
ファイルの表示
@@ -24,11 +24,15 @@ Vite の既存 `/api` proxy は3002番ポートを参照する。これらの起
一覧・詳細・相互リンクは JavaScript 無効でも利用できる。検索は HTTP 配信した
`search-index.json` を JavaScript が読む。`file://` からの検索は保証しない。
Post はタイトルに加えて、出力対象の関連 Tag の全言語名・別名から検索できる。
非公開・廃止・件数上限外の Tag や、関連しない Tag の名前は Post の検索項目に含めない。
外部動画・画像・サムネール・素材ファイルは取得も同梱もしない。Post の外部 URL は
通常のリンクとして残すため、そのリンク先の閲覧は外部サイトの存続に依存する。
各 HTML に静的保存版の表示、UTC のデータ基準時点、`noindex, nofollow`、
本家への絶対リンクを焼き込む。内部リンク・CSS・JS は相対参照。
本家リンクの初期オリジンは `https://hub.nizika.monster`。request の Host、
forwarded header、API のオリジンは採用しない。
`archive-config.js` の `window.archiveConfig.origin` を HTTP(S) の本家基点 URL
(例: `https://example.org`)に変更すれば本家リンクをまとめて変更できる。
設定 JS が削除・欠落・不正な場合や JS 無効時にも HTML の初期リンクが残る。
@@ -54,6 +58,8 @@ URL に JSON を格納しない。`at` 等の任意時点入力・未知の生
- 同時実行1件、全セッションを通じて新規登録は60秒に1件、登録から処理期限60秒。
競合・受付制限は429と `Retry-After`。状態取得・取得時の短いロック競合は503。
- ZIP とジョブの認可期限は10分。次のジョブ登録で前の ZIP / ジョブは置き換える。
queued / running の予約は cooldown が過ぎても置き換えない。75秒を超えた予約は
状態取得又は次の受付で failed にし、実行ロックが空いている場合だけ次を受け付ける。
期限後も最後のファイルがディスクに残り得るが、API では取得できない。
容量は単一 ZIP と作業ファイルに限定され、無制限に蓄積しない。
@@ -63,7 +69,9 @@ Rails の既存 Active Job と `:async` adapter を使い、生成は HTTP reque
受付・状態・ZIP は `backend/tmp/static_mirror/` の単一 spool を使う。
プロセス間の filesystem lock で実行枠と更新を制御する。各ファイルは0600、directory は
0700で作成する。Web プロセス再起動で非永続キューが失われる点が PoC の限界。
進まない queued / running は75秒後の状態取得で failed になる。再開や再実行はしない。
進まない queued / running は75秒経過後の状態取得又は次の受付で failed になる。
worker は受付中の短い実行ロック競合を待ち、競合だけを理由に queued を放棄しない。
再開や再実行はしない。実行ロック待ちも登録からの60秒の処理期限に含まれる。
失敗コードは `too_large`、`generation_timeout`、`publication_changed`、
`generation_failed`、`worker_stopped`。内部の例外本文・パス・資源属性は応答に含めない。
@@ -78,19 +86,47 @@ legacy record は安全側で対象外とする。公開不可の参照を含む
廃止 Tag は対象外。HTML / 検索 JSON / manifest の件数には認可済みの出力集合だけが入る。
user、actor、履歴版番号、監査、認証、blob 情報は投影しない。
公開条件の調査範囲は V1 の Post / Tag / TagName / Locale の model、schema、
閲覧 controller・representation、HistoryAccess と Material の抑止経路。
Post / Tag / TagName には別の private / visibility カラムや、汎用の公開抑止 scope は
見つからなかった。Tag の `deprecated_at` は除票とは別の廃止状態で、通常の Post
表示からも除外されるため、ミラーから引き続き除外する。Locale の廃止後も配布しない。
`MaterialImportBlock`、`MaterialSyncSuppression` は著作権・個人情報等を理由にした
素材取込・同期の抑止であり、Post / Tag の汎用認可として流用しない。Material と
関連ファイル・監査用の理由・同期元情報は全て出力対象外のままにする。
既存の通常 Post / Tag 閲覧経路が共通認可を一律適用しているとは仮定せず、
ミラー自身は必ず HistoryAccess を経由する。新たな抑止条件を導入する場合には
適用範囲を確認して共通認可と静的配布契約を更新する必要がある。
`CountsExporter.with_read_snapshot` の既存 repeatable-read 境界を再利用し、Post、Tag、
全言語 TagName、PostTag、publication revision を同じ読み取り view から取得する。
これには既存 HistoryAccess の SQL が動作する MySQL 環境が必要。未対応の adapter や
未整備の DB では生成失敗とし、認可を迂回した出力へフォールバックしない。
`data_at` はこの現在状態読み取りの開始時刻であり、履歴の指定日時復元を表さない。
`data_at` は DB 読み取り transaction を要求する直前の、取得処理開始時の
サーバー時計(UTC)。manifest の `data_at_basis: capture_started_at` に意味を記録する。
MySQL の read view は後の最初の consistent read で成立するため、その厳密な成立時刻や
`data_at` 以前のコミットだけを含むことは保証しない。履歴の指定日時復元も表さない。
独立した worker では repeatable-read を開始するが、呼出元の transaction がある場合は
既存 helper の契約どおり、その transaction の view と分離レベルを引き継ぐ。
`generated_at` はファイル生成後の別の時刻。
生成の最後と状態・ZIP 取得時に既存 artifact policy / discard revision を再検証する。
静的配布契約は `StaticMirror::PUBLICATION_POLICY` の
`static-mirror-public-projection-1`。Counts 用 `HistoryAccess::ARTIFACT_POLICY`、
`authority`、`authorised_artifact?` は使わない。共通 HistoryAccess の現在版認可と
全後続除票の revision 検知は再利用し、集計件数の例外や admin の配布モードは設けない。
旧 Counts 契約の metadata しかない ZIP は再生成を必要とする。
生成の最後と状態・ZIP 取得時に、別の読み取り transaction で共通 discard revision と
出力対象 ID の公開投影を再取得する。SQL query cache を使わず、対象の存在、確定版、
Tag / Locale の廃止、タイトル・URL・category、全言語名・別名・文字体系、関連の変更を
検知する。除票を伴わない訂正・削除も投影 digest の不一致として配布を止める。
対象 ID と digest はサーバー側ジョブ metadata にだけ置き、manifest や API 状態応答へ
出さない。対象は各100件・名前2,000行以内の一括取得で、行ごとの追加 query は行わない。
生成中の除票は失敗にし、生成後の除票では古い ZIP の再取得を404にする。
ZIP は再認可後のバイト列として返し、遅延 sendfile に古いパスを渡さない。
HTTP 応答は既存境界の `private, no-store`。ダウンロード済み ZIP の回収や、
最終認可と送出の間に発生する公開制御変更の完全な排他は保証できない。
新しい公開制御を導入する場合は共通 policy と artifact revision の連動が必要。
新しい公開制御を導入する場合は共通 policy と静的配布契約の連動が必要。
本文・名前・URL は escape する。外部リンクは HTTP(S)・host・userinfo 不在を検証し、
不正な URL はリンクとして出さない。外部 URL の取得は行わないため SSRF 用 DNS 検査を
@@ -132,14 +168,20 @@ HTTP 応答は既存境界の `private, no-store`。ダウンロード済み ZIP
- `backend/spec/services/static_mirror_spec.rb`: ZIP の CRC / 構造、全ファイルの hash、
内部参照、escape、基準時点、公開権限、後続除票、言語名・別名、容量・件数上限。
今回は Counts 契約との独立性、除票なしの訂正・廃止・関連変更、取得開始時刻の意味、
Post 検索への関連名の投影を追加。
- `backend/spec/requests/static_mirrors_spec.rb`: 一般受付、非同期境界、所有権、
公開制御変更、失敗・期限・競合・全体 rate limit、開発環境制限、CSRF と BAN。
今回は Host に依存しない本家リンク、訂正後の取得拒否、queued 予約の保持・期限切れ、
実 filesystem lock を使う受付競合待ちを追加。
- `frontend/src/pages/StaticMirrorPage.test.tsx`: 開始、進捗、取得、失敗、
受付エラー、認可喪失、日本語 fallback の言語属性。
- `frontend/src/lib/staticMirrorAssets.test.ts`: 静的検索の相対参照・escape と
サブディレクトリ配備、本家設定の欠落・不正・変更。
今回は Tag 名・別名から関連 Post が見つかるケースを追加。検索 JS の変更は不要。
実施したのは既存コードの調査と差分の目視確認のみ。テスト、lint、build、型検査、
実施したのは既存コードの調査、差分の目視確認と `git diff --check`(成功)。
テスト、lint、build、型検査、
migration、実ブラウザーでの表示、ZIP 展開・HTTP 配置は実行していない。
管理者指定の suite による結果確認と、サブディレクトリ配置・JS 無効・原サーバー停止・
設定 JS 欠落・静的検索の実画面確認が残る。
@@ -149,6 +191,20 @@ rate limit、容量・時間・負荷の実測、公開制御の監査と変更
asset の権利・保管方針、追加 resource の安全な投影、UI 文言・翻訳の確定が必要。
本 PoC の開発環境制限を単に外して公開することは想定しない。
## 今回のレビュー対応の変更ファイル
| ファイル | 修正と理由 |
| --- | --- |
| `backend/app/controllers/static_mirrors_controller.rb` | request オリジンを生成処理へ渡さず、本家リンクへの Host 混入を防止 |
| `backend/app/jobs/static_mirror_job.rb` | 静的配布専用の再認可、queued 予約と期限切れの共通処理、worker のロック待ちでジョブ消失を防止 |
| `backend/app/services/static_mirror.rb` | Counts と独立した公開投影の再検証、関連 Tag 名を含む Post 検索、正規の本家リンク初期値、`data_at_basis` |
| `backend/spec/services/static_mirror_spec.rb` | 専用契約・訂正・廃止・関連変更・検索投影・時刻意味の回帰テスト |
| `backend/spec/requests/static_mirrors_spec.rb` | 本家オリジン・ZIP 再認可・queued 予約・実行ロック競合の回帰テスト |
| `frontend/src/lib/staticMirrorAssets.test.ts` | 名前・別名を使う Post 検索の回帰テスト |
| `docs/static-mirror.md` | 公開条件の調査結果、配布契約、ロックと時刻の保証範囲・未解決事項を更新 |
V2、DB schema / migration、既存の Counts 契約・共通認可、UI 文言は変更していない。
## 変更ファイルの責務
| ファイル | 責務 |
+16
ファイルの表示
@@ -56,4 +56,20 @@ describe ('Portable static mirror assets', () => {
expect (document.querySelector ('a:not([data-original])'))
.toHaveAttribute ('href', 'ja/posts/index.html')
})
it.each (['tag name', 'alias']) ('finds linked posts by %s', async query => {
const input = document.querySelector ('input')!
input.value = query
vi.stubGlobal ('fetch', vi.fn ().mockResolvedValue ({ ok: true, json: async () => [
{ path: 'ja/posts/1/index.html', title: 'Post title', names: ['Tag Name', 'Alias'] },
{ path: 'ja/posts/2/index.html', title: 'Unrelated post', names: ['Other tag'] },
{ path: 'ja/tags/1/index.html', title: 'Tag Name', names: ['Tag Name', 'Alias'] }] }))
new Function (script) ()
fireEvent.submit (document.querySelector ('form')!)
await waitFor (() => expect (document.querySelectorAll ('#search-results a')).toHaveLength (2))
const links = [...document.querySelectorAll ('#search-results a')]
expect (links.map (link => link.getAttribute ('href')))
.toEqual (['ja/posts/1/index.html', 'ja/tags/1/index.html'])
expect (links[0].textContent).toBe ('Post title')
})
})