Skip to content

craft-print: a WS-Print backend on craft-wsd (feature wsd, default on) - #118

Closed
b1tninja wants to merge 22 commits into
storytold:mainfrom
b1tninja:craft-print-wsd
Closed

b1tninja wants to merge 22 commits into
storytold:mainfrom
b1tninja:craft-print-wsd

Conversation

@b1tninja

@b1tninja b1tninja commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

craft-print: a WS-Print backend for the registry (default-on wsd feature)

Based on storytold/craft-libs main (457a078) and stacked
on slice 1
(#116). This is slice 2 of 3 (print backend, WS-Print, UI destination). It
depends on craft-libs#113 (craft-wsd) through refs/pull/113/head, resolved to e06d454; pin an immutable
revision once #113 merges.

A reviewer sees six commits of WS-Print work: 74297a5 (the WS-Print backend), 450838c (docs and a CI check of
the feature-off build), 1dcf3db (the non-blocking job lifecycle rework), 03d960c (adaptation to craft-wsd's typed
kinds), c28e158 (an unclassified transport failure is not retryable) and 9616fd6 (adaptation to craft-wsd
e06d454: InvalidResponse and Io replace Other). After the owner's request from the pdfcraft adoption come
481e378 (WS-Print per-job options, typed WSD job ids and the testing feature) and e909687 and 7eaf366 (rustdoc
fixes under -D warnings), plus plain --no-ff merges of slice 1 (b5c26d7, 2fb51e9, and, for its newest commits,
59ca157, c883b2f and 2a1251c; slice 1 was pushed, so it is merged and not rebased) that bring in its per-job
options, JobId, optional totals, the document formats and the conversion. 384004b adds the WS-Print side of what the
pdfcraft adoption found missing: Quality::Photo in the ticket, every listed format, the printer's resolutions and the
registry conversion for a WS-Print printer. They describe one
change: a WS-Print Backend that submits, reports status, cancels and classifies
failures. Review the diff against #116, at the branch head.

What

craft_print::wsd, behind the cargo feature wsd (on by default; not compiled for wasm32):

  • WsdBackend, a BackendClass::Network backend registered as wsd, with printer ids wsd:<url>. It maps printer
    elements to PrinterDetails and errors to the neutral PrintError with wsd-fault native codes.

  • Typed WS-Print operations (client::Client, one method per operation over any transport) and the job flow
    (job): negotiate a format, plan the print ticket, create the job, send the document (MTOM or inline base64).

  • The print ticket with TicketShape quirk modes, and pass-through and PWG raster encoders.

  • Job lifecycle on the slice 1 trait: submit returns when SendDocument is accepted, with the JobId
    wsd:<printer url>#<job id>; job_status is one GetJobElements mapped onto the neutral JobStatus (a forgotten
    job is NotFound, with a message saying so); cancel_job is a tolerant CancelJob; watch_support is Poll, and
    the recommended interval is set with with_poll_interval.

  • Failure classification by what failed and which operation was in flight: transient or not, safe to repeat or not,
    phase and a suggested wait (typed transport kind, stage and Retry-After from craft-wsd feed retry_after,
    retry_safety and phase). WsdBackend::reconcile(printer, title) finds a job that may already have been created.

  • Per-job options (new). The request's JobOptions (slice 1) go into that job's ticket: media size, orientation,
    quality, resolution and an explicit colour choice (Colour/Mono override Job::grayscale; colour is applied when
    the picture is made, as before). honoured now lists Media, Orientation, Quality and Resolution besides
    copies, duplex and colour. The printer's capability list still decides: an unlisted value is dropped with a warning in
    Submitted::warnings, or refused in strict mode; a reduced TicketShape refuses or (with
    with_drop_ticket_settings) drops them exactly as it did for copies and sides. Ticket shape, strict mode, transfer,
    user name and limits stay backend-wide. An app that wants other ones for one invocation builds a variant:
    backend.clone().with_ticket_shape(..) shares the printer list but not the configuration (documented on WsdBackend
    and in the README, with a test), and registers it in a Registry of its own or calls Backend::submit on it.

  • Photo quality (new, 384004b). Quality::Photo (slice 1) becomes PrintQuality Photo in the ticket when the
    printer lists it (or lists no qualities); a printer that lists qualities without it gets the ticket without quality and
    a warning in Submitted::warnings; strict mode refuses it before anything is created. Draft, Normal and High follow
    the same rule.

  • Every listed format (new). accepted_formats() is every DocumentFormat (JPEG, PNG, TIFF, text, XPS and Open XPS
    join PDF, PWG raster, PostScript and octet-stream); each MIME type a printer lists that has a name appears in
    PrinterDetails::formats in the printer's order (case-insensitive, no duplicates, unknown types such as a vendor PDL
    left out) and a document in any listed format is sent unchanged, with the printer's own spelling of the type; one
    the printer does not list is UnsupportedFormat before a job exists, as before.

  • Resolutions (new). PrinterDetails::resolutions is filled from the capabilities of the GetPrinterElements the
    backend already reads, so choosing a raster dpi needs no extra request. formats_per_printer() is true: with an app
    DocumentConverter registered (slice 1) the registry reads the list (one read-only GetPrinterElements; none when the app
    passes the details it already has to Registry::submit_job_with_details) and converts to the best format the printer
    lists at the listed resolution nearest 300 dpi. Without a converter nothing is read first. The backend's own submit still
    reads the capabilities (the ticket is planned against them), so a converted print costs two reads, or one with details
    passed.

  • PWG encoder path (new). The encoder moved to craft_print::pwg (slice 1, no wsd feature needed);
    craft_print::wsd::pwg re-exports it (encode still returns WsdError; From<PwgError> for WsdError), and
    wsd::DocumentEncoder, RasterEncoder and negotiate_format are unchanged for apps that call them directly.

  • Typed WSD job ids (new). WsdBackend::job_id(printer_url, number) builds the JobId (the URL is canonicalised and
    policy-checked), parse_native(&str) and parse_job_id(&JobId) return WsdJob { printer_url, job_number }; all refuse
    with ErrorKind::InvalidRequest, never a panic. A wsd backend asked about another backend's job id refuses it without
    sending anything. Apps no longer concatenate wsd:<url>#<n>.

  • Totals. WS-Print reports MediaSheetsCompleted and no total. With JobOptions::expected_pages the registry's
    Submitted::expected gives a JobWatch an estimated sheet total (slice 1); the printer's own total would win. Submit
    progress events remain the three protocol phases (Progress::of(done, 3)), not sheets.

  • Export of the fake printer (new), cargo feature testing: craft_print::testing::FakeBackend (a configurable
    registry-level fake: printers, details (with_printer_formats, with_resolutions, with_formats_per_printer,
    detail_calls()), formats, class, scripted job_status, failing list/details/submit, progress
    events, records of submissions, status calls and cancels) and, with wsd, craft_print::wsd::testing
    (FakePrinter, FakeConfig, Ending, FakeJob, MemTransport, printer_server, ...), built on craft-wsd's testing
    feature through adapter.rs. The feature is off by default, has no effect on default builds and adds no dependency
    of its own (testing = ["craft-wsd?/testing"]). The crate's own integration tests now use these types (the private
    tests/wsd_support copy and the hand-written fakes in tests/registry.rs and tests/job_lifecycle.rs are gone);
    documented in crates/print/README.md.

Why

Slice 1 adds the seam; this is the first network backend on it, and the one pdfcraft needs to print to a WS-Print
printer by address. It keeps the protocol client in the shared crate, so the apps share one implementation, one
retry policy and one consent rule.

How

  • Built on craft-wsd. Only crates/print/src/wsd/adapter.rs names craft-wsd types, so a rename in craft-wsd: add the Web Services for Devices core for network printers and scanners #113 is a
    one-file change. Two caveats: the adapter re-exports the transport types used by the public with_transport
    signature, and WsdError exposes craft-wsd's Stage and TransportKind.
  • Nothing happens until the app asks. The backend lists only printers the app added (add, with_printers). There
    is no discovery and no multicast. Building a backend, adding a printer and listing open no connection;
    printer_details (one GetPrinterElements) and a job do.
  • Consent and address policy. UserConfirmed with BackendClass::Network is enforced by the registry. Printer
    URLs must be http:// with a numeric loopback, link-local or private address; host names, public addresses,
    redirects and proxies are refused (the policy comes from craft-wsd).
  • Ticket quirks are opt-in. Some printers' firmware does not answer tickets containing certain processing
    elements. TicketShape lists smaller tickets for them; the default is the full ticket, and a smaller one is chosen
    with with_ticket_shape. Settings a smaller ticket cannot carry are refused before anything is sent, or dropped with
    a warning when with_drop_ticket_settings is set.
  • Retry model. HTTP 408, 425, 429 and 5xx except 501 and 505 are retryable; a refused redirect, a policy refusal,
    501 and 505 are not. A connection closed or a timeout after a create or send may have been delivered, so it is
    outcome-unknown and the backend leaves any created job alone and never retries an outcome-unknown submit
    automatically
    . The same failure on a query or cancel is idempotent. reconcile matches by title and user and can
    return Ambiguous.
  • One deliberate difference from craft-wsd. craft-wsd's retry_safety marks 4xx and faults OutcomeUnknown or
    Idempotent, but the print table keeps definite refusals Safe and uses craft-wsd's value only where the request may
    have arrived. TransportKind::InvalidResponse (a peer that did not speak HTTP) is Failed and not retryable, and
    TransportKind::Io (an I/O error that fits no other kind) is Unavailable and retryable, both matching craft-wsd. A
    request the HTTP client could not build is Invalid in craft-wsd and stays a preparation failure, Safe, here.
  • Cargo.lock gains craft-wsd, ureq, ureq-proto and utf8-zero. ureq has no TLS here. With
    --no-default-features none of it is built, and CI checks that build.

How verified

As run at 384004b (after cargo clean -p craft-print), on Windows:

  • With the default features: 144 lib tests (2 ignored), 15 in conversion (slice 1's, with a test-only backend), 6 in
    conversion_fakes (the same rules driven with the exported FakeBackend), 10 in job_lifecycle, 17 in registry, 24
    in wsd_client, 58 in wsd_registry, 3 in wsd_live and 3 doctests: 280 passed, 2 ignored.
    cargo test -p craft-print --features testing gives the same numbers. With --no-default-features (and with
    --no-default-features --features testing): 148 passed, 2 ignored (the wsd tests are cfg-gated off).
    cargo test --workspace passes (488 passed, 4 ignored).
  • cargo fmt --check is clean; clippy --all-targets -D warnings is clean for the workspace and for -p craft-print
    with the default features, --no-default-features, --features testing and --no-default-features --features testing;
    cargo check -p craft-print --target wasm32-unknown-unknown passes with the default features, with none and with
    testing (neither the backend nor the wsd fakes are compiled on wasm32); cargo doc -p craft-print --no-deps with
    RUSTDOCFLAGS=-D warnings passes with the default features and with --no-default-features (two pre-existing
    broken doc links in this slice, one in wsd/ops.rs and one in lib.rs that broke when the feature is off, were
    fixed in e909687 and 7eaf366).
  • New tests of 384004b (all in the totals above): details name every listed format and list the resolutions; Photo
    reaches the ticket when listed or when no list is published, is dropped with a warning when unlisted and refused in strict
    mode; JPEG, PNG, TIFF, text, XPS, Open XPS and PostScript documents reach the fake printer byte for byte with the listed
    type, and PDF is refused with no job when unlisted; a converter makes PWG raster for a printer that lists only raster (the
    listed resolution nearest 300, the resolution in the ticket, two reads, one with details passed, none first without a
    converter, PDF sent as PDF when listed, no job and a message naming both sides when nothing is in common, no contact
    without consent); the old wsd::pwg::encode path matches the neutral one; and the six conversion_fakes tests
    (accepts as is, converted with resolution choice, the caller's resolution, per-printer formats read once, no common
    format, converter failure). Earlier: per-job options reach the ticket and an unlisted media size is dropped with a
    warning; an explicit colour choice and strict mode; a reduced ticket refuses or drops per-job settings; a per-invocation
    variant backend shares the printers but not the configuration; typed wsd job ids build, parse, refuse malformed text
    and foreign backends without sending; a typed id works with status, cancel and watch; expected pages give the sheet
    counter a total the printer does not report.
  • The tests run through the registry against an in-memory fake printer and hostile loopback servers: submit returns while
    the printer keeps the job, a watch on an injected clock, a forgotten job, a lost reply to SendDocument and to
    CreatePrintJob with reconcile, no automatic retry of an outcome-unknown submit, and the retry table for every
    error kind and operation.
  • wsd_live is skipped unless FAKEPRINT_URL names a loopback printer-service URL (it reports 3 passed when skipped). A
    run against a loopback fake-printer server passed 3 of 3 at 1dcf3db; it was not re-run since.

Not verified:

  • Nothing was exercised against a real printer: only in-memory fakes and loopback servers.
  • The unix CUPS path of slice 1 is only compile-checked on Windows and wasm.
  • The craftrules standards repository was unreadable (404), so only the AGENTS.md rules were checked.

Breaking changes (to this unmerged API only)

From slice 1: JobRef became JobId, the progress callback takes Progress { done, total: Option<u32> }, and
SubmitRequest has an options field (see its description). In this slice: JobMatch::job is a JobId;
The new commit is additive: FakeConfig gained qualities and resolutions (use ..FakeConfig::default()),
FakeBackend gained builders, WsdBackend::accepted_formats() now lists all ten formats and wsd::pwg::encode keeps its
signature (the types come from craft_print::pwg, so RasterPage and friends are the same types as before). Earlier:
wsd::testing::Config and Job are named FakeConfig and FakeJob, and the private tests/wsd_support module is
removed in favour of the exported one; Cargo.toml gains a dev-dependency of the crate on itself
(default-features = false, features = ["testing"]) so plain cargo test enables the feature, as craft-wsd does.

Boundaries

  • No discovery and no multicast code; the backend never contacts an address the app did not add.
  • Windows spooler code and unsafe stay outside craft-libs' new code; this backend is pure Rust over craft-wsd.
  • PDF generation and rendering stay in the app; the backend takes bytes plus a format, and the app's DocumentConverter
    (slice 1) makes the format. Per-invocation settings (ticket shape, strict mode, transfer, user name, limits) stay
    backend-wide: build backend.clone().with_* for the invocation, as documented on WsdBackend and in the README.
  • The crate does not retry on its own beyond what a caller asks for through JobWatch and RetryPolicy.

Consumers

pdfcraft adopts slices 1-3: CLI print --wsd, a print_wsd tool, the Print dialog destination (using
craft-ui::printing::network, slice 3), a parity entry and i18n, behind the app feature network-print (default on).

Review order

Stacked on slice 1: merge and review #116 first, then review only the commits above it (the
diff against #116). It also needs #113 (refs/pull/113/head, resolved to
e06d454), to be pinned to an immutable revision once #113 merges. Slice 3 is
independent of this one.

🤖 Generated with Claude Code

b1tninja and others added 8 commits October 14, 2026 06:36
Adds the Backend trait (blocking, Send + Sync, object safe), a Registry with
namespaced printer ids, partial-failure listing, neutral errors with native
codes, document formats, a UserConfirmed consent marker for network backends,
and the system spooler (cups or spooler) as a built-in adapter over the
existing functions. The existing public API is unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…cancel and retry vocabulary

Backend::submit now returns a Submitted as soon as the printer has accepted the document and never waits for the print. A job is followed with optional trait methods (watch_support, recommended_poll_interval, job_status, cancel_job) whose defaults say "accepted, outcome unknown". The registry routes job ids by prefix and offers submit_job, job_status, cancel_job and job_watch; Registry::submit still returns a Receipt.

JobWatch is a caller-driven state machine with an injectable clock, a backoff that slows while the status does not change, a max_wait, a cancel token and failure retries; wait_for_job is the blocking convenience built on it.

PrintError separates is_retryable (transient) from retry_safety (Safe, Idempotent, OutcomeUnknown), and adds phase and retry_after; RetryPolicy gives a bounded jittered backoff that never repeats an outcome-unknown error. The survey of how comparable stacks do this is in docs/job-lifecycle.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Adds craft_print::wsd, built on craft-wsd (named only in wsd/adapter.rs): typed
WS-Print operations, the print ticket with its TicketShape quirk modes, the job
flow with polling and tolerant cancel, pass-through and PWG raster encoders, and
WsdBackend, a Network-class registry backend named wsd. It lists only the
printers the app added, discovers nothing, maps printer elements to
PrinterDetails and errors to the neutral PrintError with wsd-fault native codes.
Tests run it through the registry against an in-memory fake printer and hostile
loopback servers; a loopback test against a real fakeprint server runs only when
FAKEPRINT_URL is set.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…build in CI

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ob status, cancel and classified retries

WsdBackend::submit creates the job and sends the document and returns as soon as SendDocument is accepted; it no longer polls for up to five minutes. The job handle is wsd:<printer url>#<job id>. job_status is one GetJobElements mapped onto the neutral JobStatus (a forgotten job is NotFound with a message that says so), cancel_job is the tolerant CancelJob, watch_support is Poll and the recommended interval is configurable (with_poll_interval replaces with_poll).

Errors are classified by what failed and which operation was in flight: transient or not, safe to repeat or not, phase, and a suggested wait. HTTP 408, 425, 429 and 5xx except 501 and 505 are retryable; a refused redirect, a policy refusal, 501 and 505 are not. A connection closed or a timeout after a create or send may have been delivered, so it is outcome-unknown and the backend leaves any created job alone; the same failure on a query or cancel is idempotent. WsdBackend::reconcile looks for the job by title and user before anything is resent.

Tests: submit returns while the printer keeps the job, a watch on an injected clock, a forgotten job, a lost reply to SendDocument and CreatePrintJob with reconcile, no automatic retry of an outcome-unknown submit, and the retry table for every error kind and operation.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…kinds, stages and Retry-After

The WSD adapter now follows craft-wsd's typed errors: a transport failure carries its kind and the stage the exchange reached, an HTTP status error and a fault carry the printer's Retry-After, and the safety of repeating comes from craft-wsd's own retry_safety(idempotent) instead of reading the failure text. The closed-connection error kind is gone (it is a transport kind now), the retry table and its tests cover every typed kind against every operation, and the lock follows craft-wsd to its new commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… other non-retryable HTTP errors

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
craft-wsd replaced TransportKind::Other with InvalidResponse (a peer that did not speak HTTP: Failed, not retryable) and Io (an I/O error that matched no other kind: Unavailable, retryable), both at the reply stage. A request the HTTP client could not build now arrives as Invalid, which stays a preparation failure and Safe. The retry table, the every-kind test and the lifecycle doc follow, and the lock resolves craft-wsd e06d454.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
b1tninja and others added 7 commits October 14, 2026 09:57
SubmitRequest carries JobOptions (media, orientation, quality, resolution, an explicit colour choice and the expected page count) as hints a backend may ignore, with new JobHint entries for what it honours. JobRef is replaced by a typed JobId with Display, FromStr, backend(), native() and new(), a typed ParseJobIdError, and the registry, watch and free functions take it. Progress is now an event with an optional total, and the expected page count becomes the sheet total for progress events and status readings only where the backend reports none.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… feature

The wsd backend maps JobOptions into each job's ticket (media size, orientation, quality, resolution, explicit colour) and keeps the ticket shape, strict mode and transfer as backend-wide configuration; a clone with different settings shares the printer list, which is how an app varies them per invocation. WsdBackend::job_id, parse_native and parse_job_id name and read wsd jobs without string handling, and a wsd backend refuses a job id of another backend. The new cargo feature testing exports craft_print::testing::FakeBackend and craft_print::wsd::testing (the in-memory WS-Print printer), and the crate's own tests use them in place of their private copies.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…nings

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… the feature is off

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
b1tninja and others added 7 commits October 14, 2026 11:29
…format conversion

Quality gains Photo (a hint, like the others). DocumentFormat gains Jpeg, Png, Tiff, PlainText, Xps
and OpenXps with mime(), from_mime(), extension(), from_extension(), sniff(), detect() and a
configurable negotiate() against a printer's own list.

PrinterDetails lists the printer's resolutions. The app registers a DocumentConverter; when a
printer does not accept the document's format the registry picks the best target the converter
makes and the printer lists, chooses the resolution nearest a target dpi from the printer's list,
runs the converter and sends the result, or fails with a typed UnsupportedFormat naming both sides.
A neutral PWG raster encoder (craft_print::pwg) is available without the wsd feature. The built-in
spooler stays PDF-only.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…sion

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ons and registry conversion

The WS-Print backend maps Quality::Photo into the ticket when the printer lists it (leaves it out
with a warning otherwise, refuses it in strict mode), names every listed MIME type that has a
DocumentFormat and passes a document in any of them through unchanged, and fills
PrinterDetails::resolutions from the GetPrinterElements it already reads. It reports
formats_per_printer, so a registry with a converter reads the printer's list before converting.
wsd::pwg now re-exports the neutral craft_print::pwg encoder. The fakes gain qualities and
resolutions (FakePrinter) and per-printer formats (FakeBackend).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@b1tninja

Copy link
Copy Markdown
Contributor Author

Folded into #116, which now carries the whole print stack as one pull request (the Backend trait and registry, the WS-Print backend, tracked jobs, the IPP backend, opt-in WS-Eventing status and print-scaling), as six logical commits. The WS-Print commit here is the second of those, with the same content. Nothing was dropped; the pull request is stacked on #113 and #120 and says so. Closing so there is one print pull request to review and merge.

@b1tninja b1tninja closed this Oct 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant