ehds-logging 0.1.0

The European logging software component of an EHR system under Regulation (EU) 2025/327: the Annex II 3.2 access record, the Article 14(1) categories and the map that classifies an access, and the record written as an IHE BALP AuditEvent
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
// SPDX-FileCopyrightText: Cadasto B.V.
// SPDX-License-Identifier: BUSL-1.1

//! An access record written as an IHE BALP `AuditEvent` (feature `balp`),
//! through the audit types of `ihe-atna`.
//!
//! The recording system received the request, so the record is the server's
//! side of the `RESTful` pattern its action names (BALP 1.1.4): a query is
//! `IHE.BasicAudit.Query`, a read `IHE.BasicAudit.Read`, a create
//! `IHE.BasicAudit.Create`, an update `IHE.BasicAudit.Update` and a delete
//! `IHE.BasicAudit.Delete`, each its `Patient` variant when the record names
//! one patient, as the implementation guide lists them: the one the request
//! named, or the one the identity service found behind the `ehr_id` it
//! reached. Its `entity:patient` slice holds one patient, so a record that
//! names several writes each and claims the plain pattern. The Delete pattern
//! fixes `outcome` to `0`, so a failed delete claims no profile. The person
//! and the client are the token's (BALP 1.1.4 §3:5.7.5.4), with the provider
//! as an agent of its own, the request id is `entity:transaction`, and the
//! query `entity:query`.
//!
//! The person's agent, `agent:user`, alone carries what Annex II 3.2(b) asks
//! about the natural person: the professional's name as `who.display` and
//! their identifier as an `ihe-otherId` extension typed `NPI`, as BALP
//! 1.1.4 §3:5.7.5.4 maps the IHE IUA `subject_name` and
//! `national_provider_identifier`; the assurance level of the
//! authentication, when one was established, as an `ihe-assuranceLevel`
//! extension coded `low`, `substantial` or `high` (Regulation (EU) No
//! 910/2014 Art 8(2)); and who acts, `person` or `client`, as its `role`.
//!
//! What Annex II 3.2 adds to a BALP record has no element of its own (BALP
//! defines none for a data category), so it rides in entities of type `4`,
//! which no slice of a pattern is discriminated by: one for the categories
//! and the record's retention, one per origin and one per `ehr_id`, each
//! with its `detail` entries named as [`detail`] lists them (no
//! specification governs the names: our own design). The professional and
//! the provider a national contact point relays (Implementing Regulation
//! (EU) 2026/2099 Annex Tables 1 and 2) ride the same way, in one entity
//! `ehds-relayed` that names the contact point and marks them `asserted`,
//! and a correlation identifier the client sent is a `detail` of the request
//! id's entity.
//!
//! The record's security labels ([`crate::label`], Annex II 3.4) are its
//! `meta.security`, which a FHIR repository can limit access by, and each is
//! also the `securityLabel` of the entity it belongs to: the categories' on
//! the `ehds-categories` entity and each origin's on its `origin` entity,
//! which the `RESTful` ATNA mapping keeps as the DICOM
//! `ParticipantObjectSensitivity` (`RESTful` ATNA Rev. 3.6
//! Table 3.20.4.2.2.1-1).
//!
//! An emergency access (Regulation (EU) 2025/327 Art 11(5)) keeps its
//! purposes of use where every purpose is written, in `agent:user`
//! `purposeOfUse` and in `purposeOfEvent`, and is marked in one entity of
//! its own, `ehds-emergency-access`, whose `description` states the mark in words and
//! whose `detail` entries name the purposes that marked it, so a reader of
//! the record need not know which codes the deployment maps, and each member
//! whose consent pre-filter denial was set aside for it.
//!
//! A population access, a query over many patients' data whose record names
//! none of them, is marked in one entity `ehds-population`, whose
//! `description` says in words that the query ran over each origin the
//! record names and that the record confirms no read of any one person's
//! record, and whose `detail` entries name why no `ehr_id` is named and the
//! template and archetype ids the query read (Regulation (EU) 2025/327 Art
//! 9(1)). BALP 1:52.4.1.6 recommends one record per patient "driven by a
//! Policy"; this record names the scope, never a person.
//!
//! Each semantic transformation the access applied is one entity of its own
//! ([`transformation`]), in the same `AuditEvent` as the access, so it is
//! kept and found with it (eHealth Network General Guidelines Release 3.1
//! Art 6(3)).

pub mod detail;
pub mod inserted;
pub mod transformation;

use std::collections::BTreeSet;
use std::sync::Arc;

use ihe_atna::balp::{
    APPLICATION, AuditRecorder, CREATE, CUSTODIAN, DELETE, DESTINATION_ROLE, DOMAIN_RESOURCE,
    Described, Detail, Direction, Entity, EventKind, Exchange, NetworkAddress, OTHER, Peer, READ,
    REQUEST_ID, REST, Reserved, SEARCH, SOURCE_ROLE, SYSTEM_OBJECT, SecurityLabel, UPDATE, What,
};
use ihe_atna::user::{Code, OnBehalfOf, PurposeOfUse, User};
use secrecy::{ExposeSecret as _, SecretString};
use url::Url;

use crate::classify::Classification;
use crate::emergency::Emergency;
use crate::label::Label;
use crate::record::{
    AccessRecord, Action, Origin, Outcome, PatientIdentifier, PatientLookup, Population, Relayed,
};
use crate::sink::{AccessSink, Reservation, SinkError};

/// The name of the entity that marks an emergency access.
pub const EMERGENCY_ENTITY: &str = "ehds-emergency-access";

/// The `description` of the entity that marks an emergency access.
pub const EMERGENCY_DESCRIPTION: &str = "Emergency access: the accessor declared that the access \
     was necessary to protect the vital interests of the data subject \
     (Regulation (EU) 2025/327 Art 11(5)).";

/// The name of the entity that marks a population access.
pub const POPULATION_ENTITY: &str = "ehds-population";

/// The `description` of the entity that marks a population access.
pub const POPULATION_DESCRIPTION: &str = "Population access: a query over many \
     patients' data ran over each origin this record names; the record does not name \
     the persons whose records it read, and does not say that it read any one \
     person's record (Regulation (EU) 2025/327 Art 9(1)).";

/// The sink that writes each record as a BALP `AuditEvent` and hands it to
/// an `ihe-atna` audit recorder, such as one that spools it for an ATNA
/// Audit Record Repository.
pub struct BalpSink {
    recorder: Arc<dyn AuditRecorder>,
    base: Url,
}

impl std::fmt::Debug for BalpSink {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BalpSink").finish_non_exhaustive()
    }
}

impl BalpSink {
    /// The sink that records through `recorder`, naming the recording system
    /// by `base`, the base its requests arrive at.
    #[must_use]
    pub fn new(recorder: Arc<dyn AuditRecorder>, base: Url) -> Self {
        Self { recorder, base }
    }
}

#[async_trait::async_trait]
impl AccessSink for BalpSink {
    async fn store(&self, record: AccessRecord) -> Result<(), SinkError> {
        self.recorder
            .record(exchange(&record, &self.base))
            .await
            .map_err(|error| SinkError(Box::new(error)))
    }

    async fn reserve(&self) -> Result<Box<dyn Reservation>, SinkError> {
        let place = self
            .recorder
            .reserve()
            .await
            .map_err(|error| SinkError(Box::new(error)))?;
        Ok(Box::new(BalpReservation {
            place,
            recorder: Arc::clone(&self.recorder),
            base: self.base.clone(),
        }))
    }
}

/// The place of one record [`BalpSink`] took: the recorder's own place, or
/// none when the recorder holds no bounded store.
struct BalpReservation {
    place: Option<Box<dyn Reserved>>,
    recorder: Arc<dyn AuditRecorder>,
    base: Url,
}

impl std::fmt::Debug for BalpReservation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BalpReservation")
            .field("place", &self.place)
            .finish_non_exhaustive()
    }
}

#[async_trait::async_trait]
impl Reservation for BalpReservation {
    async fn store(self: Box<Self>, record: AccessRecord) -> Result<(), SinkError> {
        let exchange = exchange(&record, &self.base);
        match self.place {
            Some(place) => place.record(exchange).await,
            None => self.recorder.record(exchange).await,
        }
        .map_err(|error| SinkError(Box::new(error)))
    }
}

/// The BALP exchange `record` is written as, the recording system named by
/// `base`.
#[must_use]
pub fn exchange(record: &AccessRecord, base: &Url) -> Exchange {
    let accessor = &record.accessor;
    let user = User::new(
        accessor.issuer.clone(),
        accessor.subject.clone(),
        accessor.client_id.clone(),
    )
    .with_audience(accessor.audience.clone())
    .with_purposes(
        accessor
            .purposes
            .iter()
            .map(|purpose| PurposeOfUse {
                system: purpose.system.clone(),
                code: purpose.code.clone(),
            })
            .collect(),
    )
    .with_organisation(accessor.provider.clone())
    .with_alt_id(accessor.alt_id.clone())
    .with_name(accessor.professional.name.clone())
    .with_provider_identifier(accessor.professional.identifier.clone())
    // NOTE: no specification governs these codes: our own design; BALP 1.1.4 leaves the
    // assuranceLevel vocabulary open, and names no element for who acts.
    .with_assurance(accessor.assurance.map(|level| code(level.code())))
    .with_roles(vec![code(accessor.acting.code())]);
    let client = Peer {
        who: accessor.client_id.clone(),
        network: record.request.client_address.map_or_else(
            || NetworkAddress::MachineName(String::from("unknown")),
            NetworkAddress::Ip,
        ),
    };
    Exchange {
        kind: kind(record),
        recorded: record.recorded,
        outcome: match record.outcome {
            Outcome::Success => ihe_atna::balp::Outcome::Success,
            Outcome::MinorFailure => ihe_atna::balp::Outcome::MinorFailure,
            Outcome::SeriousFailure => ihe_atna::balp::Outcome::SeriousFailure,
        },
        direction: Direction::Received {
            client,
            endpoint: base.clone(),
        },
        on_behalf: OnBehalfOf::User(user),
        entities: entities(record),
        security: security(&record.labels.all()),
    }
}

/// A code no system defines.
fn code(code: &str) -> Code {
    Code {
        system: None,
        code: code.to_owned(),
    }
}

/// What the pattern of `record`'s action fixes.
fn kind(record: &AccessRecord) -> EventKind {
    let patient = patients(record).len() == 1;
    let profile = |plain: &'static str, with_patient: &'static str| {
        if patient { with_patient } else { plain }
    };
    match record.action {
        Action::Query => EventKind {
            profile: profile(
                "https://profiles.ihe.net/ITI/BALP/StructureDefinition/IHE.BasicAudit.Query",
                "https://profiles.ihe.net/ITI/BALP/StructureDefinition/IHE.BasicAudit.PatientQuery",
            ),
            event_type: REST,
            subtypes: &[SEARCH],
            action: "E",
            client: SOURCE_ROLE,
            server: DESTINATION_ROLE,
        },
        Action::Read => EventKind {
            profile: profile(
                "https://profiles.ihe.net/ITI/BALP/StructureDefinition/IHE.BasicAudit.Read",
                "https://profiles.ihe.net/ITI/BALP/StructureDefinition/IHE.BasicAudit.PatientRead",
            ),
            event_type: REST,
            subtypes: &[READ],
            action: "R",
            client: DESTINATION_ROLE,
            server: SOURCE_ROLE,
        },
        Action::Create => EventKind {
            profile: profile(
                "https://profiles.ihe.net/ITI/BALP/StructureDefinition/IHE.BasicAudit.Create",
                "https://profiles.ihe.net/ITI/BALP/StructureDefinition/IHE.BasicAudit.PatientCreate",
            ),
            event_type: REST,
            subtypes: &[CREATE],
            action: "C",
            client: SOURCE_ROLE,
            server: DESTINATION_ROLE,
        },
        Action::Update => EventKind {
            profile: profile(
                "https://profiles.ihe.net/ITI/BALP/StructureDefinition/IHE.BasicAudit.Update",
                "https://profiles.ihe.net/ITI/BALP/StructureDefinition/IHE.BasicAudit.PatientUpdate",
            ),
            event_type: REST,
            subtypes: &[UPDATE],
            action: "U",
            client: SOURCE_ROLE,
            server: DESTINATION_ROLE,
        },
        Action::Delete => EventKind {
            profile: if record.outcome == Outcome::Success {
                profile(
                    "https://profiles.ihe.net/ITI/BALP/StructureDefinition/IHE.BasicAudit.Delete",
                    "https://profiles.ihe.net/ITI/BALP/StructureDefinition/IHE.BasicAudit.PatientDelete",
                )
            } else {
                ""
            },
            event_type: REST,
            subtypes: &[DELETE],
            action: "D",
            client: APPLICATION,
            server: CUSTODIAN,
        },
    }
}

/// The entities of `record`: the request id, the query or the resource,
/// the patient, each `ehr_id`, the categories, and each origin.
fn entities(record: &AccessRecord) -> Vec<Entity> {
    let request = &record.request;
    let mut entities = vec![Entity::Described(Described {
        what: Some(What::Identifier {
            system: None,
            value: request.id.clone(),
        }),
        kind: REQUEST_ID,
        role: None,
        name: None,
        description: None,
        details: request
            .correlation
            .iter()
            .map(|correlation| Detail::new(detail::CORRELATION, correlation.clone()))
            .collect(),
        security_labels: Vec::new(),
    })];
    match record.action {
        Action::Query => entities.push(Entity::Query(
            request
                .query
                .clone()
                .unwrap_or_else(|| SecretString::from(request.operation.clone())),
        )),
        Action::Read | Action::Create | Action::Update | Action::Delete => {
            entities.push(Entity::Described(Described {
                what: Some(What::Reference {
                    reference: request
                        .resource
                        .clone()
                        .unwrap_or_else(|| request.operation.clone()),
                    resource_type: None,
                }),
                kind: SYSTEM_OBJECT,
                role: Some(DOMAIN_RESOURCE),
                name: Some(request.operation.clone()),
                description: None,
                details: Vec::new(),
                security_labels: Vec::new(),
            }));
        }
    }
    for patient in patients(record) {
        entities.push(Entity::Patient {
            system: patient.namespace.clone(),
            value: patient.value.clone(),
        });
    }
    for ehr in &record.subject.ehrs {
        entities.push(other(
            Some(ehr.ehr_id.clone()),
            "ehr",
            vec![
                Detail::new(detail::ENDPOINT, ehr.endpoint.clone()),
                Detail::new(detail::PATIENT_LOOKUP, ehr.patient.code()),
            ],
            &[],
        ));
    }
    let mut details = categories(&record.categories);
    if let Some(delivered) = record.delivered {
        details.push(Detail::new(detail::DELIVERED, delivered.to_string()));
    }
    if let Some(name) = &request.stored_query {
        details.push(Detail::new(detail::STORED_QUERY, name.clone()));
    }
    let retention = &record.retention;
    details.extend([
        Detail::new(detail::RETENTION_YEARS, retention.years().get().to_string()),
        Detail::new(detail::RETENTION_ENDS, retention.ends().to_string()),
        Detail::new(detail::RETENTION_GROUND, retention.ground().code()),
    ]);
    entities.push(other(
        None,
        "ehds-categories",
        details,
        record.labels.categories(),
    ));
    for origin in &record.origins {
        entities.push(origin_entity(
            origin,
            record.labels.origin(&origin.endpoint),
        ));
    }
    if let Some(relayed) = &record.accessor.relayed {
        entities.push(other(None, "ehds-relayed", relayed_details(relayed), &[]));
    }
    entities.extend(record.subject.population.as_ref().map(population_entity));
    if let Some(emergency) = &record.emergency {
        entities.push(emergency_entity(emergency));
    }
    entities.extend(record.inserted.map(inserted::entity));
    entities.extend(record.transformations.iter().map(transformation::entity));
    entities
}

/// The entity of `origin`, labelled `labels`: how it answered, its node, its
/// `system_id`, its rows, the version a write left there, the `ehr_id` an
/// EHR create left there and its categories.
fn origin_entity(origin: &Origin, labels: &[Label]) -> Entity {
    let mut details = vec![Detail::new(detail::STATUS, origin.status.clone())];
    details.extend(
        origin
            .node
            .iter()
            .map(|node| Detail::new(detail::NODE, node.clone())),
    );
    details.extend(
        origin
            .system_id
            .iter()
            .map(|system_id| Detail::new(detail::SYSTEM_ID, system_id.clone())),
    );
    details.extend(
        origin
            .rows
            .map(|rows| Detail::new(detail::ROWS, rows.to_string())),
    );
    if let Some(version) = &origin.version {
        details.extend(
            version
                .named()
                .map(|named| Detail::new(detail::WRITTEN_VERSION, named)),
        );
        details.extend(
            version
                .unread()
                .map(|why| Detail::new(detail::WRITTEN_VERSION_UNREAD, why)),
        );
    }
    if let Some(created) = &origin.created_ehr {
        details.extend(
            created
                .named()
                .map(|ehr_id| Detail::new(detail::CREATED_EHR, ehr_id)),
        );
        details.extend(
            created
                .unread()
                .map(|why| Detail::new(detail::CREATED_EHR_UNREAD, why)),
        );
    }
    details.extend(origin.categories.iter().flat_map(categories));
    other(Some(origin.endpoint.clone()), "origin", details, labels)
}

/// The entity that marks an emergency access, naming the purposes that
/// marked it and each member whose consent pre-filter denial was set aside.
fn emergency_entity(emergency: &Emergency) -> Entity {
    let mut details = vec![Detail::new(detail::EMERGENCY_ACCESS, "true")];
    details.extend(emergency.purposes().iter().map(|purpose| {
        Detail::new(
            detail::EMERGENCY_PURPOSE,
            coded(purpose.system.as_deref(), &purpose.code),
        )
    }));
    details.extend(
        emergency
            .consent_set_aside()
            .iter()
            .map(|member| Detail::new(detail::CONSENT_SET_ASIDE, member.clone())),
    );
    Entity::Described(Described {
        what: None,
        kind: OTHER,
        role: None,
        name: Some(EMERGENCY_ENTITY.to_owned()),
        description: Some(EMERGENCY_DESCRIPTION.to_owned()),
        details,
        security_labels: Vec::new(),
    })
}

/// The security labels `labels` are written as.
fn security(labels: &[Label]) -> Vec<SecurityLabel> {
    labels
        .iter()
        .map(|label| SecurityLabel {
            system: label.system().to_owned(),
            version: label.version().map(str::to_owned),
            code: label.code().to_owned(),
        })
        .collect()
}

/// The entity that marks a population access, with why it names no
/// `ehr_id` and the template and archetype ids the query read.
fn population_entity(population: &Population) -> Entity {
    let mut details = vec![
        Detail::new(detail::POPULATION, "true"),
        Detail::new(detail::POPULATION_REASON, population.reason.code()),
    ];
    details.extend(
        population
            .ehrs
            .map(|ehrs| Detail::new(detail::POPULATION_EHRS, ehrs.to_string())),
    );
    details.push(Detail::new(
        detail::POPULATION_LIMIT,
        population.limit.to_string(),
    ));
    for (name, ids) in [
        (detail::TEMPLATE_ID, &population.templates),
        (detail::ARCHETYPE_ID, &population.archetypes),
    ] {
        details.extend(ids.iter().map(|id| Detail::new(name, id.clone())));
    }
    Entity::Described(Described {
        what: None,
        kind: OTHER,
        role: None,
        name: Some(POPULATION_ENTITY.to_owned()),
        description: Some(POPULATION_DESCRIPTION.to_owned()),
        details,
        security_labels: Vec::new(),
    })
}

/// `<system>|<code>`, or `<code>` when no system is named.
fn coded(system: Option<&str>, code: &str) -> String {
    match system {
        Some(system) => format!("{system}|{code}"),
        None => code.to_owned(),
    }
}

/// The `detail` entries of what a national contact point relayed, marked
/// as its assertion.
fn relayed_details(relayed: &Relayed) -> Vec<Detail> {
    let professional = &relayed.professional;
    let provider = &relayed.provider;
    let mut details = vec![
        Detail::new(detail::CONTACT_POINT, relayed.contact_point.clone()),
        Detail::new(detail::ASSERTED, "true"),
        Detail::new(detail::COUNTRY_CODE, relayed.country_code.clone()),
        Detail::new(detail::FAMILY_NAME, professional.family_name.clone()),
        Detail::new(detail::GIVEN_NAME, professional.given_name.clone()),
        Detail::new(detail::HP_IDENTIFIER, professional.identifier.clone()),
        Detail::new(
            detail::HP_ISSUING_AUTHORITY,
            professional.issuing_authority.clone(),
        ),
    ];
    details.extend(
        professional
            .roles
            .iter()
            .map(|role| Detail::new(detail::HP_ROLE, coded(role.system.as_deref(), &role.code))),
    );
    details.extend([
        Detail::new(detail::PROVIDER_IDENTIFIER, provider.identifier.clone()),
        Detail::new(
            detail::PROVIDER_ISSUING_AUTHORITY,
            provider.issuing_authority.clone(),
        ),
        Detail::new(detail::PROVIDER_NAME, provider.name.clone()),
        Detail::new(detail::PROVIDER_ADDRESS, provider.address.clone()),
    ]);
    details
}

/// Every patient `record` names, each once: the one the request named, and
/// each one the identity service found behind an `ehr_id` the access
/// reached.
fn patients(record: &AccessRecord) -> Vec<&PatientIdentifier> {
    let found = record
        .subject
        .ehrs
        .iter()
        .flat_map(|ehr| match &ehr.patient {
            PatientLookup::Found(found) => found.as_slice(),
            _ => &[],
        });
    let mut named: Vec<&PatientIdentifier> = Vec::new();
    for patient in record.subject.patient.iter().chain(found) {
        let seen = named.iter().any(|kept| {
            kept.namespace == patient.namespace
                && kept.value.expose_secret() == patient.value.expose_secret()
        });
        if !seen {
            named.push(patient);
        }
    }
    named
}

/// An entity of type `4` named `name`, identified by `value` when given,
/// labelled `labels`.
fn other(value: Option<String>, name: &str, details: Vec<Detail>, labels: &[Label]) -> Entity {
    Entity::Described(Described {
        what: value.map(|value| What::Identifier {
            system: None,
            value,
        }),
        kind: OTHER,
        role: None,
        name: Some(name.to_owned()),
        description: None,
        details,
        security_labels: security(labels),
    })
}

/// The `detail` entries of `classified`.
fn categories(classified: &Classification) -> Vec<Detail> {
    let mut details = Vec::new();
    let mut versions = BTreeSet::new();
    for (category, bases) in classified.categories() {
        details.push(Detail::new(detail::CATEGORY, category.token()));
        for basis in bases {
            details.push(Detail::new(
                detail::BASIS,
                format!("{}:{}", category.token(), basis.code()),
            ));
        }
        if let Some(version) = category.version() {
            versions.insert(format!("{}|{version}", category.system()));
        }
    }
    details.extend(
        versions
            .into_iter()
            .map(|version| Detail::new(detail::CATEGORY_VERSION, version)),
    );
    if classified.is_no_category() {
        details.push(Detail::new(detail::NO_CATEGORY, "true"));
    }
    if let Some(unclassified) = classified.unclassified() {
        details.push(Detail::new(detail::UNCLASSIFIED, unclassified.code()));
    }
    for (name, ids) in [
        (detail::TEMPLATE_ID, classified.templates()),
        (detail::ARCHETYPE_ID, classified.archetypes()),
        (detail::VERSION_UID, classified.versions()),
        (detail::UNMAPPED_ID, classified.unmapped()),
    ] {
        details.extend(ids.iter().map(|id| Detail::new(name, id.clone())));
    }
    if let Some(digest) = classified.digest() {
        details.push(Detail::new(detail::MAP_DIGEST, digest));
    }
    details
}