fprint_core/device.rs
1// SPDX-FileCopyrightText: 2026 fprintd (pure-Rust) contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! The core seam: [`Backend`] and [`Device`] traits.
6//!
7//! ## Dispatch model
8//!
9//! These traits use **native `async fn` in trait** and **static dispatch**. `fprint-core`
10//! introduces neither `dyn` nor an enum of backends: either would make the core depend on
11//! its implementors and invert the dependency arrows. Runtime backend heterogeneity (e.g.
12//! one device served by native Rust, another by the libfprint shim) is expressed *above*
13//! the core by a `CompositeBackend` whose `Device` associated type is an enum over the
14//! concrete backends — the only crate allowed to know all of them. See `ARCHITECTURE.md`.
15//!
16//! Cancellation is Rust-native: **dropping the returned future cancels the operation**.
17//! Backends release the sensor in their own `Drop`; there is no `GCancellable`-style token.
18//!
19//! Every operation takes `&mut self`, so the borrow checker forbids concurrent
20//! enroll/verify on one device — libfprint's single-in-flight-operation contract enforced
21//! by the type system rather than runtime checks.
22//!
23//! The pair of doctests below is the proof, and **only the pair proves anything**: a lone
24//! `compile_fail` passes for any reason at all, including a typo. These two differ in exactly one
25//! thing — whether the two futures are alive at once — so the failure is attributable to the
26//! overlap. Both are generic over `D: Device`, so the borrow checker rejects at the trait bound
27//! and no implementor is needed.
28//!
29//! The `E0499` on the negative states the intended cause; stable rustdoc does not verify it, so
30//! attribution rests on the control, not on the code.
31//!
32//! The positive control — the two operations in sequence compile:
33//! ```
34//! async fn sequential<D: fprint_core::Device>(dev: &mut D, p: &fprint_core::Print) {
35//! let _ = dev.enroll(p.clone(), |_| {}).await;
36//! let _ = dev.verify(p).await;
37//! }
38//! ```
39//!
40//! The negative — the same two operations overlapping do not:
41//! ```compile_fail,E0499
42//! fn concurrent<D: fprint_core::Device>(dev: &mut D, p: &fprint_core::Print) {
43//! let enrolling = dev.enroll(p.clone(), |_| {});
44//! let verifying = dev.verify(p);
45//! let _ = (enrolling, verifying);
46//! }
47//! ```
48
49use crate::error::RetryReason;
50use crate::{DeviceFeature, Error, FingerStatus, Print, Result, ScanType, Temperature};
51
52/// Stable identifier for a physical reader (opaque; assigned by the backend).
53#[derive(Clone, PartialEq, Eq, Hash, Debug)]
54pub struct DeviceId(String);
55
56impl DeviceId {
57 /// Wrap a backend-assigned identifier.
58 #[must_use]
59 pub fn new(id: impl Into<String>) -> Self {
60 Self(id.into())
61 }
62
63 /// The identifier as a string slice.
64 #[must_use]
65 pub fn as_str(&self) -> &str {
66 &self.0
67 }
68}
69
70impl core::fmt::Display for DeviceId {
71 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
72 f.write_str(&self.0)
73 }
74}
75
76impl From<&str> for DeviceId {
77 fn from(id: &str) -> Self {
78 Self::new(id)
79 }
80}
81
82impl From<String> for DeviceId {
83 fn from(id: String) -> Self {
84 Self::new(id)
85 }
86}
87
88/// Identifier of the driver a template is bound to (e.g. `"goodixmoc"`). Templates are
89/// driver-specific, so this is its own type rather than a bare `String`.
90#[derive(Clone, PartialEq, Eq, Hash, Debug)]
91pub struct DriverId(String);
92
93impl DriverId {
94 /// Wrap a driver identifier.
95 #[must_use]
96 pub fn new(id: impl Into<String>) -> Self {
97 Self(id.into())
98 }
99
100 /// The identifier as a string slice.
101 #[must_use]
102 pub fn as_str(&self) -> &str {
103 &self.0
104 }
105}
106
107impl core::fmt::Display for DriverId {
108 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
109 f.write_str(&self.0)
110 }
111}
112
113impl From<&str> for DriverId {
114 fn from(id: &str) -> Self {
115 Self::new(id)
116 }
117}
118
119impl From<String> for DriverId {
120 fn from(id: String) -> Self {
121 Self::new(id)
122 }
123}
124
125/// Static description of a device, known once it is discovered.
126#[derive(Clone, PartialEq, Eq, Debug)]
127#[non_exhaustive]
128pub struct DeviceInfo {
129 /// Backend-assigned identity of this reader.
130 pub id: DeviceId,
131 /// Driver id, which templates are bound to.
132 pub driver: DriverId,
133 /// Human-readable model name.
134 pub name: String,
135 /// How the finger is presented to this sensor.
136 pub scan_type: ScanType,
137 /// Everything this device advertises it can do; query it via [`Device::has_feature`].
138 pub features: DeviceFeature,
139 /// Number of finger presentations a full enrollment needs.
140 pub enroll_stages: u32,
141}
142
143impl DeviceInfo {
144 /// Describe a device from its discovered static metadata.
145 ///
146 /// The sensor's *thermal* state is deliberately not here: it changes as the device runs, so it
147 /// is a live reading via [`Device::temperature`], not a field frozen into this static shape.
148 #[must_use]
149 pub fn new(
150 id: DeviceId,
151 driver: DriverId,
152 name: impl Into<String>,
153 scan_type: ScanType,
154 features: DeviceFeature,
155 enroll_stages: u32,
156 ) -> Self {
157 DeviceInfo {
158 id,
159 driver,
160 name: name.into(),
161 scan_type,
162 features,
163 enroll_stages,
164 }
165 }
166}
167
168/// Progress report delivered during [`Device::enroll`], once per capture attempt.
169#[derive(Clone, PartialEq, Eq, Debug)]
170#[non_exhaustive]
171pub struct EnrollProgress {
172 /// Stages completed so far (`0..=total_stages`).
173 pub completed_stages: u32,
174 /// Stages a full enrollment needs, mirroring [`DeviceInfo::enroll_stages`].
175 pub total_stages: u32,
176 /// `Some` when this capture failed and the user should present the finger again;
177 /// the stage count did not advance.
178 pub retry: Option<RetryReason>,
179 /// Live finger-presence status accompanying this report ([`FingerStatus::NONE`] when the
180 /// backend reports none).
181 pub finger_status: FingerStatus,
182}
183
184impl EnrollProgress {
185 /// A report of `completed_stages` of `total_stages`, with no retry and no finger status.
186 #[must_use]
187 pub fn new(completed_stages: u32, total_stages: u32) -> Self {
188 EnrollProgress {
189 completed_stages,
190 total_stages,
191 retry: None,
192 finger_status: FingerStatus::NONE,
193 }
194 }
195
196 /// Mark this report as a retry with reason `r`.
197 #[must_use]
198 pub fn with_retry(mut self, r: RetryReason) -> Self {
199 self.retry = Some(r);
200 self
201 }
202
203 /// Attach the live finger-presence status.
204 #[must_use]
205 pub fn with_finger_status(mut self, s: FingerStatus) -> Self {
206 self.finger_status = s;
207 self
208 }
209}
210
211/// Result of a 1:1 [`Device::verify`].
212#[derive(Clone, PartialEq, Eq, Debug)]
213#[non_exhaustive]
214pub struct VerifyOutcome {
215 /// Whether the scan matched the enrolled print.
216 pub matched: bool,
217 /// The freshly scanned print, when the backend surfaces it (host-side sensors do; many
218 /// match-on-chip sensors do not).
219 pub scanned: Option<Print>,
220}
221
222impl VerifyOutcome {
223 /// A verify result: `matched` and the optional freshly `scanned` print.
224 #[must_use]
225 pub fn new(matched: bool, scanned: Option<Print>) -> Self {
226 VerifyOutcome { matched, scanned }
227 }
228}
229
230/// Result of a 1:N [`Device::identify`].
231#[derive(Clone, PartialEq, Eq, Debug)]
232#[non_exhaustive]
233pub struct IdentifyOutcome {
234 /// Index into the gallery passed to `identify`, or `None` for no match.
235 pub match_index: Option<usize>,
236 /// The freshly scanned print, on the same terms as [`VerifyOutcome::scanned`].
237 pub scanned: Option<Print>,
238}
239
240impl IdentifyOutcome {
241 /// An identify result: the gallery `match_index` (or `None`) and the optional freshly
242 /// `scanned` print.
243 #[must_use]
244 pub fn new(match_index: Option<usize>, scanned: Option<Print>) -> Self {
245 IdentifyOutcome {
246 match_index,
247 scanned,
248 }
249 }
250}
251
252/// A physical fingerprint reader.
253///
254/// Implemented by each backend (the libfprint shim, native Rust drivers). Consumers hold
255/// a concrete `Device` (static dispatch); the fprintd-compatible daemon is generic over
256/// its [`Backend`].
257///
258/// `async fn` in a public trait is intentional (see the module docs), so the
259/// `async_fn_in_trait` lint — which warns that callers cannot add `+ Send` bounds — is
260/// expected here and only here.
261#[expect(async_fn_in_trait)]
262pub trait Device {
263 /// Static metadata (available before and after `open`).
264 fn info(&self) -> &DeviceInfo;
265
266 /// Convenience: does this device advertise `feature`?
267 fn has_feature(&self, feature: DeviceFeature) -> bool {
268 self.info().features.contains(feature)
269 }
270
271 /// The sensor's current thermal state, or `None` when the device does not report one.
272 ///
273 /// Unlike [`info`](Device::info), this is a **live** reading: a sensor warms as it runs and
274 /// cools when idle, so a caller driving a long capture loop re-reads it rather than caching a
275 /// value. The default is `None`; a backend whose hardware reports temperature overrides it.
276 fn temperature(&self) -> Option<Temperature> {
277 None
278 }
279
280 /// Open the device for use. Must be called before any operation below.
281 async fn open(&mut self) -> Result<()>;
282
283 /// Close the device, releasing the sensor.
284 async fn close(&mut self) -> Result<()>;
285
286 /// Enroll a finger into `print` (a blank [`Print::new_for_enroll`] tagged with the target
287 /// finger), reporting each capture via `on_progress`. Returns the completed print.
288 ///
289 /// `on_progress` is a generic `FnMut`, not a trait object: progress is pushed to the
290 /// caller, and static dispatch keeps the core free of `dyn`.
291 async fn enroll<F: FnMut(EnrollProgress)>(
292 &mut self,
293 print: Print,
294 on_progress: F,
295 ) -> Result<Print>;
296
297 /// Verify a single scan against one `enrolled` print (1:1), reporting live finger-presence
298 /// through `on_status` as the sensor sees a finger arrive and leave.
299 ///
300 /// `on_status` is the verify-side counterpart of [`enroll`](Device::enroll)'s progress callback:
301 /// static dispatch, pushed to the caller, so the core stays `dyn`-free. A backend with no live
302 /// finger reporting simply never calls it.
303 async fn verify_with_status<F: FnMut(FingerStatus)>(
304 &mut self,
305 enrolled: &Print,
306 on_status: F,
307 ) -> Result<VerifyOutcome>;
308
309 /// Verify a single scan against one `enrolled` print (1:1).
310 ///
311 /// The status-free convenience form of [`verify_with_status`](Device::verify_with_status), for
312 /// callers that do not drive finger-presence UI prompts.
313 async fn verify(&mut self, enrolled: &Print) -> Result<VerifyOutcome> {
314 self.verify_with_status(enrolled, |_| {}).await
315 }
316
317 /// Identify a single scan against a `gallery` of prints (1:N), reporting live finger-presence
318 /// through `on_status`.
319 async fn identify_with_status<F: FnMut(FingerStatus)>(
320 &mut self,
321 gallery: &[Print],
322 on_status: F,
323 ) -> Result<IdentifyOutcome>;
324
325 /// Identify a single scan against a `gallery` of prints (1:N).
326 ///
327 /// The status-free convenience form of [`identify_with_status`](Device::identify_with_status).
328 async fn identify(&mut self, gallery: &[Print]) -> Result<IdentifyOutcome> {
329 self.identify_with_status(gallery, |_| {}).await
330 }
331
332 /// List prints stored on the device (match-on-chip devices with `STORAGE`).
333 ///
334 /// A device that keeps no on-sensor storage (a host-image sensor) inherits the default, which
335 /// reports [`Error::NotSupported`] — the absence of storage is spoken by *not* overriding this,
336 /// its presence by advertising [`DeviceFeature::STORAGE`] and overriding it.
337 async fn list_prints(&mut self) -> Result<Vec<Print>> {
338 Err(Error::NotSupported)
339 }
340
341 /// Delete one print from on-device storage.
342 ///
343 /// Defaults to [`Error::NotSupported`] for a device without on-sensor storage; see
344 /// [`list_prints`](Device::list_prints).
345 async fn delete_print(&mut self, print: &Print) -> Result<()> {
346 let _ = print;
347 Err(Error::NotSupported)
348 }
349
350 /// Erase all templates from on-device storage.
351 ///
352 /// Defaults to [`Error::NotSupported`] for a device without on-sensor storage; see
353 /// [`list_prints`](Device::list_prints).
354 async fn clear_storage(&mut self) -> Result<()> {
355 Err(Error::NotSupported)
356 }
357
358 /// Prepare for system suspend (the sensor may need to stop an active wait).
359 async fn suspend(&mut self) -> Result<()>;
360
361 /// Resume after system suspend.
362 async fn resume(&mut self) -> Result<()>;
363}
364
365/// A source of [`Device`]s — the entry point, analogous to libfprint's `FpContext`.
366///
367/// The associated `Device` type keeps this on static dispatch.
368#[expect(async_fn_in_trait)]
369pub trait Backend {
370 /// The concrete reader type this backend hands out.
371 type Device: Device;
372
373 /// Enumerate the readers currently attached.
374 async fn enumerate(&self) -> Result<Vec<Self::Device>>;
375
376 /// Open a specific reader by id (convenience over `enumerate` + find).
377 async fn open(&self, id: &DeviceId) -> Result<Self::Device>;
378}
379
380#[cfg(test)]
381mod tests {
382 use super::{Device, DeviceId, DeviceInfo, DriverId, EnrollProgress, IdentifyOutcome};
383 use crate::feature::FLAGS;
384 use crate::{DeviceFeature, FingerStatus, Print, Result, ScanType, VerifyOutcome};
385
386 /// Carries a [`DeviceInfo`] and nothing else. Only `info` is ever called: [`Device::has_feature`]
387 /// is a default method over it, so the sensor operations need no bodies to test it.
388 struct InfoOnly(DeviceInfo);
389
390 impl Device for InfoOnly {
391 fn info(&self) -> &DeviceInfo {
392 &self.0
393 }
394
395 async fn open(&mut self) -> Result<()> {
396 todo!("has_feature never opens the device")
397 }
398 async fn close(&mut self) -> Result<()> {
399 todo!("has_feature never opens the device")
400 }
401 async fn enroll<F: FnMut(EnrollProgress)>(&mut self, _: Print, _: F) -> Result<Print> {
402 todo!("has_feature never scans")
403 }
404 async fn verify_with_status<F: FnMut(FingerStatus)>(
405 &mut self,
406 _: &Print,
407 _: F,
408 ) -> Result<VerifyOutcome> {
409 todo!("has_feature never scans")
410 }
411 async fn identify_with_status<F: FnMut(FingerStatus)>(
412 &mut self,
413 _: &[Print],
414 _: F,
415 ) -> Result<IdentifyOutcome> {
416 todo!("has_feature never scans")
417 }
418 async fn suspend(&mut self) -> Result<()> {
419 todo!("has_feature never suspends")
420 }
421 async fn resume(&mut self) -> Result<()> {
422 todo!("has_feature never suspends")
423 }
424 }
425
426 fn device_with(features: DeviceFeature) -> InfoOnly {
427 InfoOnly(DeviceInfo::new(
428 DeviceId::new("test-0"),
429 DriverId::new("test"),
430 "Test Reader",
431 ScanType::Press,
432 features,
433 1,
434 ))
435 }
436
437 /// **`has_feature` is `info().features.contains`, for every representable set and every defined
438 /// flag** — the default body must not develop a rule of its own.
439 ///
440 /// The sets and the flags both come from [`crate::feature::FLAGS`], so an eleventh flag widens
441 /// this test on its own rather than escaping it.
442 #[test]
443 fn has_feature_agrees_with_the_advertised_set() {
444 let defined = DeviceFeature::from_bits_truncate(u32::MAX).bits();
445 for bits in 0..=u32::from(defined) {
446 let advertised = DeviceFeature::from_bits_truncate(bits);
447 let device = device_with(advertised);
448 for flag in
449 core::iter::once(DeviceFeature::NONE).chain(FLAGS.into_iter().map(|(f, _)| f))
450 {
451 assert_eq!(
452 device.has_feature(flag),
453 advertised.contains(flag),
454 "{advertised:?}.has_feature({flag:?})"
455 );
456 }
457 }
458 }
459}