diff --git a/acceleration/go.mod b/acceleration/go.mod index b18fbf4f2d..a8f37b5a22 100644 --- a/acceleration/go.mod +++ b/acceleration/go.mod @@ -55,6 +55,7 @@ require ( github.com/vektah/gqlparser/v2 v2.5.64 github.com/vmihailenco/msgpack/v5 v5.4.1 github.com/xuri/excelize/v2 v2.11.1 + github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 go.opentelemetry.io/otel v1.46.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 @@ -187,7 +188,6 @@ require ( github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect github.com/wlynxg/anet v0.0.5 // indirect github.com/xuri/efp v0.0.3-0.20260924042702-217b81952dec // indirect - github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 // indirect github.com/yosida95/uritemplate/v3 v3.0.2 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/detectors/gcp v1.44.0 // indirect diff --git a/acceleration/internal/api/documents.go b/acceleration/internal/api/documents.go index 82a736b291..720a8cfe05 100644 --- a/acceleration/internal/api/documents.go +++ b/acceleration/internal/api/documents.go @@ -122,14 +122,20 @@ func (s *Server) readDocument(ctx context.Context, found *session.Session, sourc if retry { return sentDocument{file: sandbox.File{Name: name, MIME: http.DetectContentType(data), Data: data}, sha: hex.EncodeToString(digest[:])}, nil } - read, err := s.documents.Extract(ctx, name, data) + // A format that is refused is refused before it is read: reading a workbook is work the + // person's file has no use for. + format, err := extract.Detect(data) if err != nil { return sentDocument{}, documentFailure(err) } - mime, accepted := documentFormats[read.Format] + mime, accepted := documentFormats[format] if !accepted { return sentDocument{}, newAPIError(ErrorTypeUnsupportedMediaType, - fmt.Sprintf("the file is %s: a PDF or a Word document (DOCX or DOC) can be sent", read.Format)) + fmt.Sprintf("the file is %s: a PDF or a Word document (DOCX or DOC) can be sent", format)) + } + read, err := s.documents.Extract(ctx, name, data) + if err != nil { + return sentDocument{}, documentFailure(err) } if failure := s.readDocumentPictures(ctx, spec, &read); failure != nil { return sentDocument{}, failure diff --git a/acceleration/internal/api/documents_test.go b/acceleration/internal/api/documents_test.go index 15eaea7a7a..b714c3a72a 100644 --- a/acceleration/internal/api/documents_test.go +++ b/acceleration/internal/api/documents_test.go @@ -17,6 +17,8 @@ import ( "testing" + "github.com/xuri/excelize/v2" + "github.com/GetStream/Vision-Agents/acceleration/internal/harness" "github.com/GetStream/Vision-Agents/acceleration/internal/llm" ) @@ -268,6 +270,34 @@ func (s *DocumentsSuite) TestAPictureSentAsAFileIsRefused() { s.Equal("unsupported_media_type", failure.Code) } +// A workbook is no format a question takes, and it is refused for that before it is read: one that +// the reader would refuse as too large is answered as the wrong format all the same. +func (s *DocumentsSuite) TestAWorkbookIsRefusedAsTheWrongFormatWithoutBeingRead() { + opened := s.opening(s.client) + for name, column := range map[string]int{"menu.xlsx": 1, "wide.xlsx": 16384} { + book := excelize.NewFile() + // Streamed, so each row is written as its one value, not held as wide as its last column. + writer, err := book.NewStreamWriter("Sheet1") + s.Require().NoError(err) + for row := 1; row <= 1500; row++ { + cell, err := excelize.CoordinatesToCellName(column, row) + s.Require().NoError(err) + s.Require().NoError(writer.SetRow(cell, []any{"v"})) + } + s.Require().NoError(writer.Flush()) + var out bytes.Buffer + s.Require().NoError(book.Write(&out)) + s.Require().NoError(book.Close()) + file := FileSource{Url: "data:application/octet-stream;base64," + base64.StdEncoding.EncodeToString(out.Bytes()), Name: &name} + + status, failure := s.refused(opened, CreateResponseRequest{Text: "What is this?", Files: &[]FileSource{file}}) + + s.Equal(http.StatusUnsupportedMediaType, status, name) + s.Equal("unsupported_media_type", failure.Code, name) + s.Contains(failure.Message, "the file is xlsx", name) + } +} + func (s *DocumentsSuite) TestAnEncryptedFileIsRefusedAsUnreadable() { opened := s.opening(s.client) encrypted, err := os.ReadFile("../knowledge/extract/testdata/encrypted.docx") diff --git a/acceleration/internal/knowledge/extract/extract.go b/acceleration/internal/knowledge/extract/extract.go index 547ae0b4d2..ac7d374e2a 100644 --- a/acceleration/internal/knowledge/extract/extract.go +++ b/acceleration/internal/knowledge/extract/extract.go @@ -276,7 +276,7 @@ func (e *Extractor) Extract(ctx context.Context, name string, data []byte) (Docu ctx, cancel := context.WithTimeout(ctx, e.options.Timeout) defer cancel() - format, err := detect(data) + format, err := Detect(data) if err != nil { return Document{}, err } @@ -315,9 +315,10 @@ var ( utf8BOM = []byte{0xEF, 0xBB, 0xBF} ) -// detect reads what a file is from its first bytes and, for the formats that are zip or -// OLE containers, from what the container holds. -func detect(data []byte) (Format, error) { +// Detect reads what a file is from its first bytes and, for the formats that are zip or +// OLE containers, from what the container holds. Extract reads it the same way, so a caller +// that takes only some formats can refuse the rest before any of them is read. +func Detect(data []byte) (Format, error) { // A PDF may carry junk before its header, and readers accept one within the first // kilobyte of the file. if bytes.Contains(data[:min(len(data), 1024)], pdfMagic) { diff --git a/acceleration/internal/knowledge/extract/extract_test.go b/acceleration/internal/knowledge/extract/extract_test.go index d0c47ab3a5..3930f275b2 100644 --- a/acceleration/internal/knowledge/extract/extract_test.go +++ b/acceleration/internal/knowledge/extract/extract_test.go @@ -5,12 +5,16 @@ import ( "bytes" "context" "encoding/binary" + "encoding/xml" "errors" + "fmt" "image" "image/jpeg" "image/png" + "math" "os" "path/filepath" + "runtime" "strconv" "strings" "testing" @@ -20,6 +24,7 @@ import ( "github.com/klippa-app/go-pdfium/requests" "github.com/klippa-app/go-pdfium/responses" "github.com/stretchr/testify/suite" + "github.com/xuri/excelize/v2" ) type ExtractSuite struct { @@ -675,3 +680,721 @@ func (k *killedAt) FPDFFormObj_GetObject(request *requests.FPDFFormObj_GetObject k.reach("FPDFFormObj_GetObject") return k.Pdfium.FPDFFormObj_GetObject(request) } + +// workbook is a workbook whose rows each hold one value, in the given column. Its sheet and shared +// strings are written as excelize saves them, not set cell by cell: excelize holds a row it sets as +// wide as its last value, so a workbook of rows that reach a far column takes gigabytes to build. +func (s *ExtractSuite) workbook(rows, column int) []byte { + book := excelize.NewFile() + defer book.Close() + s.Require().NoError(book.SetCellValue("Sheet1", "A1", "v1")) + var out bytes.Buffer + s.Require().NoError(book.Write(&out)) + + name, err := excelize.ColumnNumberToName(column) + s.Require().NoError(err) + var sheetData, shared strings.Builder + for row := 1; row <= rows; row++ { + number := strconv.Itoa(row) + sheetData.WriteString(`` + strconv.Itoa(row-1) + ``) + shared.WriteString(`v` + number + ``) + } + return s.rezip(out.Bytes(), map[string][]byte{ + "xl/worksheets/sheet1.xml": []byte(`` + sheetData.String() + ``), + "xl/sharedStrings.xml": []byte(`` + shared.String() + ``), + }) +} + +// A row is held as wide as its last value, so a workbook of a few kilobytes with a value in the +// last column of every row would be millions of cells. The read is refused before it holds them. +func (s *ExtractSuite) TestAWorkbookWithAValueInItsLastColumnOfEveryRowIsRefusedWithinABudget() { + const lastColumn = 16384 + data := s.workbook(1500, lastColumn) + s.Less(len(data), 32<<10, "the file is a few kilobytes") + + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + _, err := s.extractor.Extract(context.Background(), "wide.xlsx", data) + runtime.ReadMemStats(&after) + + s.requireReason(err, TooLarge) + // The refused row is the first, at most 16,384 cells of 16 bytes. Reading every row as wide + // allocates gigabytes. + s.Less(after.TotalAlloc-before.TotalAlloc, uint64(16<<20)) +} + +func (s *ExtractSuite) TestARowMayBeAsWideAsTheLimitAndNoWider() { + for _, test := range []struct { + column int + reason Reason + }{ + {maxSheetColumns, ""}, + {maxSheetColumns + 1, TooLarge}, + } { + _, err := s.extractor.Extract(context.Background(), "wide.xlsx", s.workbook(3, test.column)) + + if test.reason == "" { + s.Require().NoError(err, "column %d", test.column) + continue + } + s.requireReason(err, test.reason) + } +} + +func (s *ExtractSuite) TestAWorkbookMayHoldAsManyCellsAsTheLimitAndNoMore() { + const column = 1000 + rows := maxWorkbookCells / column + + read, err := s.extractor.Extract(context.Background(), "tall.xlsx", s.workbook(rows, column)) + s.Require().NoError(err) + s.Contains(read.Pages[0].Text, "v"+strconv.Itoa(rows)) + + _, err = s.extractor.Extract(context.Background(), "tall.xlsx", s.workbook(rows+1, column)) + s.requireReason(err, TooLarge) +} + +// Cells are counted for the whole workbook: two sheets that each hold half the limit are read, +// and one more cell in either is refused. +func (s *ExtractSuite) TestTheCellLimitIsOfTheWholeWorkbook() { + const column = 1000 + half := maxWorkbookCells / 2 / column + for _, test := range []struct { + second int + reason Reason + }{ + {half, ""}, + {half + 1, TooLarge}, + } { + book := excelize.NewFile() + _, err := book.NewSheet("Second") + s.Require().NoError(err) + // Streamed, so each row is written as its one value, not held as wide as its last column. + for sheet, rows := range map[string]int{"Sheet1": half, "Second": test.second} { + writer, err := book.NewStreamWriter(sheet) + s.Require().NoError(err) + for row := 1; row <= rows; row++ { + cell, err := excelize.CoordinatesToCellName(column, row) + s.Require().NoError(err) + s.Require().NoError(writer.SetRow(cell, []any{"v"})) + } + s.Require().NoError(writer.Flush()) + } + var out bytes.Buffer + s.Require().NoError(book.Write(&out)) + s.Require().NoError(book.Close()) + + read, err := s.extractor.Extract(context.Background(), "two.xlsx", out.Bytes()) + + if test.reason == "" { + s.Require().NoError(err) + s.Contains(read.Pages[0].Text, "## Second") + continue + } + s.requireReason(err, test.reason) + } +} + +// The rows between two rows of values are read as rows with no cells, and each is a line of the +// table, so each counts as a cell. +func (s *ExtractSuite) TestARowWithNoCellsCountsAsACell() { + row := func(number int) string { + cell := "A" + strconv.Itoa(number) + return `` + cell + `` + } + + read, err := s.extractor.Extract(context.Background(), "gaps.xlsx", s.sheet(row(1)+row(maxWorkbookCells))) + s.Require().NoError(err) + s.True(strings.HasSuffix(read.Pages[0].Text, "| A"+strconv.Itoa(maxWorkbookCells)+" |")) + + _, err = s.extractor.Extract(context.Background(), "gaps.xlsx", s.sheet(row(1)+row(maxWorkbookCells+1))) + s.requireReason(err, TooLarge) +} + +// A sheet with a value in its last row is a million rows from a few hundred bytes, and a workbook +// of many such sheets is refused before it holds them: reading them all allocates gigabytes, and +// the read is refused at the first sheet's millionth row. +func (s *ExtractSuite) TestAWorkbookOfSheetsReachingTheirLastRowIsRefusedWithinABudget() { + last := `x` + for name, test := range map[string]struct { + sheets int + sheetData string + }{ + "100 sheets with a value in their last row": {100, last}, + "40 sheets with a value in their first and last row": {40, `x` + last}, + } { + data := s.sheets(test.sheets, test.sheetData) + s.Less(len(data), 64<<10, "%s: the file is a few kilobytes", name) + + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + _, err := s.extractor.Extract(context.Background(), "far.xlsx", data) + runtime.ReadMemStats(&after) + + s.requireReason(err, TooLarge) + s.Less(after.TotalAlloc-before.TotalAlloc, uint64(256<<20), name) + } +} + +// sharedText is a workbook of the given sheets, each of rows × columns cells that all hold one +// shared string of text. +func (s *ExtractSuite) sharedText(sheets, rows, columns int, text string) []byte { + book := excelize.NewFile() + defer book.Close() + for i := 1; i <= sheets; i++ { + sheet := "S" + strconv.Itoa(i) + _, err := book.NewSheet(sheet) + s.Require().NoError(err) + for row := 1; row <= rows; row++ { + for column := 1; column <= columns; column++ { + cell, err := excelize.CoordinatesToCellName(column, row) + s.Require().NoError(err) + s.Require().NoError(book.SetCellValue(sheet, cell, "shared")) + } + } + } + s.Require().NoError(book.DeleteSheet("Sheet1")) + var out bytes.Buffer + s.Require().NoError(book.Write(&out)) + // excelize cuts a value to the 32,767 characters a cell may hold, so the one shared string is + // replaced in the file. + return s.rezip(out.Bytes(), map[string][]byte{"xl/sharedStrings.xml": []byte( + `` + text + ``)}) +} + +// One long shared string is the text of every cell it is in. A workbook whose cells are within +// the cell limit but whose text is not is refused, before its cells' copies of it are all held. +func (s *ExtractSuite) TestAWorkbookIsRefusedPastItsTextBudget() { + long := strings.Repeat("y", 100<<10) + data := s.sharedText(1, 3, 1000, long) + s.Less(len(data), 64<<10, "the file is a few kilobytes") + + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + _, err := s.extractor.Extract(context.Background(), "shared.xlsx", data) + runtime.ReadMemStats(&after) + + s.requireReason(err, TooLarge) + // The cells are refused at the budget, twice maxUnzipped. Holding all three thousand copies + // is more than twice that. + s.Less(after.TotalAlloc-before.TotalAlloc, uint64(4*maxUnzipped)) +} + +// A row's cells are each a copy of their text, built at once: one long shared string in every cell +// of one row is that string a thousand times over before the row could be counted. The cells are +// counted as they are stored before any row is built, so the read is refused within the text budget. +func (s *ExtractSuite) TestARowOfOneLongSharedStringIsRefusedBeforeItIsBuilt() { + data := s.sharedText(1, 1, maxSheetColumns, strings.Repeat("y", 2<<20)) + s.Less(len(data), 64<<10, "the file is a few kilobytes") + + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + _, err := s.extractor.Extract(context.Background(), "row.xlsx", data) + runtime.ReadMemStats(&after) + + s.requireReason(err, TooLarge) + // Building the row allocates two gigabytes, sixteen times the budget. + s.Less(after.TotalAlloc-before.TotalAlloc, uint64(maxWorkbookText)) +} + +// cellsNaming is a workbook of one row of cells, each the given XML, and the given shared strings, +// in a part of the given name. +func (s *ExtractSuite) cellsNaming(cells int, cell, part, shared string) []byte { + sheet := s.sheet(`` + strings.Repeat(cell, cells) + ``) + return s.rezip(s.withoutPart(sheet, "xl/sharedStrings.xml"), map[string][]byte{part: []byte( + `` + shared + ``)}) +} + +// A cell is counted as the shared string excelize reads for it, at the index it reads it at, or +// one long string in every cell of a row is counted as a short one and built before it is +// refused. excelize reads the strings that are the root's children when their part is small +// enough to hold, and every one in it when it is not, so a string nested one level down moves the +// strings after it to other indices in one way and not the other. +func (s *ExtractSuite) TestASharedStringIsCountedAtTheIndexItIsReadAt() { + const length = 2 << 20 + long := `` + strings.Repeat("y", length) + `` + short := `short` + first := `0` + // excelize holds a shared strings part of up to 16 MiB in memory, so a longer string makes + // it read the part as it reads one too large to hold. + const nested = 17 << 20 + for name, test := range map[string]struct { + data []byte + // row is the text of the row as it is built: the long string once in every cell. + row int + // budget overrides row/2 where the legit allocation is far under half the row. + budget uint64 + }{ + "a part small enough to hold, the first string the root's child": { + data: s.cellsNaming(128, first, "xl/sharedStrings.xml", ``+short+``+long), + row: 128 * length, + }, + "a part too large to hold, the first string nested": { + data: s.cellsNaming(128, first, "xl/sharedStrings.xml", ``+strings.Repeat("y", nested)+``+short), + row: 128 * nested, + }, + "a cell whose formula holds another index": { + data: s.cellsNaming(128, `01`, "xl/sharedStrings.xml", long+short), + row: 128 * length, + }, + "an index between spaces": { + data: s.cellsNaming(128, ` 1 `, "xl/sharedStrings.xml", short+long), + row: 128 * length, + }, + "a part named in other letters": { + data: s.cellsNaming(128, first, "XL/SharedStrings.xml", long), + row: 128 * length, + }, + "a part named with a backslash": { + data: s.cellsNaming(128, first, `xl\sharedStrings.xml`, long), + row: 128 * length, + }, + "a string of runs": { + data: s.cellsNaming(maxSheetColumns, first, "xl/sharedStrings.xml", ``+strings.Repeat("y", 1<<20)+``), + row: maxSheetColumns << 20, + // Legit allocation is about 23 MB under -race, so 128 MiB is about 5.8 times it. + budget: maxWorkbookText, + }, + "a cell of two values, the last naming the long string": { + data: s.cellsNaming(128, `10`, "xl/sharedStrings.xml", long+short), + row: 128 * length, + }, + } { + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + _, err := s.extractor.Extract(context.Background(), "named.xlsx", test.data) + runtime.ReadMemStats(&after) + + s.requireReason(err, TooLarge) + s.Contains(err.Error(), "shared strings", "%s: refused before a row is built", name) + // Counting the long string allocates a few times its length for each of the two ways it + // is read, more under the race detector: at most a quarter of the row here. Building the + // row allocates more than the row. Half the row is between the two. + budget := uint64(test.row / 2) + if test.budget != 0 { + budget = test.budget + } + s.Less(after.TotalAlloc-before.TotalAlloc, budget, name) + } +} + +// The text budget may be spent to the byte, and no further. Cells of spaces make no table, so the +// cells alone spend it. Stored, the cells are counted before they are read, and a byte past the +// budget is refused then; a number format that writes a string twice ("@@") makes them twice as +// long as they are read, and they are counted so. +func (s *ExtractSuite) TestTheTextBudgetMayBeSpentToTheByte() { + spaces := strings.Repeat(" ", 1<<20) + columns := maxWorkbookText / len(spaces) + + stored := `` + spaces + ` ` + read, err := s.extractor.Extract(context.Background(), "spaces.xlsx", + s.cellsNaming(columns, `0`, "xl/sharedStrings.xml", stored)) + s.Require().NoError(err, "stored, the cells are the budget") + s.Empty(read.Pages[0].Text) + + _, err = s.extractor.Extract(context.Background(), "spaces.xlsx", + s.cellsNaming(1, strings.Repeat(`0`, columns)+`1`, "xl/sharedStrings.xml", stored)) + s.requireReason(err, TooLarge) + s.Contains(err.Error(), "shared strings", "stored, the cells are the budget and a byte, refused before they are read") + + book := excelize.NewFile() + defer book.Close() + twice := "@@" + style, err := book.NewStyle(&excelize.Style{CustomNumFmt: &twice}) + s.Require().NoError(err) + for column := 1; column <= columns/2; column++ { + cell, err := excelize.CoordinatesToCellName(column, 1) + s.Require().NoError(err) + s.Require().NoError(book.SetCellValue("Sheet1", cell, "twice")) + s.Require().NoError(book.SetCellStyle("Sheet1", cell, cell, style)) + } + cell, err := excelize.CoordinatesToCellName(columns/2+1, 1) + s.Require().NoError(err) + s.Require().NoError(book.SetCellValue("Sheet1", cell, "once")) + var out bytes.Buffer + s.Require().NoError(book.Write(&out)) + data := s.rezip(out.Bytes(), map[string][]byte{"xl/sharedStrings.xml": []byte( + `` + spaces + ` `)}) + + _, err = s.extractor.Extract(context.Background(), "twice.xlsx", data) + + // Stored, the cells are half the budget and a byte; read, the budget and a byte. + s.requireReason(err, TooLarge) +} + +// formatted is a workbook of one row of cells, each the given XML, with the given shared strings, +// and with one number format, of the given code, which a cell of style 1 is written in. +func (s *ExtractSuite) formatted(code string, cells int, cell, shared string) []byte { + return s.formattedBy(`formatCode="`+s.escaped(code)+`"`, "xl/styles.xml", cells, cell, shared) +} + +// formattedBy is formatted with a number format of the given attributes, in a part of the given +// name. +func (s *ExtractSuite) formattedBy(numFmt, part string, cells int, cell, shared string) []byte { + data := s.withoutPart(s.cellsNaming(cells, cell, "xl/sharedStrings.xml", shared), "xl/styles.xml") + return s.rezip(data, map[string][]byte{part: []byte( + `` + + `` + + `` + + ``)}) +} + +func (s *ExtractSuite) escaped(text string) string { + var out bytes.Buffer + s.Require().NoError(xml.EscapeText(&out, []byte(text))) + return out.String() +} + +// A number format writes a cell's text once for each text placeholder of its text section, so a +// cell's text may be many times longer read than stored, and a row of such cells is built at once. +// The cells are counted as their formats write them before any row is built. +func (s *ExtractSuite) TestACellIsCountedAsItsNumberFormatWritesIt() { + text := strings.Repeat("y", 32<<10) + // Stored, the cells are 8 MiB of text, within the budget; read, a gigabyte, eight times it. + const cells = 256 + ats := strings.Repeat("@", 127) + // A fourth section is the text section, and its zero placeholders write the text as "@" does. + zeros := "0;0;0;" + strings.Repeat("0 ", 120) + shared := `` + text + `` + sharedCell := `0` + for name, data := range map[string][]byte{ + "a shared string, written by 127 text placeholders": s.formatted(ats, cells, sharedCell, shared), + "an inline string, written by 127 text placeholders": s.formatted(ats, cells, ``+text+``, ""), + "an inline string of runs, written by 127 text placeholders": s.formatted(ats, cells, ``+text+``, ""), + "a value that is no number, written by 127 text placeholders": s.formatted(ats, cells, ``+text+``, ""), + "a shared string, written by 120 zero placeholders": s.formatted(zeros, cells, sharedCell, shared), + "a format whose code is replaced by its formatCode16": s.formattedBy(`formatCode="@" x16r2:formatCode16="`+ats+`"`, "xl/styles.xml", cells, sharedCell, shared), + "a styles part named with a backslash": s.formattedBy(`formatCode="`+ats+`"`, `xl\styles.xml`, cells, sharedCell, shared), + } { + + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + _, err := s.extractor.Extract(context.Background(), "formatted.xlsx", data) + runtime.ReadMemStats(&after) + + s.requireReason(err, TooLarge) + s.Contains(err.Error(), "shared strings", "%s: refused before a row is built", name) + // Building the row allocates at least its gigabyte, four times this budget. + s.Less(after.TotalAlloc-before.TotalAlloc, uint64(2*maxWorkbookText), name) + } +} + +// A number format may be as long as Excel allows one to be, and no longer: excelize writes a long +// one's quoted text into each cell in time that grows with its square. +func (s *ExtractSuite) TestANumberFormatMayBeAsLongAsExcelAllows() { + // A character of two bytes, since the limit is of characters. + literal := func(length int) string { return `"` + strings.Repeat("é", length-3) + `"0` } + number := `1` + + read, err := s.extractor.Extract(context.Background(), "format.xlsx", s.formatted(literal(maxFormatCode), 2, number, "")) + s.Require().NoError(err) + s.Contains(read.Pages[0].Text, strings.Repeat("é", maxFormatCode-3)+"1") + + _, err = s.extractor.Extract(context.Background(), "format.xlsx", s.formatted(literal(maxFormatCode+1), 2, number, "")) + s.requireReason(err, TooLarge) + s.Contains(err.Error(), "number format") + + // Read, a format of a megabyte of quoted text takes a minute for each cell. + started := time.Now() + _, err = s.extractor.Extract(context.Background(), "format.xlsx", s.formatted(literal(1<<20), 2, number, "")) + s.requireReason(err, TooLarge) + s.Less(time.Since(started), 5*time.Second) +} + +// A workbook in the formats people use reads as it did before formats were counted: text, a code +// padded with zeros, a weight with its unit, a price, a date, and text in a number's format. +func (s *ExtractSuite) TestAWorkbookOfOrdinaryFormatsReadsAsBefore() { + book := excelize.NewFile() + defer book.Close() + styles := map[string]int{} + for _, code := range []string{"@", "0000", `0 "kg"`, "0.00", "yyyy-mm-dd"} { + custom := code + style, err := book.NewStyle(&excelize.Style{CustomNumFmt: &custom}) + s.Require().NoError(err) + styles[code] = style + } + header := []any{"Item", "Code", "Weight", "Price", "Date", "Note"} + s.Require().NoError(book.SetSheetRow("Sheet1", "A1", &header)) + var want strings.Builder + want.WriteString("## Sheet1\n\n| Item | Code | Weight | Price | Date | Note |\n| --- | --- | --- | --- | --- | --- |") + for row := 2; row <= 40; row++ { + date := time.Date(2026, 1, row, 0, 0, 0, 0, time.UTC) + values := []any{"item " + strconv.Itoa(row), row, row * 3, float64(row) + 0.5, date, "note " + strconv.Itoa(row)} + cell, err := excelize.CoordinatesToCellName(1, row) + s.Require().NoError(err) + s.Require().NoError(book.SetSheetRow("Sheet1", cell, &values)) + for column, code := range []string{"@", "0000", `0 "kg"`, "0.00", "yyyy-mm-dd", `0 "kg"`} { + cell, err := excelize.CoordinatesToCellName(column+1, row) + s.Require().NoError(err) + s.Require().NoError(book.SetCellStyle("Sheet1", cell, cell, styles[code])) + } + fmt.Fprintf(&want, "\n| item %d | %04d | %d kg | %d.50 | %s | note %d |", row, row, row*3, row, date.Format("2006-01-02"), row) + } + var out bytes.Buffer + s.Require().NoError(book.Write(&out)) + + read, err := s.extractor.Extract(context.Background(), "ordinary.xlsx", out.Bytes()) + + s.Require().NoError(err) + s.Equal(want.String(), read.Pages[0].Text) +} + +// A table may be as long as its limit and no longer, its last row counted as well as the others. +func (s *ExtractSuite) TestATableMayBeAsLongAsItsLimit() { + rows := [][]string{{"h"}, {"a"}, {"b"}} + whole := table(rows) + + text, err := tableWithin(context.Background(), rows, len(whole)) + s.Require().NoError(err) + s.Equal(whole, text) + + _, err = tableWithin(context.Background(), rows, len(whole)-1) + s.Require().ErrorIs(err, errTableTooLong) +} + +// The text budget is of the whole workbook: two sheets that each take less than half of it are +// read, and a third is refused. +func (s *ExtractSuite) TestTheTextBudgetIsOfTheWholeWorkbook() { + long := strings.Repeat("y", 100<<10) + + read, err := s.extractor.Extract(context.Background(), "shared.xlsx", s.sharedText(2, 3, 100, long)) + s.Require().NoError(err) + s.Contains(read.Pages[0].Text, "## S2") + s.Contains(read.Pages[0].Text, long) + + _, err = s.extractor.Extract(context.Background(), "shared.xlsx", s.sharedText(3, 3, 100, long)) + s.requireReason(err, TooLarge) +} + +// A table pads every row to its widest, so one row of values in every column over rows with no +// cells is a long table from few cells. It is refused when it is longer than the text budget. +func (s *ExtractSuite) TestATableLongerThanTheTextBudgetIsRefused() { + var header strings.Builder + header.WriteString(``) + for column := 1; column <= maxSheetColumns; column++ { + cell, err := excelize.CoordinatesToCellName(column, 1) + s.Require().NoError(err) + header.WriteString(`h`) + } + header.WriteString(``) + // Each line of the table is its 1,024 cells of three bytes, a pipe and a line break. The + // table is four times the text budget. + rows := 4 * maxWorkbookText / (3*maxSheetColumns + 2) + last := `x` + + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + _, err := s.extractor.Extract(context.Background(), "padded.xlsx", s.sheet(header.String()+last)) + runtime.ReadMemStats(&after) + + s.requireReason(err, TooLarge) + // Writing a table allocates five to six times its length: refused at the text budget, about + // six times the budget; written whole, over twenty times it. Twelve times is about twice the + // first and half the second. + s.Less(after.TotalAlloc-before.TotalAlloc, uint64(12*maxWorkbookText)) +} + +// The deadline is checked between the rows of a table as it is written, not only as it is read. +func (s *ExtractSuite) TestATableIsWrittenOnlyUntilTheDeadline() { + const rows = 500 + data := s.workbook(rows, 1) + + // Err is asked as the cells are counted, then once for the sheet and once for each row read: + // the deadline passes a few rows into writing the table. + _, err := readXLSX(&stopsAfter{Context: context.Background(), left: s.countingCalls(data) + 1 + rows + 5}, data) + + s.Require().ErrorIs(err, context.DeadlineExceeded) +} + +// sheets is a workbook of n sheets, each the given rows of inline strings. +func (s *ExtractSuite) sheets(n int, sheetData string) []byte { + var out bytes.Buffer + writer := zip.NewWriter(&out) + add := func(name, body string) { + part, err := writer.Create(name) + s.Require().NoError(err) + _, err = part.Write([]byte(body)) + s.Require().NoError(err) + } + types := `` + list := `` + rels := `` + for i := 1; i <= n; i++ { + types += fmt.Sprintf(``, i) + list += fmt.Sprintf(``, i, i, i) + rels += fmt.Sprintf(``, i, i) + add(fmt.Sprintf("xl/worksheets/sheet%d.xml", i), ``+sheetData+``) + } + add("[Content_Types].xml", types+``) + add("xl/workbook.xml", list+``) + add("xl/_rels/workbook.xml.rels", rels+``) + add("_rels/.rels", ``) + s.Require().NoError(writer.Close()) + return out.Bytes() +} + +// A table of many rows of an ordinary width reads as it did before the limits. Its last column is +// the tenth, so each row holds ten cells for three values. +func (s *ExtractSuite) TestAWorkbookOfManyRowsOfOrdinaryWidthIsReadInFull() { + book := excelize.NewFile() + defer book.Close() + var want strings.Builder + want.WriteString("## Sheet1\n\n| A | B | C |\n| --- | --- | --- |") + for row := 1; row <= 20000; row++ { + number := strconv.Itoa(row) + values := []any{"A", "B", nil, nil, nil, nil, nil, nil, nil, "C"} + if row > 1 { + values = []any{"a" + number, row, nil, nil, nil, nil, nil, nil, nil, "c" + number} + want.WriteString("\n| a" + number + " | " + number + " | c" + number + " |") + } + cell, err := excelize.CoordinatesToCellName(1, row) + s.Require().NoError(err) + s.Require().NoError(book.SetSheetRow("Sheet1", cell, &values)) + } + var out bytes.Buffer + s.Require().NoError(book.Write(&out)) + + read, err := s.extractor.Extract(context.Background(), "table.xlsx", out.Bytes()) + + s.Require().NoError(err) + s.Equal(want.String(), read.Pages[0].Text) +} + +// stopsAfter is a context that is done once Err has been asked this many times. +type stopsAfter struct { + context.Context + left int +} + +func (c *stopsAfter) Err() error { + if c.left--; c.left < 0 { + return context.DeadlineExceeded + } + return nil +} + +// The deadline is checked between the rows of a sheet, not only between sheets. +func (s *ExtractSuite) TestASheetIsReadOnlyUntilTheDeadline() { + data := s.workbook(500, 1) + _, err := readXLSX(context.Background(), data) + s.Require().NoError(err) + + _, err = readXLSX(&stopsAfter{Context: context.Background(), left: s.countingCalls(data) + 10}, data) + + s.Require().ErrorIs(err, context.DeadlineExceeded) + _, ok := ReasonOf(err) + s.False(ok, "a workbook stopped at the deadline is not called corrupt or too large") +} + +// countingCalls is how many times counting a workbook's cells asks for the deadline. +func (s *ExtractSuite) countingCalls(data []byte) int { + counted := &stopsAfter{Context: context.Background(), left: math.MaxInt} + count := cellCount{ctx: counted} + s.Require().NoError(count.workbook(data)) + return math.MaxInt - counted.left +} + +// The deadline is checked as the cells are counted: at each row of every part, and at each shared +// string. A workbook with a part that is no sheet, or with more shared strings than its cells +// name, is counted for longer than it is read. +func (s *ExtractSuite) TestTheCellsAreCountedOnlyUntilTheDeadline() { + var rows, shared strings.Builder + for i := 1; i <= 500; i++ { + rows.WriteString(`1`) + shared.WriteString(`s`) + } + for name, data := range map[string][]byte{ + "rows of a part that is no sheet": s.rezip(s.workbook(1, 1), map[string][]byte{"xl/rows.xml": []byte(`` + rows.String() + ``)}), + "shared strings": s.rezip(s.workbook(1, 1), map[string][]byte{"xl/sharedStrings.xml": []byte(`` + shared.String() + ``)}), + } { + _, err := readXLSX(context.Background(), data) + s.Require().NoError(err, name) + + _, err = readXLSX(&stopsAfter{Context: context.Background(), left: 10}, data) + + s.Require().ErrorIs(err, context.DeadlineExceeded, name) + } +} + +// The deadline is checked every few thousand XML tokens as the cells are counted, not only at a +// row or a string: a part of many elements that are none of them is not read to its end past it. +func (s *ExtractSuite) TestAPartOfOtherElementsIsCountedOnlyUntilTheDeadline() { + junk := strings.Repeat(``, 100_000) + for name, data := range map[string][]byte{ + "a part that is no sheet": s.rezip(s.workbook(1, 1), map[string][]byte{"xl/junk.xml": []byte(`` + junk + ``)}), + // Inside a formula, which the count of a part's cells skips whole, so the elements are + // read one by one only as the shared strings are read. + "the shared strings": s.rezip(s.workbook(1, 1), map[string][]byte{"xl/sharedStrings.xml": []byte(`s` + junk + ``)}), + "a cell": s.sheet(`0` + junk + ``), + "the styles": s.rezip(s.workbook(1, 1), map[string][]byte{"xl/styles.xml": []byte(`` + junk + ``)}), + } { + _, err := readXLSX(context.Background(), data) + s.Require().NoError(err, name) + + _, err = readXLSX(&stopsAfter{Context: context.Background(), left: 10}, data) + + s.Require().ErrorIs(err, context.DeadlineExceeded, name) + } +} + +// sheet is a workbook whose only sheet is the given XML, rows of inline strings. +func (s *ExtractSuite) sheet(sheetData string) []byte { + return s.rezip(s.workbook(1, 1), map[string][]byte{"xl/worksheets/sheet1.xml": []byte( + `` + sheetData + ``)}) +} + +func (s *ExtractSuite) TestASheetWhoseRowsCannotBeReadIsRefusedAsCorrupt() { + row := func(number, cell string) string { + return `` + cell + `` + } + for name, test := range map[string]struct { + data []byte + reason Reason + // says is what the error says, when the rows are what cannot be read. + says string + }{ + "a row past the last row a sheet has": {data: s.sheet(row("1", "A1") + row("1048577", "A1048577")), reason: Corrupt, says: `sheet "Sheet1" cannot be read`}, + "a sheet whose part is missing": {data: s.withoutPart(s.workbook(1, 1), "xl/worksheets/sheet1.xml"), reason: Corrupt}, + "a cell named by no column": {data: s.sheet(row("1", "A1") + row("2", "ZZZZ2")), reason: Corrupt}, + } { + _, err := s.extractor.Extract(context.Background(), name+".xlsx", test.data) + + s.requireReason(err, test.reason) + if test.says != "" { + s.Contains(err.Error(), test.says, name) + s.NotContains(err.Error(), "pictures", name) + } + } +} + +// A row that cannot be read ends its sheet there, as in excelize's GetRows: a workbook whose +// shared strings are cut short reads as a sheet with no text, not as a corrupt file. +func (s *ExtractSuite) TestAWorkbookWhoseSharedStringsAreCutShortReadsWithNoText() { + data := s.rezip(s.workbook(3, 1), map[string][]byte{"xl/sharedStrings.xml": []byte(`cut`)}) + + read, err := s.extractor.Extract(context.Background(), "cut.xlsx", data) + + s.Require().NoError(err) + s.Empty(read.Pages[0].Text) +} + +// withoutPart is a copy of an archive without one of its parts. +func (s *ExtractSuite) withoutPart(data []byte, name string) []byte { + archive, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) + s.Require().NoError(err) + var out bytes.Buffer + writer := zip.NewWriter(&out) + for _, file := range archive.File { + if file.Name != name { + s.Require().NoError(writer.Copy(file)) + } + } + s.Require().NoError(writer.Close()) + return out.Bytes() +} diff --git a/acceleration/internal/knowledge/extract/markdown.go b/acceleration/internal/knowledge/extract/markdown.go index a98b583d8d..6d0fb0cc0b 100644 --- a/acceleration/internal/knowledge/extract/markdown.go +++ b/acceleration/internal/knowledge/extract/markdown.go @@ -1,6 +1,9 @@ package extract import ( + "context" + "errors" + "math" "strings" ) @@ -189,6 +192,17 @@ func oneLine(text string) string { // to the widest, and columns empty in every row are dropped: a spreadsheet's formatting // often reaches well past its data. func table(rows [][]string) string { + // With no deadline and no limit, the table is always written. + text, _ := tableWithin(context.Background(), rows, math.MaxInt) + return text +} + +// errTableTooLong is a table longer than its limit. +var errTableTooLong = errors.New("the table is longer than allowed") + +// tableWithin is table, stopped at the deadline between rows and refused with errTableTooLong +// once it is longer than limit bytes. +func tableWithin(ctx context.Context, rows [][]string, limit int) (string, error) { width := 0 for _, row := range rows { width = max(width, len(row)) @@ -225,10 +239,21 @@ func table(rows [][]string) string { } } b.WriteString("\n") + // Every line ends in a line break, and the table is written without its last. + long := func() bool { return b.Len()-1 > limit } for _, row := range rows[1:] { + if err := ctx.Err(); err != nil { + return "", err + } + if long() { + return "", errTableTooLong + } write(row) } - return strings.TrimSuffix(b.String(), "\n") + if long() { + return "", errTableTooLong + } + return strings.TrimSuffix(b.String(), "\n"), nil } // tableCell is a cell's text as one line, since a Markdown table row cannot break, with diff --git a/acceleration/internal/knowledge/extract/xlsx.go b/acceleration/internal/knowledge/extract/xlsx.go index 4b243b3b96..1816dfde88 100644 --- a/acceleration/internal/knowledge/extract/xlsx.go +++ b/acceleration/internal/knowledge/extract/xlsx.go @@ -1,18 +1,61 @@ package extract import ( + "archive/zip" "bytes" "context" + "encoding/xml" + "errors" "fmt" + "io" + "strconv" "strings" + "unicode/utf8" "github.com/xuri/excelize/v2" + "github.com/xuri/nfp" ) // maxWorkbook is the most a workbook may unpack to in all. A sheet's XML is several // times the size of the values in it, so this is far more than a sheet anybody reads. const maxWorkbook = 4 * maxUnzipped +// maxSheetColumns is the widest a row may be, counted to its last value. Excel's sheet is +// 16,384 columns wide, but a table a person reads is far narrower, and a row is held as wide +// as its last value's column: one value in the last column of a few thousand rows is millions +// of cells from a file of a few kilobytes. 1,024 is sixteen times the 64 columns the ODT +// reader (odt.go) keeps of a repeated or spanned cell. +const maxSheetColumns = 1024 + +// maxWorkbookCells is the most cells one workbook may hold, the empty ones in a row counted and +// a row with no cells counted as one. The iterator returns every row up to a sheet's last, so +// one value in a sheet's last row is a million rows. A cell is a 16-byte string header, so a +// million is 16 MiB before its text, and a table of that many cells is more than a conversation +// or a knowledge passage can take in. It is counted for the whole workbook, not for each sheet: +// excelize keeps every sheet it has read for its pictures (GetPictureCells) until the workbook +// is closed, padded as the iterator pads it. +const maxWorkbookCells = 1_000_000 + +// maxWorkbookText is the most text one workbook may be read to, counted once as its cells are +// read and once more as its tables are written, since a sheet's cells and its table are held at +// once. A cell's text is its own copy, so one long shared string in many cells is that string +// many times over. Twice maxUnzipped, so a workbook's tables may be about as long as one part of +// an Office file may unpack to. +const maxWorkbookText = 2 * maxUnzipped + +// maxFormatCode is the longest number format a workbook may define, in characters: Excel's own +// limit for one ([MS-XLS] 2.4.126 Format: stFormat "MUST be greater than or equal to 1 character +// and less than or equal to 255 characters"). excelize writes a format's quoted text into a cell's +// value one character at a time, each a new copy of the value so far, so a longer one takes time +// that grows with the square of its length for each cell it is on. +const maxFormatCode = 255 + +// budget is what is left of a workbook's limits as its sheets are read. +type budget struct { + cells int + text int +} + // readXLSX reads a workbook as a table per sheet, each under its sheet's name, with its // values as the sheet shows them: a price formatted as money reads as money. A hidden // sheet is left out, since nobody reading the workbook sees it. A sheet's pictures follow @@ -27,8 +70,23 @@ func readXLSX(ctx context.Context, data []byte) (Document, error) { } defer book.Close() + count := cellCount{ctx: ctx, charset: book.CharsetReader} + if err := count.workbook(data); err != nil { + if ctx.Err() != nil { + return Document{}, unreadable(ctx, XLSX, err) + } + return Document{}, fail(Corrupt, XLSX, fmt.Errorf("the workbook cannot be read: %w", err)) + } + if count.longest > maxFormatCode { + return Document{}, fail(TooLarge, XLSX, fmt.Errorf("the workbook has a number format of %d characters, more than the %d allowed", count.longest, maxFormatCode)) + } + if count.overBudget() { + return Document{}, fail(TooLarge, XLSX, fmt.Errorf("the text of the workbook's cells, its shared strings and the rest as its number formats write them, is more than the %d bytes of text allowed", maxWorkbookText)) + } + var sections []string var kept pictures + left := budget{cells: maxWorkbookCells, text: maxWorkbookText} for _, sheet := range book.GetSheetList() { if ctx.Err() != nil { return Document{}, unreadable(ctx, XLSX, ctx.Err()) @@ -36,9 +94,9 @@ func readXLSX(ctx context.Context, data []byte) (Document, error) { if visible, err := book.GetSheetVisible(sheet); err == nil && !visible { continue } - rows, err := book.GetRows(sheet) + rows, err := sheetRows(ctx, book, sheet, &left) if err != nil { - return Document{}, fail(Corrupt, XLSX, fmt.Errorf("sheet %q cannot be read: %w", sheet, err)) + return Document{}, err } start := 0 for start < len(rows) && strings.TrimSpace(strings.Join(rows[start], "")) == "" { @@ -47,7 +105,15 @@ func readXLSX(ctx context.Context, data []byte) (Document, error) { rows = trimRows(rows[start:]) var blocks []string if len(rows) > 0 { - blocks = append(blocks, table(rows)) + text, err := tableWithin(ctx, rows, left.text) + if errors.Is(err, errTableTooLong) { + return Document{}, fail(TooLarge, XLSX, fmt.Errorf("sheet %q takes the workbook past the %d bytes of text allowed", sheet, maxWorkbookText)) + } + if err != nil { + return Document{}, unreadable(ctx, XLSX, err) + } + left.text -= len(text) + blocks = append(blocks, text) } markers, err := sheetPictures(book, sheet, &kept) if err != nil { @@ -62,6 +128,51 @@ func readXLSX(ctx context.Context, data []byte) (Document, error) { return Document{Pages: []Page{{Text: strings.Join(sections, "\n\n")}}, Pictures: kept.kept}, nil } +// sheetRows reads a sheet row by row, as excelize's GetRows does, but refuses it as too large +// when a row is wider than maxSheetColumns or the workbook's cells or text so far are more +// than left, and stops at the deadline between rows. The iterator pads a row with empty +// strings up to its last value (excelize rows.go, appendSpace), so a row is at most 16,384 +// cells before it is checked, and is dropped when it is refused. +func sheetRows(ctx context.Context, book *excelize.File, sheet string, left *budget) ([][]string, error) { + iterator, err := book.Rows(sheet) + if err != nil { + return nil, fail(Corrupt, XLSX, fmt.Errorf("sheet %q cannot be read: %w", sheet, err)) + } + var rows [][]string + for iterator.Next() { + if ctx.Err() != nil { + iterator.Close() + return nil, unreadable(ctx, XLSX, ctx.Err()) + } + row, err := iterator.Columns() + if err != nil { + // As in GetRows, a row that cannot be read ends the sheet there. + break + } + if len(row) > maxSheetColumns { + iterator.Close() + return nil, fail(TooLarge, XLSX, fmt.Errorf("sheet %q has a row of %d columns, more than the %d allowed", sheet, len(row), maxSheetColumns)) + } + // A row with no cells, one between two rows of values, is still a line of the table. + if left.cells -= max(len(row), 1); left.cells < 0 { + iterator.Close() + return nil, fail(TooLarge, XLSX, fmt.Errorf("sheet %q takes the workbook past the %d cells allowed", sheet, maxWorkbookCells)) + } + for _, cell := range row { + left.text -= len(cell) + } + if left.text < 0 { + iterator.Close() + return nil, fail(TooLarge, XLSX, fmt.Errorf("sheet %q takes the workbook past the %d bytes of text allowed", sheet, maxWorkbookText)) + } + rows = append(rows, row) + } + if err := iterator.Close(); err != nil { + return nil, fail(Corrupt, XLSX, fmt.Errorf("sheet %q cannot be read: %w", sheet, err)) + } + return rows, nil +} + // sheetPictures keeps the pictures of a sheet, by the cells they are placed at, and // returns their markers. func sheetPictures(book *excelize.File, sheet string, kept *pictures) ([]string, error) { @@ -83,3 +194,300 @@ func sheetPictures(book *excelize.File, sheet string, kept *pictures) ([]string, } return markers, nil } + +// cellCount counts the text of the shared strings a workbook's cells name, before excelize reads +// any cell. excelize builds a row's cells at once (rows.go, Columns), each its own copy of its +// text, so one long shared string in every cell of a row is that string many times over before +// the row can be counted. The workbook is refused when the shared strings its cells name are more +// than the text budget, so no row is built past it. Every part is read as a sheet, since a sheet +// may be any part the workbook names, so a hidden sheet's cells count as well. A number format +// writes a cell's text once for each text placeholder in it (numfmt.go, textHandler), so a cell's +// text is counted that many times over, for the format of the most placeholders the workbook +// defines. +type cellCount struct { + ctx context.Context + charset func(label string, input io.Reader) (io.Reader, error) + archive *zip.Reader + // shared is the length of each shared string, read at the first cell that names one. + shared []int32 + read bool + // text is the length of the shared strings the cells name. + text int + // stored is the length of the cells' own text, which a number format may write more than once. + stored int + // longest is the length of the longest number format, in characters. + longest int + // repeat is the most times a number format writes a cell's text. + repeat int + // tokens is how many XML tokens have been read, of every part. + tokens int + // styles is whether the part being read is the one of the number formats. + styles bool +} + +// tokensPerDeadlineCheck is how many XML tokens are read between two checks of the deadline, so a +// part of elements that are no row, cell or string is not read to its end past it. A token is at +// least a few bytes and costs more to read than a check, so this is a few tens of kilobytes of a +// part between checks, at a cost too small to measure. +const tokensPerDeadlineCheck = 4096 + +// tick counts one token read, and is the deadline's error at every tokensPerDeadlineCheck tokens. +func (c *cellCount) tick() error { + if c.tokens++; c.tokens%tokensPerDeadlineCheck != 0 { + return nil + } + return c.ctx.Err() +} + +// overBudget is whether the workbook's cells are more text, as excelize reads them, than the text +// budget. A cell's own text is in the file as often as the cell is, so it is counted only when a +// number format writes it more than once. +func (c *cellCount) overBudget() bool { + if c.repeat <= 1 { + return c.text > maxWorkbookText + } + return c.text+c.stored > maxWorkbookText/c.repeat +} + +// workbook counts the cells of every part of a workbook. +func (c *cellCount) workbook(data []byte) error { + archive, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) + if err != nil { + return err + } + c.archive = archive + for _, file := range archive.File { + // excelize reads the number formats from this part only (styles.go, stylesReader). + c.styles = strings.ReplaceAll(file.Name, `\`, "/") == "xl/styles.xml" + if err := c.part(file, c.cells); err != nil { + return err + } + } + return nil +} + +// numFmt reads a number format of the styles part, as excelize reads one (xlsxNumFmt): its code, +// and the code that takes its place when there is one. +func (c *cellCount) numFmt(start xml.StartElement) { + for _, attr := range start.Attr { + if attr.Name.Local == "formatCode" || attr.Name.Local == "formatCode16" { + c.format(attr.Value) + } + } +} + +// format notes the length of a number format and how many times it writes a cell's text: once for +// each text or zero placeholder of a text section, parsed as excelize parses it (numfmt.go, format). +func (c *cellCount) format(code string) { + length := utf8.RuneCountInString(code) + c.longest = max(c.longest, length) + if length > maxFormatCode { + return + } + parser := nfp.NumberFormatParser() + for _, section := range parser.Parse(code) { + if section.Type != nfp.TokenSectionText { + continue + } + placeholders := 0 + for _, item := range section.Items { + if item.TType == nfp.TokenTypeTextPlaceHolder || item.TType == nfp.TokenTypeZeroPlaceHolder { + placeholders++ + } + } + c.repeat = max(c.repeat, placeholders) + } +} + +// part reads one part of the workbook, handing each element to read. A part that is not XML, +// or not past its first error, is read no further, as excelize reads it. +func (c *cellCount) part(file *zip.File, read func(*xml.Decoder) error) error { + r, err := file.Open() + if err != nil { + return err + } + defer r.Close() + decoder := xml.NewDecoder(r) + decoder.CharsetReader = c.charset + return read(decoder) +} + +// cells counts the cells of a part, and notes the number formats of the styles part, checking the +// deadline at each row, as the rows are read, and every tokensPerDeadlineCheck tokens. +func (c *cellCount) cells(decoder *xml.Decoder) error { + for { + if err := c.tick(); err != nil { + return err + } + token, err := decoder.Token() + if err != nil { + return nil + } + start, ok := token.(xml.StartElement) + switch { + case !ok: + case start.Name.Local == "row": + if err := c.ctx.Err(); err != nil { + return err + } + case start.Name.Local == "c": + shared, stored, err := c.cell(decoder, start) + if err != nil { + return err + } + c.text += shared + c.stored += stored + case c.styles && start.Name.Local == "numFmt": + c.numFmt(start) + } + } +} + +// cell is the length of the shared string a cell names and of the cell's own text, read as excelize +// reads a cell (rows.go, cellXMLHandler; cell.go, getValueFrom): an inline string's text, or the +// cell's value. Every kind of cell but a formula's string goes through its number format. +func (c *cellCount) cell(decoder *xml.Decoder, start xml.StartElement) (int, int, error) { + kind := "" + for _, attr := range start.Attr { + if attr.Name.Local == "t" { + kind = attr.Value + } + } + var value string + inline, hasInline := 0, false + for done := false; !done; { + if err := c.tick(); err != nil { + return 0, 0, err + } + token, err := decoder.Token() + if err != nil { + break + } + switch element := token.(type) { + case xml.StartElement: + switch element.Name.Local { + case "v": + err = decoder.DecodeElement(&value, &element) + case "is": + // Read whole, so a value inside it is not the cell's. + var text sharedString + err = decoder.DecodeElement(&text, &element) + inline, hasInline = inline+text.length(), true + case "f": + // Read whole, so a value inside it is not the cell's. + err = decoder.Skip() + } + case xml.EndElement: + done = element == start.End() + } + if err != nil { + break + } + } + switch { + case kind == "str": + return 0, 0, nil + case kind == "inlineStr" && hasInline: + return 0, inline, nil + case kind != "s" || value == "": + return 0, len(value), nil + } + if err := c.readShared(); err != nil { + return 0, 0, err + } + // As in excelize, an index that is not a number is the first string. + index, _ := strconv.Atoi(strings.TrimSpace(value)) + if index < 0 || index >= len(c.shared) { + return 0, 0, nil + } + return int(c.shared[index]), 0, nil +} + +// readShared reads the length of every shared string, once. excelize reads the strings that are +// the root's children when the part is small enough to hold (rows.go, sharedStringsReader), and +// every one in the part when it is not (rows.go, getFromStringItem): both are read, and a string +// is counted as the longer of the two at its index, so a cell is never counted shorter than it +// is read. +func (c *cellCount) readShared() error { + if c.read { + return nil + } + c.read = true + for _, file := range c.archive.File { + if !strings.EqualFold(strings.ReplaceAll(file.Name, `\`, "/"), "xl/sharedStrings.xml") { + continue + } + for _, everyOne := range []bool{false, true} { + if err := c.part(file, func(decoder *xml.Decoder) error { return c.sharedStrings(decoder, everyOne) }); err != nil { + return err + } + } + } + return nil +} + +// sharedStrings reads the length of the shared strings of a part: of every one in it, or of the +// root's children only. +func (c *cellCount) sharedStrings(decoder *xml.Decoder, everyOne bool) error { + depth, index := 0, 0 + for { + if err := c.tick(); err != nil { + return err + } + token, err := decoder.Token() + if err != nil { + return nil + } + switch element := token.(type) { + case xml.StartElement: + if element.Name.Local != "si" || !everyOne && depth != 1 { + depth++ + continue + } + if err := c.ctx.Err(); err != nil { + return err + } + var text sharedString + err := decoder.DecodeElement(&text, &element) + if index == len(c.shared) { + c.shared = append(c.shared, 0) + } + // A string is at most the part it is in, a few hundred megabytes. + c.shared[index] = max(c.shared[index], int32(text.length())) + index++ + if err != nil { + return nil + } + case xml.EndElement: + depth-- + } + } +} + +// sharedString is a shared string as excelize reads it (xlsxSI): its text, and the text of its +// runs. +// excelize then only shortens it, when it unescapes characters (lib.go, bstrUnmarshal). +type sharedString struct { + T *sharedText `xml:"t"` + R []struct { + T *sharedText `xml:"t"` + } `xml:"r"` +} + +// sharedText is the text of a string or of one of its runs (xlsxT). +type sharedText struct { + Val string `xml:",chardata"` +} + +func (s *sharedString) length() int { + n := 0 + if s.T != nil { + n += len(s.T.Val) + } + for _, run := range s.R { + if run.T != nil { + n += len(run.T.Val) + } + } + return n +}