diff --git a/app/jobs/capture_job.rb b/app/jobs/capture_job.rb
index eddf7c5..7e2121a 100644
--- a/app/jobs/capture_job.rb
+++ b/app/jobs/capture_job.rb
@@ -12,7 +12,7 @@ class CaptureJob < ApplicationJob
def perform(capture)
return if capture.finished?
- capture.update!(status: "running", started_at: Time.current, error: nil)
+ capture.update!(status: "running", started_at: Time.current, error: nil, error_code: nil)
Dir.mktmpdir("stash-#{capture.method_name}-") do |workdir|
outputs = capture.capturer.new(capture, workdir).call
store(capture, outputs)
@@ -21,9 +21,9 @@ def perform(capture)
rescue Capturers::Skip => e
finish(capture, "skipped", error: e.message)
rescue Capturers::Error => e
- finish(capture, "failed", error: "#{e.class.name.demodulize}: #{e.message}")
+ finish(capture, "failed", error: "#{e.class.name.demodulize}: #{e.message}", error_code: e.code)
rescue StandardError => e
- finish(capture, "failed", error: "#{e.class}: #{e.message.to_s.first(500)}")
+ finish(capture, "failed", error: "#{e.class}: #{e.message.to_s.first(500)}", error_code: "unexpected")
raise
end
@@ -41,8 +41,11 @@ def store(capture, outputs)
end
end
- def finish(capture, status, error: nil)
- capture.update!(status: status, error: error, finished_at: Time.current)
+ def finish(capture, status, error: nil, error_code: nil)
+ # An error class that is not in CODES (a bare Capturers::Error, a new subclass) must not
+ # leave the capture running on a validation error.
+ error_code = "unexpected" if error_code && Capturers::CODES.exclude?(error_code)
+ capture.update!(status: status, error: error, error_code: error_code, finished_at: Time.current)
capture.archive.refresh_status!
end
end
diff --git a/app/models/archive.rb b/app/models/archive.rb
index 92fd5db..ff6d5ed 100644
--- a/app/models/archive.rb
+++ b/app/models/archive.rb
@@ -68,6 +68,18 @@ def finished?
%w[done partial failed].include?(status)
end
+ # What stopped the archive, when something did: the failed capture whose error code matters
+ # most to the person who submitted the URL (Capturers::CODES order), as a hash with the code,
+ # the method, the message and a hint for a person. Nil while nothing has failed.
+ def problem
+ failed = captures.select { |c| c.status == "failed" }
+ return nil if failed.empty?
+
+ capture = failed.min_by { |c| [ Capturers::CODES.index(c.error_code) || Capturers::CODES.size, c.position ] }
+ code = capture.error_code || "tool_failed"
+ { code: code, method: capture.method_name, message: capture.error, hint: Capturers.hint(code) }
+ end
+
def title
"#{host} ยท #{kind}"
end
diff --git a/app/models/capture.rb b/app/models/capture.rb
index 21fa6b2..a03f3a6 100644
--- a/app/models/capture.rb
+++ b/app/models/capture.rb
@@ -4,7 +4,9 @@
# queued waiting for a worker
# running the capturer is running
# done the capturer stored its artifacts
-# failed the capturer raised, timed out or passed the size limit; `error` says which
+# failed the capturer raised, timed out or passed the size limit; `error` says which, and
+# `error_code` is the reason in one word (Capturers::CODES: not_public, not_found,
+# blocked, too_large, timeout, tool_failed, unexpected)
# skipped the method does not apply after all (for example, HEAD said the URL is HTML, so no file)
#
# A capture is never deleted when it fails, so the archive shows what was tried.
@@ -22,6 +24,7 @@ class Capture < CentralRecord
validates :method_name, inclusion: { in: METHODS }, uniqueness: { scope: :archive_id }
validates :status, inclusion: { in: STATUSES }
validates :position, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
+ validates :error_code, inclusion: { in: Capturers::CODES }, allow_nil: true
scope :unfinished, -> { where(status: %w[queued running]) }
diff --git a/app/serializers/archive_serializer.rb b/app/serializers/archive_serializer.rb
index 239db65..6dce21d 100644
--- a/app/serializers/archive_serializer.rb
+++ b/app/serializers/archive_serializer.rb
@@ -21,6 +21,7 @@ def as_json(*)
created_at: a.created_at&.iso8601,
completed_at: a.completed_at&.iso8601,
page_url: archive_url(a, host: default_host),
+ problem: a.problem,
captures: a.captures.map { |c| capture_json(c) }
}
end
@@ -33,6 +34,7 @@ def capture_json(capture)
method: capture.method_name,
status: capture.status,
error: capture.error,
+ error_code: capture.error_code,
started_at: capture.started_at&.iso8601,
finished_at: capture.finished_at&.iso8601,
artifacts: capture.artifacts.map { |artifact| artifact_json(artifact) }
diff --git a/app/services/capturers.rb b/app/services/capturers.rb
index 612dc09..a2a78d4 100644
--- a/app/services/capturers.rb
+++ b/app/services/capturers.rb
@@ -6,15 +6,73 @@
# argument (never a shell string), a timeout and an output cap. A capturer never runs code from
# the archived content.
module Capturers
- class Error < StandardError; end
+ # A capture that cannot finish raises one of these. The class is the reason, in a form a
+ # patch app can act on: `code` goes into `captures.error_code` and into the API, the message
+ # into `captures.error`. Capturers.hint(code) is the sentence for the person who can fix it.
+ class Error < StandardError
+ # The HTTP status that caused it, when one did.
+ attr_accessor :http_status
+ # The output of the tool that failed, when one did (Base#run!).
+ attr_accessor :tool_output
+
+ def self.code
+ name.demodulize.underscore
+ end
+
+ def code
+ self.class.code
+ end
+ end
+
# The method does not apply to this URL after all. The capture becomes `skipped`.
class Skip < Error; end
# The tool ran past CAPTURE_TIMEOUT.
class Timeout < Error; end
# The output passed CAPTURE_MAX_BYTES.
class TooLarge < Error; end
- # The tool exited with an error.
+ # The tool exited with an error, and nothing more specific is known.
class ToolFailed < Error; end
+ # The source needs a sign-in or a share: a private repository, a Google document that is not
+ # shared with anyone with the link, a private video. The owner can fix it.
+ class NotPublic < Error; end
+ # Nothing is at the URL: 404 or 410, a deleted video, a repository that is gone.
+ class NotFound < Error; end
+ # The host refused the archiver: 403, 429, an anti-bot wall. Later may work.
+ class Blocked < Error; end
+
+ # The error codes a capture can carry, in the order that matters most to the person who
+ # submitted the URL. Archive#problem picks the first one present.
+ CODES = %w[not_public not_found blocked too_large timeout tool_failed unexpected].freeze
+
+ HINTS = {
+ "not_public" => "The source is private. Ask the owner to share it with anyone with the link, or to send a public URL, then run the archive again.",
+ "not_found" => "Nothing is at that URL. Ask for the right link, then run the archive again.",
+ "blocked" => "The site refused the archiver. Run the archive again later.",
+ "too_large" => "The file is larger than the size limit.",
+ "timeout" => "The capture ran out of time. Run the archive again.",
+ "tool_failed" => "The capture tool failed. Run the archive again. If it fails the same way, it is a Stash problem.",
+ "unexpected" => "Stash hit an unexpected error. Run the archive again. If it fails the same way, it is a Stash problem."
+ }.freeze
+
+ # One sentence for a person, for a code. Unknown codes get the generic one.
+ def self.hint(code)
+ HINTS.fetch(code.to_s, HINTS["tool_failed"])
+ end
+
+ # Builds the error for an HTTP status: 401 needs a sign-in, 403 and 429 are a refusal, 404 and
+ # 410 mean gone, anything else is a plain failure.
+ def self.http_error(status, message)
+ klass =
+ case status.to_i
+ when 401 then NotPublic
+ when 403, 429 then Blocked
+ when 404, 410 then NotFound
+ else ToolFailed
+ end
+ error = klass.new(message)
+ error.http_status = status.to_i
+ error
+ end
# One file for CaptureJob to store. `path` is inside the work directory.
Output = Data.define(:role, :path, :filename, :content_type)
diff --git a/app/services/capturers/base.rb b/app/services/capturers/base.rb
index 7d461da..04a2012 100644
--- a/app/services/capturers/base.rb
+++ b/app/services/capturers/base.rb
@@ -26,11 +26,33 @@ def log(line)
def run!(*command, env: {}, timeout: Capturers.timeout)
log("$ #{command.map { |part| part.to_s.include?(" ") ? part.to_s.inspect : part }.join(" ")}")
result = Subprocess.run(*command, chdir: workdir, timeout: timeout, env: env) { |line| log(line) }
- raise ToolFailed, "#{command.first} exited with status #{result.status.exitstatus}" unless result.success?
+ unless result.success?
+ error = ToolFailed.new("#{command.first} exited with status #{result.status.exitstatus}")
+ error.tool_output = result.output
+ raise error
+ end
result
end
+ # Runs the block, and when a tool fails, reads the tool's own output (never the command
+ # line or the URL) for the reason: a sign-in or a share that is missing (NotPublic) or a
+ # source that is gone (NotFound). Any other failure stays a ToolFailed. `tool` names the
+ # tool in the message.
+ def classify_tool_failure(tool, not_public:, not_found:)
+ yield
+ rescue ToolFailed => e
+ output = e.tool_output.to_s.last(4.kilobytes)
+ if not_public.any? { |pattern| output.match?(pattern) }
+ raise NotPublic, "#{tool}: the source is private or needs a sign-in. " \
+ "Ask the owner to make it public, then run the archive again. (#{e.message})"
+ elsif not_found.any? { |pattern| output.match?(pattern) }
+ raise NotFound, "#{tool}: the source is gone or the URL is wrong. (#{e.message})"
+ end
+
+ raise
+ end
+
def path(name)
::File.join(workdir, name)
end
diff --git a/app/services/capturers/document.rb b/app/services/capturers/document.rb
index 04ddff4..2ea3c9e 100644
--- a/app/services/capturers/document.rb
+++ b/app/services/capturers/document.rb
@@ -24,11 +24,14 @@ def call
private
+ GOOGLE_NAMES = { "document" => "Google Doc", "presentation" => "Google Slides deck",
+ "spreadsheets" => "Google Sheet", "drawings" => "Google Drawing" }.freeze
+
def google(kind, id)
export = GOOGLE_EXPORTS.fetch(kind)
- native = Download.fetch(google_export_url(kind, id, export[:native]), to: path("document.#{export[:native]}"))
+ native = google_export(kind, id, export[:native], export[:type])
log("Google export: #{native.byte_size} bytes as #{export[:native]}")
- pdf = Download.fetch(google_export_url(kind, id, "pdf"), to: path("document.pdf"))
+ pdf = google_export(kind, id, "pdf", "application/pdf")
log("Google export: #{pdf.byte_size} bytes as pdf")
[
output("original", "document.#{export[:native]}", content_type: export[:type], filename: "#{id}.#{export[:native]}"),
@@ -36,6 +39,37 @@ def google(kind, id)
]
end
+ # One Google export. A document that is not shared with anyone with the link answers 404,
+ # or 401, or a 302 to the Google sign-in page (a 200 of HTML on another host), the same as
+ # one that does not exist. Every one of those is NotPublic: the owner has to act. A 429
+ # stays Blocked: Google is rate limiting, and later works.
+ def google_export(kind, id, format, expected_type)
+ fetched =
+ begin
+ Download.fetch(google_export_url(kind, id, format), to: path("document.#{format}"))
+ rescue NotFound, NotPublic => e
+ raise not_shared(kind, e.http_status)
+ rescue Blocked => e
+ raise not_shared(kind, e.http_status) if e.http_status == 403
+
+ raise
+ end
+ served = fetched.content_type.to_s
+ if fetched.uri.host != "docs.google.com" || Router::HTML_TYPES.include?(served) || !served.start_with?(expected_type)
+ log("Google export answered #{served} from #{fetched.uri.host}, not the #{format}")
+ raise not_shared(kind, "a sign-in page")
+ end
+ fetched
+ end
+
+ def not_shared(kind, answer)
+ error = NotPublic.new("Google answered #{answer} for the #{GOOGLE_NAMES.fetch(kind)}: " \
+ "it is not shared with anyone with the link, or it does not exist. " \
+ "Ask the owner to share it, then run the archive again.")
+ error.http_status = answer if answer.is_a?(Integer)
+ error
+ end
+
def google_export_url(kind, id, format)
case kind
when "presentation", "drawings" then "https://docs.google.com/#{kind}/d/#{id}/export/#{format}"
diff --git a/app/services/capturers/download.rb b/app/services/capturers/download.rb
index 5d58bcb..c181a3f 100644
--- a/app/services/capturers/download.rb
+++ b/app/services/capturers/download.rb
@@ -11,8 +11,9 @@ module Download
Fetched = Data.define(:uri, :content_type, :filename, :path, :byte_size)
- # Downloads the URL into `to`. Returns a Fetched. Raises TooLarge past the cap, ToolFailed on an
- # HTTP error.
+ # Downloads the URL into `to`. Returns a Fetched. Raises TooLarge past the cap, and on an HTTP
+ # error the class for its status (Capturers.http_error): NotPublic, Blocked, NotFound or
+ # ToolFailed.
def self.fetch(url, to:, max_bytes: Capturers.max_bytes)
uri = URI.parse(url)
MAX_REDIRECTS.times do
@@ -42,7 +43,7 @@ def self.fetch(url, to:, max_bytes: Capturers.max_bytes)
result = Fetched.new(uri: uri, content_type: content_type_of(response), filename: filename_of(response, uri),
path: to, byte_size: size)
else
- raise ToolFailed, "GET #{uri.host} answered #{response.code}"
+ raise Capturers.http_error(response.code, "GET #{uri.host} answered #{response.code}")
end
end
end
diff --git a/app/services/capturers/gallery.rb b/app/services/capturers/gallery.rb
index 0f84866..1b28f9d 100644
--- a/app/services/capturers/gallery.rb
+++ b/app/services/capturers/gallery.rb
@@ -8,7 +8,11 @@ def call
command += [ "--cookies", ENV["YTDLP_COOKIES_FILE"] ] if ENV["YTDLP_COOKIES_FILE"].present?
command += [ "--proxy", ENV["YTDLP_PROXY"] ] if ENV["YTDLP_PROXY"].present?
command << "--" << url
- run!(*command, env: { "HOME" => workdir })
+ classify_tool_failure("gallery-dl",
+ not_public: [ /login required/i, /AuthenticationError/i, /AuthorizationError/i, /account is private/i, /private account/i ],
+ not_found: [ /NotFoundError/i, /HttpError.*404/i, /HttpError.*410/i ]) do
+ run!(*command, env: { "HOME" => workdir })
+ end
files = Dir.glob(path("post/**/*")).select { |f| ::File.file?(f) }.sort
raise ToolFailed, "gallery-dl downloaded nothing" if files.empty?
diff --git a/app/services/capturers/git.rb b/app/services/capturers/git.rb
index 7f89be4..95f3244 100644
--- a/app/services/capturers/git.rb
+++ b/app/services/capturers/git.rb
@@ -5,7 +5,11 @@ class Git < Base
def call
clone_url = clone_url_for(url)
log("git: cloning #{clone_url}")
- run!("git", "clone", "--mirror", "--quiet", clone_url, "repo.git")
+ classify_tool_failure("git clone",
+ not_public: [ /Authentication failed/i, /could not read Username/i, /Permission denied/i, /authentication required/i ],
+ not_found: [ /Repository not found/i, /not found/i, /does not exist/i ]) do
+ run!("git", "clone", "--mirror", "--quiet", clone_url, "repo.git")
+ end
run!("git", "-C", "repo.git", "bundle", "create", "../repo.bundle", "--all")
refs = run!("git", "-C", "repo.git", "for-each-ref", "--format=%(objectname) %(refname)").output
head = run!("git", "-C", "repo.git", "symbolic-ref", "HEAD").output.strip
diff --git a/app/services/capturers/github.rb b/app/services/capturers/github.rb
index 4388e3c..a9adbe0 100644
--- a/app/services/capturers/github.rb
+++ b/app/services/capturers/github.rb
@@ -46,12 +46,22 @@ def get(route, raw: false, allow_missing: false, allow_empty: false)
when Net::HTTPSuccess then raw ? response.body : JSON.parse(response.body)
when Net::HTTPNotFound
return nil if allow_missing
- raise ToolFailed, "GitHub answered 404 for #{uri.path}: the repository is private or gone"
+ # GitHub answers 404 for a private repository too, so the owner is the one to ask.
+ error = NotPublic.new("GitHub answered 404 for #{uri.path}: the repository is private or gone. " \
+ "Ask the owner to make it public, then run the archive again.")
+ error.http_status = 404
+ raise error
when Net::HTTPNoContent, Net::HTTPAccepted
return [] if allow_empty
raise ToolFailed, "GitHub answered #{response.code} for #{uri.path}"
+ when Net::HTTPUnauthorized
+ # Public repositories need no token, so a 401 means GITHUB_TOKEN is bad, not the source.
+ raise ToolFailed, "GitHub rejected GITHUB_TOKEN (401). Fix the token in the env file, then run the archive again."
+ when Net::HTTPForbidden, Net::HTTPTooManyRequests
+ raise Capturers.http_error(response.code, "GitHub answered #{response.code} for #{uri.path}: " \
+ "the API rate limit, or an abuse block. Run the archive again later.")
else
- raise ToolFailed, "GitHub answered #{response.code} for #{uri.path}"
+ raise Capturers.http_error(response.code, "GitHub answered #{response.code} for #{uri.path}")
end
rescue SocketError, SystemCallError, Net::OpenTimeout, Net::ReadTimeout, OpenSSL::SSL::SSLError => e
raise ToolFailed, "could not reach GitHub: #{e.class}"
diff --git a/app/services/capturers/video.rb b/app/services/capturers/video.rb
index 5acaeeb..3911211 100644
--- a/app/services/capturers/video.rb
+++ b/app/services/capturers/video.rb
@@ -15,10 +15,20 @@ def call
command += [ "--cookies", ENV["YTDLP_COOKIES_FILE"] ] if ENV["YTDLP_COOKIES_FILE"].present?
command += [ "--proxy", ENV["YTDLP_PROXY"] ] if ENV["YTDLP_PROXY"].present?
command << "--" << url
- run!(*command, env: { "HOME" => workdir })
+ classify_tool_failure("yt-dlp",
+ not_public: [ /Private video/i, /This video is private/i, /Sign in to confirm/i, /members-only/i,
+ /login required/i, /requires authentication/i, /not available to you/i ],
+ not_found: [ /Video unavailable/i, /has been removed/i, /does not exist/i, /HTTP Error 404/i ]) do
+ run!(*command, env: { "HOME" => workdir })
+ end
media = Dir.glob(path("video.*")).reject { |f| f.end_with?(".info.json", ".png") }.first
- raise ToolFailed, "yt-dlp wrote no media file" unless media
+ unless media
+ # yt-dlp exits 0 and writes nothing when --max-filesize stops the download.
+ raise TooLarge, "yt-dlp: the video is larger than the limit of #{Capturers.max_bytes} bytes" if capture.log.to_s.match?(/larger than max-filesize/i)
+
+ raise ToolFailed, "yt-dlp wrote no media file"
+ end
outputs = [ output("original", ::File.basename(media), content_type: Marcel::MimeType.for(Pathname.new(media))) ]
outputs << output("metadata", "video.info.json", content_type: "application/json") if ::File.exist?(path("video.info.json"))
diff --git a/app/views/archives/show.html.erb b/app/views/archives/show.html.erb
index dab9d52..cc26aa0 100644
--- a/app/views/archives/show.html.erb
+++ b/app/views/archives/show.html.erb
@@ -54,6 +54,20 @@
+ <% if (problem = @archive.problem) %>
+
+ <%= icon(:triangle_alert, size: 18) %>
+
+
+
<%= problem[:hint] %>
+
+
+ <%= badge problem[:code].tr("_", " "), tone: :danger %> <%= problem[:method] %>: <%= problem[:message] %>
+
+
+
+ <% end %>
+
<% unless @archive.finished? %>
<%= icon(:loader_circle, size: 18, class: "spinner") %>
@@ -72,6 +86,10 @@
<%= capture.method_name %>
<%= status_badge(capture.status) %>
+ <% if capture.error_code.present? %>
+ <%= badge capture.error_code.tr("_", " "), tone: :outline %>
+ <% end %>
+
<% if capture.duration %>
<%= capture.duration.round(1) %> s
<% end %>
diff --git a/db/central_migrate/20261109010000_add_error_code_to_captures.rb b/db/central_migrate/20261109010000_add_error_code_to_captures.rb
new file mode 100644
index 0000000..548b35f
--- /dev/null
+++ b/db/central_migrate/20261109010000_add_error_code_to_captures.rb
@@ -0,0 +1,7 @@
+# The machine-readable reason of a failed capture (Capturers::CODES), next to the message in
+# `error`. Patch apps read it from the API to tell the submitter what to fix.
+class AddErrorCodeToCaptures < ActiveRecord::Migration[8.1]
+ def change
+ add_column :captures, :error_code, :string
+ end
+end
diff --git a/db/central_schema.rb b/db/central_schema.rb
index 5d82952..4f94d59 100644
--- a/db/central_schema.rb
+++ b/db/central_schema.rb
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
-ActiveRecord::Schema[8.1].define(version: 2026_11_08_060001) do
+ActiveRecord::Schema[8.1].define(version: 2026_11_09_010000) do
create_schema "stash"
# These are extensions that must be enabled in order to support this database
@@ -102,6 +102,7 @@
t.datetime "finished_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
+ t.string "error_code"
t.index ["archive_id", "method_name"], name: "index_captures_on_archive_id_and_method_name", unique: true
t.index ["status"], name: "index_captures_on_status"
end
diff --git a/docs/api.md b/docs/api.md
index 273b2d9..d5aa8af 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -60,23 +60,49 @@ GET /api/v1/archives/arc_4k8xJm2pN9qW
"created_at": "2026-11-08T05:00:00Z",
"completed_at": "2026-11-08T05:01:12Z",
"page_url": "https://stash.patchworklabs.org/archives/arc_4k8xJm2pN9qW",
+ "problem": null,
"captures": [
{
- "id": "cap_...", "method": "github", "status": "done", "error": null,
+ "id": "cap_...", "method": "github", "status": "done", "error": null, "error_code": null,
"started_at": "...", "finished_at": "...",
"artifacts": [
{ "id": "art_...", "role": "metadata", "filename": "github.json", "content_type": "application/json",
"byte_size": 48213, "sha256": "...", "download_url": "https://stash.patchworklabs.org/artifacts/art_..." }
]
},
- { "id": "cap_...", "method": "git", "status": "done", "error": null, "artifacts": [ "..." ] },
- { "id": "cap_...", "method": "page", "status": "failed", "error": "ToolFailed: Chromium: ...", "artifacts": [] }
+ { "id": "cap_...", "method": "git", "status": "done", "error": null, "error_code": null, "artifacts": [ "..." ] },
+ { "id": "cap_...", "method": "page", "status": "failed", "error": "ToolFailed: Chromium: ...", "error_code": "tool_failed", "artifacts": [] }
]
}
```
`status` is one of `queued`, `running`, `done`, `partial` (some captures failed), `failed`. Poll until `completed_at` is set. A capture's `status` is `queued`, `running`, `done`, `failed` or `skipped`.
+### When a capture fails
+
+A failed capture carries `error` (the message, for a log) and `error_code` (the reason, for your code). The archive carries `problem`: the failed capture that matters most to the person who submitted the URL, or `null` while nothing has failed. Show `problem.hint` to that person, and `problem.message` to whoever debugs.
+
+```json
+"problem": {
+ "code": "not_public",
+ "method": "document",
+ "message": "NotPublic: Google answered 404 for the Google Slides deck: it is not shared with anyone with the link, or it does not exist. Ask the owner to share it, then run the archive again.",
+ "hint": "The source is private. Ask the owner to share it with anyone with the link, or to send a public URL, then run the archive again."
+}
+```
+
+| `error_code` | Meaning | Who fixes it |
+|---|---|---|
+| `not_public` | the source needs a sign-in or a share: a private repository, a Google document that is not shared with anyone with the link, a private video | the submitter: share it, or send a public URL |
+| `not_found` | nothing is at the URL: 404, 410, a deleted video, a repository that is gone | the submitter: send the right URL |
+| `blocked` | the host refused the archiver: 403, 429, an anti-bot wall | nobody; try again later |
+| `too_large` | the file passed `CAPTURE_MAX_BYTES` | Stash's operators, or a smaller source |
+| `timeout` | the capture ran past `CAPTURE_TIMEOUT` | try again; then Stash's operators |
+| `tool_failed` | the tool failed and nothing more specific is known | try again; then Stash's operators |
+| `unexpected` | Stash itself hit an error | Stash's operators |
+
+The codes come in that order of importance: when two captures fail, `problem` names the one with the earlier code. A `partial` archive with a `problem` of `not_public` means Stash kept what it could (often the `page` capture of the sign-in wall) and the source still needs the owner's action. Run the archive again from its page after the fix.
+
`download_url` needs a signed-in person: it is a Stash page URL that redirects to a short-lived storage URL. An app that needs the bytes should ask for that later; today the API gives the checksums and the sizes. Page URLs hold the id without its prefix (`/archives/4k8xJm2pN9qW`); the API accepts both forms.
An unknown id answers `404 {"error":"not_found"}`.
diff --git a/docs/design.md b/docs/design.md
index e73ca0b..555547e 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -86,6 +86,14 @@ The router never pulls a whole account: a profile URL on a gallery host is a pag
Each capturer has a timeout (`CAPTURE_TIMEOUT`, default 10 minutes) and a size limit (`CAPTURE_MAX_BYTES`, default 2 GB). A capture past either limit fails with that reason in `error`. Nothing is deleted on failure: the other captures of the archive still run.
+### Why a capture failed
+
+A failure is a `Capturers::Error` subclass, and the class is the reason: `NotPublic` (a private repository, a Google document that is not shared with anyone with the link, a private video), `NotFound` (404, 410, gone), `Blocked` (403, 429, an anti-bot wall), `TooLarge`, `Timeout`, `ToolFailed` (nothing more specific is known). `CaptureJob` stores the class as `captures.error_code` (`not_public`, `not_found`, `blocked`, `too_large`, `timeout`, `tool_failed`; `unexpected` for a bug) next to the message in `error`.
+
+HTTP downloads map the status (`Capturers.http_error`). Google exports turn 401, 403 and 404 into `NotPublic`, because Google answers 404 for a document that exists but is not shared. GitHub's 404 is `NotPublic` for the same reason. Tools that only exit non-zero (git, yt-dlp, gallery-dl) run through `classify_tool_failure`, which reads the last lines of their output for the known phrases ("could not read Username", "Private video", "login required", "not found").
+
+`Archive#problem` picks the failed capture whose code comes first in `Capturers::CODES` and gives it with a hint for a person (`Capturers.hint`). The archive page shows it in a callout, and the API returns it as `problem`, so the patch app that submitted the URL can tell the submitter what to fix (see `api.md`).
+
Every external tool runs in a subprocess with a clean environment and the URL as an argument, never through a shell string. A capturer never runs code from the archived content.
## Who can do what
diff --git a/test/controllers/api/v1/archives_controller_test.rb b/test/controllers/api/v1/archives_controller_test.rb
index 950c67a..94e2c46 100644
--- a/test/controllers/api/v1/archives_controller_test.rb
+++ b/test/controllers/api/v1/archives_controller_test.rb
@@ -108,13 +108,38 @@ def post_archive(token: TOKEN, **body)
assert_response :success
body = response.parsed_body
assert_equal "done", body["status"]
+ assert_nil body["problem"]
capture = body["captures"].sole
assert_equal "page", capture["method"]
+ assert_nil capture["error_code"]
art = capture["artifacts"].sole
assert_equal artifact.public_id, art["id"]
assert_includes art["download_url"], "/artifacts/#{artifact.encoded_id}"
end
+ test "show carries the problem of a failed archive, so the patch app can say what to fix" do
+ archive = create_archive_with_captures({ "document" => "failed", "page" => "done" })
+ archive.captures.find_by(method_name: "document").update!(
+ error: "NotPublic: Google answered 404 for the Google Slides deck: it is not shared with anyone with the link, or it does not exist. Ask the owner to share it, then run the archive again.",
+ error_code: "not_public"
+ )
+
+ with_fake_weave do
+ stub_introspection(token: TOKEN, scope: "stash")
+ get api_v1_archive_path(archive.public_id), headers: { "Authorization" => "Bearer #{TOKEN}" }
+ end
+
+ assert_response :success
+ body = response.parsed_body
+ assert_equal "partial", body["status"]
+ assert_equal "not_public", body["problem"]["code"]
+ assert_equal "document", body["problem"]["method"]
+ assert_includes body["problem"]["message"], "Google Slides deck"
+ assert_includes body["problem"]["hint"], "Ask the owner to share it"
+ document = body["captures"].find { |c| c["method"] == "document" }
+ assert_equal "not_public", document["error_code"]
+ end
+
test "show for an unknown id or a raw UUID is 404" do
archive = create_archive
with_fake_weave do
diff --git a/test/jobs/capture_job_test.rb b/test/jobs/capture_job_test.rb
index cf4e7f1..941f5df 100644
--- a/test/jobs/capture_job_test.rb
+++ b/test/jobs/capture_job_test.rb
@@ -45,14 +45,27 @@ class CaptureJobTest < ActiveJob::TestCase
assert_equal "skipped", @capture.reload.status
assert_equal "does not apply", @capture.error
+ assert_nil @capture.error_code
end
- test "a capturer error makes the capture failed, with the reason" do
+ test "a capturer error makes the capture failed, with the reason and its code" do
with_capturer(FakeCapturer::Fails) { CaptureJob.perform_now(@capture) }
assert_equal "failed", @capture.reload.status
assert_equal "ToolFailed: the tool said no", @capture.error
+ assert_equal "tool_failed", @capture.error_code
assert_equal "failed", @archive.reload.status
+ assert_equal "tool_failed", @archive.problem[:code]
+ end
+
+ test "a private source fails the capture with the not_public code" do
+ with_capturer(FakeCapturer::Private) { CaptureJob.perform_now(@capture) }
+
+ assert_equal "failed", @capture.reload.status
+ assert_equal "not_public", @capture.error_code
+ assert_includes @capture.error, "NotPublic: ask the owner"
+ assert_equal "not_public", @archive.reload.problem[:code]
+ assert_includes @archive.problem[:hint], "Ask the owner to share it"
end
test "an unexpected exception fails the capture and is raised again" do
@@ -60,6 +73,7 @@ class CaptureJobTest < ActiveJob::TestCase
assert_equal "failed", @capture.reload.status
assert_includes @capture.error, "ArgumentError"
+ assert_equal "unexpected", @capture.error_code
end
test "a finished capture is not run again" do
diff --git a/test/models/archive_test.rb b/test/models/archive_test.rb
index b83e4b1..7e313f1 100644
--- a/test/models/archive_test.rb
+++ b/test/models/archive_test.rb
@@ -36,6 +36,27 @@ class ArchiveTest < ActiveSupport::TestCase
assert_equal "queued", create_archive_with_captures({ "page" => "queued", "git" => "queued" }, url: "https://example.org/f").status
end
+ test "problem names the failed capture whose code matters most, and is nil without a failure" do
+ archive = create_archive_with_captures({ "github" => "failed", "git" => "failed", "page" => "done" })
+ archive.captures.find_by(method_name: "github").update!(error: "ToolFailed: GitHub answered 500", error_code: "tool_failed")
+ archive.captures.find_by(method_name: "git").update!(error: "NotPublic: git clone: private", error_code: "not_public")
+
+ problem = archive.problem
+ assert_equal "not_public", problem[:code]
+ assert_equal "git", problem[:method]
+ assert_equal "NotPublic: git clone: private", problem[:message]
+ assert_includes problem[:hint], "Ask the owner"
+
+ assert_nil create_archive_with_captures({ "page" => "done" }).problem
+ end
+
+ test "a failed capture without a code reads as tool_failed" do
+ archive = create_archive_with_captures({ "page" => "failed" })
+ archive.captures.first.update!(error: "ToolFailed: Chromium died")
+
+ assert_equal "tool_failed", archive.problem[:code]
+ end
+
test "completed_at is set only when finished" do
assert_nil create_archive_with_captures({ "page" => "running" }).completed_at
assert_not_nil create_archive_with_captures({ "page" => "done" }, url: "https://example.org/a").completed_at
diff --git a/test/services/capturers/document_test.rb b/test/services/capturers/document_test.rb
new file mode 100644
index 0000000..c19cea4
--- /dev/null
+++ b/test/services/capturers/document_test.rb
@@ -0,0 +1,100 @@
+require "test_helper"
+
+# The document capturer against stubbed HTTP (WebMock). No LibreOffice runs here: the PDF cases
+# stop before the conversion.
+class Capturers::DocumentTest < ActiveSupport::TestCase
+ DECK = "https://docs.google.com/presentation/d/1AbCdEfGhIjKlMnOpQrStUvWxYz0123456789abcd/edit".freeze
+
+ setup do
+ @workdir = Dir.mktmpdir
+ end
+
+ teardown do
+ FileUtils.rm_rf(@workdir)
+ end
+
+ def capture_for(url)
+ archive = create_archive(url: url)
+ archive.captures.create!(method_name: "document", status: "running", position: 0)
+ end
+
+ test "a Google deck that is not shared fails as not_public, with what the owner has to do" do
+ stub_request(:get, %r{docs\.google\.com/presentation/d/.*/export/pptx}).to_return(status: 404, body: "")
+ capture = capture_for(DECK)
+
+ error = assert_raises(Capturers::NotPublic) { Capturers::Document.new(capture, @workdir).call }
+
+ assert_equal "not_public", error.code
+ assert_equal 404, error.http_status
+ assert_includes error.message, "Google answered 404 for the Google Slides deck"
+ assert_includes error.message, "Ask the owner to share it"
+ end
+
+ test "a Google deck behind a sign-in (401) fails as not_public too" do
+ stub_request(:get, %r{docs\.google\.com/presentation/d/.*/export/pptx}).to_return(status: 401, body: "")
+ capture = capture_for(DECK)
+
+ error = assert_raises(Capturers::NotPublic) { Capturers::Document.new(capture, @workdir).call }
+ assert_equal 401, error.http_status
+ end
+
+ test "a Google deck that redirects to the sign-in page fails as not_public, not as a done capture" do
+ stub_request(:get, %r{docs\.google\.com/presentation/d/.*/export/pptx})
+ .to_return(status: 302, headers: { "Location" => "https://accounts.google.com/ServiceLogin?continue=x" })
+ stub_request(:get, %r{accounts\.google\.com/ServiceLogin})
+ .to_return(status: 200, body: "Sign in - Google Accounts", headers: { "Content-Type" => "text/html; charset=utf-8" })
+ capture = capture_for(DECK)
+
+ error = assert_raises(Capturers::NotPublic) { Capturers::Document.new(capture, @workdir).call }
+
+ assert_includes error.message, "Google answered a sign-in page for the Google Slides deck"
+ assert_includes capture.log, "not the pptx"
+ end
+
+ test "a Google rate limit stays blocked, so nobody is told to share a shared deck" do
+ stub_request(:get, %r{docs\.google\.com/presentation/d/.*/export/pptx}).to_return(status: 429, body: "")
+ capture = capture_for(DECK)
+
+ error = assert_raises(Capturers::Blocked) { Capturers::Document.new(capture, @workdir).call }
+ assert_equal 429, error.http_status
+ end
+
+ test "a shared Google deck exports both files" do
+ stub_request(:get, %r{docs\.google\.com/presentation/d/.*/export/pptx})
+ .to_return(status: 200, body: "PK deck", headers: { "Content-Type" => "application/vnd.openxmlformats-officedocument.presentationml.presentation" })
+ stub_request(:get, %r{docs\.google\.com/presentation/d/.*/export/pdf})
+ .to_return(status: 200, body: "%PDF-1.4", headers: { "Content-Type" => "application/pdf" })
+ capture = capture_for(DECK)
+
+ outputs = Capturers::Document.new(capture, @workdir).call
+
+ assert_equal %w[original rendition], outputs.map(&:role)
+ assert_includes capture.log, "Google export: 7 bytes as pptx"
+ end
+
+ test "a direct file that is gone fails as not_found" do
+ stub_request(:get, "https://example.org/report.pdf").to_return(status: 404, body: "")
+ capture = capture_for("https://example.org/report.pdf")
+
+ error = assert_raises(Capturers::NotFound) { Capturers::Document.new(capture, @workdir).call }
+ assert_equal "GET example.org answered 404", error.message
+ end
+
+ test "a direct file behind a refusal fails as blocked" do
+ stub_request(:get, "https://example.org/report.pdf").to_return(status: 403, body: "")
+ capture = capture_for("https://example.org/report.pdf")
+
+ assert_raises(Capturers::Blocked) { Capturers::Document.new(capture, @workdir).call }
+ end
+
+ test "a direct PDF is stored as served, with no conversion" do
+ stub_request(:get, "https://example.org/report.pdf")
+ .to_return(status: 200, body: "%PDF-1.4 report", headers: { "Content-Type" => "application/pdf" })
+ capture = capture_for("https://example.org/report.pdf")
+
+ outputs = Capturers::Document.new(capture, @workdir).call
+
+ assert_equal [ "original" ], outputs.map(&:role)
+ assert_equal "report.pdf", outputs.first.filename
+ end
+end
diff --git a/test/services/capturers/tool_failure_test.rb b/test/services/capturers/tool_failure_test.rb
new file mode 100644
index 0000000..80ac141
--- /dev/null
+++ b/test/services/capturers/tool_failure_test.rb
@@ -0,0 +1,66 @@
+require "test_helper"
+
+# A tool that exits with an error becomes NotPublic or NotFound when its output says why, and
+# stays ToolFailed otherwise. The subprocess is stubbed: nothing runs.
+class Capturers::ToolFailureTest < ActiveSupport::TestCase
+ setup do
+ @workdir = Dir.mktmpdir
+ archive = create_archive(url: "https://github.com/someone/secret")
+ @capture = archive.captures.create!(method_name: "git", status: "running", position: 0)
+ end
+
+ teardown do
+ FileUtils.rm_rf(@workdir)
+ end
+
+ # Subprocess.run that answers the given lines as the tool's output and exits 128. The
+ # classification reads that output, not the log, so the URL on the command line never counts.
+ def failing_run(_capture, *lines)
+ status = Struct.new(:exitstatus) { def success? = false }.new(128)
+ lambda do |*_command, **_options|
+ Capturers::Subprocess::Result.new(status: status, output: lines.join("\n"))
+ end
+ end
+
+ test "the URL on the command line does not decide the code" do
+ archive = create_archive(url: "https://github.com/someone/private-404-login")
+ capture = archive.captures.create!(method_name: "git", status: "running", position: 0)
+
+ stub_method(Capturers::Subprocess, :run, failing_run(capture, "fatal: the remote end hung up unexpectedly")) do
+ assert_raises(Capturers::ToolFailed) { Capturers::Git.new(capture, @workdir).call }
+ end
+ assert_includes capture.log, "private-404-login", "the command line is logged"
+ end
+
+ test "git clone of a private repository is not_public" do
+ error = stub_method(Capturers::Subprocess, :run, failing_run(@capture, "fatal: could not read Username for 'https://github.com': terminal prompts disabled")) do
+ assert_raises(Capturers::NotPublic) { Capturers::Git.new(@capture, @workdir).call }
+ end
+
+ assert_includes error.message, "git clone: the source is private or needs a sign-in"
+ assert_includes error.message, "exited with status 128"
+ end
+
+ test "git clone of a missing repository is not_found" do
+ error = stub_method(Capturers::Subprocess, :run, failing_run(@capture, "fatal: repository 'https://example.org/x/y' not found")) do
+ assert_raises(Capturers::NotFound) { Capturers::Git.new(@capture, @workdir).call }
+ end
+
+ assert_includes error.message, "the source is gone or the URL is wrong"
+ end
+
+ test "any other clone failure stays tool_failed" do
+ stub_method(Capturers::Subprocess, :run, failing_run(@capture, "fatal: the remote end hung up unexpectedly")) do
+ assert_raises(Capturers::ToolFailed) { Capturers::Git.new(@capture, @workdir).call }
+ end
+ end
+
+ test "yt-dlp on a private video is not_public" do
+ archive = create_archive(url: "https://www.youtube.com/watch?v=abcdefghijk")
+ capture = archive.captures.create!(method_name: "video", status: "running", position: 0)
+
+ stub_method(Capturers::Subprocess, :run, failing_run(capture, "ERROR: [youtube] abcdefghijk: Private video. Sign in if you've been granted access to this video")) do
+ assert_raises(Capturers::NotPublic) { Capturers::Video.new(capture, @workdir).call }
+ end
+ end
+end
diff --git a/test/services/capturers_test.rb b/test/services/capturers_test.rb
new file mode 100644
index 0000000..72900f8
--- /dev/null
+++ b/test/services/capturers_test.rb
@@ -0,0 +1,28 @@
+require "test_helper"
+
+class CapturersTest < ActiveSupport::TestCase
+ test "every error class but Skip has a code the captures table accepts" do
+ classes = Capturers::Error.subclasses - [ Capturers::Skip ]
+ assert_operator classes.size, :>=, 6
+ classes.each do |klass|
+ assert_includes Capturers::CODES, klass.code, klass.name
+ assert_equal klass.code, klass.new("x").code
+ end
+ end
+
+ test "http_error picks the class from the status" do
+ assert_instance_of Capturers::NotPublic, Capturers.http_error(401, "x")
+ assert_instance_of Capturers::Blocked, Capturers.http_error(403, "x")
+ assert_instance_of Capturers::Blocked, Capturers.http_error(429, "x")
+ assert_instance_of Capturers::NotFound, Capturers.http_error(404, "x")
+ assert_instance_of Capturers::NotFound, Capturers.http_error("410", "x")
+ assert_instance_of Capturers::ToolFailed, Capturers.http_error(500, "x")
+ assert_equal 404, Capturers.http_error(404, "x").http_status
+ assert_equal "x", Capturers.http_error(404, "x").message
+ end
+
+ test "every code has a hint, and an unknown code gets the generic one" do
+ Capturers::CODES.each { |code| assert Capturers.hint(code).present?, code }
+ assert_equal Capturers.hint("tool_failed"), Capturers.hint("something_else")
+ end
+end
diff --git a/test/support/fake_capturer.rb b/test/support/fake_capturer.rb
index f100016..6bb4d86 100644
--- a/test/support/fake_capturer.rb
+++ b/test/support/fake_capturer.rb
@@ -27,6 +27,12 @@ def call
end
end
+ class Private < Capturers::Base
+ def call
+ raise Capturers::NotPublic, "ask the owner"
+ end
+ end
+
# Runs the block with Capturers::Router.capturer_for answering the given class for every method.
def with_capturer(klass, &)
stub_method(Capturers::Router, :capturer_for, ->(_method) { klass }, &)