Skip to main content

isis_report_lib/
api.rs

1//! Public API (sync + async aliases).
2//!
3//! The canonical names are idiomatic Rust (`generate_pdf`,
4//! `generate_pdf_async`, `render_html`, ...). Python-compatible aliases
5//! (`agenerate_pdf`, `arender_html`, ...) are provided for migration.
6
7use std::path::Path;
8
9use crate::error::{Error, Result};
10use crate::export::{build_workbook, collect_tables, render_csv};
11use crate::service::prepare_report;
12use crate::text::{sanitize_text, wrap_report_text};
13use crate::toon::parse_toon;
14use crate::value::Value;
15use crate::Limits;
16use crate::ReportService;
17
18/// Render only the intermediate HTML (sync, no browser).
19pub fn render_html(
20    payload: &Value,
21    template_dir: Option<&Path>,
22    template_name: &str,
23    inline_css: bool,
24    limits: Option<Limits>,
25) -> Result<String> {
26    let template_dir = template_dir.map(Path::to_path_buf);
27    let template_name = template_name.to_string();
28    #[cfg(feature = "pdf")]
29    let service = ReportService {
30        template_dir,
31        template_name,
32        inline_css,
33        limits,
34        ..ReportService::default()
35    };
36    #[cfg(not(feature = "pdf"))]
37    let service = ReportService {
38        template_dir,
39        template_name,
40        inline_css,
41        limits,
42    };
43    service.render_html(payload)
44}
45
46/// Render HTML from `.toon` text.
47pub fn render_html_from_toon(
48    text: &str,
49    template_dir: Option<&Path>,
50    template_name: &str,
51    inline_css: bool,
52    limits: Option<Limits>,
53) -> Result<String> {
54    render_html(&parse_toon(text)?, template_dir, template_name, inline_css, limits)
55}
56
57/// Generate CSV text (no browser).
58pub fn generate_csv(payload: &Value, delimiter: char, bom: bool, limits: Option<Limits>) -> Result<String> {
59    let prepared = prepare_report(payload, limits)?;
60    let meta = prepared.meta.to_value();
61    let (tables, summaries) = collect_tables(&prepared.dataset, &prepared.layout, Some(&meta));
62    let text = render_csv(&tables, &summaries, Some(&meta), delimiter)?;
63    Ok(if bom { format!("\u{feff}{text}") } else { text })
64}
65
66/// Generate CSV from `.toon` text.
67pub fn generate_csv_from_toon(text: &str, delimiter: char, bom: bool, limits: Option<Limits>) -> Result<String> {
68    generate_csv(&parse_toon(text)?, delimiter, bom, limits)
69}
70
71/// Render a visible-only, sanitized plain-text export (no browser).
72pub fn render_text(payload: &Value, sanitize: bool, limits: Option<Limits>) -> Result<String> {
73    let text = generate_csv(payload, ',', false, limits)?;
74    let text = if sanitize { sanitize_text(&text) } else { text };
75    Ok(wrap_report_text(&text))
76}
77
78/// Render plain text from `.toon` text.
79pub fn render_text_from_toon(text: &str, sanitize: bool, limits: Option<Limits>) -> Result<String> {
80    render_text(&parse_toon(text)?, sanitize, limits)
81}
82
83/// Generate an `.xlsx` workbook (sync, no browser).
84pub fn generate_xlsx(payload: &Value, limits: Option<Limits>) -> Result<Vec<u8>> {
85    let prepared = prepare_report(payload, limits)?;
86    let meta = prepared.meta.to_value();
87    let (tables, summaries) = collect_tables(&prepared.dataset, &prepared.layout, Some(&meta));
88    build_workbook(&tables, &summaries, Some(&meta))
89}
90
91/// Generate `.xlsx` from `.toon` text.
92pub fn generate_xlsx_from_toon(text: &str, limits: Option<Limits>) -> Result<Vec<u8>> {
93    generate_xlsx(&parse_toon(text)?, limits)
94}
95
96/// Generate a PDF (sync). Requires the `pdf` feature and Chromium.
97#[cfg(not(feature = "pdf"))]
98pub fn generate_pdf(_payload: &Value, _limits: Option<Limits>) -> Result<Vec<u8>> {
99    Err(Error::FeatureDisabled("PDF generation requires the 'pdf' feature and Chromium"))
100}
101
102/// Generate a PDF (sync). Requires the `pdf` feature and Chromium.
103///
104/// The page format, orientation and margins come from `meta.page`; other
105/// options use their defaults. Use [`generate_pdf_with`] to override them.
106#[cfg(feature = "pdf")]
107pub fn generate_pdf(payload: &Value, limits: Option<Limits>) -> Result<Vec<u8>> {
108    let service = ReportService {
109        limits,
110        ..ReportService::default()
111    };
112    service.generate_pdf(payload)
113}
114
115/// Generate a PDF with explicit options, template directory and template.
116#[cfg(feature = "pdf")]
117pub fn generate_pdf_with(
118    payload: &Value,
119    options: &crate::pdf_backend::PdfOptions,
120    template_dir: Option<&Path>,
121    template_name: &str,
122    limits: Option<Limits>,
123) -> Result<Vec<u8>> {
124    let service = ReportService {
125        template_dir: template_dir.map(Path::to_path_buf),
126        template_name: template_name.to_string(),
127        limits,
128        pdf_options: Some(options.clone()),
129        ..ReportService::default()
130    };
131    service.generate_pdf(payload)
132}
133
134/// Generate a PDF from `.toon` text.
135pub fn generate_pdf_from_toon(text: &str, limits: Option<Limits>) -> Result<Vec<u8>> {
136    generate_pdf(&parse_toon(text)?, limits)
137}
138
139/// Generate a PDF from `.toon` text with explicit options.
140#[cfg(feature = "pdf")]
141pub fn generate_pdf_from_toon_with(
142    text: &str,
143    options: &crate::pdf_backend::PdfOptions,
144    template_dir: Option<&Path>,
145    template_name: &str,
146    limits: Option<Limits>,
147) -> Result<Vec<u8>> {
148    generate_pdf_with(&parse_toon(text)?, options, template_dir, template_name, limits)
149}
150
151#[cfg(feature = "pdf")]
152fn validate_concurrency(max_concurrency: usize) -> Result<()> {
153    if max_concurrency < 1 {
154        return Err(Error::option(format!("max_concurrency must be >= 1, got {max_concurrency}")));
155    }
156    Ok(())
157}
158
159/// Generate several PDFs concurrently (feature `pdf`).
160#[cfg(feature = "pdf")]
161pub async fn generate_many_async(
162    payloads: &[Value],
163    max_concurrency: usize,
164    options: Option<&crate::pdf_backend::PdfOptions>,
165    template_dir: Option<&Path>,
166    template_name: &str,
167    limits: Option<Limits>,
168) -> Result<Vec<Vec<u8>>> {
169    use futures::StreamExt;
170
171    validate_concurrency(max_concurrency)?;
172    let service = ReportService {
173        template_dir: template_dir.map(Path::to_path_buf),
174        template_name: template_name.to_string(),
175        limits,
176        pdf_options: options.cloned(),
177        ..ReportService::default()
178    };
179    let results: Vec<Result<Vec<u8>>> = futures::stream::iter(payloads.iter().cloned().map(|payload| {
180        let service = service.clone();
181        async move { service.generate_pdf_async(&payload).await }
182    }))
183    .buffered(max_concurrency)
184    .collect()
185    .await;
186    results.into_iter().collect()
187}
188
189/// Generate several PDFs concurrently (sync, feature `pdf`).
190#[cfg(feature = "pdf")]
191pub fn generate_many(payloads: &[Value], max_concurrency: usize, limits: Option<Limits>) -> Result<Vec<Vec<u8>>> {
192    validate_concurrency(max_concurrency)?;
193    let payloads = payloads.to_vec();
194    let outcome = std::thread::spawn(move || -> Result<Vec<Vec<u8>>> {
195        let runtime = tokio::runtime::Builder::new_current_thread()
196            .enable_all()
197            .build()
198            .map_err(|error| Error::pdf(format!("Cannot start the PDF runtime: {error}")))?;
199        runtime.block_on(generate_many_async(&payloads, max_concurrency, None, None, "tabular.jinja", limits))
200    })
201    .join()
202    .map_err(|_| Error::pdf("PDF worker thread panicked"))?;
203    outcome
204}
205
206/// Generate several PDFs concurrently (requires the `pdf` feature).
207#[cfg(not(feature = "pdf"))]
208pub fn generate_many(_payloads: &[Value], _max_concurrency: usize, _limits: Option<Limits>) -> Result<Vec<Vec<u8>>> {
209    Err(Error::FeatureDisabled("PDF generation requires the 'pdf' feature and Chromium"))
210}
211
212/// Generate several PDFs concurrently with explicit options.
213#[cfg(feature = "pdf")]
214pub fn generate_many_with(
215    payloads: &[Value],
216    options: &crate::pdf_backend::PdfOptions,
217    max_concurrency: usize,
218    template_dir: Option<&Path>,
219    template_name: &str,
220    limits: Option<Limits>,
221) -> Result<Vec<Vec<u8>>> {
222    validate_concurrency(max_concurrency)?;
223    let payloads = payloads.to_vec();
224    let options = options.clone();
225    let template_dir = template_dir.map(Path::to_path_buf);
226    let template_name = template_name.to_string();
227    std::thread::spawn(move || -> Result<Vec<Vec<u8>>> {
228        let runtime = tokio::runtime::Builder::new_current_thread()
229            .enable_all()
230            .build()
231            .map_err(|error| Error::pdf(format!("Cannot start the PDF runtime: {error}")))?;
232        runtime.block_on(generate_many_async(
233            &payloads,
234            max_concurrency,
235            Some(&options),
236            template_dir.as_deref(),
237            &template_name,
238            limits,
239        ))
240    })
241    .join()
242    .map_err(|_| Error::pdf("PDF worker thread panicked"))?
243}
244
245/// Async HTML render (parity alias).
246pub async fn render_html_async(
247    payload: &Value,
248    template_dir: Option<&Path>,
249    template_name: &str,
250    inline_css: bool,
251    limits: Option<Limits>,
252) -> Result<String> {
253    render_html(payload, template_dir, template_name, inline_css, limits)
254}
255
256/// Async CSV export (parity alias).
257pub async fn generate_csv_async(payload: &Value, delimiter: char, bom: bool, limits: Option<Limits>) -> Result<String> {
258    generate_csv(payload, delimiter, bom, limits)
259}
260
261/// Async text export (parity alias).
262pub async fn render_text_async(payload: &Value, sanitize: bool, limits: Option<Limits>) -> Result<String> {
263    render_text(payload, sanitize, limits)
264}
265
266/// Async XLSX export (parity alias).
267pub async fn generate_xlsx_async(payload: &Value, limits: Option<Limits>) -> Result<Vec<u8>> {
268    generate_xlsx(payload, limits)
269}
270
271/// Async PDF export (parity alias).
272#[cfg(not(feature = "pdf"))]
273pub async fn generate_pdf_async(payload: &Value, limits: Option<Limits>) -> Result<Vec<u8>> {
274    generate_pdf(payload, limits)
275}
276
277/// Async PDF export (parity alias).
278#[cfg(feature = "pdf")]
279pub async fn generate_pdf_async(payload: &Value, limits: Option<Limits>) -> Result<Vec<u8>> {
280    let service = ReportService {
281        limits,
282        ..ReportService::default()
283    };
284    service.generate_pdf_async(payload).await
285}
286
287/// Async PDF export with explicit options and template selection.
288#[cfg(feature = "pdf")]
289pub async fn generate_pdf_with_async(
290    payload: &Value,
291    options: &crate::pdf_backend::PdfOptions,
292    template_dir: Option<&Path>,
293    template_name: &str,
294    limits: Option<Limits>,
295) -> Result<Vec<u8>> {
296    let service = ReportService {
297        template_dir: template_dir.map(Path::to_path_buf),
298        template_name: template_name.to_string(),
299        limits,
300        pdf_options: Some(options.clone()),
301        ..ReportService::default()
302    };
303    service.generate_pdf_async(payload).await
304}
305
306/// Python-compatible alias.
307pub fn agenerate_pdf(payload: &Value, limits: Option<Limits>) -> Result<Vec<u8>> {
308    generate_pdf(payload, limits)
309}
310
311/// Python-compatible alias.
312pub fn agenerate_csv(payload: &Value, delimiter: char, bom: bool, limits: Option<Limits>) -> Result<String> {
313    generate_csv(payload, delimiter, bom, limits)
314}
315
316/// Python-compatible alias.
317pub fn agenerate_xlsx(payload: &Value, limits: Option<Limits>) -> Result<Vec<u8>> {
318    generate_xlsx(payload, limits)
319}
320
321/// Python-compatible alias.
322pub fn arender_html(
323    payload: &Value,
324    template_dir: Option<&Path>,
325    template_name: &str,
326    inline_css: bool,
327    limits: Option<Limits>,
328) -> Result<String> {
329    render_html(payload, template_dir, template_name, inline_css, limits)
330}
331
332/// Python-compatible alias.
333pub fn arender_text(payload: &Value, sanitize: bool, limits: Option<Limits>) -> Result<String> {
334    render_text(payload, sanitize, limits)
335}
336
337/// Python-compatible alias.
338pub async fn agenerate_pdf_from_toon(text: &str, limits: Option<Limits>) -> Result<Vec<u8>> {
339    generate_pdf_async(&parse_toon(text)?, limits).await
340}
341
342/// Python-compatible alias.
343pub async fn agenerate_csv_from_toon(text: &str, delimiter: char, bom: bool, limits: Option<Limits>) -> Result<String> {
344    generate_csv_from_toon(text, delimiter, bom, limits)
345}
346
347/// Python-compatible alias.
348pub async fn agenerate_xlsx_from_toon(text: &str, limits: Option<Limits>) -> Result<Vec<u8>> {
349    generate_xlsx_from_toon(text, limits)
350}
351
352/// Python-compatible alias.
353pub async fn arender_html_from_toon(
354    text: &str,
355    template_dir: Option<&Path>,
356    template_name: &str,
357    inline_css: bool,
358    limits: Option<Limits>,
359) -> Result<String> {
360    render_html_from_toon(text, template_dir, template_name, inline_css, limits)
361}
362
363/// Python-compatible alias.
364pub async fn arender_text_from_toon(text: &str, sanitize: bool, limits: Option<Limits>) -> Result<String> {
365    render_text_from_toon(text, sanitize, limits)
366}
367
368/// Python-compatible alias; runs the batch on the async PDF pipeline.
369#[cfg(feature = "pdf")]
370pub async fn agenerate_many(payloads: &[Value], max_concurrency: usize, limits: Option<Limits>) -> Result<Vec<Vec<u8>>> {
371    generate_many_async(payloads, max_concurrency, None, None, "tabular.jinja", limits).await
372}
373
374/// Python-compatible alias (requires the `pdf` feature).
375#[cfg(not(feature = "pdf"))]
376pub async fn agenerate_many(_payloads: &[Value], _max_concurrency: usize, _limits: Option<Limits>) -> Result<Vec<Vec<u8>>> {
377    Err(Error::FeatureDisabled("PDF generation requires the 'pdf' feature and Chromium"))
378}