forge
Explore
Log in

Don't you dare go Hollow

A huge workbook is read only as far as it is drawn

Browse files at this commit

cf7b6297301cc2c0a1d10443a547d445de2c96d7Ahmet Kaan GümüşParent: 54615d4
  • perf
    • a huge workbook is read only as far as it is drawn
Show full message
⚡ perf(web): a huge workbook is read only as far as it is drawn

Opening a 300,000-row xlsx read the whole range first and clipped after:
380MB and 732ms, on a runtime thread, per open. An xlsx is now read a cell
at a time and abandoned at the first row past the clip — 59MB and 12ms for
the same file — and the read happens on a blocking thread either way, so a
book nobody can stream is not every other request waiting.

xls, xlsb and ods keep the whole-range read: calamine hands over cells one
at a time for xlsx alone, and those three are bounded by the upload limit
and their own row ceilings.
crates/izlek-web/src/detail.rsmodified+9 -1
@@ -2147,9 +2147,17 @@ pub async fn file_viewer_modal(
2147 // A workbook is the one viewer whose bytes are read here rather than2147 // A workbook is the one viewer whose bytes are read here rather than
2148 // handed to an element; every other kind streams from `/files/{id}` and2148 // handed to an element; every other kind streams from `/files/{id}` and
2149 // never loads the file into the page's own request.2149 // never loads the file into the page's own request.
2150+ // Reading a workbook is the one piece of real CPU a page render does, so
2151+ // it happens off the runtime's own threads: a big book is most of a
2152+ // second, and a second of a worker thread is every other request waiting.
2150 let sheet = if kind == crate::files::ViewerKind::Sheet {2153 let sheet = if kind == crate::files::ViewerKind::Sheet {
2151 match store.attachment_bytes(file_id).await {2154 match store.attachment_bytes(file_id).await {
2152- Ok(Some(bytes)) => crate::sheet::read(bytes, sheet_index),2155+ Ok(Some(bytes)) => {
2156+ tokio::task::spawn_blocking(move || crate::sheet::read(bytes, sheet_index))
2157+ .await
2158+ .ok()
2159+ .flatten()
2160+ }
2153 _ => None,2161 _ => None,
2154 }2162 }
2155 } else {2163 } else {
crates/izlek-web/src/sheet.rsmodified+80 -2
@@ -7,7 +7,7 @@
7 7
8 use std::io::Cursor;8 use std::io::Cursor;
9 9
10-use calamine::{Data, Reader, open_workbook_auto_from_rs};10+use calamine::{Data, Reader, Xlsx, open_workbook_auto_from_rs, open_workbook_from_rs};
11 11
12 /// How much of one sheet is drawn. A workbook is a million rows wide open,12 /// How much of one sheet is drawn. A workbook is a million rows wide open,
13 /// and a table that size is a page that never paints; past this the view says13 /// and a table that size is a page that never paints; past this the view says
@@ -32,6 +32,71 @@ pub(crate) struct Sheet {
32 /// (a hand-edited query string) falls back to the first sheet rather than32 /// (a hand-edited query string) falls back to the first sheet rather than
33 /// failing.33 /// failing.
34 pub(crate) fn read(bytes: Vec<u8>, index: usize) -> Option<Sheet> {34 pub(crate) fn read(bytes: Vec<u8>, index: usize) -> Option<Sheet> {
35+ // xlsx first, because that is the format that holds millions of rows and
36+ // the only one calamine will hand over a cell at a time. Reading the
37+ // whole range of a 300,000-row book costs about 380MB and most of a
38+ // second; stopping at the rows that are drawn costs neither.
39+ read_streamed(&bytes, index).or_else(|| read_whole(bytes, index))
40+}
41+
42+/// The lazy path: an xlsx read cell by cell in stream order, abandoned the
43+/// moment the rows past [`MAX_ROWS`] start. `None` when the bytes are not an
44+/// xlsx at all, which is the caller's cue to try the other formats.
45+fn read_streamed(bytes: &[u8], index: usize) -> Option<Sheet> {
46+ let mut book: Xlsx<Cursor<Vec<u8>>> = open_workbook_from_rs(Cursor::new(bytes.to_vec())).ok()?;
47+ let names = book.sheet_names();
48+ if names.is_empty() {
49+ return None;
50+ }
51+ let index = if index < names.len() { index } else { 0 };
52+ let mut cells = book.worksheet_cells_reader(&names[index]).ok()?;
53+ let bounds = cells.dimensions();
54+ let (first_row, first_column) = bounds.start;
55+ let height = bounds.end.0.saturating_sub(first_row) as usize + 1;
56+ let width = bounds.end.1.saturating_sub(first_column) as usize + 1;
57+ let mut clipped = height > MAX_ROWS || width > MAX_COLS;
58+ let mut rows: Vec<Vec<String>> = Vec::new();
59+ while let Ok(Some(found)) = cells.next_cell() {
60+ let (row, column) = found.get_position();
61+ // A cell before the sheet's own first row or column is a dimension
62+ // that lied; there is nowhere to put it, so it is passed over.
63+ let (Some(row), Some(column)) = (
64+ row.checked_sub(first_row).map(|row| row as usize),
65+ column.checked_sub(first_column).map(|column| column as usize),
66+ ) else {
67+ continue;
68+ };
69+ // Cells arrive in row order, so the first one past the last drawn row
70+ // is the end of the reading — whatever the dimension claimed.
71+ if row >= MAX_ROWS {
72+ clipped = true;
73+ break;
74+ }
75+ if column >= MAX_COLS {
76+ clipped = true;
77+ continue;
78+ }
79+ if rows.len() <= row {
80+ rows.resize(row + 1, Vec::new());
81+ }
82+ let line = &mut rows[row];
83+ if line.len() <= column {
84+ line.resize(column + 1, String::new());
85+ }
86+ line[column] = cell(&Data::from(found.get_value().clone()));
87+ }
88+ Some(Sheet {
89+ names,
90+ index,
91+ rows,
92+ clipped,
93+ })
94+}
95+
96+/// The whole-workbook path, for the formats with no cell-at-a-time reader:
97+/// xls, xlsb and ods. All three are bounded by the upload limit and by their
98+/// own row ceilings, so the range fits in memory in a way an xlsx need not.
99+fn read_whole(bytes: Vec<u8>, index: usize) -> Option<Sheet> {
35 let mut book = open_workbook_auto_from_rs(Cursor::new(bytes)).ok()?;100 let mut book = open_workbook_auto_from_rs(Cursor::new(bytes)).ok()?;
36 let names = book.sheet_names();101 let names = book.sheet_names();
37 if names.is_empty() {102 if names.is_empty() {
@@ -143,8 +208,21 @@ mod tests {
143 assert_eq!(column_name(702), "AAA");208 assert_eq!(column_name(702), "AAA");
144 }209 }
145 210
211+ /// The clip is what keeps a workbook of any size from becoming a page of
212+ /// that size — and on the streamed path, from being read at all past the
213+ /// rows that are drawn.
214+ #[test]
215+ fn a_book_past_the_clip_is_read_only_as_far_as_it_is_drawn() {
216+ let bytes = include_bytes!("../tests/fixtures/tall.xlsx").to_vec();
217+ let sheet = read(bytes, 0).expect("the workbook opens");
218+ assert_eq!(sheet.rows.len(), MAX_ROWS);
219+ assert!(sheet.clipped);
220+ assert_eq!(sheet.rows[0][0], "Row 1");
221+ assert_eq!(sheet.rows[MAX_ROWS - 1][0], format!("Row {MAX_ROWS}"));
222+ }
223+
146 #[test]224 #[test]
147 fn bytes_that_are_not_a_workbook_have_no_sheet() {225 fn bytes_that_are_not_a_workbook_have_no_sheet() {
148 assert!(read(b"not a workbook at all".to_vec(), 0).is_none());226 assert!(read(b"not a workbook at all".to_vec(), 0).is_none());
149 }227 }
150-}228+}
\ No newline at end of file\ No newline at end of file
crates/izlek-web/tests/fixtures/tall.xlsxadded+0 -0

Binary file changed