dcmnorm 0.20.0

Fast DICOM toolkit: parse, render, transcode, reformat, de-identify and network (DIMSE) DICOM medical images.
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
//! Native DICOM Upper Layer / DIMSE service class **provider** (SCP): a listener accepting
//! inbound associations and answering C-ECHO, C-STORE, C-FIND, and C-MOVE requests. Handles
//! association negotiation and C-ECHO/C-STORE entirely in Rust; C-FIND and C-MOVE (which need
//! to query/queue against the host application's own HTTP API) and "association complete" (which needs to
//! POST the studies just stored) are delegated to a caller-supplied [`ScpHandlers`]
//! implementation, kept deliberately free of any napi/JS awareness here - the node bindings
//! crate is what adapts a JS callback into this trait.
//!
//! One OS thread per accepted connection (matching the fully-synchronous style the rest of this
//! crate's DIMSE code already uses - see `dimse.rs`'s SCU functions and their mock-SCP tests).

use std::collections::HashMap;
use std::fmt;
use std::fs::{File, OpenOptions};
use std::io::{BufWriter, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;

use dcmnorm_core::{dicom_value, DataElement, VR};
use dcmnorm_dictionary::{tags, uids};
use dcmnorm_dimse::{
    association::server::ServerAssociationOptions,
    pdu::{PDataValue, PDataValueType, Pdu, PresentationContextResultReason},
    Incoming, ServerAssociation,
};
use dcmnorm_encoding::transfer_syntax::Codec;
use dcmnorm_encoding::TransferSyntax;
use dcmnorm_object::{FileMetaTableBuilder, InMemDicomObject, OpenFileOptions, ReadPreamble};

use super::dimse::{implicit_vr_le, log_event, transfer_syntax, DimseLogger};
use super::io::normalize_transfer_syntax_uid;
use super::streaming_transcode::receive_and_transcode_stream_to_file;

static SCP_TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Business logic an embedding application supplies for the DIMSE operations that need it - the
/// SCP itself only owns protocol/association mechanics and (for C-STORE) writing the received
/// file to disk. Implementations must be safe to call concurrently from multiple connection
/// threads at once.
pub trait ScpHandlers: Send + Sync {
    /// A C-FIND request's Identifier, reduced to whichever of StudyInstanceUID/StudyDate/
    /// PatientName/PatientID were actually present (DICOM keyword keys). Returns matched
    /// studies, each a keyword-keyed field map for whichever of StudyInstanceUID/
    /// AccessionNumber/PatientID/PatientName/PatientBirthDate/StudyDate/StudyTime/
    /// StudyDescription/ModalitiesInStudy/NumberOfStudyRelatedSeries/
    /// NumberOfStudyRelatedInstances it has values for.
    fn on_find(
        &self,
        filter: &HashMap<String, String>,
    ) -> Result<Vec<HashMap<String, String>>, String>;

    /// What the SCP actually calls for a C-FIND: as [`Self::on_find`], plus the request's Affected SOP Class UID (one of
    /// [`ScpOptions::find_sop_classes`]: Study Root or Patient Root FIND by default). The default ignores the SOP class
    /// and calls `on_find`, so an implementation that only knows `on_find` keeps working unchanged.
    fn on_find_with_sop_class(
        &self,
        _sop_class_uid: &str,
        filter: &HashMap<String, String>,
    ) -> Result<Vec<HashMap<String, String>>, String> {
        self.on_find(filter)
    }

    /// Returns `Ok(true)` if the move was successfully queued - mirrors a "fire and forget"
    /// C-MOVE that delegates the actual transfer elsewhere and only reports whether it was
    /// accepted for processing, not whether the transfer itself later succeeds.
    fn on_move(&self, study_instance_uid: &str, move_destination_ae: &str) -> Result<bool, String>;

    /// Called once per association, when it ends (cleanly or otherwise), if any C-STORE
    /// happened during it - maps each StudyInstanceUID to the on-disk paths of every instance
    /// stored for it during this association.
    fn on_association_complete(&self, stored_instances_by_study: &HashMap<String, Vec<String>>);
}

#[derive(Clone)]
pub struct ScpOptions {
    pub ae_title: String,
    /// The acceptor's own advertised max PDU length (sent back in A-ASSOCIATE-AC's Maximum
    /// Length sub-item). dcmnorm-dimse's strict-mode reader also enforces this as a hard ceiling on
    /// every *incoming* PDU on this connection - including the initial A-ASSOCIATE-RQ itself,
    /// before we've parsed it - so this can't be chosen per-requestor; it has to be generous
    /// enough up front for whatever any requestor proposes (a request with many presentation
    /// contexts can itself exceed a small ceiling well before any C-STORE payload is involved).
    pub max_pdu_length: u32,
    /// Applied as both the read and write timeout on each connection's socket - matches
    /// dcmjs-dimse's `pduTimeout` option (how long an established association may sit idle
    /// between PDUs before being dropped).
    pub idle_timeout: Duration,
    /// Optional sink for the same association-negotiation/per-message/release debug detail
    /// `*ScuOptions::on_log` reports on the SCU side (see `DimseLogger`'s doc comment) - `Arc`
    /// rather than `Box` since `ScpOptions` is cloned once per accepted connection.
    pub on_log: Option<Arc<dyn DimseLogger>>,
    /// C-FIND SOP classes (Affected SOP Class UID of the C-FIND-RQ) answered through
    /// [`ScpHandlers::on_find_with_sop_class`] as a study-level search. Any other C-FIND (Modality Worklist, General
    /// Purpose Worklist, ...) is answered with status 0x0122 (SOP class not supported) and an Error Comment without
    /// calling the handler: the association itself still accepts every abstract syntax, so a modality that proposes
    /// MWL alongside Storage can still C-STORE. Default: Study Root and Patient Root Query/Retrieve FIND.
    pub find_sop_classes: Vec<String>,
    /// Optional target transfer syntax UID for on-the-fly streaming transcode while receiving
    /// C-STORE instances to disk (for example `1.2.840.10008.1.2.4.201` to store incoming
    /// uncompressed or JPEG Lossless images directly as HTJ2K without writing the raw file first).
    /// Non-image SOP classes (SR, RTSTRUCT, ...) or instances ineligible for the target codec are
    /// stored verbatim in their negotiated transfer syntax. `None` (default) stores every instance
    /// verbatim as received.
    pub storage_transfer_syntax: Option<String>,
}

impl Default for ScpOptions {
    fn default() -> Self {
        Self {
            ae_title: "ANY-SCP".to_owned(),
            // 256 KiB - matches dcmnorm-dimse's own internal LARGE_PDU_SIZE, so this doesn't cost any
            // extra buffer pre-allocation over what the crate already budgets for a "large" PDU.
            max_pdu_length: 262_144,
            idle_timeout: Duration::from_secs(300),
            on_log: None,
            find_sop_classes: vec![
                uids::STUDY_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_FIND.to_owned(),
                uids::PATIENT_ROOT_QUERY_RETRIEVE_INFORMATION_MODEL_FIND.to_owned(),
            ],
            storage_transfer_syntax: None,
        }
    }
}

#[derive(Debug)]
pub enum ScpError {
    Io(std::io::Error),
}

impl fmt::Display for ScpError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io(error) => write!(formatter, "I/O error: {error}"),
        }
    }
}

impl std::error::Error for ScpError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(error) => Some(error),
        }
    }
}

impl From<std::io::Error> for ScpError {
    fn from(value: std::io::Error) -> Self {
        Self::Io(value)
    }
}

/// A running SCP. Dropping this without calling [`DicomScp::stop`] leaves the listener thread
/// running in the background (it is not tied to this handle's lifetime) - always call `stop()`
/// during shutdown.
pub struct DicomScp {
    stop_flag: Arc<AtomicBool>,
    local_addr: SocketAddr,
    accept_thread: Option<std::thread::JoinHandle<()>>,
}

impl DicomScp {
    pub fn local_port(&self) -> u16 {
        self.local_addr.port()
    }

    /// Stops accepting new associations and waits for the accept loop to exit. Associations
    /// already in progress on their own connection threads are not interrupted - each finishes
    /// (or times out via `idle_timeout`) independently.
    pub fn stop(mut self) {
        self.stop_flag.store(true, Ordering::SeqCst);
        // Unblock the listener thread's blocking accept() call with a throwaway local
        // connection - it's dropped immediately once the accept loop observes the stop flag.
        let _ = TcpStream::connect(("127.0.0.1", self.local_addr.port()));
        if let Some(handle) = self.accept_thread.take() {
            let _ = handle.join();
        }
    }
}

/// Starts listening on `port` (0 binds an ephemeral port - see [`DicomScp::local_port`]),
/// accepting DICOM associations and dispatching C-ECHO/C-STORE/C-FIND/C-MOVE requests.
/// C-STORE'd instances are written under `cache_path` as
/// `S_<StudyInstanceUID>/<Modality>_<SOPInstanceUID>.dcm`. Accepts every proposed presentation
/// context regardless of abstract syntax (`ServerAssociationOptions::promiscuous`), matching a
/// permissive "accept anything a real sender proposes" SCP rather than a curated allow-list; a
/// C-FIND whose SOP class is not in [`ScpOptions::find_sop_classes`] is refused per message
/// (0x0122) instead. A C-CANCEL-RQ during a C-FIND ends it with 0xFE00; one after the final
/// response is ignored.
pub fn start_scp(
    port: u16,
    cache_path: PathBuf,
    handlers: Arc<dyn ScpHandlers>,
    options: ScpOptions,
) -> Result<DicomScp, ScpError> {
    if let Some(ref ts_uid) = options.storage_transfer_syntax {
        super::streaming_transcode::validate_storage_transfer_syntax(ts_uid).map_err(|msg| {
            ScpError::Io(std::io::Error::new(std::io::ErrorKind::InvalidInput, msg))
        })?;
    }
    let listener = TcpListener::bind(("0.0.0.0", port))?;
    let local_addr = listener.local_addr()?;
    let stop_flag = Arc::new(AtomicBool::new(false));
    let stop_flag_thread = stop_flag.clone();

    let accept_thread = std::thread::spawn(move || loop {
        let stream = match listener.accept() {
            Ok((stream, _peer)) => stream,
            Err(_) => break,
        };
        if stop_flag_thread.load(Ordering::SeqCst) {
            break;
        }

        let handlers = handlers.clone();
        let cache_path = cache_path.clone();
        let options = options.clone();
        std::thread::spawn(move || {
            handle_association(stream, &cache_path, handlers.as_ref(), &options);
        });
    });

    Ok(DicomScp {
        stop_flag,
        local_addr,
        accept_thread: Some(accept_thread),
    })
}

fn handle_association(
    stream: TcpStream,
    cache_path: &Path,
    handlers: &dyn ScpHandlers,
    options: &ScpOptions,
) {
    let logger = options.on_log.as_deref();
    let peer = stream
        .peer_addr()
        .map(|addr| addr.to_string())
        .unwrap_or_else(|_| "<unknown>".to_owned());

    log_event(logger, || {
        format!(
            "accepting association from {peer} (AE title {:?}, max PDU {})",
            options.ae_title, options.max_pdu_length
        )
    });

    let association_options = ServerAssociationOptions::new()
        .ae_title(options.ae_title.clone())
        .promiscuous(true)
        .max_pdu_length(options.max_pdu_length)
        .read_timeout(options.idle_timeout)
        .write_timeout(options.idle_timeout);

    let mut association = match association_options.establish(stream) {
        Ok(association) => {
            log_event(logger, || {
                let contexts = association.presentation_contexts();
                // `promiscuous(true)` only bypasses the *abstract syntax* check - dcmnorm-dimse still
                // negotiates a transfer syntax per context against its own registry's supported
                // set, and a context whose only proposed transfer syntax isn't supported (e.g. a
                // JPEG variant this build's registry can't decode) comes back here with `reason
                // != Acceptance` and a bogus placeholder transfer_syntax - not actually usable by
                // the peer for that context, even though it's still present in this list. Every
                // context is logged with its real outcome so that's visible up front, instead of
                // silently matching production incident 2026-07-28 (sb-st98vv4a-1): a peer
                // proposing several presentation contexts, releasing without ever sending a
                // C-STORE, and this line alone giving no hint that most of them may have actually
                // been rejected.
                let accepted_count = contexts
                    .iter()
                    .filter(|pc| pc.reason == PresentationContextResultReason::Acceptance)
                    .count();
                let negotiated = contexts
                    .iter()
                    .map(|pc| {
                        format!(
                            "#{} {} / {} ({:?})",
                            pc.id, pc.abstract_syntax, pc.transfer_syntax, pc.reason
                        )
                    })
                    .collect::<Vec<_>>()
                    .join(", ");
                format!(
                    "association with {peer} established; negotiated presentation context(s) \
                     ({accepted_count}/{} accepted): [{negotiated}]",
                    contexts.len()
                )
            });
            association
        }
        Err(error) => {
            log_event(logger, || {
                format!("association with {peer} rejected: {error}")
            });
            return;
        }
    };

    let mut stored_instances_by_study: HashMap<String, Vec<String>> = HashMap::new();
    // A message read while polling for a C-CANCEL-RQ during a C-FIND that turned out to be something else; handled next.
    let mut deferred: Option<Incoming> = None;

    loop {
        // Message-level (dcmnorm-dimse's `message.rs`): a sender may put the command and the first fragment of its data set
        // in one PDU and the rest in later ones (dcm4che does), so PDU boundaries are never used as message boundaries.
        let received = match deferred.take() {
            Some(incoming) => Ok(incoming),
            None => association.receive_command(),
        };
        let incoming = match received {
            Ok(incoming) => incoming,
            Err(error) => {
                log_event(logger, || {
                    format!("association with {peer} closed: {error}")
                });
                break;
            }
        };

        match incoming {
            Incoming::Pdu(Pdu::ReleaseRQ) => {
                // Logged before the reply is sent (matching every other log/act pairing in this
                // file) rather than after: `assoc.release()` on the SCU side returns as soon as
                // it reads A-RELEASE-RP off the wire, which races this thread's next instruction
                // otherwise - logging first guarantees a caller that just observed `*_scu` return
                // has also already observed this line.
                log_event(logger, || format!("association with {peer} released"));
                let _ = association.send(&Pdu::ReleaseRP);
                break;
            }
            Incoming::Pdu(Pdu::AbortRQ { .. }) => {
                log_event(logger, || {
                    format!("association with {peer} aborted by peer")
                });
                break;
            }
            Incoming::Command {
                presentation_context_id: pc_id,
                data: command_data,
            } => {
                let Ok(command) = InMemDicomObject::read_dataset_with_ts(
                    command_data.as_slice(),
                    implicit_vr_le(),
                ) else {
                    log_event(logger, || {
                        format!("association with {peer} closed: failed to parse DIMSE command")
                    });
                    break;
                };
                let Some(negotiated_ts) = negotiated_transfer_syntax(&association, pc_id) else {
                    log_event(logger, || {
                        format!("association with {peer} closed: no negotiated presentation context #{pc_id}")
                    });
                    break;
                };

                let command_field = command_u16(&command, tags::COMMAND_FIELD);
                let outcome = match command_field {
                    0x0030 => handle_echo(&mut association, pc_id, &command, logger),
                    0x0001 => handle_store(
                        &mut association,
                        pc_id,
                        &command,
                        negotiated_ts,
                        options.storage_transfer_syntax.as_deref(),
                        cache_path,
                        &mut stored_instances_by_study,
                        logger,
                    ),
                    0x0020 => handle_find(
                        &mut association,
                        pc_id,
                        &command,
                        negotiated_ts,
                        handlers,
                        &options.find_sop_classes,
                        &mut deferred,
                        logger,
                    ),
                    0x0021 => handle_move(
                        &mut association,
                        pc_id,
                        &command,
                        negotiated_ts,
                        handlers,
                        logger,
                    ),
                    // C-CANCEL-RQ with no C-FIND in progress (it arrived after the final response): nothing to cancel,
                    // and C-CANCEL has no response (PS3.7 9.3.2.3), so it is ignored rather than closing the association.
                    0x0FFF => {
                        let cancelled_id =
                            command_u16(&command, tags::MESSAGE_ID_BEING_RESPONDED_TO);
                        log_event(logger, || {
                            format!("received C-CANCEL-RQ (message id being responded to {cancelled_id}) with no C-FIND in progress; ignored")
                        });
                        Ok(())
                    }
                    _ => Err(()),
                };
                if outcome.is_err() {
                    log_event(logger, || {
                        format!("association with {peer} closed: error handling command field 0x{command_field:04X}")
                    });
                    break;
                }
            }
            _ => {
                log_event(logger, || {
                    format!("association with {peer} closed: unexpected PDU")
                });
                break;
            }
        }
    }

    if stored_instances_by_study.is_empty() {
        // Deliberately explicit rather than just an absence of "received C-STORE-RQ" lines - an
        // association that connects, negotiates presentation contexts, and releases/aborts
        // without ever sending a C-STORE is easy to miss when scanning logs by eye, and looks
        // identical to a real C-STORE whose own logging got lost - this line rules that out.
        log_event(logger, || {
            format!("association with {peer} ended with no C-STORE received")
        });
    } else {
        log_event(logger, || {
            let total_instances: usize = stored_instances_by_study.values().map(Vec::len).sum();
            let study_count = stored_instances_by_study.len();
            format!(
                "association with {peer} stored {total_instances} instance(s) across {study_count} stud{} before ending",
                if study_count == 1 { "y" } else { "ies" }
            )
        });
        handlers.on_association_complete(&stored_instances_by_study);
    }
}

fn negotiated_transfer_syntax(
    association: &ServerAssociation<TcpStream>,
    pc_id: u8,
) -> Option<&'static TransferSyntax> {
    let pc = association
        .presentation_contexts()
        .iter()
        .find(|pc| pc.id == pc_id)?;
    transfer_syntax(&pc.transfer_syntax).ok()
}

fn command_u16(command: &InMemDicomObject, tag: dcmnorm_core::Tag) -> u16 {
    command
        .element(tag)
        .ok()
        .and_then(|element| element.to_int::<u16>().ok())
        .unwrap_or(0)
}

fn command_str(command: &InMemDicomObject, tag: dcmnorm_core::Tag) -> Option<String> {
    command
        .element(tag)
        .ok()
        .and_then(|element| element.to_str().ok())
        .map(|value| value.trim().to_owned())
}

fn element_str(object: &InMemDicomObject, tag: dcmnorm_core::Tag) -> Option<String> {
    object
        .element(tag)
        .ok()
        .and_then(|element| element.to_str().ok())
        .map(|value| value.trim().to_owned())
}

fn send_command(
    association: &mut ServerAssociation<TcpStream>,
    pc_id: u8,
    command: &InMemDicomObject,
) -> Result<(), ()> {
    let mut data = Vec::with_capacity(128);
    command
        .write_dataset_with_ts(&mut data, implicit_vr_le())
        .map_err(|_| ())?;
    association
        .send(&Pdu::PData {
            data: vec![PDataValue {
                presentation_context_id: pc_id,
                value_type: PDataValueType::Command,
                is_last: true,
                data,
            }],
        })
        .map_err(|_| ())
}

fn send_data(
    association: &mut ServerAssociation<TcpStream>,
    pc_id: u8,
    data: Vec<u8>,
) -> Result<(), ()> {
    association
        .send(&Pdu::PData {
            data: vec![PDataValue {
                presentation_context_id: pc_id,
                value_type: PDataValueType::Data,
                is_last: true,
                data,
            }],
        })
        .map_err(|_| ())
}

/// The data set that follows the request command just received, reassembled from however many PDVs/PDUs the sender used.
fn receive_data(
    association: &mut ServerAssociation<TcpStream>,
    logger: Option<&dyn DimseLogger>,
) -> Result<Vec<u8>, ()> {
    association.receive_data_set().map_err(|error| {
        log_event(logger, || {
            format!("failed to receive data set PDU(s): {error}")
        });
    })
}

fn handle_echo(
    association: &mut ServerAssociation<TcpStream>,
    pc_id: u8,
    command: &InMemDicomObject,
    logger: Option<&dyn DimseLogger>,
) -> Result<(), ()> {
    let message_id = command_u16(command, tags::MESSAGE_ID);
    log_event(logger, || {
        format!("received C-ECHO-RQ (message id {message_id})")
    });

    let response = InMemDicomObject::command_from_element_iter([
        DataElement::new(
            tags::AFFECTED_SOP_CLASS_UID,
            VR::UI,
            dicom_value!(Str, uids::VERIFICATION),
        ),
        DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8030])),
        DataElement::new(
            tags::MESSAGE_ID_BEING_RESPONDED_TO,
            VR::US,
            dicom_value!(U16, [message_id]),
        ),
        DataElement::new(
            tags::COMMAND_DATA_SET_TYPE,
            VR::US,
            dicom_value!(U16, [0x0101]),
        ),
        DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [0x0000])),
    ]);
    log_event(logger, || "sending C-ECHO-RSP: status=0x0000".to_owned());
    send_command(association, pc_id, &response)
}

#[allow(clippy::too_many_arguments)]
fn handle_store(
    association: &mut ServerAssociation<TcpStream>,
    pc_id: u8,
    command: &InMemDicomObject,
    negotiated_ts: &'static TransferSyntax,
    storage_transfer_syntax: Option<&str>,
    cache_path: &Path,
    stored_instances_by_study: &mut HashMap<String, Vec<String>>,
    logger: Option<&dyn DimseLogger>,
) -> Result<(), ()> {
    let message_id = command_u16(command, tags::MESSAGE_ID);
    let affected_sop_class_uid =
        command_str(command, tags::AFFECTED_SOP_CLASS_UID).unwrap_or_default();
    let affected_sop_instance_uid =
        command_str(command, tags::AFFECTED_SOP_INSTANCE_UID).unwrap_or_default();

    log_event(logger, || {
        format!("received C-STORE-RQ: SOP instance {affected_sop_instance_uid}")
    });

    let status = match receive_and_store_dataset(
        association,
        pc_id,
        negotiated_ts,
        storage_transfer_syntax,
        &affected_sop_class_uid,
        &affected_sop_instance_uid,
        cache_path,
        stored_instances_by_study,
        logger,
    ) {
        Ok(status) => status,
        Err(StoreReceiveError::Transport(message)) => {
            log_event(logger, || {
                format!("failed to receive data set PDU(s): {message}")
            });
            return Err(());
        }
        Err(StoreReceiveError::Processing(error)) => {
            log_event(logger, || {
                format!("failed to store C-STORE dataset for SOP instance {affected_sop_instance_uid}: {error}")
            });
            // 0xC000: "Processing failure" (PS3.7 Annex C, generic non-specific failure) - matches
            // the Status this SCP's predecessor (dcmjs-dimse) used for any C-STORE write failure.
            0xC000
        }
    };

    log_event(logger, || {
        format!("sending C-STORE-RSP: status=0x{status:04X}")
    });

    let response = InMemDicomObject::command_from_element_iter([
        DataElement::new(
            tags::AFFECTED_SOP_CLASS_UID,
            VR::UI,
            dicom_value!(Str, affected_sop_class_uid),
        ),
        DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8001])),
        DataElement::new(
            tags::MESSAGE_ID_BEING_RESPONDED_TO,
            VR::US,
            dicom_value!(U16, [message_id]),
        ),
        DataElement::new(
            tags::COMMAND_DATA_SET_TYPE,
            VR::US,
            dicom_value!(U16, [0x0101]),
        ),
        DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [status])),
        DataElement::new(
            tags::AFFECTED_SOP_INSTANCE_UID,
            VR::UI,
            dicom_value!(Str, affected_sop_instance_uid),
        ),
    ]);
    send_command(association, pc_id, &response)
}

enum StoreReceiveError {
    /// Wire/PDU error — the association cannot continue cleanly.
    Transport(String),
    /// Dataset parse, encode, or filesystem error after the wire message was completely drained.
    Processing(String),
}

struct ScpTempFile {
    path: PathBuf,
    file: Option<File>,
    persisted: bool,
}

impl ScpTempFile {
    fn create_in(dir: &Path) -> Result<Self, std::io::Error> {
        std::fs::create_dir_all(dir)?;
        let pid = std::process::id();
        for _ in 0..64 {
            let seq = SCP_TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
            let candidate = dir.join(format!(".dcmnorm-scp-{pid}-{seq}.tmp"));
            let mut opts = OpenOptions::new();
            opts.read(true).write(true).create_new(true);
            match opts.open(&candidate) {
                Ok(file) => {
                    return Ok(Self {
                        path: candidate,
                        file: Some(file),
                        persisted: false,
                    });
                }
                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
                Err(error) => return Err(error),
            }
        }
        Err(std::io::Error::new(
            std::io::ErrorKind::AlreadyExists,
            "could not allocate unique SCP temp file",
        ))
    }

    fn file(&self) -> &File {
        self.file.as_ref().expect("temp file open")
    }

    fn file_mut(&mut self) -> &mut File {
        self.file.as_mut().expect("temp file open")
    }

    fn persist(mut self, target: &Path) -> Result<(), std::io::Error> {
        let temp_path = self.path.clone();
        self.persisted = true;
        drop(self.file.take());

        // Preserve existing destination permissions on overwrite (matching TempOutputFile::persist),
        // while avoiding granting group access if a setgid directory assigned a different GID.
        #[cfg(unix)]
        if let (Ok(existing_meta), Ok(temp_meta)) =
            (std::fs::metadata(target), std::fs::metadata(&temp_path))
        {
            use std::os::unix::fs::{MetadataExt, PermissionsExt};
            let mut mode = existing_meta.permissions().mode() & 0o777;
            if temp_meta.gid() != existing_meta.gid() {
                mode &= !0o070;
            }
            let _ = std::fs::set_permissions(&temp_path, std::fs::Permissions::from_mode(mode));
        }

        if let Err(err) = super::streaming_transcode::replace_file_atomically(&temp_path, target) {
            let _ = std::fs::remove_file(&temp_path);
            return Err(err);
        }
        Ok(())
    }
}

impl Drop for ScpTempFile {
    fn drop(&mut self) {
        if !self.persisted {
            let _ = std::fs::remove_file(&self.path);
        }
    }
}

fn validate_scp_path_component<'a>(
    value: &'a str,
    label: &str,
    allow_empty: bool,
) -> Result<&'a str, String> {
    if value.is_empty() {
        if allow_empty {
            return Ok(value);
        }
        return Err(format!("empty {label} in received C-STORE dataset"));
    }
    if value == "."
        || value == ".."
        || value.contains("..")
        || !value
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_'))
    {
        return Err(format!("unsafe {label} for filesystem path: {value:?}"));
    }
    Ok(value)
}

#[allow(clippy::too_many_arguments)]
fn receive_and_store_dataset(
    association: &mut ServerAssociation<TcpStream>,
    pc_id: u8,
    negotiated_ts: &'static TransferSyntax,
    storage_transfer_syntax: Option<&str>,
    affected_sop_class_uid: &str,
    affected_sop_instance_uid: &str,
    cache_path: &Path,
    stored_instances_by_study: &mut HashMap<String, Vec<String>>,
    logger: Option<&dyn DimseLogger>,
) -> Result<u16, StoreReceiveError> {
    let mut temp = match ScpTempFile::create_in(cache_path) {
        Ok(temp) => temp,
        Err(err) => {
            // Drain the incoming dataset so the association stays aligned for C-STORE-RSP 0xC000.
            let mut reader = association.receive_data_set_reader(pc_id);
            reader
                .drain_to_end()
                .map_err(|e| StoreReceiveError::Transport(e.to_string()))?;
            return Err(StoreReceiveError::Processing(format!(
                "creating temp file in {}: {err}",
                cache_path.display()
            )));
        }
    };

    let want_on_the_fly_transcode = storage_transfer_syntax.filter(|uid| {
        let target = normalize_transfer_syntax_uid(uid);
        !target.is_empty()
            && target != normalize_transfer_syntax_uid(negotiated_ts.uid())
            && !matches!(negotiated_ts.codec(), Codec::Dataset(_))
    });

    let (study_instance_uid, modality) = if let Some(target_uid) = want_on_the_fly_transcode {
        let temp_path = temp.path.clone();
        let mut pdata = association.receive_data_set_reader(pc_id);
        match receive_and_transcode_stream_to_file(
            &mut pdata,
            negotiated_ts,
            target_uid,
            affected_sop_class_uid,
            affected_sop_instance_uid,
            temp.file_mut(),
            &temp_path,
        ) {
            Ok(pair) => {
                // Ensure any remaining unread bytes (e.g. trailing empty final PDV) are drained.
                pdata
                    .drain_to_end()
                    .map_err(|e| StoreReceiveError::Transport(e.to_string()))?;
                pair
            }
            Err(err) => {
                if let Some(wire_err) = pdata.wire_error() {
                    return Err(StoreReceiveError::Transport(wire_err.to_owned()));
                }
                pdata
                    .drain_to_end()
                    .map_err(|e| StoreReceiveError::Transport(e.to_string()))?;
                return Err(StoreReceiveError::Processing(err));
            }
        }
    } else {
        // Default passthrough streaming: write the ~200-byte Part 10 File Meta header directly,
        // stream incoming Data PDVs straight to disk via PDataReader (distinguishing wire errors
        // from disk-write errors so a disk failure drains the PDVs and returns 0xC000 instead of
        // dropping the association), then validate full element/PixelData structure in O(1) RAM
        // before publishing.
        let meta = FileMetaTableBuilder::new()
            .transfer_syntax(negotiated_ts.uid())
            .media_storage_sop_class_uid(affected_sop_class_uid)
            .media_storage_sop_instance_uid(affected_sop_instance_uid)
            .build()
            .map_err(|e| StoreReceiveError::Processing(format!("building file meta table: {e}")))?;
        {
            let mut pdata = association.receive_data_set_reader(pc_id);
            let mut writer = BufWriter::new(temp.file());
            if let Err(err) = meta.write_to(&mut writer) {
                pdata
                    .drain_to_end()
                    .map_err(|e| StoreReceiveError::Transport(e.to_string()))?;
                return Err(StoreReceiveError::Processing(format!(
                    "writing Part 10 header: {err}"
                )));
            }
            let mut buf = [0u8; 64 * 1024];
            loop {
                let n = std::io::Read::read(&mut pdata, &mut buf)
                    .map_err(|e| StoreReceiveError::Transport(e.to_string()))?;
                if n == 0 {
                    break;
                }
                if let Err(err) = writer.write_all(&buf[..n]) {
                    pdata
                        .drain_to_end()
                        .map_err(|e| StoreReceiveError::Transport(e.to_string()))?;
                    return Err(StoreReceiveError::Processing(format!(
                        "writing received dataset to disk: {err}"
                    )));
                }
            }
            if let Err(err) = writer.flush() {
                return Err(StoreReceiveError::Processing(format!(
                    "flushing received dataset: {err}"
                )));
            }
        }

        // Validate element headers, native PixelData length, and encapsulated sequence delimiter
        // (FFFE,E0DD) using O(1)-RAM seeking instead of loading PixelData into memory.
        let validated_obj = match OpenFileOptions::new()
            .read_preamble(ReadPreamble::Always)
            .open_file_deferring_pixel_data(&temp.path)
        {
            Ok(Some((obj, _, _))) => obj,
            Ok(None) => {
                // Dataset-level codec (e.g. Deflated Explicit VR LE): validate via full parse.
                super::io::read_dicom_file(&temp.path).map_err(|e| {
                    StoreReceiveError::Processing(format!("validating deflated dataset: {e}"))
                })?
            }
            Err(e) => {
                return Err(StoreReceiveError::Processing(format!(
                    "validating received dataset: {e}"
                )));
            }
        };
        // Reject datasets whose embedded SOP Class or SOP Instance UID disagrees with the
        // C-STORE-RQ command so a mismatched payload cannot overwrite another stored instance.
        if let Some(ds_sop_class) = element_str(&validated_obj, tags::SOP_CLASS_UID) {
            if ds_sop_class.trim_end_matches(['\0', ' '])
                != affected_sop_class_uid.trim_end_matches(['\0', ' '])
            {
                return Err(StoreReceiveError::Processing(format!(
                    "dataset SOPClassUID ({ds_sop_class}) does not match C-STORE-RQ AffectedSOPClassUID ({affected_sop_class_uid})"
                )));
            }
        }
        if let Some(ds_sop_instance) = element_str(&validated_obj, tags::SOP_INSTANCE_UID) {
            if ds_sop_instance.trim_end_matches(['\0', ' '])
                != affected_sop_instance_uid.trim_end_matches(['\0', ' '])
            {
                return Err(StoreReceiveError::Processing(format!(
                    "dataset SOPInstanceUID ({ds_sop_instance}) does not match C-STORE-RQ AffectedSOPInstanceUID ({affected_sop_instance_uid})"
                )));
            }
        }
        let study_uid = element_str(&validated_obj, tags::STUDY_INSTANCE_UID).unwrap_or_default();
        let modality =
            element_str(&validated_obj, tags::MODALITY).unwrap_or_else(|| "UN".to_owned());
        (study_uid, modality)
    };

    log_event(logger, || {
        format!(
            "received C-STORE-RQ dataset: study {study_instance_uid}, SOP instance {affected_sop_instance_uid}"
        )
    });

    validate_scp_path_component(&study_instance_uid, "StudyInstanceUID", true)
        .map_err(StoreReceiveError::Processing)?;
    validate_scp_path_component(affected_sop_instance_uid, "AffectedSOPInstanceUID", false)
        .map_err(StoreReceiveError::Processing)?;
    validate_scp_path_component(&modality, "Modality", false)
        .map_err(StoreReceiveError::Processing)?;

    let study_dir = cache_path.join(format!("S_{study_instance_uid}"));
    let file_path = study_dir.join(format!("{modality}_{affected_sop_instance_uid}.dcm"));
    if study_dir.parent() != Some(cache_path) || file_path.parent() != Some(study_dir.as_path()) {
        return Err(StoreReceiveError::Processing(
            "resolved storage path escapes cache directory".to_owned(),
        ));
    }

    std::fs::create_dir_all(&study_dir)
        .map_err(|e| StoreReceiveError::Processing(format!("creating study directory: {e}")))?;
    temp.persist(&file_path).map_err(|e| {
        StoreReceiveError::Processing(format!("persisting received DICOM file: {e}"))
    })?;

    stored_instances_by_study
        .entry(study_instance_uid)
        .or_default()
        .push(file_path.to_string_lossy().into_owned());

    Ok(0x0000)
}

const FIND_IDENTIFIER_KEYS: &[(&str, dcmnorm_core::Tag)] = &[
    ("StudyInstanceUID", tags::STUDY_INSTANCE_UID),
    ("StudyDate", tags::STUDY_DATE),
    ("PatientName", tags::PATIENT_NAME),
    ("PatientID", tags::PATIENT_ID),
];

const FIND_RESPONSE_FIELDS: &[(&str, dcmnorm_core::Tag, VR)] = &[
    ("StudyInstanceUID", tags::STUDY_INSTANCE_UID, VR::UI),
    ("AccessionNumber", tags::ACCESSION_NUMBER, VR::SH),
    ("PatientID", tags::PATIENT_ID, VR::LO),
    ("PatientName", tags::PATIENT_NAME, VR::PN),
    ("PatientBirthDate", tags::PATIENT_BIRTH_DATE, VR::DA),
    ("StudyDate", tags::STUDY_DATE, VR::DA),
    ("StudyTime", tags::STUDY_TIME, VR::TM),
    ("StudyDescription", tags::STUDY_DESCRIPTION, VR::LO),
    ("ModalitiesInStudy", tags::MODALITIES_IN_STUDY, VR::CS),
    (
        "NumberOfStudyRelatedSeries",
        tags::NUMBER_OF_STUDY_RELATED_SERIES,
        VR::IS,
    ),
    (
        "NumberOfStudyRelatedInstances",
        tags::NUMBER_OF_STUDY_RELATED_INSTANCES,
        VR::IS,
    ),
];

/// Error Comment (0000,0902, LO: at most 64 characters) for a C-FIND whose SOP class is not in `find_sop_classes`.
fn unsupported_find_error_comment(sop_class_uid: &str) -> String {
    let mut comment = format!("C-FIND SOP class {sop_class_uid} not supported");
    if comment.len() > 64 {
        comment = "C-FIND SOP class not supported".to_owned();
    }
    comment
}

fn find_response_command(
    sop_class_uid: &str,
    message_id: u16,
    status: u16,
    error_comment: Option<String>,
) -> InMemDicomObject {
    let mut elements = vec![
        DataElement::new(
            tags::AFFECTED_SOP_CLASS_UID,
            VR::UI,
            dicom_value!(Str, sop_class_uid.to_owned()),
        ),
        DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8020])),
        DataElement::new(
            tags::MESSAGE_ID_BEING_RESPONDED_TO,
            VR::US,
            dicom_value!(U16, [message_id]),
        ),
        // 0x0001: an Identifier follows (a Pending response); 0x0101: none (the final response).
        DataElement::new(
            tags::COMMAND_DATA_SET_TYPE,
            VR::US,
            dicom_value!(U16, [if status == 0xFF00 { 0x0001 } else { 0x0101 }]),
        ),
        DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [status])),
    ];
    if let Some(comment) = error_comment {
        elements.push(DataElement::new(
            tags::ERROR_COMMENT,
            VR::LO,
            dicom_value!(Str, comment),
        ));
    }
    InMemDicomObject::command_from_element_iter(elements)
}

/// Whether the peer has sent a C-CANCEL-RQ for C-FIND `message_id` (PS3.7 9.1.2.1.6), checked without blocking between
/// responses. Anything else that arrived (a stray C-CANCEL for another message id is ignored) is kept in `deferred` for
/// the association loop, so polling never loses a message.
fn find_cancel_requested(
    association: &mut ServerAssociation<TcpStream>,
    message_id: u16,
    deferred: &mut Option<Incoming>,
    logger: Option<&dyn DimseLogger>,
) -> Result<bool, ()> {
    if deferred.is_some() {
        return Ok(false);
    }
    association
        .inner_stream()
        .set_nonblocking(true)
        .map_err(|_| ())?;
    let polled = association.receive_command();
    association
        .inner_stream()
        .set_nonblocking(false)
        .map_err(|_| ())?;
    match polled {
        // Nothing (or only part of a PDU, which the receiver keeps) has arrived.
        Err(dcmnorm_dimse::Error::Io(error))
            if matches!(
                error.kind(),
                std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
            ) =>
        {
            Ok(false)
        }
        Err(error) => {
            log_event(logger, || {
                format!("failed to read from the association during C-FIND: {error}")
            });
            Err(())
        }
        Ok(Incoming::Command {
            presentation_context_id,
            data,
        }) => {
            let parsed =
                InMemDicomObject::read_dataset_with_ts(data.as_slice(), implicit_vr_le()).ok();
            if let Some(command) =
                parsed.filter(|command| command_u16(command, tags::COMMAND_FIELD) == 0x0FFF)
            {
                let cancelled_id = command_u16(&command, tags::MESSAGE_ID_BEING_RESPONDED_TO);
                if cancelled_id == message_id {
                    log_event(logger, || {
                        format!(
                            "received C-CANCEL-RQ (message id being responded to {cancelled_id})"
                        )
                    });
                    return Ok(true);
                }
                log_event(logger, || {
                    format!("received C-CANCEL-RQ (message id being responded to {cancelled_id}) for another message; ignored")
                });
                return Ok(false);
            }
            *deferred = Some(Incoming::Command {
                presentation_context_id,
                data,
            });
            Ok(false)
        }
        Ok(other) => {
            *deferred = Some(other);
            Ok(false)
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn handle_find(
    association: &mut ServerAssociation<TcpStream>,
    pc_id: u8,
    command: &InMemDicomObject,
    negotiated_ts: &TransferSyntax,
    handlers: &dyn ScpHandlers,
    find_sop_classes: &[String],
    deferred: &mut Option<Incoming>,
    logger: Option<&dyn DimseLogger>,
) -> Result<(), ()> {
    let message_id = command_u16(command, tags::MESSAGE_ID);
    let affected_sop_class_uid =
        command_str(command, tags::AFFECTED_SOP_CLASS_UID).unwrap_or_default();

    let identifier_bytes = receive_data(association, logger)?;
    let identifier =
        InMemDicomObject::read_dataset_with_ts(identifier_bytes.as_slice(), negotiated_ts)
            .map_err(|_| ())?;

    // Only study-level searches go to the handler: answering a Modality Worklist (or any other) C-FIND as a study search
    // would hand archived studies to a device that asked for something else (an MWL query without PatientName/PatientID
    // would match every study).
    if !find_sop_classes
        .iter()
        .any(|sop_class| sop_class == &affected_sop_class_uid)
    {
        log_event(logger, || {
            format!("received C-FIND-RQ (message id {message_id}); SOP class {affected_sop_class_uid} not supported")
        });
        // 0x0122: "SOP class not supported" (PS3.7 Annex C, general status).
        log_event(logger, || {
            "sending C-FIND-RSP: 0 match(es), final status=0x0122".to_owned()
        });
        let error_comment = unsupported_find_error_comment(&affected_sop_class_uid);
        return send_command(
            association,
            pc_id,
            &find_response_command(
                &affected_sop_class_uid,
                message_id,
                0x0122,
                Some(error_comment),
            ),
        );
    }

    let mut filter = HashMap::new();
    for (keyword, tag) in FIND_IDENTIFIER_KEYS {
        if let Some(value) = element_str(&identifier, *tag) {
            if !value.is_empty() {
                filter.insert((*keyword).to_owned(), value);
            }
        }
    }

    // Logs query key names only, not values - an Identifier commonly carries PHI (PatientName,
    // PatientID) that a debug log shouldn't echo even at the debug tier. Mirrors `find_scu`'s own
    // logging of the same request shape on the SCU side.
    log_event(logger, || {
        let mut keys: Vec<&str> = filter.keys().map(String::as_str).collect();
        keys.sort_unstable();
        format!(
            "received C-FIND-RQ (message id {message_id}); query key(s): [{}]; SOP class {affected_sop_class_uid}",
            keys.join(", ")
        )
    });

    let mut match_count = 0usize;
    let final_status =
        match handlers.on_find_with_sop_class(&affected_sop_class_uid, &filter) {
            Ok(studies) => {
                let mut cancelled = false;
                for study in &studies {
                    // A C-CANCEL-RQ may arrive at any time before the final response (PS3.4 C.4.1.3.1): stop sending
                    // matches and answer 0xFE00. Checked before each match (the handler may have taken a while).
                    if find_cancel_requested(association, message_id, deferred, logger)? {
                        cancelled = true;
                        break;
                    }
                    // SpecificCharacterSet is declared unconditionally (not just when a value
                    // actually needs it) - PS3.5 6.1.2.3's default repertoire (used when this is
                    // absent) is 7-bit ASCII, and `on_find` results come from customer data
                    // (patient/study text) that isn't guaranteed to be ASCII-only. Without this,
                    // dicom-rs's writer hard-fails on encountering the first non-ASCII byte in any
                    // LO/SH/PN/etc. value below - aborting the whole C-FIND response (and, since
                    // that error propagates out of this association's handling loop, the connection
                    // itself) rather than just garbling that one field.
                    let mut elements = vec![DataElement::new(
                        tags::SPECIFIC_CHARACTER_SET,
                        VR::CS,
                        dicom_value!(Str, "ISO_IR 192"),
                    )];
                    elements.extend(FIND_RESPONSE_FIELDS.iter().filter_map(
                        |(keyword, tag, vr)| {
                            study.get(*keyword).map(|value| {
                                DataElement::new(*tag, *vr, dicom_value!(Str, value.clone()))
                            })
                        },
                    ));
                    let match_dataset = InMemDicomObject::from_element_iter(elements);
                    let mut match_bytes = Vec::new();
                    match_dataset
                        .write_dataset_with_ts(&mut match_bytes, negotiated_ts)
                        .map_err(|_| ())?;

                    // 0xFF00: Pending, matches follow (PS3.7 C.4.1) - the standard "another match
                    // is coming next" status for a C-FIND-RSP.
                    send_command(
                        association,
                        pc_id,
                        &find_response_command(&affected_sop_class_uid, message_id, 0xFF00, None),
                    )?;
                    send_data(association, pc_id, match_bytes)?;
                    match_count += 1;
                }
                if cancelled || find_cancel_requested(association, message_id, deferred, logger)? {
                    // 0xFE00: "Matching terminated due to Cancel request" (PS3.4 C.4.1.1.4).
                    0xFE00u16
                } else {
                    0x0000u16
                }
            }
            // 0xC000: "Unable to process" (generic C-FIND failure). Logged, not just swallowed - the
            // handler's own error (e.g. a malformed match JS returned, an HTTP failure it hit) is the
            // only trace of *why* a C-FIND failed, since the DIMSE status code itself carries none of
            // that detail to the SCU.
            Err(error) => {
                eprintln!("[dicom-scp] C-FIND on_find handler failed: {error}");
                0xC000u16
            }
        };

    log_event(logger, || {
        format!("sending C-FIND-RSP: {match_count} match(es), final status=0x{final_status:04X}")
    });

    send_command(
        association,
        pc_id,
        &find_response_command(&affected_sop_class_uid, message_id, final_status, None),
    )
}

fn handle_move(
    association: &mut ServerAssociation<TcpStream>,
    pc_id: u8,
    command: &InMemDicomObject,
    negotiated_ts: &TransferSyntax,
    handlers: &dyn ScpHandlers,
    logger: Option<&dyn DimseLogger>,
) -> Result<(), ()> {
    let message_id = command_u16(command, tags::MESSAGE_ID);
    let affected_sop_class_uid =
        command_str(command, tags::AFFECTED_SOP_CLASS_UID).unwrap_or_default();
    let move_destination = command_str(command, tags::MOVE_DESTINATION).unwrap_or_default();

    let identifier_bytes = receive_data(association, logger)?;
    let identifier =
        InMemDicomObject::read_dataset_with_ts(identifier_bytes.as_slice(), negotiated_ts)
            .map_err(|_| ())?;
    let study_instance_uid = element_str(&identifier, tags::STUDY_INSTANCE_UID).unwrap_or_default();

    log_event(logger, || {
        format!("received C-MOVE-RQ (message id {message_id}): study {study_instance_uid} -> move destination AE {move_destination}")
    });

    let status: u16 = if study_instance_uid.is_empty() {
        // 0x0120: "Missing Attribute" (PS3.7 Annex C, general status - no StudyInstanceUID given).
        0x0120
    } else if move_destination.is_empty() {
        // 0xA801: "Move Destination unknown" (C-MOVE-specific status, PS3.7 C.4.2.1.5).
        0xA801
    } else {
        match handlers.on_move(&study_instance_uid, &move_destination) {
            Ok(true) => 0x0000,
            // 0xC000: "Unable to process" (generic C-MOVE failure - matches the queueing failure
            // this SCP's predecessor reported here, since the actual transfer's own success/
            // failure is reported separately and asynchronously by whatever performs it).
            Ok(false) => 0xC000,
            Err(error) => {
                eprintln!("[dicom-scp] C-MOVE on_move handler failed: {error}");
                0xC000
            }
        }
    };

    log_event(logger, || {
        format!("sending C-MOVE-RSP: status=0x{status:04X}")
    });

    let response = InMemDicomObject::command_from_element_iter([
        DataElement::new(
            tags::AFFECTED_SOP_CLASS_UID,
            VR::UI,
            dicom_value!(Str, affected_sop_class_uid),
        ),
        DataElement::new(tags::COMMAND_FIELD, VR::US, dicom_value!(U16, [0x8021])),
        DataElement::new(
            tags::MESSAGE_ID_BEING_RESPONDED_TO,
            VR::US,
            dicom_value!(U16, [message_id]),
        ),
        DataElement::new(
            tags::COMMAND_DATA_SET_TYPE,
            VR::US,
            dicom_value!(U16, [0x0101]),
        ),
        DataElement::new(tags::STATUS, VR::US, dicom_value!(U16, [status])),
    ]);
    send_command(association, pc_id, &response)
}