From 36349e1d69d4b48a820d80cdbed136420c823c28 Mon Sep 17 00:00:00 2001 From: "adrian.crainic@bgasoft.com" Date: Tue, 24 Nov 2026 16:04:56 +0200 Subject: [PATCH] organize sftp pdfs by date --- CHANGELOG.md | 14 +++ Cargo.lock | 1 + .../2026-11-24-pdf-report-date-folders.md | 19 +++ console/help/pdf-reports.json | 2 +- .../src/features/config/EndpointFields.tsx | 6 +- crates/packie-routing/Cargo.toml | 1 + crates/packie-routing/src/message/pdf.rs | 108 ++++++++++++++---- crates/packie-routing/tests/message_pdf.rs | 99 ++++++++++++++-- crates/packie-transport/tests/folder.rs | 18 ++- docs/operations/configuration-reference.md | 4 +- docs/spec/acceptance.md | 2 +- docs/spec/configuration.md | 4 +- docs/spec/message-channels.md | 2 +- docs/spec/pdf-reports.md | 2 +- 14 files changed, 235 insertions(+), 47 deletions(-) create mode 100644 changelog.d/2026-11-24-pdf-report-date-folders.md diff --git a/CHANGELOG.md b/CHANGELOG.md index f7c17d6..745c25c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -173,6 +173,20 @@ top, then by impact. Types follow [Keep a Changelog](https://keepachangelog.com/ ### Medium impact +- **Changed:** PDF reports are filed by date inside their outcome folders (2026-11-24) + + When a PDF report channel moves an incoming PDF after reading it, the engine now places the + file inside a `YYYY/MM/DD` date folder (using the host computer's local date when the report + was received) under the configured processed, filtered or unreadable folder — for example + `processed/2026/11/24/report.pdf`. The configured folder names stay the same, and the date + folders are created automatically on both local folders and SFTP servers. + + Technical notes: + + Applies to `pdf_report` sources with `on_consumed: move` on `folder` and `sftp` endpoints, + using the message's `received_at` converted to the host's local calendar date + (`/YYYY/MM/DD`). Delimited file sources are unchanged. + - **Fixed:** SFTP endpoints connect to servers with RSA host keys (2026-11-24) SFTP endpoints now connect to servers that identify themselves with an RSA host key, including diff --git a/Cargo.lock b/Cargo.lock index dcd31a8..d02576f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2515,6 +2515,7 @@ dependencies = [ name = "packie-routing" version = "0.2.0" dependencies = [ + "jiff", "packie-astm", "packie-au", "packie-config", diff --git a/changelog.d/2026-11-24-pdf-report-date-folders.md b/changelog.d/2026-11-24-pdf-report-date-folders.md new file mode 100644 index 0000000..e787c06 --- /dev/null +++ b/changelog.d/2026-11-24-pdf-report-date-folders.md @@ -0,0 +1,19 @@ +--- +date: 2026-11-24 +type: changed +impact: medium +title: PDF reports are filed by date inside their outcome folders +area: Endpoints +link: /endpoints +--- +When a PDF report channel moves an incoming PDF after reading it, the engine now places the +file inside a `YYYY/MM/DD` date folder (using the host computer's local date when the report +was received) under the configured processed, filtered or unreadable folder — for example +`processed/2026/11/24/report.pdf`. The configured folder names stay the same, and the date +folders are created automatically on both local folders and SFTP servers. + +## Technical notes + +Applies to `pdf_report` sources with `on_consumed: move` on `folder` and `sftp` endpoints, +using the message's `received_at` converted to the host's local calendar date +(`/YYYY/MM/DD`). Delimited file sources are unchanged. diff --git a/console/help/pdf-reports.json b/console/help/pdf-reports.json index 92f5dd4..df4eb9e 100644 --- a/console/help/pdf-reports.json +++ b/console/help/pdf-reports.json @@ -16,7 +16,7 @@ { "title": "Folders and embedding", "paragraphs": [ - "On the folder or SFTP endpoint, under After a file is read, a filtered and an unreadable reports folder keep left-out and unreadable reports apart. A mapping embeds the report with report.file_base64; an HL7 v2 files destination writes each message as a file for the receiver to collect." + "On the folder or SFTP endpoint, under After a file is read, a filtered and an unreadable reports folder keep left-out and unreadable reports apart; moved PDF reports are filed under YYYY/MM/DD date folders inside them. A mapping embeds the report with report.file_base64; an HL7 v2 files destination writes each message as a file for the receiver to collect." ] } ] diff --git a/console/src/features/config/EndpointFields.tsx b/console/src/features/config/EndpointFields.tsx index 6c58aac..172fe79 100644 --- a/console/src/features/config/EndpointFields.tsx +++ b/console/src/features/config/EndpointFields.tsx @@ -213,19 +213,19 @@ function AfterReading() { label="Processed folder" isRequired validate={subfolder} - description="Inside the endpoint's folder; created when needed." + description="Inside the endpoint's folder; created when needed (PDF reports use YYYY/MM/DD date folders inside it)." /> )} diff --git a/crates/packie-routing/Cargo.toml b/crates/packie-routing/Cargo.toml index 7a3e90e..4295b75 100644 --- a/crates/packie-routing/Cargo.toml +++ b/crates/packie-routing/Cargo.toml @@ -8,6 +8,7 @@ license.workspace = true publish.workspace = true [dependencies] +jiff = { workspace = true } rust_decimal = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/packie-routing/src/message/pdf.rs b/crates/packie-routing/src/message/pdf.rs index 4a48a7f..e5a601c 100644 --- a/crates/packie-routing/src/message/pdf.rs +++ b/crates/packie-routing/src/message/pdf.rs @@ -2,10 +2,11 @@ //! each complete file is one message, committed whole with the identifiers its template //! reads; the pipeline parses it on a blocking thread. The file is consumed right after the //! commit, or, with a filtered or invalid directory, once the pipeline has decided the -//! message, into the directory of its outcome. +//! message, into `YYYY/MM/DD` (local date of receipt) under the directory of its outcome. use std::sync::Arc; +use jiff::tz::TimeZone; use packie_config::{Consumption, EndpointConfig, PdfReportSettings}; use packie_core::{MessageId, MessageState, ProtocolKind, Timestamp}; use packie_engine::pdf::PdfReader; @@ -112,6 +113,27 @@ enum Outcome { Invalid, } +impl Outcome { + fn directory<'a>(self, consumption: &Consumption<'a>) -> &'a str { + match self { + Self::Processed => consumption.processed, + Self::Filtered => consumption.filtered.unwrap_or(consumption.processed), + Self::Invalid => consumption.invalid.unwrap_or(consumption.processed), + } + } +} + +/// `/YYYY/MM/DD` for `at` in the computer's time zone. +fn dated_directory(base: &str, at: Timestamp) -> String { + dated_directory_in(base, at, &TimeZone::system()) +} + +fn dated_directory_in(base: &str, at: Timestamp, zone: &TimeZone) -> String { + let base = base.trim().trim_end_matches(['/', '\\']); + let date = at.as_jiff().to_zoned(zone.clone()).strftime("%Y/%m/%d"); + format!("{base}/{date}") +} + /// Commits the report, runs its pipeline and consumes the file. async fn take_report( cx: &MessageContext, @@ -123,12 +145,16 @@ async fn take_report( let Some(consumption) = endpoint.consumption() else { return Ok(()); }; + let received_at = Timestamp::now(); let committed = if unit.too_large.is_some() { - commit_too_large(cx, unit).await + commit_too_large(cx, unit, received_at).await } else { let identifiers = read_identifiers(reader, unit).await; cx.store - .commit_received(receipt(cx, unit, identifiers), unit.bytes.clone()) + .commit_received( + receipt(cx, unit, identifiers, received_at), + unit.bytes.clone(), + ) .await .map(Some) }; @@ -142,14 +168,16 @@ async fn take_report( let committed = committed?; cx.shared.session_stable(); if !consumption.by_outcome() { - consume(cx, source, unit, &consumption, Outcome::Processed).await; + let target = dated_directory(Outcome::Processed.directory(&consumption), received_at); + consume(cx, source, unit, &target).await; } let outcome = match committed { None => Outcome::Invalid, Some(receipt) => after_commit(cx, &receipt, &unit.bytes).await, }; if consumption.by_outcome() { - consume(cx, source, unit, &consumption, outcome).await; + let target = dated_directory(outcome.directory(&consumption), received_at); + consume(cx, source, unit, &target).await; } Ok(()) } @@ -158,10 +186,11 @@ async fn take_report( async fn commit_too_large( cx: &MessageContext, unit: &FileUnit, + received_at: Timestamp, ) -> Result, StoreError> { let message = cx .store - .begin_transfer(receipt(cx, unit, identifiers(&[])), Vec::new()) + .begin_transfer(receipt(cx, unit, identifiers(&[]), received_at), Vec::new()) .await?; cx.store.abort_transfer(message, "file_too_large").await?; Ok(None) @@ -211,25 +240,16 @@ async fn outcome_of(cx: &MessageContext, original: MessageId) -> Outcome { } } -/// Moves (or deletes, or leaves) the file per `on_consumed`; a move goes to the outcome's -/// directory. A file that cannot be consumed is logged; reading it again records a duplicate. +/// Moves (or deletes, or leaves) the file per `on_consumed`; a move goes to `directory` +/// (`/YYYY/MM/DD`). A file that cannot be consumed is logged; reading it again +/// records a duplicate. async fn consume( cx: &MessageContext, source: &mut dyn FileSource, unit: &FileUnit, - consumption: &Consumption<'_>, - outcome: Outcome, + directory: &str, ) { - let directory = match outcome { - Outcome::Processed => None, - Outcome::Filtered => consumption.filtered, - Outcome::Invalid => consumption.invalid, - }; - let result = match directory { - Some(directory) => source.consumed_into(unit, directory).await, - None => source.consumed(unit).await, - }; - if let Err(error) = result { + if let Err(error) = source.consumed_into(unit, directory).await { tracing::warn!( event = "file.consume_failed", operation = %error.operation, @@ -241,7 +261,12 @@ async fn consume( } } -fn receipt(cx: &MessageContext, unit: &FileUnit, mut identifiers: Identifiers) -> Receipt { +fn receipt( + cx: &MessageContext, + unit: &FileUnit, + mut identifiers: Identifiers, + received_at: Timestamp, +) -> Receipt { identifiers.source_identity = Some(unit.name.clone()); Receipt { channel_id: cx.shared.id, @@ -251,7 +276,7 @@ fn receipt(cx: &MessageContext, unit: &FileUnit, mut identifiers: Identifiers) - protocol: ProtocolKind::PdfReport, // When the engine takes the file, not the file's modified time: an old file dropped // today is received today (and retention counts from today). - received_at: Timestamp::now(), + received_at, config_version: cx.shared.config_version(), duplicate_detection: cx.channel.source.duplicate_detection, identifiers, @@ -268,3 +293,42 @@ fn receipt(cx: &MessageContext, unit: &FileUnit, mut identifiers: Identifiers) - }), } } + +#[cfg(test)] +mod tests { + use super::*; + use packie_config::OnConsumed; + + #[test] + fn dated_directories_use_the_local_calendar_date_with_zero_padded_parts() { + let chicago = TimeZone::get("America/Chicago").unwrap(); + let bucharest = TimeZone::get("Europe/Bucharest").unwrap(); + // 2026-03-05 23:30 UTC: still March 5 in Chicago (-06:00), already March 6 in Bucharest (+02:00). + let at = Timestamp::parse("2026-03-05T23:30:00Z").unwrap(); + assert_eq!( + dated_directory_in("processed", at, &chicago), + "processed/2026/03/05" + ); + assert_eq!( + dated_directory_in("processed/", at, &bucharest), + "processed/2026/03/06" + ); + assert_eq!( + dated_directory_in("errors/pdf\\", at, &bucharest), + "errors/pdf/2026/03/06" + ); + } + + #[test] + fn unset_outcome_directories_fall_back_to_processed() { + let consumption = Consumption { + on_consumed: OnConsumed::Move, + processed: "processed", + filtered: Some("filtered"), + invalid: None, + }; + assert_eq!(Outcome::Processed.directory(&consumption), "processed"); + assert_eq!(Outcome::Filtered.directory(&consumption), "filtered"); + assert_eq!(Outcome::Invalid.directory(&consumption), "processed"); + } +} diff --git a/crates/packie-routing/tests/message_pdf.rs b/crates/packie-routing/tests/message_pdf.rs index 7e90121..383fea8 100644 --- a/crates/packie-routing/tests/message_pdf.rs +++ b/crates/packie-routing/tests/message_pdf.rs @@ -93,6 +93,20 @@ fn state_of(store: &Store, sample: &str) -> Option { .map(|r| r.summary.state) } +fn local_date_path(at: Timestamp) -> String { + at.as_jiff() + .to_zoned(jiff::tz::TimeZone::system()) + .strftime("%Y/%m/%d") + .to_string() +} + +fn date_for(store: &Store, file_name: &str) -> Option { + records(store) + .into_iter() + .find(|r| r.source_file.as_ref().is_some_and(|f| f.name == file_name)) + .map(|r| local_date_path(r.summary.received_at)) +} + #[tokio::test] async fn reports_move_into_the_directory_of_their_outcome() { let rig = rig().await; @@ -120,12 +134,14 @@ async fn reports_move_into_the_directory_of_their_outcome() { ("other.pdf", "skipped"), ("broken.pdf", "errors"), ] { - let moved = rig.inbox.join(directory).join(name); - until(&format!("{name} in {directory}"), || { + let day = until(&format!("{name} is stored"), || date_for(&rig.store, name)).await; + let moved = rig.inbox.join(directory).join(&day).join(name); + until(&format!("{name} in {directory}/{day}"), || { moved.exists().then_some(()) }) .await; assert!(!rig.inbox.join(name).exists()); + assert!(!rig.inbox.join(directory).join(name).exists()); } assert!(!rig.outbox.join("ORU_SYN-0002.hl7").exists()); assert_eq!(state_of(&rig.store, "SYN-0001"), Some(MessageState::Routed)); @@ -134,8 +150,8 @@ async fn reports_move_into_the_directory_of_their_outcome() { Some(MessageState::Filtered) ); - let records = records(&rig.store); - let broken = records + let records_now = records(&rig.store); + let broken = records_now .iter() .find(|r| r.summary.state == MessageState::Invalid) .expect("the unreadable file is a message"); @@ -144,20 +160,31 @@ async fn reports_move_into_the_directory_of_their_outcome() { broken.reason_detail.as_deref(), Some("the file is not a readable PDF") ); - for record in &records { + for record in &records_now { assert_eq!(record.summary.protocol, ProtocolKind::PdfReport); assert_eq!(record.summary.message_type.as_deref(), Some("pdf_report")); } - // The same filtered report again: a duplicate, moved where its original went. + // The same filtered report again: a duplicate, moved where its original went under today's date. std::fs::write(rig.inbox.join("other.pdf"), report("SYN-0002", "F9999")).unwrap(); - let again = rig.inbox.join("skipped").join("other-1.pdf"); + until("the duplicate is stored", || { + (records_in(&rig.store, MessageState::Duplicate) == 1).then_some(()) + }) + .await; + let duplicate_day = records(&rig.store) + .into_iter() + .find(|r| r.summary.state == MessageState::Duplicate) + .map(|r| local_date_path(r.summary.received_at)) + .unwrap(); + let again = rig + .inbox + .join("skipped") + .join(&duplicate_day) + .join("other-1.pdf"); until("the repeated report is skipped too", || { again.exists().then_some(()) }) .await; - let duplicates = records_in(&rig.store, MessageState::Duplicate); - assert_eq!(duplicates, 1); } #[tokio::test] @@ -167,7 +194,11 @@ async fn a_report_without_its_required_label_is_invalid_with_a_detail() { let at = bytes.windows(11).position(|w| w == b"Lab Number:").unwrap(); bytes[at..at + 11].copy_from_slice(b"Lab Numbr: "); std::fs::write(rig.inbox.join("mismatch.pdf"), bytes).unwrap(); - let moved = rig.inbox.join("errors").join("mismatch.pdf"); + let day = until("mismatch.pdf is stored", || { + date_for(&rig.store, "mismatch.pdf") + }) + .await; + let moved = rig.inbox.join("errors").join(&day).join("mismatch.pdf"); until("the report is in errors", || moved.exists().then_some(())).await; let record = records(&rig.store).pop().unwrap(); assert_eq!(record.summary.state, MessageState::Invalid); @@ -210,4 +241,52 @@ async fn an_old_report_dropped_now_is_received_now() { received >= before, "received {received}, dropped after {before}" ); + let moved = rig + .inbox + .join("processed") + .join(local_date_path(received)) + .join("old.pdf"); + until("the old report is moved under today's date", || { + moved.exists().then_some(()) + }) + .await; +} + +#[tokio::test] +async fn reports_without_outcome_directories_also_move_into_dated_processed_folders() { + let dir = tempfile::tempdir().unwrap(); + let inbox = dir.path().join("in"); + let outbox = dir.path().join("out"); + std::fs::create_dir_all(&inbox).unwrap(); + std::fs::create_dir_all(&outbox).unwrap(); + let store = open_store(dir.path(), None); + let mut h = Harness::with_options(options_with_store(system_transports(), &store)); + let channel = json!({ + "kind": "message", "channel_id": "reports", "label": "Reports", + "source": {"endpoint": "in-dir", "protocol": "pdf_report", "settings": { + "fields": [{"name": "sample_id", "label": "Lab Number:", "required": true}], + }}, + "destinations": [{ + "destination_id": "out", "label": "Out", "endpoint": "out-dir", + "protocol": "hl7_file", + "settings": {"file_name": "ORU_{sample_id}.hl7"}, + "mapping": {"rules": [ + {"op": "constant", "value": "ORU^R01^ORU_R01", "to": "MSH.9"}, + {"op": "copy", "from": "field.sample_id", "to": "PID.3.1"}, + ]}, + }], + }); + h.apply(document( + vec![folder("in-dir", &inbox), folder("out-dir", &outbox)], + vec![channel], + )) + .await; + + std::fs::write(inbox.join("single.pdf"), report("SYN-0005", "F0001")).unwrap(); + let day = until("single.pdf is stored", || date_for(&store, "single.pdf")).await; + let moved = inbox.join("processed").join(&day).join("single.pdf"); + until("single.pdf in processed/YYYY/MM/DD", || { + moved.exists().then_some(()) + }) + .await; } diff --git a/crates/packie-transport/tests/folder.rs b/crates/packie-transport/tests/folder.rs index 859f344..b9b044d 100644 --- a/crates/packie-transport/tests/folder.rs +++ b/crates/packie-transport/tests/folder.rs @@ -387,16 +387,26 @@ async fn files_move_into_outcome_directories_that_recursive_listing_skips() { .unwrap() .unwrap(); assert_eq!(unit.name, "in/report.pdf"); - source.consumed_into(&unit, "skipped").await.unwrap(); - assert!(dir.path().join("skipped/in/report.pdf").exists()); + source + .consumed_into(&unit, "skipped/2026/11/24") + .await + .unwrap(); + assert!(dir.path().join("skipped/2026/11/24/in/report.pdf").exists()); std::fs::write(dir.path().join("in/other.pdf"), "y").unwrap(); let unit = tokio::time::timeout(Duration::from_secs(10), source.next()) .await .unwrap() .unwrap(); - source.consumed_into(&unit, "errors/pdf").await.unwrap(); - assert!(dir.path().join("errors/pdf/in/other.pdf").exists()); + source + .consumed_into(&unit, "errors/pdf/2026/11/24") + .await + .unwrap(); + assert!( + dir.path() + .join("errors/pdf/2026/11/24/in/other.pdf") + .exists() + ); // Moved files are never listed again, though the source descends into sub-directories. let again = tokio::time::timeout(Duration::from_millis(2500), source.next()).await; assert!(again.is_err(), "a moved file came back"); diff --git a/docs/operations/configuration-reference.md b/docs/operations/configuration-reference.md index 9a24264..663a4e3 100644 --- a/docs/operations/configuration-reference.md +++ b/docs/operations/configuration-reference.md @@ -177,8 +177,8 @@ OS timing and log a warning; see the [TCP settings specification](../spec/config | `stable_seconds` | Both | `2` | Integer, 0–3600; unchanged size and modification time before reading. | | `exclusive_open_check` | `folder` | `true` | Boolean; also require exclusive read access before reading. | | `on_consumed` | Both | `move` | `move`, `delete`, `leave`; after durable receipt. | -| `processed_directory` | Both | `processed` | Relative to source directory; created when needed. | -| `filtered_directory` | Both | `null` | `pdf_report` sources with `on_consumed=move`: where a filtered report goes; `null` uses `processed_directory`. Relative, created when needed, different from the other two. | +| `processed_directory` | Both | `processed` | Relative to source directory; created when needed (`pdf_report` sources add `YYYY/MM/DD` by local receipt date). | +| `filtered_directory` | Both | `null` | `pdf_report` sources with `on_consumed=move`: where a filtered report goes (under `YYYY/MM/DD`); `null` uses `processed_directory`. Relative, created when needed, different from the other two. | | `invalid_directory` | Both | `null` | As `filtered_directory`, for a report that does not parse or is too large. With either set, a report is moved once it is filtered, invalid or routed. | | `write_mode` | Both | `atomic_rename` | `atomic_rename` or `direct`. | diff --git a/docs/spec/acceptance.md b/docs/spec/acceptance.md index 6552e5c..8882119 100644 --- a/docs/spec/acceptance.md +++ b/docs/spec/acceptance.md @@ -124,7 +124,7 @@ The release sentence of requirements.md, clause by clause. | E-11 | A scanned report, an encrypted file, a truncated file, random bytes, an oversized or over-long file, glyphs without a character mapping | `pdf_no_text`, `pdf_unreadable`, `pdf_limits` or `aborted` (`file_too_large`); never a panic, never a shorter report | PRO-06, PRO-07 | `crate: packie-pdf`, fuzzing | | E-12 | Correct the template of an `invalid` report, then resend it with `new_message` | The stored original parses with the new template and is delivered | PRO-07, MSG-04 | `msg-pdf-report-invalid` | | E-13 | **Test with a PDF…** and `packie pdf test` with a template, a file and a destination | Extracted lines, model or reason, and the mapped message with the embedded file shortened; nothing stored or sent; audited once as `pdf_report_test` | PRO-07, P2 | `crate: packie-engine`, `cli`, console `pdfReportTest` | -| E-14 | A source filter on the birth hospital's facility code with `filtered_directory` and `invalid_directory`: a report of a listed client, one of another client, an unreadable file, the listed report again, and an engine crash between a commit and its pipeline decision | Listed: `routed`, one HL7 file, PDF in `processed_directory`; other client: `filtered`, no HL7 file, PDF in `filtered_directory`; unreadable: `invalid`, PDF in `invalid_directory`; repeated: `duplicate`, no second HL7 file, PDF where the original went; after the crash the file ends in the right directory with one HL7 file | PRO-07, MSG-02, EPT-03 | `msg-pdf-report-folders` | +| E-14 | A source filter on the birth hospital's facility code with `filtered_directory` and `invalid_directory`: a report of a listed client, one of another client, an unreadable file, the listed report again, and an engine crash between a commit and its pipeline decision | Listed: `routed`, one HL7 file, PDF in `processed_directory/YYYY/MM/DD`; other client: `filtered`, no HL7 file, PDF in `filtered_directory/YYYY/MM/DD`; unreadable: `invalid`, PDF in `invalid_directory/YYYY/MM/DD`; repeated: `duplicate`, no second HL7 file, PDF under the same outcome directory; after the crash the file ends in the right directory with one HL7 file | PRO-07, MSG-02, EPT-03 | `msg-pdf-report-folders` | ## 7. Configuration diff --git a/docs/spec/configuration.md b/docs/spec/configuration.md index 10d7a3d..9ad481f 100644 --- a/docs/spec/configuration.md +++ b/docs/spec/configuration.md @@ -217,8 +217,8 @@ one directory; use two endpoints for separate in and out directories. | `stable_seconds` | both | integer | `2` | 0–3600. A file is complete when its size and modified time have not changed for this long (sftp: across two polls at least this far apart). | | `exclusive_open_check` | folder | boolean | `true` | Also require that the file can be opened for exclusive read, which detects a writer holding it. | | `on_consumed` | both | string | `move` | What happens to a source file after its content is committed: `move` (to `processed_directory`), `delete`, `leave`. With `leave`, duplicate detection prevents reprocessing. | -| `processed_directory` | both | string | `processed` | Non-empty after trimming. Relative path inside the source directory, with `/` or `\` separators; an absolute path or a `..` part is rejected. Created when needed. A moved file keeps its relative path below it; a name that already exists there gets a `-1`, `-2`… suffix. | -| `filtered_directory`, `invalid_directory` | both | string or null | `null` | `pdf_report` sources only, with `on_consumed: move`; as `processed_directory`, and different from it and from each other. A report the source filters exclude (`filtered`) is moved to `filtered_directory`, one that does not parse or is too large (`invalid`, `aborted`) to `invalid_directory`, the others to `processed_directory`. `null` uses `processed_directory`. | +| `processed_directory` | both | string | `processed` | Non-empty after trimming. Relative path inside the source directory, with `/` or `\` separators; an absolute path or a `..` part is rejected. Created when needed. `pdf_report` sources place moved files inside a `YYYY/MM/DD` subdirectory (local date of receipt) below the target directory. A moved file keeps its relative path below that; a name that already exists there gets a `-1`, `-2`… suffix. | +| `filtered_directory`, `invalid_directory` | both | string or null | `null` | `pdf_report` sources only, with `on_consumed: move`; as `processed_directory` (including the `YYYY/MM/DD` date subdirectory), and different from it and from each other. A report the source filters exclude (`filtered`) is moved to `filtered_directory`, one that does not parse or is too large (`invalid`, `aborted`) to `invalid_directory`, the others to `processed_directory`. `null` uses `processed_directory`. | | `write_mode` | both | string | `atomic_rename` | Destination writes: `atomic_rename` (write a uniquely named hidden `..part` file created exclusively in the same directory, then move it into place; on Windows a replacing move refused because another program briefly holds the name (another writer replacing it, a virus scanner) is retried for up to about 1.4 s; `on_exists` `fail`/`suffix` never replace a file) or `direct` (write the final name; links are never written through). `on_exists` `append` always appends to the existing file in place, in either mode. | ## 6. Channels diff --git a/docs/spec/message-channels.md b/docs/spec/message-channels.md index f38dabc..2643c8c 100644 --- a/docs/spec/message-channels.md +++ b/docs/spec/message-channels.md @@ -53,7 +53,7 @@ stores later. | `au` | Each accepted frame's exact wire bytes are committed; the sample message completes after its final block. Class A (no ACK/NAK on receive) commits frames without any response. Instrument queries and session messages are stored and closed `filtered` (`control_message`); well-framed text that does not parse is stored `invalid` (`unparseable`); neither is routed. Host-direction frames are rejected without being stored. | Class B: each block ACK waits for its frame commit and the 500 ms turnaround. The final ACK precedes the transaction that finalizes the sample and checks duplicates; all of its wire frames are already durable. | An incomplete sample: `aborted`. | | `hl7_mllp` | One MLLP frame (the whole message). Bytes between the start and end block characters are the original bytes. | Per `ack_mode` (below). | A started frame that receives no further bytes for `frame_timeout_ms` (counted while the engine waits for them, not while it commits the frames before it) is discarded and the connection closed. A connection the peer closes or resets ends at once, inside a frame too. An operating system can ignore a reset that arrives right behind bytes it has not yet acknowledged (macOS does on a busy connection), leaving the connection open with nothing to read; so while a TCP source waits for the rest of a message (an HL7 frame, an ASTM or AU transfer with its timer running) it probes the peer with a TCP keep-alive after 1 s of silence, whatever the endpoint's `keep_alive` settings, which apply again once the message is complete. The peer's system answers the probe with a reset that is taken, so a dead sender does not hold the source's single session. A frame left open by either is discarded (`source.frame_abandoned`); it was never acknowledged, so the sender sends it again. | | `delimited_file` | Each record or group of a complete file is one message; all of a file's messages are committed in one transaction. A message's original bytes are its rows rewritten with the source columns, including a header when `header_row` is true, without skipped lines or a BOM. The stored form uses the codec's 1 GiB limit because quoting and line endings can make it larger than the input. Its `source_file` holds the file name, the SHA-256 of the whole file and its row range (data rows counted from 1). | The source file is moved, deleted or left per `on_consumed`, only after the commit. A file that cannot be moved or deleted is logged (`file.consume_failed`); reading it again records duplicates when duplicate detection is enabled. | A file over `max_file_bytes` is not read into memory (the transport stops at the limit); one `aborted` message (`file_too_large`, no bytes, `source_file` with its name and an empty hash) records it. A file that does not parse as configured is committed whole as one `invalid` message (`malformed_file`, `encoding`). Both are then consumed like any other file. A commit failure leaves the file where it is; the source reopens the endpoint after the retry delay and reads it again. | -| `pdf_report` | A complete file is one message; its original bytes are the file's bytes. `source_file` holds the file name and the SHA-256 of the file. Parsing follows the commit, in the pipeline ([pdf-reports.md](pdf-reports.md#2-receipt)). | The source file is moved, deleted or left per `on_consumed`, only after the commit. Without `filtered_directory` and `invalid_directory` that is right after the commit, whether or not the report parses later. With either set, the move waits until parsing and the source filters have decided the message, and its outcome picks the directory: `routed` to `processed_directory`, `filtered` to `filtered_directory`, `invalid` or `aborted` to `invalid_directory`; a `duplicate` goes where the message it repeats went, once that is decided (so a file read again after a restart before the decision is not misplaced). | A file over `max_file_bytes` is recorded `aborted` (`file_too_large`) as for delimited files. A report that does not parse becomes `invalid` in the pipeline with a reason code and `reason_detail`; the original stays. | +| `pdf_report` | A complete file is one message; its original bytes are the file's bytes. `source_file` holds the file name and the SHA-256 of the file. Parsing follows the commit, in the pipeline ([pdf-reports.md](pdf-reports.md#2-receipt)). | The source file is moved, deleted or left per `on_consumed`, only after the commit. A moved report goes into `/YYYY/MM/DD`, where `YYYY/MM/DD` is the engine host's local date at `received_at`. Without `filtered_directory` and `invalid_directory` that is right after the commit into `processed_directory/YYYY/MM/DD`, whether or not the report parses later. With either set, the move waits until parsing and the source filters have decided the message, and its outcome picks ``: `routed` to `processed_directory`, `filtered` to `filtered_directory`, `invalid` or `aborted` to `invalid_directory` (`null` uses `processed_directory`); a `duplicate` goes to the outcome directory of the message it repeats, under its own receipt date, once that message is decided (so a file read again after a restart before the decision is not misplaced). | A file over `max_file_bytes` is recorded `aborted` (`file_too_large`) as for delimited files. A report that does not parse becomes `invalid` in the pipeline with a reason code and `reason_detail`; the original stays. | HL7 acknowledgement content (source side): diff --git a/docs/spec/pdf-reports.md b/docs/spec/pdf-reports.md index 925a8ce..ecbd97f 100644 --- a/docs/spec/pdf-reports.md +++ b/docs/spec/pdf-reports.md @@ -25,7 +25,7 @@ limits and the test tool. Connector settings sit in | Read | The endpoint finds a complete file (configuration §5.4: pattern, stable size, ignored suffixes). A file over `max_file_bytes` is not read; one `aborted` message (`file_too_large`) records it, as for delimited files. | | Commit | The whole file is committed as one `received` message: original bytes, `source_file` (relative path, SHA-256 of the file, no row range), duplicate check, and the identifiers of section 2's table, read from the report just before (a report that does not parse is committed without them). | | Parse | The pipeline's parse stage ([message-channels.md §6](message-channels.md#6-pipeline)) extracts the text (section 3) and applies the template in force (section 4). Failure: the message becomes `invalid` with a reason code and `reason_detail` (section 7); no delivery is created. | -| Consume | The source file is moved, deleted or left per the endpoint's `on_consumed`. With `filtered_directory` or `invalid_directory` set, it is moved once parsing and the source filters have decided the message: `routed` to `processed_directory`, `filtered` to `filtered_directory`, `invalid` or `aborted` to `invalid_directory` ([message-channels.md §2.2](message-channels.md#22-per-protocol)). | +| Consume | The source file is moved, deleted or left per the endpoint's `on_consumed`. A moved file goes into `/YYYY/MM/DD` (the engine host's local calendar date at `received_at`, zero-padded, created when needed). Without `filtered_directory` and `invalid_directory`, `` is `processed_directory` right after the commit. With either set, the move waits until parsing and the source filters have decided the message: `routed` to `processed_directory`, `filtered` to `filtered_directory`, `invalid` or `aborted` to `invalid_directory` (`null` uses `processed_directory`; [message-channels.md §2.2](message-channels.md#22-per-protocol)). | | Isolation | Extraction runs off the channel's I/O tasks within the limits of section 8, so a slow or hostile file never stalls receipt on this or another channel. | Because the original is stored before parsing, a report that failed because the template was