Import existing pre-cutoff GitHub work into Gitea #3
No files matched your search
@@ -12,10 +12,10 @@ on:
|
||||
inputs:
|
||||
product-version:
|
||||
type: string
|
||||
default: '0.3.2'
|
||||
default: '0.4.0'
|
||||
release-version:
|
||||
type: string
|
||||
default: '0.3.2-rc.1'
|
||||
default: '0.4.0-rc.1'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -42,7 +42,7 @@ jobs:
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: QRun-IO/qqq-print-protocol
|
||||
ref: f3cbc02e9b0fb4fdfefaa59d976c04df747cc589
|
||||
ref: a26c18c90c7d6102bbe26eb50cbb90fcd1bd46e3
|
||||
path: qqq-print-protocol
|
||||
persist-credentials: false
|
||||
- name: Set up .NET
|
||||
@@ -59,8 +59,8 @@ jobs:
|
||||
./build/Test-PackagingInputs.ps1
|
||||
- name: Build unsigned prerelease MSI
|
||||
env:
|
||||
PRODUCT_VERSION: ${{ inputs.product-version || '0.3.2' }}
|
||||
RELEASE_VERSION: ${{ inputs.release-version || '0.3.2-rc.1' }}
|
||||
PRODUCT_VERSION: ${{ inputs.product-version || '0.4.0' }}
|
||||
RELEASE_VERSION: ${{ inputs.release-version || '0.4.0-rc.1' }}
|
||||
run: |
|
||||
./build/Build-Installer.ps1 -ProductVersion $env:PRODUCT_VERSION -ReleaseVersion $env:RELEASE_VERSION
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
|
||||
@@ -90,7 +90,7 @@ jobs:
|
||||
global-json-file: global.json
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3
|
||||
uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
build-mode: ${{ contains(fromJSON('["actions","javascript-typescript","python","ruby"]'), matrix.language) && 'none' || inputs.build-mode }}
|
||||
@@ -110,7 +110,7 @@ jobs:
|
||||
eval "$BUILD_COMMAND"
|
||||
|
||||
- name: Analyze
|
||||
uses: github/codeql-action/analyze@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3
|
||||
uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
with:
|
||||
category: /language:${{ matrix.language }}
|
||||
output: codeql-sarif
|
||||
|
||||
@@ -110,7 +110,7 @@ jobs:
|
||||
# A failed submission must not turn existing required reviews into skipped
|
||||
# (passing) checks. They still run; the submission job reports its own failure.
|
||||
if: ${{ !cancelled() }}
|
||||
uses: KofTwentyTwo/standards/.github/workflows/pr.yml@fdf5ed029603c938615a32b1beca3628b8787945 # v0.1.2
|
||||
uses: KofTwentyTwo/standards/.github/workflows/pr.yml@70b555bd5658273090769991bfc4c9b6681dde18 # v1.2.1
|
||||
with:
|
||||
# EX-0014: exact reviewed SDK inventory, guarded through 2027-04-30 UTC.
|
||||
# https://github.com/KofTwentyTwo/standards/blob/fbfc8d2cf3b5e16ae9750b04cf9de1794f1e7152/exceptions/register.md#ex-0014
|
||||
|
||||
@@ -95,6 +95,8 @@ jobs:
|
||||
|
||||
This client requires QQQ's semantic printing extension >=2.0.0 <3.0.0 and standard QQQ sign-in. When upgrading from 0.2, upgrade the server first: native API 2.0 makes a synchronized authenticated WebSocket mandatory for claims. An existing 0.3 server remains compatible with this client follow-up. Existing pairings and history are preserved; unbound devices require explicit account association.
|
||||
|
||||
New in 0.4.0: optional printer-media selection. The agent reports each queue's machine-default paper dimensions and resolution as an opaque, revision-bound profile, advertised only to printing 2.3+ servers (printing 2.2 remains a three-capability peer), and refuses a selected-media job whose profile has drifted. Defaults are configured facts, not physical stock sensing. Each job also writes one phase-timing log line. Upgrade the server first for selected-media jobs. This candidate has no installed or physical-output qualification, and no stable 1.0 readiness is claimed.
|
||||
|
||||
New in 0.3.2: a successful MSI result is accepted only when app, service and CLI have the requested release and identical full build versions. Missing, unreadable or mixed builds report an inconsistent installation without claiming rollback. The SDK credit references Microsoft's separate terms and installed notices. The native test host now matches production's PerMonitorV2 DPI declaration while retaining unelevated execution.
|
||||
|
||||
New in 0.3.1: the footer shows explicit WebSocket state, a server-settings link, live QQQ service upload/download payload rates and totals since service start. Lightweight local observations add no QQQ job/control polling. Windows-normalized startup account names are accepted only when they resolve to the exact expected SID; this preference controls the tray companion, independently of the automatic print service.
|
||||
@@ -105,7 +107,7 @@ jobs:
|
||||
|
||||
Existing features include standard QQQ sign-in and protected service sessions, PDF/ZPL printing and warehouse diagnostic profiles, exact owned spool cancellation, synchronized device/printer profiles, configurable logs, customer branding, AppKit settings/logs/update prompts, machine-wide MSI updates, tray status and explicit printer exposure. Replacement pairing and recovery from damaged saved credentials preserve history and printer choices without silently enabling printing.
|
||||
|
||||
The published 0.3.1 MSI was installed with pairing, printer profiles, local receipts and log settings preserved; its service automatically restored the native QQQ session and WebSocket. The operator confirmed successful test prints and a responsive window. This 0.3.2 candidate still needs actual in-app update acceptance. Configured provider/browser callbacks also need end-to-end qualification against a compatible native-session API. See docs/ACCEPTANCE.md for version-specific evidence and remaining limits. Spool acceptance alone does not establish physical output or scanner readability; no stable 1.0 readiness is claimed.
|
||||
The published 0.3.2 MSI was reached by a real in-app update from 0.3.1 with pairing, printer profiles and local receipts preserved, and its service restored the native QQQ session and WebSocket. The operator confirmed successful test prints on 0.3.1. Configured provider/browser callbacks also need end-to-end qualification against a compatible native-session API. See docs/ACCEPTANCE.md for version-specific evidence and remaining limits. Spool acceptance alone does not establish physical output or scanner readability; no stable 1.0 readiness is claimed.
|
||||
|
||||
See CHANGELOG.md, docs/INSTALLATION.md and docs/ACCEPTANCE.md in the tagged source for scope and limitations.
|
||||
NOTES
|
||||
|
||||
@@ -37,7 +37,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Run Scorecard
|
||||
uses: ossf/scorecard-action@2d1146689b8cda280b9bc96326124645441f03bc # v2.4.4
|
||||
uses: ossf/scorecard-action@fa7117db83c52d787ae5a89f350999701505d78e # v2.5.0
|
||||
with:
|
||||
results_file: scorecard.sarif
|
||||
results_format: sarif
|
||||
@@ -51,7 +51,7 @@ jobs:
|
||||
retention-days: 30
|
||||
|
||||
- name: Upload SARIF to code scanning
|
||||
uses: github/codeql-action/upload-sarif@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3
|
||||
uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
with:
|
||||
sarif_file: scorecard.sarif
|
||||
category: scorecard
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Set up Node
|
||||
uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
|
||||
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: '24'
|
||||
package-manager-cache: false
|
||||
|
||||
@@ -102,7 +102,7 @@ jobs:
|
||||
- name: Upload SARIF to code scanning
|
||||
# Fork pull requests get a read-only token, so only same-repository runs upload.
|
||||
if: always() && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)
|
||||
uses: github/codeql-action/upload-sarif@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3
|
||||
uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
with:
|
||||
sarif_file: trivy.sarif
|
||||
category: trivy-sca
|
||||
@@ -157,7 +157,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up uv
|
||||
uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0
|
||||
uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2
|
||||
with:
|
||||
enable-cache: false
|
||||
|
||||
@@ -168,7 +168,7 @@ jobs:
|
||||
|
||||
- name: Upload SARIF to code scanning
|
||||
if: always() && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)
|
||||
uses: github/codeql-action/upload-sarif@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3
|
||||
uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
with:
|
||||
sarif_file: zizmor.sarif
|
||||
category: zizmor
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
This is QRun-IO/qqq-print-agent, built on KofTwentyTwo AppKit's Windows service variant. Follow the current user request and repository .editorconfig/central package versions.
|
||||
|
||||
- Verify with `./build/Verify.ps1`; package with `./build/Build-Installer.ps1 -ProductVersion 0.3.2 -ReleaseVersion 0.3.2-rc.1`.
|
||||
- Verify with `./build/Verify.ps1`; package with `./build/Build-Installer.ps1 -ProductVersion 0.4.0 -ReleaseVersion 0.4.0-rc.1`.
|
||||
- Core owns protocol/state/policy; Windows owns OS adapters/storage/runtime; Service owns hosting; UI owns native views/tray plumbing.
|
||||
- Zero compiler/analyzer warnings; locked dependencies. Coverage is reported for the initial prerelease under docs/adr/0002-prerelease-quality-and-packaging.md.
|
||||
- Keep the service alive independently of the companion. Use AppKit update UX with the machine MSI adapter; update service, companion and CLI together. Do not install a per-user-only replacement over the machine package.
|
||||
|
||||
+27
-1
@@ -1,6 +1,32 @@
|
||||
# Changelog
|
||||
|
||||
## 0.3.2-rc.1 — unreleased
|
||||
## 0.4.0-rc.1 — unreleased candidate
|
||||
|
||||
Not tagged, not installed. Upgrade the server first: selected-media jobs require
|
||||
printing extension 2.3.0 (wire payload v1 unchanged). Against a 2.0, 2.1 or 2.2
|
||||
(rendering) server the client keeps its three-capability HELLO and offers no media
|
||||
profiles, so existing behavior is unchanged.
|
||||
|
||||
- Report each queue's machine-default paper dimensions and resolution as an opaque, revision-bound media profile, and advertise `printer-media-v1` only when the discovered server supports it. Defaults are configured facts, not physical stock sensing.
|
||||
- Refuse a selected-media job before spooling when the profile is unknown or its revision has drifted, and again at the native submission boundary. A proven pre-submit refusal is recorded as FAILED and is never treated as an uncertain outcome.
|
||||
- Normalize job-only driver copies and scale for selected PDFs and verify the effective device-context dimensions and resolution before StartDoc. ZPL (RAW) only rechecks the profile immediately before StartDocPrinter.
|
||||
- Log one phase-timing line per processed job (inventory, claim and receipt, download, revalidation, submit gate, native submit) with the job identifier only, to attribute print latency from the service log. No new request, payload or printer access.
|
||||
- Pin the printing protocol to the reviewed media contract (`a26c18c9…`). Later protocol compatibility documentation is an unmerged draft and changes no pin.
|
||||
- Split `PrintWorker` job processing into named submission, revalidation, dispatch-gate and native-submit steps (analyzer MA0051 rejected the first form of the timing instrumentation). Behavior, state order and lease release are unchanged.
|
||||
|
||||
Observed so far, all local: after the extraction the focused negotiation/runtime run
|
||||
passed 16 of 16 with no warnings or analyzer errors, and a token comparison against
|
||||
the merge base showed only the four intended semantic files changed. The hosted gate
|
||||
on the earlier PR head 35ed93c (154 Core, 317 CLI/Windows, zero warnings) is
|
||||
historical: that head predates protected main's changes, the timing line and the
|
||||
printing 2.3 negotiation, so the final candidate head needs its own hosted gate, which
|
||||
has not run. The local Core test assembly remains blocked by a Defender quarantine
|
||||
and was not rebuilt; hosted results will not clear that detection. Installer and
|
||||
upgrade preservation, profile-selected physical output, and installed
|
||||
browser/private-callback acceptance against a published API 1.9+ server are not yet
|
||||
qualified. No 1.0 claim.
|
||||
|
||||
## 0.3.2-rc.1 — 2026-11-01
|
||||
|
||||
- Verify that the app, service and CLI all have the requested release and identical full build versions before recording MSI update success. Report missing, unreadable or mixed builds without claiming rollback.
|
||||
- Correct the Windows App SDK credit to reference its Microsoft terms and installed third-party notices.
|
||||
|
||||
@@ -60,7 +60,7 @@
|
||||
commit as "+<sha>" on AssemblyInformationalVersion, which the About dialog and the
|
||||
CLI's version output show as a short hash. -->
|
||||
<PropertyGroup>
|
||||
<VersionPrefix>0.3.2</VersionPrefix>
|
||||
<VersionPrefix>0.4.0</VersionPrefix>
|
||||
<VersionSuffix>rc.1</VersionSuffix>
|
||||
</PropertyGroup>
|
||||
|
||||
|
||||
@@ -13,6 +13,8 @@ The native setup and status application uses the same [KofTwentyTwo AppKit](http
|
||||
|
||||
> **Published and installed prerelease: [0.3.2-rc.1](https://github.com/QRun-IO/qqq-print-agent/releases/tag/v0.3.2-rc.1).** All four assets, checksums and provenance attestations were verified. The real in-app update completed with matching app/service/CLI builds, retained identity and history, and an automatically reopened Connected app. The installer remains unsigned.
|
||||
|
||||
> **Candidate 0.4.0-rc.1 — unreleased, not installed, no tag.** Adds optional printer-media selection against printing extension 2.3+ servers (2.2 is rendering only and stays a three-capability peer), plus one phase-timing log line per job. The hosted gate on PR head 35ed93c passed 154 Core and 317 CLI/Windows tests with zero warnings (the timing line is newer and needs its own gate), but no installed, physical-output or published-cohort native-callback qualification exists yet. See [release readiness](docs/RELEASE-READINESS.md) and [upgrade qualification](docs/UPGRADE-QUALIFICATION.md). No 1.0 readiness is claimed.
|
||||
|
||||
**0.3.2-rc.1** checks the app, service and CLI for the same complete
|
||||
build version after an update, reports an inconsistent installation explicitly,
|
||||
and corrects the SDK license credit. Its native test host now uses production's
|
||||
@@ -131,7 +133,7 @@ git clone https://github.com/QRun-IO/qqq-print-agent.git
|
||||
git clone https://github.com/QRun-IO/qqq-print-protocol.git
|
||||
Set-Location qqq-print-agent
|
||||
./build/Verify.ps1
|
||||
./build/Build-Installer.ps1 -ProductVersion 0.3.2 -ReleaseVersion 0.3.2-rc.1
|
||||
./build/Build-Installer.ps1 -ProductVersion 0.4.0 -ReleaseVersion 0.4.0-rc.1
|
||||
```
|
||||
|
||||
[Realtime architecture and settings](docs/REALTIME.md) · [History and log limits](docs/SCALABILITY.md) · [Customer branding](docs/BRANDING.md) · [Developer guide](docs/DEVELOPMENT.md) · [Administrator guide](docs/ADMINISTRATION.md) · [Troubleshooting](docs/TROUBLESHOOTING.md) · [Release process](docs/RELEASING.md) · [Contributing](CONTRIBUTING.md) · [Security policy](SECURITY.md)
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[ValidatePattern('^\d+\.\d+\.\d+$')]
|
||||
[string] $ProductVersion = '0.3.2',
|
||||
[string] $ProductVersion = '0.4.0',
|
||||
[ValidatePattern('^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$')]
|
||||
[string] $ReleaseVersion = '0.3.2-rc.1',
|
||||
[string] $ReleaseVersion = '0.4.0-rc.1',
|
||||
[string] $PayloadDirectory,
|
||||
[switch] $SkipPublish,
|
||||
[string] $CertificateThumbprint,
|
||||
|
||||
@@ -14,6 +14,13 @@ if(-not (Test-Path -LiteralPath $protocolFixtures))
|
||||
{
|
||||
throw 'Check out the pinned qqq-print-protocol repository beside qqq-print-agent before running verification.'
|
||||
}
|
||||
foreach($fixture in @('claim.response.json', 'enroll.response.json', 'control-poll.response.json', 'printing-session.response.json', 'printing-session-bound.response.json'))
|
||||
{
|
||||
if(-not (Test-Path -LiteralPath (Join-Path $ProtocolFixtures $fixture) -PathType Leaf))
|
||||
{
|
||||
throw "Required protocol fixture is missing: $fixture. Use the protocol revision pinned in .github/workflows/ci.yml, or pass its fixtures directory with -ProtocolFixtures."
|
||||
}
|
||||
}
|
||||
Push-Location $projectRoot
|
||||
try
|
||||
{
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
# Windows queue-default media profiles
|
||||
|
||||
The candidate client advertises `printer-media-v1` only when standard discovery
|
||||
reports a stable printing extension version of at least 2.3.0 within major two.
|
||||
Printing 2.0, 2.1 and 2.2 (rendering, no media negotiation) servers retain the original three realtime capabilities and
|
||||
legacy unselected jobs. Each WebSocket establishment refreshes standard discovery
|
||||
once under the authenticated session gate, then uses that refreshed snapshot
|
||||
for HELLO. This handles same-session server upgrades and downgrades without an
|
||||
HTTP polling schedule. An unverified test or
|
||||
custom transport does not claim media support.
|
||||
|
||||
The client includes optional `mediaProfiles` in exposed-printer inventory. It reports at most one profile per
|
||||
queue: the machine-wide Windows driver default. It does not enumerate stock that
|
||||
an operator might have available, infer dimensions from document pages, or claim
|
||||
that the configured stock is physically loaded.
|
||||
|
||||
Discovery reads `GetPrinter` level 8, rather than the current user's level 9
|
||||
preferences. Custom paper dimensions come from both valid DEVMODE width/length
|
||||
fields, converted from tenths of a millimeter to integer microns. Otherwise, a
|
||||
single matching paper ID in the driver's `DeviceCapabilities` paper/size arrays
|
||||
is required. Landscape defaults swap the effective page axes. Positive explicit
|
||||
DEVMODE resolutions are retained; symbolic quality values require resolution
|
||||
from a driver DC created with that exact machine DEVMODE. Unknown, incomplete,
|
||||
ambiguous or out-of-contract values produce no profile, without guessing.
|
||||
|
||||
Each profile has a stable opaque queue/default ID, a lowercase SHA-256 revision,
|
||||
a display name, width/height in microns, horizontal/vertical DPI,
|
||||
`source: WINDOWS_QUEUE_DEFAULT` and `applyMode: DRIVER_DEFAULT`. The revision
|
||||
includes driver identity, resolved dimensions/resolution, and the complete
|
||||
returned public/private DEVMODE bytes. This is deliberately conservative: even a
|
||||
driver-private setting change invalidates an old selection. Drivers returning
|
||||
volatile private bytes may require reselection; the client does not guess which
|
||||
vendor fields can be ignored. The fingerprint is not a credential.
|
||||
|
||||
Consumers submit `options.mediaProfile: {id, revision}` exactly as advertised.
|
||||
It cannot be combined with `paperWidthMm` or `paperHeightMm`. The worker checks
|
||||
the current selection after download and before its submission state. The
|
||||
native helper checks again immediately before opening a spool document. A known
|
||||
media refusal is propagated across the helper boundary and recorded as FAILED
|
||||
with no document submitted; arbitrary native failures and timeouts retain their
|
||||
existing uncertain-outcome handling and are not retried automatically.
|
||||
|
||||
For selected PDF jobs, the captured machine DEVMODE remains the selection
|
||||
fingerprint. A separate job-only copy requests one driver copy and 100% driver
|
||||
scale, only for fields supported by the captured defaults, through
|
||||
`DocumentProperties(DM_IN_BUFFER | DM_OUT_BUFFER)`. Unsupported fields remain
|
||||
absent; drivers without native scale support use the software renderer's scale.
|
||||
This allows
|
||||
the driver to reconcile its private settings without prompting or changing
|
||||
queue defaults. Software remains responsible for requested copies and
|
||||
ACTUAL_SIZE/FIT rendering. The normalized result must confirm these overrides
|
||||
and preserve the original support flags and selected geometry/DPI; otherwise
|
||||
submission is refused. A previously supported override cannot silently disappear.
|
||||
`CreateDC` receives those normalized bytes, never a null/current-user default.
|
||||
Before `StartDoc`, the effective DC must also report matching physical page
|
||||
dimensions and exact horizontal/vertical DPI. Dimension tolerance is one device
|
||||
pixel plus 50 microns (half the DEVMODE 0.1 mm form unit), including landscape
|
||||
axes. Unknown or substituted dimensions/DPI are refused before spooling.
|
||||
RAW ZPL has no DEVMODE application mechanism: the helper rechecks the current
|
||||
profile immediately before `StartDocPrinter`, but cannot lock loaded stock or
|
||||
prevent a physical/device-setting change afterward. `DRIVER_DEFAULT` never
|
||||
changes queue settings, calibrates hardware or loads stock. Such changes require
|
||||
operator verification and fresh discovery. Legacy jobs without a media selection
|
||||
retain their existing path.
|
||||
|
||||
The candidate's actual read-only probe reported the configured label default as
|
||||
101,600 × 152,400 microns at 300 × 300 DPI, with an identical fingerprint across
|
||||
three separate helper launches. Synthetic tests also cover 101,600 × 25,400 and
|
||||
101,600 × 50,800 microns; these are not advertised as current configuration.
|
||||
Physical queue names, driver selectors and inventory evidence remain private.
|
||||
No print, installation, queue change or service operation was performed for this
|
||||
feature's discovery qualification. End-to-end server acceptance and physical
|
||||
printing of a profile-selected job remain separate gates.
|
||||
|
||||
A subsequent read-only probe of the compiled corrected adapter successfully
|
||||
normalized the configured label driver's supported copy field while retaining
|
||||
its absent native scale field. The resulting DC reported 1,200 × 1,800 physical
|
||||
pixels at 300 × 300 DPI. It invoked no StartDoc and changed no queue defaults.
|
||||
All 24 focused adapter regression cases pass; this does not resolve the separate
|
||||
Core test-assembly quarantine or qualify a physical profile-selected print.
|
||||
|
||||
Native references: [machine-wide PRINTER_INFO_8 defaults](https://learn.microsoft.com/en-us/windows/win32/printdocs/printer-info-8),
|
||||
[DEVMODE dimensions and resolution](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-devmodew),
|
||||
and [driver paper capabilities](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-devicecapabilitiesw).
|
||||
Job-only driver normalization follows [DocumentProperties](https://learn.microsoft.com/en-us/windows/win32/printdocs/documentproperties);
|
||||
effective page checks use [GetDeviceCaps](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-getdevicecaps).
|
||||
@@ -0,0 +1,50 @@
|
||||
# Release readiness matrix — candidate 0.4.0-rc.1 (unreleased)
|
||||
|
||||
Updated 2026-11-01 to the observed results below. This is a working matrix, not a release claim: **no 1.0 or production-readiness statement is made**, and nothing here has been installed. Installed baseline stays 0.3.2-rc.1 against the local QQQ API 1.8 / printing 2.0 server.
|
||||
|
||||
## Observed gates
|
||||
|
||||
Historical (superseded heads, kept as evidence): Windows PR #16 head `35ed93c7…` hosted run 41340470827 passed Core 154 and CLI/Windows 317 with 0 warnings; server PR #30 head `4eee28e9…` passed 183 reported / 182 executed / 1 opt-in skip / Checkstyle 0. Protected main then advanced (server rendering at printing 2.2.0; client virtual-agent), so those heads are not the candidate.
|
||||
|
||||
Current candidate, local results only:
|
||||
|
||||
| Tree | Gate | Result |
|
||||
| --- | --- | --- |
|
||||
| Windows | First focused build | **Rejected**: `PrintWorker.cs(96,29)` MA0051 (method 67 lines, maximum 60), caused by the phase-timing instrumentation. Log preserved. An earlier sandbox build had stalled with orphaned build workers; that was environmental, not source. |
|
||||
| Windows | After extracting `SubmitJobAsync`, `RequireCurrentPrinter`, `RequireSubmitAllowed`, `SubmitNativeAsync` and `JobAttempt` (no analyzer waiver) | Focused negotiation/runtime run **16 of 16 passed**, no warnings, no analyzer errors. Core.Tests was not built. |
|
||||
| Windows | Roslyn token compare against merge base `c4c663a` | Exactly the four intended semantic files differ (`PrintWorker.cs`, `PrintWorkerTests.cs`, `QqqApiDiscovery.cs`, `AgentRealtimeMediaCapabilitiesTests.cs`); no fifth file. The worker refactor was reviewed: same reservation, staged-file and submission disposal inside the same catch, same authority checks and state order. |
|
||||
| Server | Full verify, sandbox | 188 reported, 0 assertion failures, 11 loopback setup errors, 1 skip. Environmental; log preserved. |
|
||||
| Server | Full verify, actual user, before fix | 188 reported, 0 assertion failures, **1 error** (`PrintingRealtimeTest.mediaCapabilityIsReplacedOnEveryAuthenticatedHello`, temp-directory cleanup). Cause: `PrintingRealtimeRoutes.close()` did not wait for in-flight channel drains, which recreated the stopped file database. Log preserved. |
|
||||
| Server | After `stopWorkers()` fix and regression `closeWaitsForChannelWorkersAlreadyRunning` | `PrintingRealtimeTest` five consecutive runs, 4 tests each, no empty-database warnings. Full verify **189 reported / 188 executed / 1 intentional opt-in workload skip / 0 failures / 0 errors, Checkstyle 0**. Source-header guard over 146 tracked files passed; staged whitespace checks passed. |
|
||||
| Protocol | Check | 76 definitions and 78 fixtures passed locally; compatibility docs published as a signed draft PR #15 (commit `1916324e6d2c0dac0fd48f2401b654303ab228f9`). |
|
||||
|
||||
**Not yet observed:** hosted CI on the final signed candidate heads (Windows Core.Tests, the new `RunOnce_LogsOnePhaseTimingLinePerJobWithoutDocumentContent`, Cli.Tests totals, MSI build at ProductVersion 0.4.0; server verify). Hosted passes do not clear the local Defender quarantine of the Core test assembly, which stays unbuilt and unrestored. No installer, installed-upgrade, physical-output or published-cohort native-callback result exists for this candidate.
|
||||
|
||||
Status words are strict. **Proven** names evidence that was observed for the stated scope. **Partial** means part of the requirement has evidence. **Incomplete** means no qualifying evidence exists yet, including where only source or a plan exists.
|
||||
|
||||
| Requirement | Status | Evidence on record | Open gap / exact next evidence |
|
||||
| --- | --- | --- | --- |
|
||||
| AppKit parity (menu, About, settings, theme, logs, tray, update) | Partial | [APPKIT-PARITY.md](APPKIT-PARITY.md); real in-app 0.3.1 → 0.3.2 update accepted ([ACCEPTANCE.md](ACCEPTANCE.md)); 426-test Release gate at 0.3.2 | Update download/installer failure, cancel and reboot-required paths; high contrast, Narrator, scaling and small-screen matrix. Not re-run for this candidate. |
|
||||
| Realtime, reconnect, large-file control concurrency | Partial | Source tests: `PauseAndCancelRemainResponsiveDuringLargeDownloadWithoutHttpPolling`, `NativeCookieAndDeviceProofUpgradeKeepsReceivingDuringStalledDocument`, ordering/generation/bandwidth suites; installed 0.3.x reconnect observed ([REALTIME.md](REALTIME.md)) | [TODO.md](TODO.md) still lists the combined runtime review (stalled transfer, lost ACK, reconnect) as unchecked. Needs the hosted Core + Windows gate on the exact head, then an installed reconnect check on a compatible server. |
|
||||
| Jobs table, details, sorting, 10k/day scale | Partial | `JobSortingTests.TenThousandJobs_AllColumnsSortAcrossPagesAndInterleaveBoundedCloudQueue`; `AgentStoreScaleTests`; 375,000-job store measurements in [SCALABILITY.md](SCALABILITY.md); installed UI checks at 0.1.9/0.3.1 | Measurements are local storage with fake printers. GUI rendering at scale, service scheduling and printer throughput are unmeasured. Not a throughput claim. |
|
||||
| Printer media (this candidate) | Partial | Read-only real-driver/DC normalization probe 4×6 in / 300 DPI with no queue change ([PRINTER-MEDIA.md](PRINTER-MEDIA.md)); media is offered only to stable printing 2.3+ in major 2 (2.2 rendering stays a three-capability peer), covered by the 16 passing focused negotiation/runtime tests (HELLO per version, reconnect upgrade and downgrade) | The earlier hosted Core pass was on a superseded head. Final-head hosted Core is pending and does not clear the local Defender quarantine. No installed profile-selected print has occurred. |
|
||||
| Print latency (measured 5–7 s ZPL test print) | **Incomplete** | Source trace of the per-job path and a bounded read-only diagnostic plan (`LATENCY-DIAGNOSTIC-PLAN.md` in the coordination outbox); the candidate logs one phase-timing line per job | Cause unproven. Needs per-state timestamps for the measured jobs and helper noop-versus-discover timing before any change. No hardware or server blame. |
|
||||
| Branding and install | Partial | [BRANDING.md](BRANDING.md); branding tests; MSI payload/resource/notice checks recorded for 0.3.2 | Candidate MSI is built only by the hosted job on the final head (pending). Needs MSI resource comparison against the 0.3.2 baseline after CI, then the install-free plan in [UPGRADE-QUALIFICATION.md](UPGRADE-QUALIFICATION.md). |
|
||||
| Status and log rotation | Partial | `AgentLogSettingsTests` (10k jobs × 3 entries inside the default daily budget); daily-cap marker and clear-logs behavior in [SCALABILITY.md](SCALABILITY.md) | Installed rotation across a local-midnight boundary and cap visibility in the UI are not observed. |
|
||||
| Native auth, permissions, recovery | Partial | Isolated real Authentik login, permission, logout, expiry/renewal and revocation against an unreleased API 1.9 candidate in local Docker; recovery regressions in [QQQ-SIGN-IN.md](QQQ-SIGN-IN.md) | Installed browser/private-callback and long-lived grant need a compatible published API 1.9+ cohort. The local server 1.8 does not qualify. **Incomplete** until that cohort exists. |
|
||||
| Retained-source and S3 retention boundaries | Partial | Server local full verify on the merged candidate: 189 reported / 188 executed / 1 intentional opt-in 10k skip / 0 failures, Checkstyle 0; callback authority and accepted-row history fixes independently reviewed; the server's `docs/STORAGE-AND-RETENTION.md` states the layout, outbox-copy and versioning boundaries | Final-head server hosted CI pending. Production IAM, bucket policy, noncurrent-version retention and cross-platform key migration are deployment work, not proven. Echo's experimental core tuple is unqualified; no silent repin. |
|
||||
| Packaging, CI/CD, notices, About | Partial | Notice and Query About guards merged into both bases; release workflow pins actions and protocol; candidate version inputs (0.4.0 / 0.4.0-rc.1) and the reviewed workflow patch are applied by the coordinator, with action pins unchanged | Protocol pin is still the reviewed `a26c18c9…`; the new protocol compatibility docs are an unmerged draft PR #15, so no new pin is claimed. Hosted packaging steps on the final head are pending. MSI remains unsigned. |
|
||||
| C# source standards (XML how/why headers, member layout) | **Incomplete** | License headers on all tracked C# (IDE0073, [SOURCE-HEADER-COMPLIANCE.md](SOURCE-HEADER-COMPLIANCE.md)); new media types documented with token proof; Roslyn inventory/compare helper built and its controls passed | Inventory over 230 files, 0 parse errors: 1254 types/methods without a header, 10 trivial headers, 1083 structural plus 413 other member-spacing gaps. No old-code batch has been done; batches of at most 8 files each, token-proved, start after the functional baseline is committed. |
|
||||
|
||||
## Order of closure
|
||||
|
||||
1. Done locally: both trees pass their focused/full local gates (table above). Pending: signed functional commits and exact-head hosted CI for the Windows and server candidate heads.
|
||||
2. Done: the Roslyn inventory/compare helper passed its positive and negative controls.
|
||||
3. After the functional baseline is committed: documentation-only C# standards batches of at most 8 files, each with token-equivalence proof and never mixed with semantic fixes.
|
||||
4. Version inputs (`Directory.Build.props`, `build/Build-Installer.ps1`, README, CHANGELOG) and the `ci.yml`/`release.yml` patch are applied for the candidate. No tag.
|
||||
5. Upgrade-preservation qualification: install-free plan in [UPGRADE-QUALIFICATION.md](UPGRADE-QUALIFICATION.md), executed by the master only with authorization.
|
||||
6. Latency: measure first (per-state timestamps and helper noop-versus-discover timing); change nothing speculatively.
|
||||
|
||||
## Not claimed
|
||||
|
||||
Authenticode signing, physical-stock sensing, installed profile-selected printing, desktop/native OAuth callback or long-lived grant on a published cohort, remote cloud deployment, broad driver matrix, and any 1.0 readiness.
|
||||
@@ -1,5 +1,74 @@
|
||||
# Session state — 2026-11-01
|
||||
|
||||
## Candidate 0.4.0-rc.1 integration with protected main — 2026-11-01
|
||||
|
||||
Protected main advanced during qualification (client virtual-agent behavior; server
|
||||
printing 2.2.0 rendering), so the earlier green PR heads are historical evidence
|
||||
only. The media/operator/retained feature moved to printing **2.3.0**; this client
|
||||
offers `printer-media-v1` only to a stable 2.3+ server in major two and stays a
|
||||
three-capability peer on 2.0, 2.1 and 2.2. Product candidate 0.4.0-rc.1, wire
|
||||
payload v1, no tag.
|
||||
|
||||
Observed locally (no hosted result for the final heads yet):
|
||||
|
||||
- A focused build was **rejected** by analyzer MA0051 on `PrintWorker.ProcessJobAsync`
|
||||
(67 lines, maximum 60), caused by the new per-job phase-timing instrumentation.
|
||||
It was fixed by extracting `SubmitJobAsync`, `RequireCurrentPrinter`,
|
||||
`RequireSubmitAllowed`, `SubmitNativeAsync` and a nested `JobAttempt`, with no
|
||||
analyzer waiver. Reservation, staged-file and submission leases are still
|
||||
released inside the same catch, and the authority checks and state order are
|
||||
unchanged (reviewed by the coordinator).
|
||||
- The focused negotiation/runtime run then passed **16 of 16** with no warnings or
|
||||
analyzer errors. Core.Tests was not built locally (Defender quarantine unchanged).
|
||||
- The Roslyn token compare against the merge base found exactly the four intended
|
||||
semantic files changed and no fifth file.
|
||||
- Server: the merged candidate's full verify passed 189 reported / 188 executed /
|
||||
1 intentional opt-in skip / 0 failures, Checkstyle 0, after fixing a real
|
||||
lifecycle defect (realtime channel workers outliving the stopped host).
|
||||
|
||||
Pending, not claimed: hosted CI on the final signed heads (including Core.Tests and
|
||||
the MSI build), installer and upgrade-preservation qualification
|
||||
([UPGRADE-QUALIFICATION.md](UPGRADE-QUALIFICATION.md)), profile-selected physical
|
||||
output, the unexplained 5–7 s ZPL test-print latency (measure first), and installed
|
||||
browser/private-callback sign-in against a published API 1.9+ server. No 1.0 claim.
|
||||
See [RELEASE-READINESS.md](RELEASE-READINESS.md).
|
||||
|
||||
## Candidate Echo media discovery — 2026-11-01
|
||||
|
||||
The isolated candidate implements `printer-media-v1`, machine-wide queue-default
|
||||
profiles, immutable media selection and pre-spool drift refusal. Selected PDFs
|
||||
use a driver-normalized job-only copy of the captured DEVMODE; RAW's physical-stock limitation is explicit
|
||||
in `docs/PRINTER-MEDIA.md`. Read-only native discovery produced a stable configured
|
||||
4 × 6 inch, 300 × 300 DPI profile across three helper launches. No live component
|
||||
was changed and no physical output was submitted.
|
||||
|
||||
Core/Windows/CLI and synthetic test projects compile without warnings. Seven
|
||||
initial adapter cases and one isolated-worker refusal case passed. Review added
|
||||
driver-normalized copies/scale overrides and effective DC geometry/DPI validation
|
||||
before StartDoc; all 24 focused Windows adapter cases now pass with zero build
|
||||
warnings. The original queue fingerprint remains unchanged, and the driver may
|
||||
update private settings only in the job's in-memory buffer. Unsupported override
|
||||
fields stay absent. A read-only probe of the corrected production adapter passed
|
||||
on the configured label driver, including its absent native-scale flag and an
|
||||
effective 1,200 × 1,800 pixel DC at 300 DPI, without StartDoc or queue changes.
|
||||
A Core run executed
|
||||
150 cases, with 147 passing (including the new media/worker cases) and three
|
||||
failing because the new worktree's linked fixtures were missing. The subsequent
|
||||
full rerun is blocked by local Defender quarantine of the Core test assembly;
|
||||
no protection changes, exclusions or quarantine restoration were performed.
|
||||
This is not a clean full-suite or release qualification. Parent review owns the
|
||||
security provenance investigation and the remaining server/hardware gates.
|
||||
The shared selection validator also enforces protocol IDs of at most 128 ASCII
|
||||
URL-safe characters, profile names of 1–512 characters and at most 32 profiles.
|
||||
New Core boundary regressions are present for hosted validation and were not
|
||||
locally compiled or run after the quarantine.
|
||||
Capability negotiation requires discovered stable printing 2.3+ within major
|
||||
two (2.2 is the rendering extension without media negotiation); older 2.0/2.1/2.2 servers retain the original three-capability HELLO. The real
|
||||
session/loopback-WebSocket compatibility tests cover same-session upgrade and
|
||||
downgrade, refreshing discovery once per socket (separate from initial sign-in
|
||||
discovery), with zero forbidden HTTP polls. The combined focused Windows gate
|
||||
passed 40 cases with zero build warnings/errors.
|
||||
|
||||
## Query in About — 2026-11-01
|
||||
|
||||
The shared AppKit About dialog now places Query and its public links in a compact
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
# TODO
|
||||
|
||||
## Candidate Echo printer media
|
||||
|
||||
- [x] Discover truthful machine-default dimensions/DPI and expose an opaque, revision-bound profile.
|
||||
- [x] Reject stale/unknown selection before spool; pass captured validated defaults to selected PDF DCs.
|
||||
- [x] Normalize supported job-only driver copies/scale and verify effective DC dimensions/DPI before StartDoc (24 focused Windows tests plus read-only actual driver/DC probe).
|
||||
- [x] Verify synthetic 4 × 1 / 4 × 2 / 4 × 6 profiles, driver-private drift, unknown DPI and isolated-worker refusal.
|
||||
- [x] Verify configured 4 × 6 / 300 DPI fingerprint stability across three read-only helper launches.
|
||||
- [ ] Resolve the local Core test-assembly quarantine through the normal security review; obtain a complete clean gate without disabling protections.
|
||||
- [ ] Qualify the matching server/consumer catalog, immutable selection and authorized retained-document submission.
|
||||
- [ ] Perform separately authorized installed/profile-selected physical acceptance; available alternative stock is not current queue configuration.
|
||||
## Query in About
|
||||
|
||||
- [x] Place the official mascot and dogfooding/Query links directly below the
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# Upgrade-preservation qualification plan — candidate 0.4.0-rc.1
|
||||
|
||||
Status: **plan only.** Nothing here has been run. The installed baseline is 0.3.2-rc.1 (MSI SHA-256 `1191C337265469EB06136AF232DB57FAC6BC5014357521D80B35E5CCA5AF6E18`) against the local QQQ on port 18081 (API 1.8 / printing 2.0). This plan follows the observer pattern recorded for the 0.3.1 and 0.3.2 acceptances in [ACCEPTANCE.md](ACCEPTANCE.md). It needs explicit user authorization before any installation, and it never submits a job.
|
||||
|
||||
## Preconditions (all must hold before an authorized install)
|
||||
|
||||
1. Final candidate head has a green hosted gate, including the Core test job. A green hosted gate does not clear the local Defender detection of the Core test assembly.
|
||||
2. The candidate MSI comes from that exact head's CI artifact. Record its SHA-256 and compare with `SHA256SUMS` in the artifact.
|
||||
3. Static MSI inspection (no install): ProductVersion `0.4.0`; app, service and CLI payloads all carry the same full informational version `0.4.0-rc.1+<head sha>`; Windows App SDK resources, service configuration (LocalSystem, automatic start, two 30-second recovery restarts), callback registration and the packaged notice files match the 0.3.2 baseline except for intended differences. Stable component identities must match the baseline so Windows Installer upgrades rather than duplicates.
|
||||
4. A read-only "before" report exists for the installed 0.3.2 state (below).
|
||||
|
||||
## Before/after observations (read-only, no secrets)
|
||||
|
||||
Capture the same fields before and after. Use hashes or counts for protected material; never print credentials, device keys, tokens or document payloads.
|
||||
|
||||
| Item | Method | Pass condition |
|
||||
| --- | --- | --- |
|
||||
| Component versions | File version/ProductVersion of app, service and CLI | After: all three equal `0.4.0-rc.1+<head>`; bytes equal the CI payload |
|
||||
| Machine credential file | Existence and SHA-256 only | Unchanged by the upgrade |
|
||||
| Pairing and identity | Device ID presence and server URL (no token) | Unchanged |
|
||||
| Local job history | Per-row digest of job ID, state, creation time, printer ID | Every prior row present with identical digest; additions accounted for separately |
|
||||
| Server job history | Same digests from the server view | Prior rows unchanged |
|
||||
| Printer exposure and profiles | Exposed set and per-printer profile fields | Unchanged |
|
||||
| Log settings | Retention days and daily cap | Unchanged |
|
||||
| Service configuration | SCM start type, account, recovery actions | Unchanged |
|
||||
| Connectivity | Native QQQ session and authenticated WebSocket state | Restored without operator action |
|
||||
| Companion | In-app update path (Not now, then Update and restart) | Same handoff as 0.3.2; app reopens Connected |
|
||||
|
||||
## Compatibility checks specific to this candidate
|
||||
|
||||
- **Older server, new client.** Against the local printing 2.0 server the HELLO must carry exactly the three pre-existing capabilities and no `printer-media-v1`, inventory must carry no `mediaProfiles`, and existing jobs must behave as before. This is the expected state on the installed local server and is itself a required qualification result.
|
||||
- **Capability only on 2.3+.** `printer-media-v1` and `mediaProfiles` appear only after the client discovers a stable printing 2.3+ server in major 2. A printing 2.2 (rendering) server must leave the client a three-capability peer. Qualify against a server that actually runs the 2.3.0 candidate, in an isolated environment, not the installed 18081 instance.
|
||||
- **Latency diagnostic line.** After upgrade, an authorized later job (not part of this plan) writes one `timing` line per job to the service log with the job ID only. Confirm that the line contains no document text.
|
||||
|
||||
## Failure handling
|
||||
|
||||
- Windows Installer same-upgrade-code downgrade is not supported. Keep the 0.3.2 MSI and its hash so a manual return can be planned, and treat that as a separate authorized operation.
|
||||
- An MSI exit code of 3010 means restart required; report it as such. Do not delete journal, staging or credential files to recover.
|
||||
- A mismatch in any prior-row digest, credential hash or exposure set stops qualification and is reported as a failure with the earlier evidence preserved.
|
||||
|
||||
## Explicitly not covered here
|
||||
|
||||
Physical output with a selected media profile, Authenticode signing, update download or installer failure/cancellation, reboot recovery, installed browser/private-callback sign-in against a published API 1.9+ server, and any 1.0 claim. Each needs its own authorization and evidence.
|
||||
@@ -15,6 +15,19 @@ public sealed class QqqApiDiscovery
|
||||
public IReadOnlyList<string> ClientChannels { get; init; } = [];
|
||||
public IReadOnlyList<Extension> Extensions { get; init; } = [];
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Enables additive media negotiation only for one standard-path stable printing 2.3-or-newer extension within major two. Printing 2.2 is
|
||||
/// the rendering extension and carries no media negotiation, so a 2.2 server must keep this client a three-capability peer.
|
||||
/// </summary>
|
||||
public bool SupportsPrinterMedia() => Extensions is not null
|
||||
&& Extensions.Count(extension => extension is not null && string.Equals(extension.Name, "printing", StringComparison.Ordinal)) == 1
|
||||
&& Extensions.Any(extension => extension is not null && string.Equals(extension.Name, "printing", StringComparison.Ordinal)
|
||||
&& string.Equals(extension.PathPrefix, "/qbit/printing", StringComparison.Ordinal) && SupportedVersion(extension.Version, 3, "2"));
|
||||
|
||||
|
||||
|
||||
public sealed record Extension(string Name, string Version, string PathPrefix);
|
||||
|
||||
internal void Validate(bool nativeSession = false)
|
||||
|
||||
@@ -9,7 +9,7 @@ namespace Qqq.PrintAgent.Core.Authentication;
|
||||
|
||||
public sealed partial class QqqSessionClient
|
||||
{
|
||||
/// <summary>Connects only to the discovered origin, using the current native session and approved device proof.</summary>
|
||||
/// <summary>Refreshes standard discovery once per socket establishment, then connects only to that origin with the current session and approved device proof.</summary>
|
||||
public async Task<WebSocket> ConnectPrintingAsync(TimeSpan heartbeatInterval, TimeSpan heartbeatTimeout, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var invoker = new HttpMessageInvoker(new SocketsHttpHandler { AllowAutoRedirect = false, UseCookies = false });
|
||||
@@ -21,12 +21,7 @@ public sealed partial class QqqSessionClient
|
||||
try
|
||||
{
|
||||
RequireAuthenticated();
|
||||
QqqApiDiscovery discovery = _discovery ?? throw QqqApiDiscovery.Configuration();
|
||||
QqqApiDiscovery.Extension extension = discovery.Extensions.Single(item => string.Equals(item.Name, "printing", StringComparison.Ordinal));
|
||||
if(!Version.TryParse(extension.Version, out Version? version) || version.Major != 2)
|
||||
{
|
||||
throw new QqqSessionException(QqqSessionException.FailureKind.ConfigurationRequired, "Upgrade the server to printing extension 2.x for realtime printing.");
|
||||
}
|
||||
await RefreshPrintingDiscoveryAsync(cancellationToken).ConfigureAwait(false);
|
||||
if(_device is null || _binding?.HasApprovedDevice != true)
|
||||
{
|
||||
throw new QqqSessionException(QqqSessionException.FailureKind.PermissionDenied, "An approved device binding is required.");
|
||||
@@ -71,4 +66,18 @@ public sealed partial class QqqSessionClient
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>Refreshes discovery under the caller-held session gate and rejects incompatible printing majors before sending any WebSocket credentials.</summary>
|
||||
private async Task RefreshPrintingDiscoveryAsync(CancellationToken token)
|
||||
{
|
||||
_discovery = null;
|
||||
QqqApiDiscovery discovery = await DiscoverCoreAsync(token).ConfigureAwait(false);
|
||||
QqqApiDiscovery.Extension extension = discovery.Extensions.Single(item => string.Equals(item.Name, "printing", StringComparison.Ordinal));
|
||||
if(!Version.TryParse(extension.Version, out Version? version) || version.Major != 2)
|
||||
{
|
||||
throw new QqqSessionException(QqqSessionException.FailureKind.ConfigurationRequired, "Upgrade the server to printing extension 2.x for realtime printing.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,6 @@
|
||||
|
||||
namespace Qqq.PrintAgent.Core.Printing;
|
||||
|
||||
public sealed record PrintOptions(int Copies = 1, string Scale = "ACTUAL_SIZE", double? PaperWidthMm = null, double? PaperHeightMm = null);
|
||||
public sealed record PrintOptions(int Copies = 1, string Scale = "ACTUAL_SIZE", double? PaperWidthMm = null, double? PaperHeightMm = null, PrinterMediaSelection? MediaProfile = null);
|
||||
|
||||
|
||||
@@ -29,7 +29,9 @@ public sealed class PrintWorker(PrintApiClient api, IPrinterBackend printers, IJ
|
||||
// Drain a bounded outbox batch before claiming more work after an outage.
|
||||
return false;
|
||||
}
|
||||
long inventoryStarted = System.Diagnostics.Stopwatch.GetTimestamp();
|
||||
IReadOnlyList<PrinterInfo> inventory = printers.Discover();
|
||||
TimeSpan inventoryElapsed = System.Diagnostics.Stopwatch.GetElapsedTime(inventoryStarted);
|
||||
if(canSynchronize?.Invoke() == false)
|
||||
{
|
||||
return false;
|
||||
@@ -40,13 +42,15 @@ public sealed class PrintWorker(PrintApiClient api, IPrinterBackend printers, IJ
|
||||
{
|
||||
return false;
|
||||
}
|
||||
long claimStarted = System.Diagnostics.Stopwatch.GetTimestamp();
|
||||
PrintJob? job = await ClaimAndRegisterAsync(inventory, token).ConfigureAwait(false);
|
||||
TimeSpan claimElapsed = System.Diagnostics.Stopwatch.GetElapsedTime(claimStarted);
|
||||
if(job is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
try
|
||||
{ return await ProcessJobAsync(job, inventory, token).ConfigureAwait(false); }
|
||||
{ return await ProcessJobAsync(job, inventory, new JobAttempt(inventoryElapsed, claimElapsed), token).ConfigureAwait(false); }
|
||||
finally { options?.ActiveJobChanged?.Invoke(null); }
|
||||
}
|
||||
|
||||
@@ -84,7 +88,14 @@ public sealed class PrintWorker(PrintApiClient api, IPrinterBackend printers, IJ
|
||||
finally { options?.ClaimGate?.Release(); }
|
||||
}
|
||||
|
||||
private async Task<bool> ProcessJobAsync(PrintJob job, IReadOnlyList<PrinterInfo> inventory, CancellationToken token)
|
||||
/// <summary>
|
||||
/// Runs one claimed job and reports its outcome. The submission steps live in <see cref="SubmitJobAsync"/> so their
|
||||
/// disposal scope stays inside this method's try block, which keeps every failure, including one raised while
|
||||
/// releasing a reservation, recorded through the same FAILED or OUTCOME_UNKNOWN decision. One timing line per job is
|
||||
/// logged afterwards so a slow print can be attributed to a phase from the service's own log without any extra
|
||||
/// request, payload or printer access.
|
||||
/// </summary>
|
||||
private async Task<bool> ProcessJobAsync(PrintJob job, IReadOnlyList<PrinterInfo> inventory, JobAttempt attempt, CancellationToken token)
|
||||
{
|
||||
PrinterInfo? assignedPrinter = inventory.FirstOrDefault(printer => string.Equals(printer.PrinterId, job.PrinterId, StringComparison.Ordinal));
|
||||
journal.TrackJob(job, string.IsNullOrWhiteSpace(assignedPrinter?.DisplayName) ? assignedPrinter?.Name : assignedPrinter.DisplayName);
|
||||
@@ -95,47 +106,89 @@ public sealed class PrintWorker(PrintApiClient api, IPrinterBackend printers, IJ
|
||||
return false;
|
||||
}
|
||||
|
||||
bool submitting = false;
|
||||
bool spooled = false;
|
||||
attempt.Restart();
|
||||
try
|
||||
{
|
||||
if(job.Options.Copies < 1 || job.Options.Copies > EffectiveSettings.MaxCopies)
|
||||
{
|
||||
throw new InvalidDataException("Copies exceed the effective printing policy.");
|
||||
}
|
||||
await using IAsyncDisposable? reservation = options?.ReserveDocumentAsync is null ? null : await options.ReserveDocumentAsync(job, token).ConfigureAwait(false);
|
||||
using DownloadedDocument? file = options?.StagingDirectory is null ? null : await api.DownloadFileAsync(job, options.StagingDirectory, options.Settings, token, options.ThrottleDownloadAsync).ConfigureAwait(false);
|
||||
byte[]? content = file is null ? await api.DownloadAsync(job, token).ConfigureAwait(false) : null;
|
||||
if(!printers.Discover().Any(p => string.Equals(p.PrinterId, job.PrinterId, StringComparison.Ordinal) && p.Formats.Contains(job.Format, StringComparer.Ordinal)))
|
||||
{
|
||||
throw new InvalidOperationException("Assigned printer or document format is unavailable.");
|
||||
}
|
||||
|
||||
await using IAsyncDisposable? submission = options?.AcquireSubmissionAsync is null ? null : await options.AcquireSubmissionAsync(job, token).ConfigureAwait(false);
|
||||
if((options?.CanSubmit ?? canDispatch)?.Invoke() == false)
|
||||
{ throw new InvalidOperationException("Dispatch is paused before native submission."); }
|
||||
Record(job, "SUBMITTING");
|
||||
await FlushAsync(token).ConfigureAwait(false);
|
||||
if((options?.CanSubmit ?? canDispatch)?.Invoke() == false)
|
||||
{ throw new InvalidOperationException("Dispatch stopped before native submission; no bytes were submitted."); }
|
||||
RealtimeSettings submissionSettings = EffectiveSettings;
|
||||
if(job.Options.Copies > submissionSettings.MaxCopies || job.ContentLength > submissionSettings.MaximumDocumentBytes(job.Format))
|
||||
{ throw new InvalidDataException("Document or copies exceed the current submission policy."); }
|
||||
token.ThrowIfCancellationRequested();
|
||||
submitting = true;
|
||||
string spoolId = file is not null && printers is IFilePrinterBackend files
|
||||
? await files.PrintFileAsync(job, file.Path, TimeSpan.FromMilliseconds(submissionSettings.NativeSubmissionTimeoutMillis), token).ConfigureAwait(false)
|
||||
: await printers.PrintAsync(job, content ?? throw new InvalidOperationException("File printing is required."), token).ConfigureAwait(false);
|
||||
Record(job, "SPOOLED", spoolerJobId: spoolId);
|
||||
spooled = true;
|
||||
}
|
||||
{ await SubmitJobAsync(job, attempt, token).ConfigureAwait(false); }
|
||||
catch(Exception exception)
|
||||
{
|
||||
Record(job, submitting ? "OUTCOME_UNKNOWN" : "FAILED", exception.Message);
|
||||
Record(job, attempt.Submitting && exception is not PrinterMediaMismatchException ? "OUTCOME_UNKNOWN" : "FAILED", exception.Message);
|
||||
}
|
||||
log?.Invoke(attempt.TimingMessage(job.JobId));
|
||||
if(!token.IsCancellationRequested)
|
||||
{ await FlushAsync(token).ConfigureAwait(false); }
|
||||
return spooled || options?.RecoverIncomplete == false;
|
||||
return attempt.Spooled || options?.RecoverIncomplete == false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Downloads, revalidates and submits one job. The reservation, staged file and submission lease are declared here and
|
||||
/// released when this method returns, after SPOOLED is recorded, exactly as when the same steps ran inline. The
|
||||
/// attempt records how far the job got so the caller can tell a refusal before any bytes from an uncertain submission.
|
||||
/// </summary>
|
||||
private async Task SubmitJobAsync(PrintJob job, JobAttempt attempt, CancellationToken token)
|
||||
{
|
||||
if(job.Options.Copies < 1 || job.Options.Copies > EffectiveSettings.MaxCopies)
|
||||
{
|
||||
throw new InvalidDataException("Copies exceed the effective printing policy.");
|
||||
}
|
||||
await using IAsyncDisposable? reservation = options?.ReserveDocumentAsync is null ? null : await options.ReserveDocumentAsync(job, token).ConfigureAwait(false);
|
||||
using DownloadedDocument? file = options?.StagingDirectory is null ? null : await api.DownloadFileAsync(job, options.StagingDirectory, options.Settings, token, options.ThrottleDownloadAsync).ConfigureAwait(false);
|
||||
byte[]? content = file is null ? await api.DownloadAsync(job, token).ConfigureAwait(false) : null;
|
||||
attempt.Download = attempt.Lap();
|
||||
RequireCurrentPrinter(job);
|
||||
attempt.Revalidate = attempt.Lap();
|
||||
|
||||
await using IAsyncDisposable? submission = options?.AcquireSubmissionAsync is null ? null : await options.AcquireSubmissionAsync(job, token).ConfigureAwait(false);
|
||||
RequireSubmitAllowed("Dispatch is paused before native submission.");
|
||||
Record(job, "SUBMITTING");
|
||||
await FlushAsync(token).ConfigureAwait(false);
|
||||
attempt.Gate = attempt.Lap();
|
||||
RequireSubmitAllowed("Dispatch stopped before native submission; no bytes were submitted.");
|
||||
RealtimeSettings submissionSettings = EffectiveSettings;
|
||||
if(job.Options.Copies > submissionSettings.MaxCopies || job.ContentLength > submissionSettings.MaximumDocumentBytes(job.Format))
|
||||
{ throw new InvalidDataException("Document or copies exceed the current submission policy."); }
|
||||
token.ThrowIfCancellationRequested();
|
||||
attempt.Submitting = true;
|
||||
attempt.Restart();
|
||||
string spoolId = await SubmitNativeAsync(job, file, content, submissionSettings, token).ConfigureAwait(false);
|
||||
attempt.Submit = attempt.Lap();
|
||||
Record(job, "SPOOLED", spoolerJobId: spoolId);
|
||||
attempt.Spooled = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Discovers the printers again after the download and requires the assigned queue to still offer the job's format and
|
||||
/// the selected media profile, so a queue or driver default that changed while the document streamed is refused before
|
||||
/// any submission instead of printing on the wrong stock.
|
||||
/// </summary>
|
||||
private void RequireCurrentPrinter(PrintJob job)
|
||||
{
|
||||
PrinterInfo? currentPrinter = printers.Discover().SingleOrDefault(p => string.Equals(p.PrinterId, job.PrinterId, StringComparison.Ordinal) && p.Formats.Contains(job.Format, StringComparer.Ordinal));
|
||||
if(currentPrinter is null)
|
||||
{
|
||||
throw new InvalidOperationException("Assigned printer or document format is unavailable.");
|
||||
}
|
||||
PrinterMediaProfile.RequireMatch(job.Options, currentPrinter.MediaProfiles);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Refuses the submission when dispatch is paused or stopped. It is checked before and after the SUBMITTING receipt is
|
||||
/// acknowledged, because a pause can arrive while that acknowledgement is in flight and no bytes may be sent after it.
|
||||
/// </summary>
|
||||
private void RequireSubmitAllowed(string refusal)
|
||||
{
|
||||
if((options?.CanSubmit ?? canDispatch)?.Invoke() == false)
|
||||
{ throw new InvalidOperationException(refusal); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Hands the verified staged file, or the in-memory content for a backend without file support, to the native printer
|
||||
/// and returns its spooler receipt. This is the only step after which an outcome is uncertain.
|
||||
/// </summary>
|
||||
private Task<string> SubmitNativeAsync(PrintJob job, DownloadedDocument? file, byte[]? content, RealtimeSettings submissionSettings, CancellationToken token)
|
||||
{
|
||||
return file is not null && printers is IFilePrinterBackend files
|
||||
? files.PrintFileAsync(job, file.Path, TimeSpan.FromMilliseconds(submissionSettings.NativeSubmissionTimeoutMillis), token)
|
||||
: printers.PrintAsync(job, content ?? throw new InvalidOperationException("File printing is required."), token);
|
||||
}
|
||||
|
||||
private RealtimeSettings EffectiveSettings => options?.CurrentSettings?.Invoke() ?? options?.Settings ?? new();
|
||||
@@ -165,7 +218,48 @@ public sealed class PrintWorker(PrintApiClient api, IPrinterBackend printers, IJ
|
||||
}
|
||||
finally { options?.EventGate?.Release(); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Progress and phase timing of one claimed job. Progress tells the caller whether native submission began, which
|
||||
/// decides between a known refusal and an uncertain outcome; the durations come from the monotonic clock and feed the
|
||||
/// single timing line, so they carry no document content.
|
||||
/// </summary>
|
||||
private sealed class JobAttempt(TimeSpan inventory, TimeSpan claim)
|
||||
{
|
||||
private long _mark = System.Diagnostics.Stopwatch.GetTimestamp();
|
||||
|
||||
public bool Submitting { get; set; }
|
||||
|
||||
public bool Spooled { get; set; }
|
||||
|
||||
public TimeSpan Download { get; set; }
|
||||
|
||||
public TimeSpan Revalidate { get; set; }
|
||||
|
||||
public TimeSpan Gate { get; set; }
|
||||
|
||||
public TimeSpan Submit { get; set; }
|
||||
|
||||
/// <summary>Starts the next phase now, discarding the time since the previous mark.</summary>
|
||||
public void Restart()
|
||||
{
|
||||
_mark = System.Diagnostics.Stopwatch.GetTimestamp();
|
||||
}
|
||||
|
||||
/// <summary>Returns the time since the previous mark and starts the next phase at the same instant, so phases never overlap or leave a gap.</summary>
|
||||
public TimeSpan Lap()
|
||||
{
|
||||
long now = System.Diagnostics.Stopwatch.GetTimestamp();
|
||||
TimeSpan elapsed = System.Diagnostics.Stopwatch.GetElapsedTime(_mark, now);
|
||||
_mark = now;
|
||||
return elapsed;
|
||||
}
|
||||
|
||||
/// <summary>Formats the one per-job log line: the job identifier and whole milliseconds per phase, nothing else.</summary>
|
||||
public string TimingMessage(string jobId)
|
||||
{
|
||||
return string.Create(System.Globalization.CultureInfo.InvariantCulture,
|
||||
$"{jobId}: timing inventory={inventory.TotalMilliseconds:F0}ms claim={claim.TotalMilliseconds:F0}ms download={Download.TotalMilliseconds:F0}ms revalidate={Revalidate.TotalMilliseconds:F0}ms gate={Gate.TotalMilliseconds:F0}ms submit={Submit.TotalMilliseconds:F0}ms");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
namespace Qqq.PrintAgent.Core.Printing;
|
||||
|
||||
public sealed record PrinterInfo(string PrinterId, string Name, string DriverName, string PortName, string Status, string[] Formats, string? DisplayName = null, string? Description = null, string? Location = null);
|
||||
public sealed record PrinterInfo(string PrinterId, string Name, string DriverName, string PortName, string Status, string[] Formats, string? DisplayName = null, string? Description = null, string? Location = null,
|
||||
IReadOnlyList<PrinterMediaProfile>? MediaProfiles = null);
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
/*
|
||||
* Copyright (c) 2026 James Maes
|
||||
* SPDX-License-Identifier: MIT
|
||||
*/
|
||||
|
||||
namespace Qqq.PrintAgent.Core.Printing;
|
||||
|
||||
/// <summary>A media validation refusal made before StartDoc/StartDocPrinter; no document bytes were submitted.</summary>
|
||||
public sealed class PrinterMediaMismatchException(string message) : InvalidOperationException(message);
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Copyright (c) 2026 James Maes
|
||||
* SPDX-License-Identifier: MIT
|
||||
*/
|
||||
|
||||
namespace Qqq.PrintAgent.Core.Printing;
|
||||
|
||||
/// <summary>A measured Windows machine queue default, not a claim about physically loaded stock.</summary>
|
||||
public sealed record PrinterMediaProfile(string Id, string Revision, string Name, int WidthMicrons, int HeightMicrons,
|
||||
int DpiX, int DpiY, string Source = "WINDOWS_QUEUE_DEFAULT", string ApplyMode = "DRIVER_DEFAULT")
|
||||
{
|
||||
/// <summary>Refuse stale, ambiguous or unavailable selected defaults before any native submission.</summary>
|
||||
public static void RequireMatch(PrintOptions options, IReadOnlyList<PrinterMediaProfile>? profiles)
|
||||
{
|
||||
PrinterMediaSelection? selection = options.MediaProfile;
|
||||
if(selection is null)
|
||||
{ return; }
|
||||
if(options.PaperWidthMm is not null || options.PaperHeightMm is not null || !ValidId(selection.Id)
|
||||
|| profiles is { Count: > 32 }
|
||||
|| selection.Revision is not { Length: 64 } || selection.Revision.Any(character => character is not (>= '0' and <= '9' or >= 'a' and <= 'f')))
|
||||
{ throw new PrinterMediaMismatchException("The selected printer media profile is invalid or conflicts with explicit paper dimensions."); }
|
||||
PrinterMediaProfile[] matches = profiles?.Where(profile => string.Equals(profile.Id, selection.Id, StringComparison.Ordinal)).ToArray() ?? [];
|
||||
if(matches.Length != 1 || !string.Equals(matches[0].Revision, selection.Revision, StringComparison.Ordinal)
|
||||
|| matches[0].Name is not { Length: >= 1 and <= 512 }
|
||||
|| matches[0].WidthMicrons is < 1 or > 2_000_000 || matches[0].HeightMicrons is < 1 or > 2_000_000
|
||||
|| matches[0].DpiX is < 1 or > 9600 || matches[0].DpiY is < 1 or > 9600
|
||||
|| !string.Equals(matches[0].Source, "WINDOWS_QUEUE_DEFAULT", StringComparison.Ordinal)
|
||||
|| !string.Equals(matches[0].ApplyMode, "DRIVER_DEFAULT", StringComparison.Ordinal))
|
||||
{ throw new PrinterMediaMismatchException("The selected printer media profile changed or is unavailable. Refresh the printer and select its current default."); }
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Matches the shared opaque-ID alphabet and length before profile lookup, preventing malformed selectors from reaching native submission.
|
||||
/// </summary>
|
||||
private static bool ValidId(string? id)
|
||||
=> id is { Length: >= 1 and <= 128 }
|
||||
&& id.All(character => character is >= 'A' and <= 'Z' or >= 'a' and <= 'z' or >= '0' and <= '9' or '.' or '_' or '-');
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/*
|
||||
* Copyright (c) 2026 James Maes
|
||||
* SPDX-License-Identifier: MIT
|
||||
*/
|
||||
|
||||
namespace Qqq.PrintAgent.Core.Printing;
|
||||
|
||||
/// <summary>An immutable reference to the exact queue default selected when the server created the job.</summary>
|
||||
public sealed record PrinterMediaSelection(string Id, string Revision);
|
||||
@@ -119,7 +119,7 @@ public sealed partial class AgentRuntime
|
||||
RealtimeSettings settings = _realtimeSettings;
|
||||
using var handshake = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token);
|
||||
handshake.CancelAfter(settings.WebSocketHandshakeTimeoutMillis);
|
||||
WebSocket socket = await ConnectRealtimeSocketAsync(settings, lifetime, handshake.Token).ConfigureAwait(false);
|
||||
(WebSocket socket, bool supportsMedia) = await ConnectRealtimeSocketAsync(settings, lifetime, handshake.Token).ConfigureAwait(false);
|
||||
using var channel = new PrintingRealtimeChannel(socket, settings, _traffic);
|
||||
var updates = Channel.CreateBounded<RealtimeStateUpdate>(4096);
|
||||
var commands = Channel.CreateBounded<RealtimeEnvelope>(4096);
|
||||
@@ -147,7 +147,7 @@ public sealed partial class AgentRuntime
|
||||
await channel.SendAsync("HELLO", new
|
||||
{
|
||||
agentVersion = PrintApiClient.AgentVersion,
|
||||
capabilities = RealtimeCapabilities,
|
||||
capabilities = supportsMedia ? [.. RealtimeCapabilities, "printer-media-v1"] : RealtimeCapabilities,
|
||||
lastAppliedRevision = _controlState.DesiredState.Revision,
|
||||
lastSettingsRevision = settings.Revision,
|
||||
limits = RealtimeSettings.ClientLimits,
|
||||
@@ -168,12 +168,20 @@ public sealed partial class AgentRuntime
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<WebSocket> ConnectRealtimeSocketAsync(RealtimeSettings settings, CancellationTokenSource lifetime, CancellationToken token)
|
||||
/// <summary>Reads the discovery refreshed by this socket establishment, so server upgrades and downgrades change capabilities on reconnect without polling.</summary>
|
||||
private async Task<(WebSocket Socket, bool SupportsMedia)> ConnectRealtimeSocketAsync(RealtimeSettings settings, CancellationTokenSource lifetime, CancellationToken token)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await (_sessionClient ?? throw new InvalidOperationException("Sign in is required.")).ConnectPrintingAsync(
|
||||
IQqqSessionClient session = _sessionClient ?? throw new InvalidOperationException("Sign in is required.");
|
||||
WebSocket socket = await session.ConnectPrintingAsync(
|
||||
TimeSpan.FromSeconds(settings.HeartbeatIntervalSeconds), TimeSpan.FromSeconds(settings.HeartbeatTimeoutSeconds), token).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
QqqApiDiscovery discovery = await session.DiscoverAsync(token).ConfigureAwait(false);
|
||||
return (socket, discovery.SupportsPrinterMedia());
|
||||
}
|
||||
catch { socket.Dispose(); throw; }
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
@@ -202,7 +202,7 @@ public sealed partial class AgentRuntime(string directory, Action<string> log, I
|
||||
using AgentStore store = new(directory, recoverUnreadableConfiguration: true);
|
||||
AgentConfiguration? configuration = store.LoadConfiguration();
|
||||
IReadOnlySet<string> exposed = store.GetExposedPrinterIds();
|
||||
var printers = new ProfiledPrinterBackend(_printers, store).Discover().Select(printer => new PrinterSnapshot(printer.PrinterId, printer.Name, printer.DriverName, printer.PortName, printer.Status, printer.Formats, exposed.Contains(printer.PrinterId), printer.DisplayName, printer.Description, printer.Location)).ToList();
|
||||
var printers = new ProfiledPrinterBackend(_printers, store).Discover().Select(printer => new PrinterSnapshot(printer.PrinterId, printer.Name, printer.DriverName, printer.PortName, printer.Status, printer.Formats, exposed.Contains(printer.PrinterId), printer.DisplayName, printer.Description, printer.Location, printer.MediaProfiles)).ToList();
|
||||
foreach(string missing in exposed.Where(id => !printers.Any(printer => string.Equals(printer.PrinterId, id, StringComparison.Ordinal))))
|
||||
{
|
||||
PrinterProfile profile = store.GetPrinterProfile(missing);
|
||||
|
||||
@@ -76,11 +76,7 @@ public sealed class IsolatedPrinterBackend(string helperExecutable) : IFilePrint
|
||||
PrinterWorkerHost.Response response = JsonSerializer.Deserialize<PrinterWorkerHost.Response>(text, PrintApiClient.JsonOptions) ?? throw new InvalidDataException("Printer worker returned no response.");
|
||||
if(child.ExitCode != 0 || !response.Success)
|
||||
{
|
||||
if(response.ErrorCode is "ALREADY_ABSENT" or "OWNERSHIP_MISMATCH")
|
||||
{
|
||||
throw new SpoolCancellationException(response.ErrorCode, response.Error ?? "Verified spool cancellation was refused.");
|
||||
}
|
||||
throw new IOException(response.Error ?? "The printer worker stopped unexpectedly. Inspect the printer before retrying.");
|
||||
ThrowWorkerFailure(response);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
@@ -105,4 +101,13 @@ public sealed class IsolatedPrinterBackend(string helperExecutable) : IFilePrint
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ThrowWorkerFailure(PrinterWorkerHost.Response response)
|
||||
{
|
||||
if(string.Equals(response.ErrorCode, "MEDIA_PROFILE_MISMATCH", StringComparison.Ordinal))
|
||||
{ throw new PrinterMediaMismatchException(response.Error ?? "The selected printer default changed before submission."); }
|
||||
if(response.ErrorCode is "ALREADY_ABSENT" or "OWNERSHIP_MISMATCH")
|
||||
{ throw new SpoolCancellationException(response.ErrorCode, response.Error ?? "Verified spool cancellation was refused."); }
|
||||
throw new IOException(response.Error ?? "The printer worker stopped unexpectedly. Inspect the printer before retrying.");
|
||||
}
|
||||
}
|
||||
@@ -7,5 +7,6 @@ namespace Qqq.PrintAgent.Windows;
|
||||
|
||||
/// <summary>A locally discovered queue and whether its owner has exposed it to QQQ.</summary>
|
||||
public sealed record PrinterSnapshot(string PrinterId, string Name, string DriverName, string PortName, string Status, string[] Formats, bool Exposed,
|
||||
string? DisplayName = null, string? Description = null, string? Location = null);
|
||||
string? DisplayName = null, string? Description = null, string? Location = null,
|
||||
IReadOnlyList<Qqq.PrintAgent.Core.Printing.PrinterMediaProfile>? MediaProfiles = null);
|
||||
|
||||
@@ -70,7 +70,7 @@ public static class PrinterWorkerHost
|
||||
}
|
||||
catch(Exception exception)
|
||||
{
|
||||
await Console.Out.WriteLineAsync(JsonSerializer.Serialize(new Response(false, Error: AgentActivityLog.Redact(exception.Message), ErrorCode: (exception as SpoolCancellationException)?.Outcome), PrintApiClient.JsonOptions)).ConfigureAwait(false);
|
||||
await Console.Out.WriteLineAsync(JsonSerializer.Serialize(new Response(false, Error: AgentActivityLog.Redact(exception.Message), ErrorCode: exception is PrinterMediaMismatchException ? "MEDIA_PROFILE_MISMATCH" : (exception as SpoolCancellationException)?.Outcome), PrintApiClient.JsonOptions)).ConfigureAwait(false);
|
||||
return 1;
|
||||
}
|
||||
finally
|
||||
|
||||
@@ -33,18 +33,19 @@ public sealed partial class WindowsPrinters
|
||||
}
|
||||
if(string.Equals(job.Format, "ZPL", StringComparison.Ordinal))
|
||||
{
|
||||
return PrintRawStream(printer.Name, job, input, cancellationToken);
|
||||
return PrintRawStream(printer, job, input, cancellationToken);
|
||||
}
|
||||
using global::Windows.Storage.Streams.IRandomAccessStream random = input.AsRandomAccessStream();
|
||||
PdfDocument document = await PdfDocument.LoadFromStreamAsync(random).AsTask(cancellationToken).ConfigureAwait(false);
|
||||
return await PrintPdfDocumentAsync(printer.Name, job, document, cancellationToken).ConfigureAwait(false);
|
||||
return await PrintPdfDocumentAsync(printer, job, document, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static string PrintRawStream(string printerName, PrintJob job, Stream input, CancellationToken token)
|
||||
private static string PrintRawStream(PrinterInfo selectedPrinter, PrintJob job, Stream input, CancellationToken token)
|
||||
{
|
||||
Check(Native.OpenPrinter(printerName, out IntPtr printer, IntPtr.Zero));
|
||||
Check(Native.OpenPrinter(selectedPrinter.Name, out IntPtr printer, IntPtr.Zero));
|
||||
try
|
||||
{
|
||||
_ = RequireCurrentMedia(selectedPrinter, job);
|
||||
Native.DocInfo1 info = new() { DocumentName = $"QQQ {job.JobId}", DataType = "RAW" };
|
||||
uint id = Native.StartDocPrinter(printer, 1, ref info);
|
||||
if(id == 0)
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
/*
|
||||
* Copyright (c) 2026 James Maes
|
||||
* SPDX-License-Identifier: MIT
|
||||
*/
|
||||
|
||||
using System.Buffers.Binary;
|
||||
using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Qqq.PrintAgent.Core.Printing;
|
||||
|
||||
namespace Qqq.PrintAgent.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// Reads machine queue defaults and verifies selected media before native submission, without inferring loaded stock.
|
||||
/// </summary>
|
||||
public sealed partial class WindowsPrinters
|
||||
{
|
||||
/// <summary>
|
||||
/// Keeps the complete driver bytes beside their resolved profile so validation and submission use the same captured defaults.
|
||||
/// </summary>
|
||||
private sealed record QueueDefaultMedia(byte[] DevMode, PrinterMediaProfile? Profile);
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Resolves bounded machine defaults into a selectable profile; unreadable queues remain discoverable without a media claim.
|
||||
/// </summary>
|
||||
private static QueueDefaultMedia? ReadQueueMedia(string id, string name, string driver, string port)
|
||||
{
|
||||
try
|
||||
{
|
||||
byte[]? mode = ReadMachineDevMode(name);
|
||||
if(mode is null)
|
||||
{ return null; }
|
||||
var pinned = GCHandle.Alloc(mode, GCHandleType.Pinned);
|
||||
try
|
||||
{
|
||||
IntPtr pointer = pinned.AddrOfPinnedObject();
|
||||
(int width, int height) = ResolvePaperDimensions(name, port, mode, pointer);
|
||||
(int dpiX, int dpiY) = ResolveResolution(name, mode, pointer);
|
||||
return new QueueDefaultMedia(mode, BuildMediaProfile(id, driver, mode, width, height, dpiX, dpiY));
|
||||
}
|
||||
finally { pinned.Free(); }
|
||||
}
|
||||
catch(Win32Exception)
|
||||
{
|
||||
// A queue without readable machine defaults has no selectable media profile.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Copies level-eight machine defaults only after checking native pointer and length bounds, avoiding per-user preferences.
|
||||
/// </summary>
|
||||
private static byte[]? ReadMachineDevMode(string name)
|
||||
{
|
||||
Check(Native.OpenPrinter(name, out IntPtr printer, IntPtr.Zero));
|
||||
try
|
||||
{
|
||||
_ = Native.GetPrinter(printer, 8, IntPtr.Zero, 0, out uint needed);
|
||||
if(needed < IntPtr.Size + 102 || needed > 1_048_576)
|
||||
{ return null; }
|
||||
IntPtr buffer = Marshal.AllocHGlobal(checked((int)needed));
|
||||
try
|
||||
{
|
||||
Check(Native.GetPrinter(printer, 8, buffer, needed, out _));
|
||||
IntPtr mode = Marshal.ReadIntPtr(buffer);
|
||||
long offset = mode.ToInt64() - buffer.ToInt64();
|
||||
if(mode == IntPtr.Zero || offset < IntPtr.Size || offset > needed - 102)
|
||||
{ return null; }
|
||||
int size = (ushort)Marshal.ReadInt16(mode, 68);
|
||||
int extra = (ushort)Marshal.ReadInt16(mode, 70);
|
||||
if(size < 102 || size + extra > needed - offset)
|
||||
{ return null; }
|
||||
byte[] bytes = new byte[size + extra];
|
||||
Marshal.Copy(mode, bytes, 0, bytes.Length);
|
||||
return bytes;
|
||||
}
|
||||
finally { Marshal.FreeHGlobal(buffer); }
|
||||
}
|
||||
finally { _ = Native.ClosePrinter(printer); }
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Uses both explicit form dimensions or an unambiguous driver paper-ID mapping, because partial dimensions are not reliable stock data.
|
||||
/// </summary>
|
||||
private static (int Width, int Height) ResolvePaperDimensions(string name, string port, byte[] mode, IntPtr pointer)
|
||||
{
|
||||
uint fields = BinaryPrimitives.ReadUInt32LittleEndian(mode.AsSpan(72));
|
||||
if((fields & 12) != 0)
|
||||
{
|
||||
// Both explicit fields are required; a half-specified custom form is ambiguous.
|
||||
return ReadExplicitDimensions(mode);
|
||||
}
|
||||
if((fields & 2) == 0)
|
||||
{ return (0, 0); }
|
||||
return ReadDriverPaperSize(name, port, pointer, ReadModeShort(mode, 78));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Pairs the driver's paper identifiers and size arrays and accepts exactly one bounded match, rather than guessing a standard form.
|
||||
/// </summary>
|
||||
private static (int Width, int Height) ReadDriverPaperSize(string name, string port, IntPtr mode, short paperId)
|
||||
{
|
||||
int count = Native.DeviceCapabilities(name, port, 2, IntPtr.Zero, mode);
|
||||
if(count is < 1 or > ushort.MaxValue || Native.DeviceCapabilities(name, port, 3, IntPtr.Zero, mode) != count)
|
||||
{ return (0, 0); }
|
||||
IntPtr identifiers = Marshal.AllocHGlobal(count * sizeof(short));
|
||||
IntPtr dimensions = Marshal.AllocHGlobal(count * 2 * sizeof(int));
|
||||
try
|
||||
{
|
||||
if(Native.DeviceCapabilities(name, port, 2, identifiers, mode) != count || Native.DeviceCapabilities(name, port, 3, dimensions, mode) != count)
|
||||
{ return (0, 0); }
|
||||
List<(int Width, int Height)> matches = [];
|
||||
for(int index = 0; index < count; index++)
|
||||
{
|
||||
if(Marshal.ReadInt16(identifiers, index * 2) == paperId)
|
||||
{
|
||||
int width = Marshal.ReadInt32(dimensions, index * 8);
|
||||
int height = Marshal.ReadInt32(dimensions, index * 8 + 4);
|
||||
if(width is < 1 or > 20_000 || height is < 1 or > 20_000)
|
||||
{ return (0, 0); }
|
||||
matches.Add((width * 100, height * 100));
|
||||
}
|
||||
}
|
||||
return matches.Count == 1 ? matches[0] : (0, 0);
|
||||
}
|
||||
finally { Marshal.FreeHGlobal(identifiers); Marshal.FreeHGlobal(dimensions); }
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Uses positive explicit DPI or a DC built from the captured defaults; symbolic quality values are not treated as resolution.
|
||||
/// </summary>
|
||||
private static (int X, int Y) ResolveResolution(string name, byte[] mode, IntPtr pointer)
|
||||
{
|
||||
uint fields = BinaryPrimitives.ReadUInt32LittleEndian(mode.AsSpan(72));
|
||||
if((fields & 0x2400) == 0x2400 && ReadModeShort(mode, 90) > 0 && ReadModeShort(mode, 96) > 0)
|
||||
{ return (ReadModeShort(mode, 90), ReadModeShort(mode, 96)); }
|
||||
// Symbolic quality values are not DPI. Ask this driver with this exact machine DEVMODE.
|
||||
IntPtr dc = Native.CreateDC("WINSPOOL", name, null, pointer);
|
||||
if(dc == IntPtr.Zero)
|
||||
{ return (0, 0); }
|
||||
try
|
||||
{ return (Native.GetDeviceCaps(dc, 88), Native.GetDeviceCaps(dc, 90)); }
|
||||
finally { _ = Native.DeleteDC(dc); }
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Validates dimensions, orientation and resolution, then fingerprints all public/private defaults so driver changes invalidate stale selections.
|
||||
/// </summary>
|
||||
internal static PrinterMediaProfile? BuildMediaProfile(string printerId, string driver, byte[] mode, int width, int height, int dpiX, int dpiY)
|
||||
{
|
||||
if(mode.Length < 102 || BinaryPrimitives.ReadUInt16LittleEndian(mode.AsSpan(68)) < 102
|
||||
|| BinaryPrimitives.ReadUInt16LittleEndian(mode.AsSpan(68)) + BinaryPrimitives.ReadUInt16LittleEndian(mode.AsSpan(70)) != mode.Length
|
||||
|| width is < 1 or > 2_000_000 || height is < 1 or > 2_000_000 || dpiX is < 1 or > 9600 || dpiY is < 1 or > 9600)
|
||||
{ return null; }
|
||||
uint fields = BinaryPrimitives.ReadUInt32LittleEndian(mode.AsSpan(72));
|
||||
if((fields & 1) == 0 || ReadModeShort(mode, 76) is not (1 or 2))
|
||||
{ return null; }
|
||||
if(ReadModeShort(mode, 76) == 2)
|
||||
{ (width, height) = (height, width); }
|
||||
string id = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(printerId + ":machine-default"))).ToLowerInvariant()[..24];
|
||||
string canonical = string.Create(CultureInfo.InvariantCulture, $"{printerId}\n{driver}\n{width}\n{height}\n{dpiX}\n{dpiY}\n");
|
||||
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
hash.AppendData(Encoding.UTF8.GetBytes(canonical));
|
||||
hash.AppendData(mode);
|
||||
string revision = Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant();
|
||||
string label = string.Create(CultureInfo.InvariantCulture, $"Windows queue default ({width / 1000m} × {height / 1000m} mm, {dpiX} × {dpiY} DPI)");
|
||||
return new PrinterMediaProfile(id, revision, label, width, height, dpiX, dpiY);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Reads a validated DEVMODE short at its native little-endian offset without interpreting driver-private bytes.
|
||||
/// </summary>
|
||||
private static short ReadModeShort(byte[] mode, int offset) => BinaryPrimitives.ReadInt16LittleEndian(mode.AsSpan(offset));
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Converts complete DEVMODE form dimensions from tenths of a millimeter to microns; missing fields return unknown geometry.
|
||||
/// </summary>
|
||||
internal static (int Width, int Height) ReadExplicitDimensions(byte[] mode)
|
||||
=> mode.Length >= 84 && (BinaryPrimitives.ReadUInt32LittleEndian(mode.AsSpan(72)) & 12) == 12
|
||||
? (ReadModeShort(mode, 82) * 100, ReadModeShort(mode, 80) * 100) : (0, 0);
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Re-reads and matches selected defaults at the native submission boundary, while leaving legacy unselected jobs on their existing path.
|
||||
/// </summary>
|
||||
private static QueueDefaultMedia? RequireCurrentMedia(PrinterInfo printer, PrintJob job)
|
||||
{
|
||||
if(job.Options.MediaProfile is null)
|
||||
{ return null; }
|
||||
QueueDefaultMedia? media = ReadQueueMedia(printer.PrinterId, printer.Name, printer.DriverName, printer.PortName);
|
||||
PrinterMediaProfile.RequireMatch(job.Options, media?.Profile is null ? [] : [media.Profile]);
|
||||
return media;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Passes the pinned captured or normalized job settings to GDI so selected jobs do not silently request current-user defaults.
|
||||
/// </summary>
|
||||
private static IntPtr CreateDocumentContext(string printerName, byte[]? mode)
|
||||
=> WithPinnedMode(mode, pointer => Native.CreateDC("WINSPOOL", printerName, null, pointer));
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Checks active overrides and the effective DC's physical dimensions/DPI before invoking StartDoc, so substituted defaults cannot open a spool document.
|
||||
/// </summary>
|
||||
internal static int StartValidatedPdfDocument(byte[]? mode, PrinterMediaProfile? profile, Func<int, int> deviceCaps, Func<int> startDocument)
|
||||
{
|
||||
if(profile is not null)
|
||||
{
|
||||
RequirePdfDefaults(mode);
|
||||
int dpiX = deviceCaps(88);
|
||||
int dpiY = deviceCaps(90);
|
||||
if(dpiX != profile.DpiX || dpiY != profile.DpiY
|
||||
|| !MatchesPhysicalDimension(deviceCaps(110), dpiX, profile.WidthMicrons)
|
||||
|| !MatchesPhysicalDimension(deviceCaps(111), dpiY, profile.HeightMicrons))
|
||||
{
|
||||
throw new PrinterMediaMismatchException("The printer device context does not match the selected media dimensions and resolution.");
|
||||
}
|
||||
}
|
||||
return startDocument();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Rejects active driver copy or scale settings that would multiply or resize the renderer's output; unsupported fields remain ignored.
|
||||
/// </summary>
|
||||
private static void RequirePdfDefaults(byte[]? mode)
|
||||
{
|
||||
if(mode is null || mode.Length < 102)
|
||||
{
|
||||
throw new PrinterMediaMismatchException("The selected PDF media has no complete machine defaults.");
|
||||
}
|
||||
uint fields = BinaryPrimitives.ReadUInt32LittleEndian(mode.AsSpan(72));
|
||||
// The renderer owns copies and scaling. Do not patch vendor-private DEVMODE data.
|
||||
if(((fields & 0x100) != 0 && ReadModeShort(mode, 86) != 1)
|
||||
|| ((fields & 0x10) != 0 && ReadModeShort(mode, 84) != 100))
|
||||
{
|
||||
throw new PrinterMediaMismatchException("Selected PDF media requires Windows queue defaults of one copy and 100 percent scale.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Compares physical pixels with selected microns using only device-pixel and form-unit rounding tolerance, never printable-area dimensions.
|
||||
/// </summary>
|
||||
private static bool MatchesPhysicalDimension(int pixels, int dpi, int microns)
|
||||
{
|
||||
if(pixels <= 0 || dpi <= 0)
|
||||
{ return false; }
|
||||
// Allow one device pixel plus half the DEVMODE form unit (0.1 mm).
|
||||
double pixelMicrons = 25_400d / dpi;
|
||||
return Math.Abs(pixels * pixelMicrons - microns) <= pixelMicrons + 50;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Pins the complete settings buffer for the synchronous native call and always releases it; null is reserved for the legacy path.
|
||||
/// </summary>
|
||||
internal static IntPtr WithPinnedMode(byte[]? mode, Func<IntPtr, IntPtr> create)
|
||||
{
|
||||
if(mode is null)
|
||||
{ return create(IntPtr.Zero); }
|
||||
var pinned = GCHandle.Alloc(mode, GCHandleType.Pinned);
|
||||
try
|
||||
{ return create(pinned.AddrOfPinnedObject()); }
|
||||
finally { pinned.Free(); }
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Contains read-only Winspool entry points used to obtain machine defaults and driver form capabilities.
|
||||
/// </summary>
|
||||
private static partial class Native
|
||||
{
|
||||
/// <summary>
|
||||
/// Reads printer information into a caller-sized buffer; level eight supplies machine-wide DEVMODE defaults.
|
||||
/// </summary>
|
||||
[DllImport("winspool.drv", EntryPoint = "GetPrinterW", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static extern bool GetPrinter(IntPtr printer, uint level, IntPtr buffer, uint size, out uint needed);
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Queries driver capabilities against the supplied DEVMODE so paper IDs and sizes refer to the same captured configuration.
|
||||
/// </summary>
|
||||
[DllImport("winspool.drv", EntryPoint = "DeviceCapabilitiesW", CharSet = CharSet.Unicode)]
|
||||
internal static extern int DeviceCapabilities(string device, string port, ushort capability, IntPtr output, IntPtr devMode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
* Copyright (c) 2026 James Maes
|
||||
* SPDX-License-Identifier: MIT
|
||||
*/
|
||||
|
||||
using System.Buffers.Binary;
|
||||
using System.Runtime.InteropServices;
|
||||
using Qqq.PrintAgent.Core.Printing;
|
||||
|
||||
namespace Qqq.PrintAgent.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// Prepares job-local PDF settings through the driver while preserving the queue-default fingerprint and leaving persistent settings untouched.
|
||||
/// </summary>
|
||||
public sealed partial class WindowsPrinters
|
||||
{
|
||||
/// <summary>
|
||||
/// Normalizes a selected PDF job and resolves the returned driver settings again, refusing any geometry or DPI change.
|
||||
/// </summary>
|
||||
private static byte[] PreparePdfMode(PrinterInfo printer, QueueDefaultMedia media)
|
||||
=> NormalizePdfMode(media.DevMode, media.Profile!, mode => MergeDriverMode(printer.Name, mode), mode =>
|
||||
{
|
||||
var pinned = GCHandle.Alloc(mode, GCHandleType.Pinned);
|
||||
try
|
||||
{
|
||||
IntPtr pointer = pinned.AddrOfPinnedObject();
|
||||
(int width, int height) = ResolvePaperDimensions(printer.Name, printer.PortName, mode, pointer);
|
||||
(int dpiX, int dpiY) = ResolveResolution(printer.Name, mode, pointer);
|
||||
return BuildMediaProfile(printer.PrinterId, printer.DriverName, mode, width, height, dpiX, dpiY);
|
||||
}
|
||||
finally { pinned.Free(); }
|
||||
});
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Clones captured defaults, overrides only supported copy/scale fields, and verifies driver output without altering the selection fingerprint.
|
||||
/// </summary>
|
||||
internal static byte[] NormalizePdfMode(byte[] captured, PrinterMediaProfile selected,
|
||||
Func<byte[], byte[]> normalize, Func<byte[], PrinterMediaProfile?> resolve)
|
||||
{
|
||||
byte[] input = captured.ToArray();
|
||||
uint fields = BinaryPrimitives.ReadUInt32LittleEndian(input.AsSpan(72));
|
||||
uint overrides = fields & 0x110;
|
||||
if((overrides & 0x10) != 0)
|
||||
{ BinaryPrimitives.WriteInt16LittleEndian(input.AsSpan(84), 100); }
|
||||
if((overrides & 0x100) != 0)
|
||||
{ BinaryPrimitives.WriteInt16LittleEndian(input.AsSpan(86), 1); }
|
||||
byte[] output = normalize(input);
|
||||
RequirePdfDefaults(output);
|
||||
if((BinaryPrimitives.ReadUInt32LittleEndian(output.AsSpan(72)) & 0x110) != overrides)
|
||||
{
|
||||
throw new PrinterMediaMismatchException("The driver changed support for job-level copies or scale.");
|
||||
}
|
||||
PrinterMediaProfile? effective = resolve(output);
|
||||
if(effective is null || effective.WidthMicrons != selected.WidthMicrons || effective.HeightMicrons != selected.HeightMicrons
|
||||
|| effective.DpiX != selected.DpiX || effective.DpiY != selected.DpiY)
|
||||
{
|
||||
throw new PrinterMediaMismatchException("The driver changed selected media while applying job-level copies and scale.");
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Lets DocumentProperties reconcile private settings in bounded buffers using input/output flags only, with no prompt or queue update.
|
||||
/// </summary>
|
||||
private static byte[] MergeDriverMode(string printerName, byte[] input)
|
||||
{
|
||||
Check(Native.OpenPrinter(printerName, out IntPtr printer, IntPtr.Zero));
|
||||
try
|
||||
{
|
||||
int required = Native.DocumentProperties(IntPtr.Zero, printer, printerName, IntPtr.Zero, IntPtr.Zero, 0);
|
||||
if(required is < 102 or > 1_048_576)
|
||||
{
|
||||
throw new PrinterMediaMismatchException("The driver did not provide a bounded document-settings buffer.");
|
||||
}
|
||||
byte[] output = new byte[required];
|
||||
var source = GCHandle.Alloc(input, GCHandleType.Pinned);
|
||||
var destination = GCHandle.Alloc(output, GCHandleType.Pinned);
|
||||
try
|
||||
{
|
||||
// DM_IN_BUFFER | DM_OUT_BUFFER only: no prompt and no queue-default update.
|
||||
if(Native.DocumentProperties(IntPtr.Zero, printer, printerName, destination.AddrOfPinnedObject(), source.AddrOfPinnedObject(), 10) != 1)
|
||||
{
|
||||
throw new PrinterMediaMismatchException("The driver refused job-level document settings.");
|
||||
}
|
||||
}
|
||||
finally { destination.Free(); source.Free(); }
|
||||
int size = BinaryPrimitives.ReadUInt16LittleEndian(output.AsSpan(68));
|
||||
int extra = BinaryPrimitives.ReadUInt16LittleEndian(output.AsSpan(70));
|
||||
if(size < 102 || size + extra > output.Length)
|
||||
{
|
||||
throw new PrinterMediaMismatchException("The driver returned incomplete document settings.");
|
||||
}
|
||||
return output[..(size + extra)];
|
||||
}
|
||||
finally { _ = Native.ClosePrinter(printer); }
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Contains the driver-normalization call used to create application-local DEVMODE settings.
|
||||
/// </summary>
|
||||
private static partial class Native
|
||||
{
|
||||
/// <summary>
|
||||
/// Queries required buffer size or merges job settings; callers deliberately omit prompt and persistent-update flags.
|
||||
/// </summary>
|
||||
[DllImport("winspool.drv", EntryPoint = "DocumentPropertiesW", CharSet = CharSet.Unicode)]
|
||||
internal static extern int DocumentProperties(IntPtr window, IntPtr printer, string device, IntPtr output, IntPtr input, uint mode);
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,9 @@ public sealed partial class WindowsPrinters : IFilePrinterBackend
|
||||
string port = Marshal.PtrToStringUni(info.PortName) ?? "";
|
||||
bool interactive = RequiresInteractiveOutput(port, driver);
|
||||
string id = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(name))).ToLowerInvariant()[..24];
|
||||
printers.Add(new PrinterInfo(id, name, driver, port, interactive ? "UNKNOWN" : status, interactive ? [] : zebra ? ["PDF", "ZPL"] : ["PDF"]));
|
||||
QueueDefaultMedia? media = interactive ? null : ReadQueueMedia(id, name, driver, port);
|
||||
printers.Add(new PrinterInfo(id, name, driver, port, interactive ? "UNKNOWN" : status, interactive ? [] : zebra ? ["PDF", "ZPL"] : ["PDF"],
|
||||
MediaProfiles: media?.Profile is null ? [] : [media.Profile]));
|
||||
}
|
||||
return printers;
|
||||
}
|
||||
@@ -118,18 +120,19 @@ public sealed partial class WindowsPrinters : IFilePrinterBackend
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
return job.Format switch
|
||||
{
|
||||
"ZPL" => PrintRaw(printer.Name, job, content),
|
||||
"PDF" => await PrintPdfAsync(printer.Name, job, content, cancellationToken).ConfigureAwait(false),
|
||||
"ZPL" => PrintRaw(printer, job, content),
|
||||
"PDF" => await PrintPdfAsync(printer, job, content, cancellationToken).ConfigureAwait(false),
|
||||
_ => throw new InvalidDataException("Unsupported document format."),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Send printer-ready ZPL bytes, handling partial spooler writes.</summary>
|
||||
private static string PrintRaw(string printerName, PrintJob job, byte[] content)
|
||||
private static string PrintRaw(PrinterInfo selectedPrinter, PrintJob job, byte[] content)
|
||||
{
|
||||
Check(Native.OpenPrinter(printerName, out IntPtr printer, IntPtr.Zero));
|
||||
Check(Native.OpenPrinter(selectedPrinter.Name, out IntPtr printer, IntPtr.Zero));
|
||||
try
|
||||
{
|
||||
_ = RequireCurrentMedia(selectedPrinter, job);
|
||||
Native.DocInfo1 info = new() { DocumentName = $"QQQ {job.JobId}", DataType = "RAW" };
|
||||
uint id = Native.StartDocPrinter(printer, 1, ref info);
|
||||
if(id == 0)
|
||||
@@ -163,7 +166,7 @@ public sealed partial class WindowsPrinters : IFilePrinterBackend
|
||||
}
|
||||
|
||||
/// <summary>Own the native document lifecycle while rendering its PDF pages.</summary>
|
||||
private static async Task<string> PrintPdfAsync(string printerName, PrintJob job, byte[] content, CancellationToken cancellationToken)
|
||||
private static async Task<string> PrintPdfAsync(PrinterInfo printer, PrintJob job, byte[] content, CancellationToken cancellationToken)
|
||||
{
|
||||
using InMemoryRandomAccessStream pdfStream = new();
|
||||
using(DataWriter writer = new(pdfStream))
|
||||
@@ -174,12 +177,14 @@ public sealed partial class WindowsPrinters : IFilePrinterBackend
|
||||
}
|
||||
pdfStream.Seek(0);
|
||||
PdfDocument document = await PdfDocument.LoadFromStreamAsync(pdfStream);
|
||||
return await PrintPdfDocumentAsync(printerName, job, document, cancellationToken).ConfigureAwait(false);
|
||||
return await PrintPdfDocumentAsync(printer, job, document, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task<string> PrintPdfDocumentAsync(string printerName, PrintJob job, PdfDocument document, CancellationToken cancellationToken)
|
||||
private static async Task<string> PrintPdfDocumentAsync(PrinterInfo printer, PrintJob job, PdfDocument document, CancellationToken cancellationToken)
|
||||
{
|
||||
IntPtr dc = Native.CreateDC("WINSPOOL", printerName, null, IntPtr.Zero);
|
||||
QueueDefaultMedia? media = RequireCurrentMedia(printer, job);
|
||||
byte[]? documentMode = media is null ? null : PreparePdfMode(printer, media);
|
||||
IntPtr dc = CreateDocumentContext(printer.Name, documentMode);
|
||||
if(dc == IntPtr.Zero)
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
@@ -188,7 +193,8 @@ public sealed partial class WindowsPrinters : IFilePrinterBackend
|
||||
try
|
||||
{
|
||||
Native.DocInfo info = new() { Size = Marshal.SizeOf<Native.DocInfo>(), DocumentName = $"QQQ {job.JobId}" };
|
||||
int jobId = Native.StartDoc(dc, ref info);
|
||||
int jobId = StartValidatedPdfDocument(documentMode, media?.Profile,
|
||||
capability => Native.GetDeviceCaps(dc, capability), () => Native.StartDoc(dc, ref info));
|
||||
if(jobId <= 0)
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
@@ -272,7 +278,7 @@ public sealed partial class WindowsPrinters : IFilePrinterBackend
|
||||
}
|
||||
}
|
||||
|
||||
private static class Native
|
||||
private static partial class Native
|
||||
{
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal struct PrinterInfo2
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Copyright (c) 2026 James Maes
|
||||
* SPDX-License-Identifier: MIT
|
||||
*/
|
||||
|
||||
using Qqq.PrintAgent.Core.Authentication;
|
||||
using Qqq.PrintAgent.Core.Printing;
|
||||
|
||||
namespace Qqq.PrintAgent.Cli.Tests;
|
||||
|
||||
/// <summary>Checks the real session/realtime handshake against controlled discovery so additive media support cannot disconnect older servers.</summary>
|
||||
public sealed class AgentRealtimeMediaCapabilitiesTests
|
||||
{
|
||||
/// <summary>Reads actual HELLO frames before and after reconnect, proving each socket refreshes discovery once without HTTP polling.</summary>
|
||||
[Theory]
|
||||
[InlineData("2.0.0", false)]
|
||||
[InlineData("2.1.9", false)]
|
||||
[InlineData("2.2.0", false)]
|
||||
[InlineData("2.2.9", false)]
|
||||
[InlineData("2.3.0", true)]
|
||||
[InlineData("2.4.0", true)]
|
||||
public async Task HelloAdvertisesMediaOnlyAfterStandardDiscoveryConfirmsSupport(string version, bool media)
|
||||
{
|
||||
await using var fixture = new RealtimeRuntimeFixture(printingVersion: version);
|
||||
RealtimeRuntimeFixture.Connection first = await fixture.ConnectAsync();
|
||||
string[] expected = media ? ["realtime-v1", "REFRESH_INVENTORY", "CANCEL_SPOOL", "printer-media-v1"]
|
||||
: ["realtime-v1", "REFRESH_INVENTORY", "CANCEL_SPOOL"];
|
||||
Assert.Equal(expected, fixture.LastHelloCapabilities);
|
||||
// One initial authentication discovery, then one fresh discovery per socket.
|
||||
Assert.Equal(2, fixture.DiscoveryRequests);
|
||||
first.Abort();
|
||||
_ = await fixture.ConnectAsync();
|
||||
Assert.Equal(expected, fixture.LastHelloCapabilities);
|
||||
Assert.Equal(3, fixture.DiscoveryRequests);
|
||||
Assert.Equal(0, fixture.ForbiddenPolls);
|
||||
Assert.Equal(0, fixture.Printer.Prints);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>Changes a running server's version and proves capabilities change only on the next socket, with the existing session retained.</summary>
|
||||
[Theory]
|
||||
[InlineData("2.0.0", "2.3.0", true)]
|
||||
[InlineData("2.2.0", "2.3.0", true)]
|
||||
[InlineData("2.3.0", "2.2.0", false)]
|
||||
[InlineData("2.3.0", "2.1.0", false)]
|
||||
public async Task SameSessionReconnectTracksServerUpgradeAndDowngrade(string initial, string replacement, bool mediaAfter)
|
||||
{
|
||||
await using var fixture = new RealtimeRuntimeFixture(printingVersion: initial);
|
||||
RealtimeRuntimeFixture.Connection first = await fixture.ConnectAsync();
|
||||
Assert.Equal(!mediaAfter, fixture.LastHelloCapabilities.Contains("printer-media-v1", StringComparer.Ordinal));
|
||||
Assert.Equal(2, fixture.DiscoveryRequests);
|
||||
fixture.PrintingVersion = replacement;
|
||||
await first.SendAsync("DESIRED_STATE", new DeviceDesiredState(2, true, "CONNECTED"));
|
||||
await fixture.WaitAsync(() => fixture.Runtime.GetSnapshot().Control!.DesiredState.Revision == 2);
|
||||
Assert.Equal(2, fixture.DiscoveryRequests);
|
||||
first.Abort();
|
||||
_ = await fixture.ConnectAsync(desiredState: new DeviceDesiredState(2, true, "CONNECTED"));
|
||||
Assert.Equal(mediaAfter, fixture.LastHelloCapabilities.Contains("printer-media-v1", StringComparer.Ordinal));
|
||||
Assert.Equal(3, fixture.DiscoveryRequests);
|
||||
Assert.Equal(0, fixture.ForbiddenPolls);
|
||||
Assert.Equal(0, fixture.Printer.Prints);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>Rejects ambiguous or nonstable discovery claims even when a test transport bypasses the production discovery validator.</summary>
|
||||
[Theory]
|
||||
[InlineData("2.3.0-rc.1")]
|
||||
[InlineData("2.3")]
|
||||
[InlineData("2.3.0.1")]
|
||||
[InlineData("02.3.0")]
|
||||
[InlineData("2.2.0")]
|
||||
[InlineData("3.0.0")]
|
||||
public void UnverifiedSemanticVersionsCannotClaimMedia(string version)
|
||||
{
|
||||
var discovery = new QqqApiDiscovery { Extensions = [new("printing", version, "/qbit/printing")] };
|
||||
Assert.False(discovery.SupportsPrinterMedia());
|
||||
Assert.False(new QqqApiDiscovery().SupportsPrinterMedia());
|
||||
Assert.False(new QqqApiDiscovery { Extensions = [new("printing", "2.3.0", "/wrong")] }.SupportsPrinterMedia());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
/*
|
||||
* Copyright (c) 2026 James Maes
|
||||
* SPDX-License-Identifier: MIT
|
||||
*/
|
||||
|
||||
using System.Buffers.Binary;
|
||||
using System.Runtime.InteropServices;
|
||||
using Qqq.PrintAgent.Core.Printing;
|
||||
using Qqq.PrintAgent.Windows;
|
||||
|
||||
namespace Qqq.PrintAgent.Cli.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Tests native-media decisions with synthetic DEVMODE bytes and injected driver/DC results; no test opens a real spool document.
|
||||
/// </summary>
|
||||
public sealed class PrinterMediaTests
|
||||
{
|
||||
/// <summary>
|
||||
/// Checks 4-by-1, 4-by-2 and 4-by-6 form conversion using queue bytes rather than PDF dimensions or assumptions about loaded labels.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(254, 25400)]
|
||||
[InlineData(508, 50800)]
|
||||
[InlineData(1524, 152400)]
|
||||
public void ConfiguredLabelDimensionsComeFromMachineDevMode(int length, int expectedHeight)
|
||||
{
|
||||
byte[] mode = Mode((short)length);
|
||||
(int width, int height) = WindowsPrinters.ReadExplicitDimensions(mode);
|
||||
PrinterMediaProfile profile = Assert.IsType<PrinterMediaProfile>(WindowsPrinters.BuildMediaProfile("fixture", "driver", mode, width, height, 300, 300));
|
||||
Assert.Equal(101600, profile.WidthMicrons);
|
||||
Assert.Equal(expectedHeight, profile.HeightMicrons);
|
||||
Assert.Equal(300, profile.DpiX);
|
||||
Assert.Equal(300, profile.DpiY);
|
||||
Assert.Equal("WINDOWS_QUEUE_DEFAULT", profile.Source);
|
||||
Assert.Equal("DRIVER_DEFAULT", profile.ApplyMode);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Ensures incomplete geometry, unknown DPI and out-of-range dimensions cannot produce a selectable profile.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void PartialDimensionsAndUnknownDpiCannotAdvertiseSupportedStock()
|
||||
{
|
||||
byte[] mode = Mode(1524);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(mode.AsSpan(72), 5);
|
||||
Assert.Equal((0, 0), WindowsPrinters.ReadExplicitDimensions(mode));
|
||||
Assert.Null(WindowsPrinters.BuildMediaProfile("fixture", "driver", mode, 101600, 152400, 0, 300));
|
||||
Assert.Null(WindowsPrinters.BuildMediaProfile("fixture", "driver", mode, 101600, 152400, 300, -4));
|
||||
Assert.Null(WindowsPrinters.BuildMediaProfile("fixture", "driver", mode, 2_000_001, 152400, 300, 300));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Checks repeatable fingerprints and invalidation by private defaults or driver identity, including landscape axis resolution.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void RevisionIsStableButPrivateConfigurationAndDriverChangesInvalidateIt()
|
||||
{
|
||||
byte[] mode = Mode(1524);
|
||||
PrinterMediaProfile first = Profile(mode);
|
||||
Assert.Equal(first, Profile(mode.ToArray()));
|
||||
mode[^1] = 1;
|
||||
PrinterMediaProfile changed = Profile(mode);
|
||||
Assert.Equal(first.Id, changed.Id);
|
||||
Assert.NotEqual(first.Revision, changed.Revision, StringComparer.Ordinal);
|
||||
Assert.NotEqual(first.Revision, WindowsPrinters.BuildMediaProfile("fixture", "different driver", Mode(1524), 101600, 152400, 300, 300)!.Revision, StringComparer.Ordinal);
|
||||
BinaryPrimitives.WriteInt16LittleEndian(mode.AsSpan(76), 2);
|
||||
Assert.Equal(152400, Profile(mode).WidthMicrons);
|
||||
Assert.Equal(101600, Profile(mode).HeightMicrons);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Reads the actual pinned callback buffer to prove selected bytes are passed intact and the legacy null path remains distinct.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void PdfFactoryReceivesTheCapturedDefaultBytesRatherThanCurrentUserDefaults()
|
||||
{
|
||||
byte[] captured = Mode(508);
|
||||
IntPtr result = WindowsPrinters.WithPinnedMode(captured, pointer =>
|
||||
{
|
||||
Assert.NotEqual(IntPtr.Zero, pointer);
|
||||
byte[] actual = new byte[captured.Length];
|
||||
Marshal.Copy(pointer, actual, 0, actual.Length);
|
||||
Assert.Equal(captured, actual);
|
||||
return new IntPtr(42);
|
||||
});
|
||||
Assert.Equal(new IntPtr(42), result);
|
||||
Assert.Equal(IntPtr.Zero, WindowsPrinters.WithPinnedMode(null, pointer => pointer));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Rejects invalid orientation and incomplete private settings instead of advertising unverifiable media.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void UnknownOrientationAndTruncatedDriverDataDoNotProduceProfiles()
|
||||
{
|
||||
byte[] mode = Mode(1524);
|
||||
BinaryPrimitives.WriteInt16LittleEndian(mode.AsSpan(76), 0);
|
||||
Assert.Null(WindowsPrinters.BuildMediaProfile("fixture", "driver", mode, 101600, 152400, 300, 300));
|
||||
Assert.Null(WindowsPrinters.BuildMediaProfile("fixture", "driver", Mode(1524)[..^1], 101600, 152400, 300, 300));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Builds a synthetic 300-DPI profile from supplied driver bytes, allowing tests to isolate normalization and fingerprint changes.
|
||||
/// </summary>
|
||||
private static PrinterMediaProfile Profile(byte[] mode)
|
||||
=> Assert.IsType<PrinterMediaProfile>(WindowsPrinters.BuildMediaProfile("fixture", "driver", mode, 101600, 152400, 300, 300));
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Verifies conflicting active driver settings fail before the injected StartDoc callback and leave captured bytes untouched.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(2, 100)]
|
||||
[InlineData(1, 50)]
|
||||
[InlineData(0, 100)]
|
||||
public void DriverCopiesOrScalingCannotMultiplyOrResizeSelectedPdf(int copies, int scale)
|
||||
{
|
||||
byte[] mode = Mode(1524);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(mode.AsSpan(72), 0x11d);
|
||||
BinaryPrimitives.WriteInt16LittleEndian(mode.AsSpan(86), (short)copies);
|
||||
BinaryPrimitives.WriteInt16LittleEndian(mode.AsSpan(84), (short)scale);
|
||||
byte[] original = mode.ToArray();
|
||||
int submissions = 0;
|
||||
Assert.Throws<PrinterMediaMismatchException>(() => WindowsPrinters.StartValidatedPdfDocument(mode, Profile(mode),
|
||||
capability => Caps(capability, 1200, 1800, 300, 300), () => ++submissions));
|
||||
Assert.Equal(0, submissions);
|
||||
Assert.Equal(original, mode);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Simulates wrong physical size, orientation, resolution and unknown caps to prove effective-DC mismatches make zero submissions.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(1200, 600, 300, 300)]
|
||||
[InlineData(1800, 1200, 300, 300)]
|
||||
[InlineData(1200, 1800, 203, 300)]
|
||||
[InlineData(1200, 1800, 300, 600)]
|
||||
[InlineData(0, 1800, 300, 300)]
|
||||
public void RejectedOrSubstitutedDeviceContextNeverStartsDocument(int width, int height, int dpiX, int dpiY)
|
||||
{
|
||||
byte[] mode = Mode(1524);
|
||||
int submissions = 0;
|
||||
Assert.Throws<PrinterMediaMismatchException>(() => WindowsPrinters.StartValidatedPdfDocument(mode, Profile(mode),
|
||||
capability => Caps(capability, width, height, dpiX, dpiY), () => ++submissions));
|
||||
Assert.Equal(0, submissions);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Accepts matching portrait/landscape device contexts within one-pixel rounding and invokes the document callback exactly once.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void MatchingEffectiveContextAllowsOneDocumentWithDevicePixelRounding(bool landscape)
|
||||
{
|
||||
byte[] mode = Mode(1524);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(mode.AsSpan(72), 0x11d);
|
||||
BinaryPrimitives.WriteInt16LittleEndian(mode.AsSpan(86), 1);
|
||||
BinaryPrimitives.WriteInt16LittleEndian(mode.AsSpan(84), 100);
|
||||
BinaryPrimitives.WriteInt16LittleEndian(mode.AsSpan(76), (short)(landscape ? 2 : 1));
|
||||
int submissions = 0;
|
||||
int result = WindowsPrinters.StartValidatedPdfDocument(mode, Profile(mode),
|
||||
capability => Caps(capability, landscape ? 1801 : 1201, landscape ? 1200 : 1800, 300, 300), () => ++submissions);
|
||||
Assert.Equal(1, result);
|
||||
Assert.Equal(1, submissions);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Maps only the physical-size and DPI capability indices used by validation, making accidental reliance on other driver values fail the test.
|
||||
/// </summary>
|
||||
private static int Caps(int capability, int width, int height, int dpiX, int dpiY) => capability switch
|
||||
{
|
||||
110 => width,
|
||||
111 => height,
|
||||
88 => dpiX,
|
||||
90 => dpiY,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(capability)),
|
||||
};
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Simulates a driver's private copy-count mirror update and proves job-only normalization preserves original queue bytes and revision.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void JobOverridesAreMergedByDriverWithoutChangingQueueFingerprintOrPrivateInput()
|
||||
{
|
||||
byte[] captured = Mode(1524);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(captured.AsSpan(72), 0x11d);
|
||||
BinaryPrimitives.WriteInt16LittleEndian(captured.AsSpan(86), 3);
|
||||
BinaryPrimitives.WriteInt16LittleEndian(captured.AsSpan(84), 50);
|
||||
captured[^1] = 3;
|
||||
byte[] original = captured.ToArray();
|
||||
PrinterMediaProfile selected = Profile(captured);
|
||||
int merges = 0;
|
||||
byte[] result = WindowsPrinters.NormalizePdfMode(captured, selected, input =>
|
||||
{
|
||||
merges++;
|
||||
Assert.Equal(1, BinaryPrimitives.ReadInt16LittleEndian(input.AsSpan(86)));
|
||||
Assert.Equal(100, BinaryPrimitives.ReadInt16LittleEndian(input.AsSpan(84)));
|
||||
Assert.Equal(3, input[^1]);
|
||||
byte[] merged = input.ToArray();
|
||||
merged[^1] = 1; // A driver updates its private copy-count mirror during normalization.
|
||||
return merged;
|
||||
}, Profile);
|
||||
Assert.Equal(1, merges);
|
||||
Assert.Equal(1, result[^1]);
|
||||
Assert.Equal(original, captured);
|
||||
Assert.Equal(selected.Revision, Profile(captured).Revision);
|
||||
int submissions = 0;
|
||||
Assert.Equal(1, WindowsPrinters.StartValidatedPdfDocument(result, selected,
|
||||
capability => Caps(capability, 1200, 1800, 300, 300), () => ++submissions));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Simulates ignored overrides, stripped flags and changed geometry/DPI, asserting refusal before the document callback.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("copies")]
|
||||
[InlineData("scale")]
|
||||
[InlineData("flags")]
|
||||
[InlineData("geometry")]
|
||||
[InlineData("dpi")]
|
||||
public void UnverifiableDriverNormalizationCannotReachSpoolBoundary(string change)
|
||||
{
|
||||
byte[] captured = Mode(1524);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(captured.AsSpan(72), 0x11d);
|
||||
int submissions = 0;
|
||||
Assert.Throws<PrinterMediaMismatchException>(() =>
|
||||
{
|
||||
byte[] result = WindowsPrinters.NormalizePdfMode(captured, Profile(captured), input =>
|
||||
{
|
||||
if(string.Equals(change, "copies", StringComparison.Ordinal))
|
||||
{ BinaryPrimitives.WriteInt16LittleEndian(input.AsSpan(86), 2); }
|
||||
if(string.Equals(change, "scale", StringComparison.Ordinal))
|
||||
{ BinaryPrimitives.WriteInt16LittleEndian(input.AsSpan(84), 50); }
|
||||
if(string.Equals(change, "flags", StringComparison.Ordinal))
|
||||
{ BinaryPrimitives.WriteUInt32LittleEndian(input.AsSpan(72), 13); }
|
||||
return input;
|
||||
}, output => Profile(output) with
|
||||
{
|
||||
HeightMicrons = string.Equals(change, "geometry", StringComparison.Ordinal) ? 50800 : 152400,
|
||||
DpiX = string.Equals(change, "dpi", StringComparison.Ordinal) ? 203 : 300,
|
||||
});
|
||||
WindowsPrinters.StartValidatedPdfDocument(result, Profile(captured),
|
||||
capability => Caps(capability, 1200, 1800, 300, 300), () => ++submissions);
|
||||
});
|
||||
Assert.Equal(0, submissions);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Covers the observed label-driver field mask so absent native scaling does not exclude a valid selected PDF configuration.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void QueueWithoutNativeScaleSupportKeepsThatFieldAbsentAndUsesSoftwareScaling()
|
||||
{
|
||||
byte[] captured = Mode(1524);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(captured.AsSpan(72), 290573);
|
||||
BinaryPrimitives.WriteInt16LittleEndian(captured.AsSpan(86), 3);
|
||||
byte[] original = captured.ToArray();
|
||||
byte[] normalized = WindowsPrinters.NormalizePdfMode(captured, Profile(captured), input =>
|
||||
{
|
||||
Assert.Equal(290573u, BinaryPrimitives.ReadUInt32LittleEndian(input.AsSpan(72)));
|
||||
Assert.Equal(0, BinaryPrimitives.ReadInt16LittleEndian(input.AsSpan(84)));
|
||||
Assert.Equal(1, BinaryPrimitives.ReadInt16LittleEndian(input.AsSpan(86)));
|
||||
return input;
|
||||
}, Profile);
|
||||
int submissions = 0;
|
||||
Assert.Equal(1, WindowsPrinters.StartValidatedPdfDocument(normalized, Profile(captured),
|
||||
capability => Caps(capability, 1200, 1800, 300, 300), () => ++submissions));
|
||||
Assert.Equal(original, captured);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Creates a bounded synthetic DEVMODE with explicit form fields and private bytes for deterministic tests without native driver calls.
|
||||
/// </summary>
|
||||
private static byte[] Mode(short height)
|
||||
{
|
||||
byte[] mode = new byte[224];
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(mode.AsSpan(68), 220);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(mode.AsSpan(70), 4);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(mode.AsSpan(72), 13);
|
||||
BinaryPrimitives.WriteInt16LittleEndian(mode.AsSpan(76), 1);
|
||||
BinaryPrimitives.WriteInt16LittleEndian(mode.AsSpan(80), height);
|
||||
BinaryPrimitives.WriteInt16LittleEndian(mode.AsSpan(82), 1016);
|
||||
return mode;
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,21 @@ public sealed class PrinterWorkerIsolationTests
|
||||
{
|
||||
private static string FixtureExecutable => Path.ChangeExtension(typeof(WorkerFixture.Program).Assembly.Location, ".exe");
|
||||
|
||||
[Fact]
|
||||
public async Task VerifiedMediaRefusalSurvivesTheWorkerBoundaryWithoutAnUncertainOutcome()
|
||||
{
|
||||
var backend = new IsolatedPrinterBackend(FixtureExecutable)
|
||||
{
|
||||
StartProcess = start =>
|
||||
{
|
||||
start.ArgumentList.Add("--media-drift");
|
||||
return Process.Start(start) ?? throw new InvalidOperationException("Fixture failed.");
|
||||
},
|
||||
};
|
||||
PrintJob job = new("fixture", "fixture", "Not printed", "PDF", new string('0', 64), 1, new PrintOptions(), "", "RECEIVED");
|
||||
await Assert.ThrowsAsync<PrinterMediaMismatchException>(() => backend.PrintFileAsync(job, Path.Combine(Path.GetTempPath(), "unused-media-fixture.pdf"), CancellationToken.None));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FileSubmissionUsesConfiguredWatchdogInsteadOfFixedTwoMinuteTimeout()
|
||||
{
|
||||
|
||||
@@ -37,14 +37,30 @@ internal sealed class RealtimeRuntimeFixture : IAsyncDisposable
|
||||
internal TaskCompletionSource? StateAppliedRelease { get; set; }
|
||||
internal Func<RealtimeEnvelope, Task>? BeforeAcknowledgement { get; set; }
|
||||
internal long LastHelloSettingsRevision;
|
||||
|
||||
|
||||
|
||||
/// <summary>Captures the actual HELLO payload so compatibility tests observe the wire rather than duplicating capability selection.</summary>
|
||||
internal string[] LastHelloCapabilities { get; private set; } = [];
|
||||
|
||||
|
||||
|
||||
/// <summary>Counts discovery requests to distinguish reconnect reuse from an added HTTP polling schedule.</summary>
|
||||
internal int DiscoveryRequests;
|
||||
|
||||
|
||||
|
||||
/// <summary>Controls advertised discovery across a server upgrade or downgrade while retaining the same authenticated client session.</summary>
|
||||
internal string PrintingVersion { get; set; }
|
||||
private readonly Lock _claimLock = new();
|
||||
private PrintJob? _claimed;
|
||||
private readonly CancellationTokenSource _stopping = new(TimeSpan.FromSeconds(30));
|
||||
private readonly Task _run;
|
||||
private readonly List<Connection> _connections = [];
|
||||
|
||||
internal RealtimeRuntimeFixture(int downloads = 1, RealtimeSettings? settings = null, TimeProvider? timeProvider = null, bool cacheSettings = false)
|
||||
internal RealtimeRuntimeFixture(int downloads = 1, RealtimeSettings? settings = null, TimeProvider? timeProvider = null, bool cacheSettings = false, string printingVersion = "2.0.0")
|
||||
{
|
||||
PrintingVersion = printingVersion;
|
||||
Settings = (settings ?? Settings) with { MaxConcurrentDownloads = downloads };
|
||||
using(var store = new AgentStore(DirectoryPath))
|
||||
{
|
||||
@@ -73,6 +89,7 @@ internal sealed class RealtimeRuntimeFixture : IAsyncDisposable
|
||||
RealtimeEnvelope hello = await LoopbackWebSocketPeer.ReceiveAsync(socket, _stopping.Token);
|
||||
Assert.Equal("HELLO", hello.Type);
|
||||
LastHelloSettingsRevision = hello.Payload.GetProperty("lastSettingsRevision").GetInt64();
|
||||
LastHelloCapabilities = hello.Payload.GetProperty("capabilities").EnumerateArray().Select(item => item.GetString()!).ToArray();
|
||||
await connection.SendAsync("WELCOME", new { connectionId = Guid.NewGuid().ToString("N"), serverTime = Now(), desiredState = desiredState ?? new DeviceDesiredState(1, false, "CONNECTED"), settings = Settings });
|
||||
connection.Start();
|
||||
await WaitAsync(() =>
|
||||
@@ -217,6 +234,17 @@ internal sealed class RealtimeRuntimeFixture : IAsyncDisposable
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
string path = request.RequestUri!.AbsolutePath;
|
||||
if(string.Equals(path, "/qqq/v1/version", StringComparison.Ordinal))
|
||||
{
|
||||
Interlocked.Increment(ref fixture.DiscoveryRequests);
|
||||
return Response(JsonSerializer.Serialize(new
|
||||
{
|
||||
apiVersion = "1.9.0",
|
||||
features = new[] { "version", "metaData", "processes", "processCancel", "extensions", "widgets", "nativeSessionLogin" },
|
||||
clientChannels = new[] { "api" },
|
||||
extensions = new[] { new { name = "printing", version = fixture.PrintingVersion, pathPrefix = "/qbit/printing" } },
|
||||
}));
|
||||
}
|
||||
if(path.EndsWith("/content", StringComparison.Ordinal))
|
||||
{
|
||||
string id = path.Split('/')[^2];
|
||||
@@ -246,7 +274,6 @@ internal sealed class RealtimeRuntimeFixture : IAsyncDisposable
|
||||
}
|
||||
return Response(path switch
|
||||
{
|
||||
"/qqq/v1/version" => """{"apiVersion":"1.9.0","features":["version","metaData","processes","processCancel","extensions","widgets","nativeSessionLogin"],"clientChannels":["api"],"extensions":[{"name":"printing","version":"2.0.0","pathPrefix":"/qbit/printing"}]}""",
|
||||
"/qqq/v1/manageSession" => """{"uuid":"synthetic-session"}""",
|
||||
"/qqq/v1/metaData/authentication" => """{"name":"local","type":"TABLE_BASED"}""",
|
||||
"/qqq/v1/qbit/printing/session" => """{"principalId":"user","tenantId":"tenant","deviceId":"device"}""",
|
||||
|
||||
@@ -103,7 +103,7 @@ internal sealed class SessionFixture : IDisposable
|
||||
object body = new DeviceControlPoll(1, DateTime.UtcNow.ToString("O", System.Globalization.CultureInfo.InvariantCulture), 5, new DeviceDesiredState(1, false, "CONNECTED"), []);
|
||||
return new HttpResponseMessage(Status) { Content = new StringContent(JsonSerializer.Serialize(body, PrintApiClient.JsonOptions), Encoding.UTF8, "application/json") };
|
||||
}
|
||||
public Task<QqqApiDiscovery> DiscoverAsync(CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||
public Task<QqqApiDiscovery> DiscoverAsync(CancellationToken cancellationToken = default) => Task.FromResult(new QqqApiDiscovery());
|
||||
public Task<QqqAuthenticationMetadata> GetAuthenticationMetadataAsync(CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||
public Task SignInWithPasswordAsync(string username, string password, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||
public Task<QqqBrowserLogin> BeginBrowserLoginAsync(Uri redirectUri, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
||||
|
||||
@@ -12,6 +12,27 @@ namespace Qqq.PrintAgent.Core.Tests;
|
||||
|
||||
public sealed class PrintWorkerTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(true, false, "FAILED", 0)]
|
||||
[InlineData(false, true, "FAILED", 0)]
|
||||
[InlineData(false, false, "SPOOLED", 1)]
|
||||
public async Task SelectedMediaDriftCannotSpoolAndKnownNativeRefusalIsNotUncertain(bool discoveryDrift, bool nativeDrift, string expected, int spoolCount)
|
||||
{
|
||||
byte[] content = [1];
|
||||
PrinterMediaProfile profile = new("default-id", new string('a', 64), "Default", 101600, 152400, 300, 300);
|
||||
PrintOptions options = new(MediaProfile: new(profile.Id, profile.Revision));
|
||||
PrintJob job = new("job1", "printer1", "Test", "ZPL", Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(content)), 1, options, "", "CLAIMED");
|
||||
using FixtureHandler handler = new(job, content);
|
||||
using PrintApiClient api = new("http://localhost", "fixture", handler);
|
||||
MemoryJournal journal = new();
|
||||
FakePrinter printer = new(profile: profile, discoveryDrift: discoveryDrift, nativeDrift: nativeDrift);
|
||||
await new PrintWorker(api, printer, journal).RunOnceAsync();
|
||||
Assert.Equal(spoolCount, printer.PrintCount);
|
||||
Assert.Equal(expected, journal.GetState(job.JobId));
|
||||
if(discoveryDrift)
|
||||
{ Assert.DoesNotContain("SUBMITTING", handler.Events, StringComparer.Ordinal); }
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
@@ -69,6 +90,31 @@ public sealed class PrintWorkerTests
|
||||
Assert.Equal(new[] { "RECEIVED", "SUBMITTING", "SPOOLED" }, handler.Events, StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Proves each processed job logs exactly one phase-timing line naming every phase and only the job identifier, so a slow print can be
|
||||
/// attributed from the service log without exposing document content or adding any request.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task RunOnce_LogsOnePhaseTimingLinePerJobWithoutDocumentContent()
|
||||
{
|
||||
byte[] content = Encoding.UTF8.GetBytes("^XA^FO10,10^FDprivate label text^FS^XZ");
|
||||
PrintJob job = new("timing-job", "printer1", "Test", "ZPL", Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(content)), content.Length, new PrintOptions(), "2026-10-29T00:00:00Z", "CLAIMED");
|
||||
using FixtureHandler handler = new(job, content);
|
||||
using PrintApiClient api = new("http://localhost", "test-device", handler);
|
||||
List<string> lines = [];
|
||||
PrintWorker worker = new(api, new FakePrinter(), new MemoryJournal(), lines.Add);
|
||||
Assert.True(await worker.RunOnceAsync());
|
||||
string timing = Assert.Single(lines, line => line.Contains(": timing ", StringComparison.Ordinal));
|
||||
Assert.StartsWith("timing-job: timing ", timing, StringComparison.Ordinal);
|
||||
foreach(string phase in new[] { "inventory=", "claim=", "download=", "revalidate=", "gate=", "submit=" })
|
||||
{
|
||||
Assert.Contains(phase, timing, StringComparison.Ordinal);
|
||||
}
|
||||
Assert.DoesNotContain(lines, line => line.Contains("private label text", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
|
||||
|
||||
[Theory]
|
||||
[InlineData("Dispatch labels", "Dispatch labels")]
|
||||
[InlineData("", "Test")]
|
||||
@@ -185,11 +231,24 @@ public sealed class PrintWorkerTests
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FakePrinter(string? displayName = null) : IPrinterBackend
|
||||
private sealed class FakePrinter(string? displayName = null, PrinterMediaProfile? profile = null, bool discoveryDrift = false, bool nativeDrift = false) : IPrinterBackend
|
||||
{
|
||||
private int _discoveries;
|
||||
public int PrintCount { get; private set; }
|
||||
public IReadOnlyList<PrinterInfo> Discover() => [new("printer1", "Test", "Zebra", "USB", "READY", ["ZPL"], DisplayName: displayName)];
|
||||
public Task<string> PrintAsync(PrintJob job, byte[] content, CancellationToken cancellationToken) { PrintCount++; return Task.FromResult("123"); }
|
||||
public IReadOnlyList<PrinterInfo> Discover()
|
||||
{
|
||||
PrinterMediaProfile? current = profile;
|
||||
if(discoveryDrift && _discoveries++ > 0 && current is not null)
|
||||
{ current = current with { Revision = new string('b', 64) }; }
|
||||
return [new("printer1", "Test", "Zebra", "USB", "READY", ["ZPL"], DisplayName: displayName, MediaProfiles: current is null ? null : [current])];
|
||||
}
|
||||
public Task<string> PrintAsync(PrintJob job, byte[] content, CancellationToken cancellationToken)
|
||||
{
|
||||
if(nativeDrift)
|
||||
{ throw new PrinterMediaMismatchException("Fixture default changed before native submission."); }
|
||||
PrintCount++;
|
||||
return Task.FromResult("123");
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class MemoryJournal : IJobJournal
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
/*
|
||||
* Copyright (c) 2026 James Maes
|
||||
* SPDX-License-Identifier: MIT
|
||||
*/
|
||||
|
||||
using System.Text.Json;
|
||||
using Qqq.PrintAgent.Core.Printing;
|
||||
|
||||
namespace Qqq.PrintAgent.Core.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Checks additive media wire compatibility and rejection boundaries before any operating-system adapter is involved.
|
||||
/// </summary>
|
||||
public sealed class PrinterMediaContractTests
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides a bounded synthetic queue default so contract tests do not depend on installed printers or physical stock.
|
||||
/// </summary>
|
||||
private static readonly PrinterMediaProfile Profile = new("opaque-default", new string('a', 64), "Default", 101600, 152400, 300, 300);
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Round-trips inventory and selection while verifying that legacy options still omit the optional media field.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void OptionalMediaSelectionAndInventoryRoundTripWithoutChangingLegacyOptions()
|
||||
{
|
||||
var printer = new PrinterInfo("p", "Queue", "Driver", "Port", "READY", ["PDF", "ZPL"], MediaProfiles: [Profile]);
|
||||
string json = JsonSerializer.Serialize(printer, PrintApiClient.JsonOptions);
|
||||
PrinterInfo restored = JsonSerializer.Deserialize<PrinterInfo>(json, PrintApiClient.JsonOptions)!;
|
||||
Assert.Equal(Profile, Assert.Single(restored.MediaProfiles!));
|
||||
Assert.DoesNotContain("mediaProfile", JsonSerializer.Serialize(new PrintOptions(), PrintApiClient.JsonOptions), StringComparison.Ordinal);
|
||||
PrintOptions options = new(MediaProfile: new(Profile.Id, Profile.Revision));
|
||||
Assert.Equal(options, JsonSerializer.Deserialize<PrintOptions>(JsonSerializer.Serialize(options, PrintApiClient.JsonOptions), PrintApiClient.JsonOptions));
|
||||
PrinterMediaProfile.RequireMatch(options, [Profile]);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Exercises unavailable, stale and ambiguous selections plus dimension conflicts, while preserving the unselected legacy path.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void MissingChangedDuplicateAndConflictingMediaSelectionsAreRejected()
|
||||
{
|
||||
PrintOptions options = new(MediaProfile: new(Profile.Id, Profile.Revision));
|
||||
Assert.Throws<PrinterMediaMismatchException>(() => PrinterMediaProfile.RequireMatch(options, null));
|
||||
Assert.Throws<PrinterMediaMismatchException>(() => PrinterMediaProfile.RequireMatch(options, [Profile with { Revision = new string('b', 64) }]));
|
||||
Assert.Throws<PrinterMediaMismatchException>(() => PrinterMediaProfile.RequireMatch(options, [Profile, Profile]));
|
||||
Assert.Throws<PrinterMediaMismatchException>(() => PrinterMediaProfile.RequireMatch(options with { PaperWidthMm = 101.6 }, [Profile]));
|
||||
Assert.Throws<PrinterMediaMismatchException>(() => PrinterMediaProfile.RequireMatch(options with { PaperHeightMm = 152.4 }, [Profile]));
|
||||
Assert.Throws<PrinterMediaMismatchException>(() => PrinterMediaProfile.RequireMatch(options with { MediaProfile = new(Profile.Id, new string('A', 64)) }, [Profile]));
|
||||
PrinterMediaProfile.RequireMatch(new PrintOptions(), null);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Checks the exact 128-character boundary and forbidden slash against matching inventory, so lookup success cannot hide malformed IDs.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(128, false, true)]
|
||||
[InlineData(129, false, false)]
|
||||
[InlineData(128, true, false)]
|
||||
public void SelectionIdsRespectTheSharedOpaqueIdBoundary(int length, bool slash, bool accepted)
|
||||
{
|
||||
string id = new string('a', length - 4) + (slash ? "A9_/" : "A9_.");
|
||||
PrinterMediaProfile current = Profile with { Id = id };
|
||||
PrintOptions options = new(MediaProfile: new(id, current.Revision));
|
||||
if(accepted)
|
||||
{
|
||||
PrinterMediaProfile.RequireMatch(options, [current]);
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.Throws<PrinterMediaMismatchException>(() => PrinterMediaProfile.RequireMatch(options, [current]));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Accepts maximum legal names and inventory sizes, then rejects single-step overflows and empty names.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void CurrentProfileNamesAndInventoryHaveBoundedContractSizes()
|
||||
{
|
||||
PrinterMediaProfile current = Profile with { Name = new string('a', 512) };
|
||||
PrintOptions options = new(MediaProfile: new(current.Id, current.Revision));
|
||||
PrinterMediaProfile[] profiles = Enumerable.Range(0, 32).Select(index => current with { Id = $"p-{index}" }).ToArray();
|
||||
profiles[0] = current;
|
||||
PrinterMediaProfile.RequireMatch(options, profiles);
|
||||
Assert.Throws<PrinterMediaMismatchException>(() => PrinterMediaProfile.RequireMatch(options, [.. profiles, current with { Id = "overflow" }]));
|
||||
Assert.Throws<PrinterMediaMismatchException>(() => PrinterMediaProfile.RequireMatch(options, [current with { Name = new string('a', 513) }]));
|
||||
Assert.Throws<PrinterMediaMismatchException>(() => PrinterMediaProfile.RequireMatch(options, [current with { Name = "" }]));
|
||||
}
|
||||
}
|
||||
@@ -31,10 +31,10 @@ public static class Program
|
||||
Console.WriteLine(child.Id.ToString(CultureInfo.InvariantCulture));
|
||||
return 0;
|
||||
}
|
||||
return await PrinterWorkerHost.RunAsync(new FakePrinters(args.Contains("--hang", StringComparer.Ordinal))).ConfigureAwait(false);
|
||||
return await PrinterWorkerHost.RunAsync(new FakePrinters(args.Contains("--hang", StringComparer.Ordinal), args.Contains("--media-drift", StringComparer.Ordinal))).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private sealed class FakePrinters(bool hang) : IFilePrinterBackend
|
||||
private sealed class FakePrinters(bool hang, bool mediaDrift) : IFilePrinterBackend
|
||||
{
|
||||
public IReadOnlyList<PrinterInfo> Discover()
|
||||
{
|
||||
@@ -52,6 +52,8 @@ public static class Program
|
||||
|
||||
public Task<string> PrintFileAsync(PrintJob job, string path, CancellationToken cancellationToken)
|
||||
{
|
||||
if(mediaDrift)
|
||||
{ throw new PrinterMediaMismatchException("The fixture changed its default before submission."); }
|
||||
if(hang)
|
||||
{ Thread.Sleep(Timeout.Infinite); }
|
||||
throw new InvalidOperationException("This fixture never opens documents or prints.");
|
||||
|
||||
@@ -14,16 +14,18 @@ and does not qualify the Windows service. A written file is `SPOOLED` and then
|
||||
|
||||
```sh
|
||||
# first run: enroll through the native "Enroll a print device" process and approve the printer
|
||||
node tools/virtual-agent/virtual-agent.mjs --server http://localhost:8078 --out ./printed --enroll --approve
|
||||
# later runs reuse the identity in ./printed/.agent-state.json
|
||||
node tools/virtual-agent/virtual-agent.mjs --server http://localhost:8078 --enroll --approve
|
||||
# later runs reuse the identity in ~/.qqq-print-agent/state.json; printed PDFs land in ~/Downloads
|
||||
node tools/virtual-agent/virtual-agent.mjs --server http://localhost:8078
|
||||
# or somewhere else
|
||||
node tools/virtual-agent/virtual-agent.mjs --server http://localhost:8078 --out ./printed
|
||||
```
|
||||
|
||||
| Option | Meaning |
|
||||
|---|---|
|
||||
| `--server <origin>` | QQQ server (`QQQ_PRINT_SERVER`); plain http only for loopback |
|
||||
| `--out <dir>` | where printed documents go (`QQQ_PRINT_OUT`); each job writes `<time>_<jobId>_<title>.pdf` (or `.zpl`) plus a `.json` receipt |
|
||||
| `--state <file>` | device identity and applied revisions (default `<out>/.agent-state.json`, mode 0600) |
|
||||
| `--out <dir>` | where printed documents go (`QQQ_PRINT_OUT`; default `~/Downloads`, as browser downloads and qqq exports); each job writes `<time>_<jobId>_<title>.pdf` (or `.zpl`) plus a `.json` receipt |
|
||||
| `--state <file>` | device identity and applied revisions (default `~/.qqq-print-agent/state.json`, mode 0600; an identity an earlier version kept at `<out>/.agent-state.json` is still used) |
|
||||
| `--enroll` | with no stored identity, run `printingEnrollDevice` for a code and enroll |
|
||||
| `--approve` | approve the virtual printer with `printingEnableSelectedPrinters` (local testing only; approval is normally an administrator's decision) |
|
||||
| `--name`, `--device-name`, `--printer-id`, `--formats PDF,ZPL`, `--facility` | inventory and enrollment details |
|
||||
|
||||
@@ -4,12 +4,12 @@
|
||||
*/
|
||||
import assert from 'node:assert/strict'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { createServer } from 'node:http'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { test } from 'node:test'
|
||||
import { Agent, LIMITS, backoff, checkTransport, compareVersions, frame, outputName, parseArgs, requirePrinting, sessionCookie, verifyDocument } from '../virtual-agent.mjs'
|
||||
import { Agent, LIMITS, defaultOutDir, defaultStateFile, backoff, checkTransport, compareVersions, frame, outputName, parseArgs, requirePrinting, sessionCookie, verifyDocument } from '../virtual-agent.mjs'
|
||||
|
||||
// Stable native-major boundary from qqq-print-protocol/tools/verify-realtime.mjs.
|
||||
test('discovery accepts stable compatible minors and rejects noncanonical versions', () => {
|
||||
@@ -63,7 +63,8 @@ test('native cookie POSTs carry exact Origin; foreign targets and redirects rece
|
||||
})
|
||||
const directory = mkdtempSync(join(tmpdir(), 'qqq-virtual-http-'))
|
||||
t.after(() => rmSync(directory, { recursive: true, force: true }))
|
||||
const agent = new Agent(parseArgs(['--server', origin, '--out', directory], {}), () => {})
|
||||
// the home directory is the temporary one too, so the identity never lands in the real home
|
||||
const agent = new Agent(parseArgs(['--server', origin, '--out', directory], {}, directory), () => {})
|
||||
agent.cookie = 'sessionUUID=synthetic-only'
|
||||
for (const badOrigin of [undefined, foreign]) {
|
||||
const headers = { Cookie: agent.cookie }
|
||||
@@ -121,11 +122,27 @@ test('frames, cookies, backoff, limits and arguments', () => {
|
||||
assert.equal(backoff(0, {}, () => 0.5), 1000)
|
||||
assert.equal(backoff(10, {}, () => 1), 30000)
|
||||
assert.equal(LIMITS.maxConcurrentPrints, 1)
|
||||
const o = parseArgs(['--server', 'http://localhost:8078/x', '--out', '/tmp/out', '--enroll', '--formats', 'pdf'], {})
|
||||
const o = parseArgs(['--server', 'http://localhost:8078/x', '--out', '/tmp/qqq-va-no-such-dir', '--enroll', '--formats', 'pdf'], {}, '/home/u')
|
||||
assert.equal(o.server, 'http://localhost:8078')
|
||||
assert.equal(o.state, join(o.out, '.agent-state.json'))
|
||||
assert.equal(o.state, '/home/u/.qqq-print-agent/state.json')
|
||||
assert.deepEqual(o.formats, ['PDF'])
|
||||
assert.ok(o.enroll && !o.approve)
|
||||
assert.throws(() => parseArgs(['--formats', 'PS'], {}), /PDF/)
|
||||
assert.throws(() => parseArgs(['--bogus'], {}), /unknown/)
|
||||
})
|
||||
|
||||
test('documents go to ~/Downloads unless --out or QQQ_PRINT_OUT says otherwise; an older identity next to the output is still used', () => {
|
||||
assert.equal(defaultOutDir('/home/u'), join('/home/u', 'Downloads'))
|
||||
assert.equal(defaultStateFile('/home/u'), join('/home/u', '.qqq-print-agent', 'state.json'))
|
||||
assert.equal(parseArgs([], {}, '/home/u').out, join('/home/u', 'Downloads'))
|
||||
assert.equal(parseArgs([], { QQQ_PRINT_OUT: '' }, '/home/u').out, join('/home/u', 'Downloads'))
|
||||
assert.equal(parseArgs([], { QQQ_PRINT_OUT: '/srv/printed' }, '/home/u').out, '/srv/printed')
|
||||
assert.equal(parseArgs(['--out', '/x/y'], { QQQ_PRINT_OUT: '/srv/printed' }, '/home/u').out, '/x/y')
|
||||
const directory = mkdtempSync(join(tmpdir(), 'qqq-va-legacy-'))
|
||||
try {
|
||||
writeFileSync(join(directory, '.agent-state.json'), '{}')
|
||||
assert.equal(parseArgs(['--out', directory], {}, '/home/u').state, join(directory, '.agent-state.json'))
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
@@ -29,6 +29,7 @@
|
||||
|
||||
import { createHash, randomUUID } from 'node:crypto'
|
||||
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { join, resolve } from 'node:path'
|
||||
|
||||
export const AGENT_VERSION = '0.3.1-virtual'
|
||||
@@ -50,10 +51,20 @@ export const LIMITS = {
|
||||
maxStagedBytes: 9007199254740991,
|
||||
}
|
||||
|
||||
export function parseArgs(argv, env = process.env) {
|
||||
/** Where printed documents go by default: the user's Downloads folder, as browser downloads and qqq exports do. */
|
||||
export function defaultOutDir(home = homedir()) {
|
||||
return join(home, 'Downloads')
|
||||
}
|
||||
|
||||
/** The device identity and revisions: kept in a dot folder of the home directory, not among the printed files. */
|
||||
export function defaultStateFile(home = homedir()) {
|
||||
return join(home, '.qqq-print-agent', 'state.json')
|
||||
}
|
||||
|
||||
export function parseArgs(argv, env = process.env, home = homedir()) {
|
||||
const options = {
|
||||
server: env.QQQ_PRINT_SERVER ?? 'http://localhost:8078',
|
||||
out: env.QQQ_PRINT_OUT ?? './virtual-printer-output',
|
||||
out: env.QQQ_PRINT_OUT || defaultOutDir(home),
|
||||
state: env.QQQ_PRINT_STATE,
|
||||
name: env.QQQ_PRINT_PRINTER_NAME ?? 'Virtual PDF printer',
|
||||
deviceName: env.QQQ_PRINT_DEVICE_NAME ?? 'Virtual print agent',
|
||||
@@ -89,7 +100,9 @@ export function parseArgs(argv, env = process.env) {
|
||||
}
|
||||
options.server = new URL(options.server).origin
|
||||
options.out = resolve(options.out)
|
||||
options.state = resolve(options.state ?? join(options.out, '.agent-state.json'))
|
||||
// an identity kept next to the output by earlier versions is still used; new ones go to the home dot folder
|
||||
const legacy = join(options.out, '.agent-state.json')
|
||||
options.state = resolve(options.state ?? (existsSync(legacy) ? legacy : defaultStateFile(home)))
|
||||
if (!options.formats.length || options.formats.some((f) => f !== 'PDF' && f !== 'ZPL')) throw new Error('--formats takes PDF and/or ZPL')
|
||||
return options
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user