Skip to content

Distributed Peer-to-Peer Web Search Engine and Intranet Search Appliance

Added data structures to store simple csv tables in YaCy. The purpose of those tables is to provide a data exchange plattform for agent access that can communicate with YaCy over a MCP server that provides simple listTables, readTable and writeTable tool calls.

Michael Peter Christen95078f5f1f37
diff --git a/source/net/yacy/data/tables/Table.java b/source/net/yacy/data/tables/Table.java
new file mode 100644
index 000000000..fe18564ce
--- /dev/null
+++ b/source/net/yacy/data/tables/Table.java
@@ -0,0 +1,214 @@
+/**
+ * Table
+ * Copyright 2026 by Michael Peter Christen
+ * First released 29.08.2026 at https://yacy.net
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program in the file lgpl21.txt
+ * If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.yacy.data.tables;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.ConcurrentModificationException;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * A persistent table handle with an in-memory snapshot. Mutating methods are
+ * available according to the selected {@link AccessMode} and persist their
+ * changes before returning.
+ * <p>
+ * Each handle owns an independent snapshot. Getters do not read the file;
+ * call {@link #reload()} to see changes made through other handles or the store.
+ * Successful appends add only the new row to this handle's snapshot, so its row
+ * indices may differ from the file until reloaded. An edit requires the entire
+ * stored header and rows to still match this snapshot; otherwise it fails with
+ * {@link ConcurrentModificationException} before writing. Appends require only
+ * an unchanged header, including column names and order.
+ * <p>
+ * A rejected mutation leaves this snapshot unchanged. After a conflict, reload
+ * and select the intended row/column again before retrying. Coordination covers
+ * calls through {@link TableStore} in the same JVM, not external file writers.
+ * On an I/O failure the handle remains unchanged, but the file may need inspection
+ * before retrying; see {@link TableStore} for rollback and atomic-move guarantees.
+ */
+public final class Table {
+
+ /** Controls which persistent operations a table handle may perform. */
+ public enum AccessMode {
+ /** Read the snapshot and reload it, but do not mutate the table. */
+ READ_ONLY,
+ /** Read the snapshot and efficiently append complete rows. */
+ APPEND_ONLY,
+ /** Append rows or edit arbitrary cells with immediate persistence. */
+ EDITABLE
+ }
+
+ private final TableStore store;
+ private final String tableName;
+ private final AccessMode accessMode;
+ private List<String> header;
+ private List<List<String>> rows;
+
+ Table(final TableStore store, final String tableName, final AccessMode accessMode,
+ final TableStore.TableData data) {
+ this.store = Objects.requireNonNull(store, "store must not be null");
+ this.tableName = Objects.requireNonNull(tableName, "tableName must not be null");
+ this.accessMode = Objects.requireNonNull(accessMode, "accessMode must not be null");
+ replaceSnapshot(data);
+ }
+
+ /** @return the table name including its file extension */
+ public String getTableName() {
+ return this.tableName;
+ }
+
+ /** @return the access mode selected when this handle was opened */
+ public AccessMode getAccessMode() {
+ return this.accessMode;
+ }
+
+ /** @return an immutable copy of the header from the current snapshot */
+ public synchronized List<String> getHeader() {
+ return Collections.unmodifiableList(new ArrayList<>(this.header));
+ }
+
+ /** @return an immutable deep copy of all rows from the current snapshot */
+ public synchronized List<List<String>> getRows() {
+ return immutableRowsCopy(this.rows);
+ }
+
+ /**
+ * Reload the in-memory snapshot from persistent storage.
+ * Header and rows are replaced together; a failed read leaves both unchanged.
+ * Copies returned by earlier getter calls remain unchanged.
+ *
+ * @throws IOException when the table cannot be read or is malformed
+ */
+ public synchronized void reload() throws IOException {
+ replaceSnapshot(this.store.readTableData(this.tableName));
+ }
+
+ /**
+ * Edit a zero-based data cell and immediately rewrite the persistent file.
+ * Only available in {@link AccessMode#EDITABLE} mode.
+ * The entire current file must still match this handle's snapshot. Comparison
+ * and writing share the same table lock, preventing stale indices or values
+ * from overwriting another handle's changes. On success this snapshot also
+ * contains the edited value; other handles are not refreshed.
+ *
+ * @param rowIndex zero-based data row index
+ * @param columnIndex zero-based column index
+ * @param value new cell value
+ * @throws IOException when the table cannot be read or written
+ * @throws ConcurrentModificationException when the stored header or rows
+ * differ from this snapshot; reload and reselect the cell before retrying
+ */
+ public synchronized void editCell(final int rowIndex, final int columnIndex, final String value)
+ throws IOException {
+ requireMode(AccessMode.EDITABLE, "edit cells");
+ replaceSnapshot(this.store.editCellAndRead(this.tableName, rowIndex, columnIndex, value, snapshot()));
+ }
+
+ /**
+ * Append a row directly to persistent storage without rewriting existing
+ * data. Available in append-only and editable modes.
+ * Column names and order must still match this snapshot. The row is appended
+ * to the current file and to this snapshot, without importing intervening
+ * changes from other writers. Call {@link #reload()} to obtain current row
+ * indices before editing after another writer has changed the table.
+ *
+ * @param row cells to append; the number must match the header
+ * @throws IOException when the table cannot be appended
+ * @throws ConcurrentModificationException when the stored header differs
+ * from this snapshot; reload and adapt the row before retrying
+ */
+ public synchronized void addRow(final List<String> row) throws IOException {
+ if (this.accessMode == AccessMode.READ_ONLY) {
+ throw new IllegalStateException("Table was opened read-only; cannot append rows");
+ }
+ final List<String> validatedRow = copyAndValidateRow(row, this.header.size(), "appended row");
+ this.store.addRow(this.tableName, validatedRow, this.header);
+ this.rows.add(validatedRow);
+ }
+
+ synchronized TableStore.TableData snapshot() {
+ return new TableStore.TableData(this.header, this.rows);
+ }
+
+ private void requireMode(final AccessMode requiredMode, final String operation) {
+ if (this.accessMode != requiredMode) {
+ throw new IllegalStateException("Table access mode " + this.accessMode + " cannot " + operation);
+ }
+ }
+
+ private void replaceSnapshot(final TableStore.TableData data) {
+ this.header = new ArrayList<>(data.header);
+ this.rows = mutableRowsCopy(data.rows);
+ }
+
+ static List<String> validateHeader(final List<String> header) {
+ Objects.requireNonNull(header, "header must not be null");
+ if (header.isEmpty()) {
+ throw new IllegalArgumentException("Table header must contain at least one column");
+ }
+ return copyAndValidateRow(header, header.size(), "header");
+ }
+
+ static List<String> copyAndValidateRow(final List<String> row, final int columnCount,
+ final String description) {
+ Objects.requireNonNull(row, description + " must not be null");
+ if (row.size() != columnCount) {
+ throw new IllegalArgumentException(description + " has " + row.size() + " cells; expected "
+ + columnCount);
+ }
+ final List<String> copy = new ArrayList<>(row.size());
+ for (final String cell : row) {
+ copy.add(validateCell(cell));
+ }
+ return copy;
+ }
+
+ static String validateCell(final String value) {
+ if (value == null) {
+ throw new IllegalArgumentException("Table cells must not be null");
+ }
+ if (value.indexOf(TableStore.SEPARATOR) >= 0) {
+ throw new IllegalArgumentException("Table cells must not contain semicolons");
+ }
+ if (value.indexOf('\n') >= 0 || value.indexOf('\r') >= 0) {
+ throw new IllegalArgumentException("Table cells must not contain line breaks");
+ }
+ return value;
+ }
+
+ private static List<List<String>> mutableRowsCopy(final List<? extends List<String>> source) {
+ final List<List<String>> copy = new ArrayList<>(source.size());
+ for (final List<String> row : source) {
+ copy.add(new ArrayList<>(row));
+ }
+ return copy;
+ }
+
+ private static List<List<String>> immutableRowsCopy(final List<? extends List<String>> source) {
+ final List<List<String>> copy = new ArrayList<>(source.size());
+ for (final List<String> row : source) {
+ copy.add(Collections.unmodifiableList(new ArrayList<>(row)));
+ }
+ return Collections.unmodifiableList(copy);
+ }
+}
diff --git a/source/net/yacy/data/tables/TableStore.java b/source/net/yacy/data/tables/TableStore.java
new file mode 100644
index 000000000..72caeaab6
--- /dev/null
+++ b/source/net/yacy/data/tables/TableStore.java
@@ -0,0 +1,518 @@
+/**
+ * TableStore
+ * Copyright 2026 by Michael Peter Christen
+ * First released 29.08.2026 at https://yacy.net
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program in the file lgpl21.txt
+ * If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package net.yacy.data.tables;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.AtomicMoveNotSupportedException;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.NoSuchFileException;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.StandardOpenOption;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.ConcurrentModificationException;
+import java.util.List;
+import java.util.Locale;
+import java.util.Objects;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+/**
+ * Thread-safe access to UTF-8 encoded, semicolon-separated CSV tables below
+ * {@code DATA/TABLES}.
+ * <p>
+ * This deliberately implements a restricted CSV dialect without quoting or
+ * escaping. Every file has a header row, all rows have the same number of
+ * cells and cells must not contain semicolons or line breaks.
+ * <p>
+ * Directory aliases are resolved before acquiring shared JVM locks. Table files
+ * must be regular files, not symbolic links; hard links are rejected on file
+ * systems exposing a Unix link count. Hard-link aliases on other file systems
+ * and concurrent external file writers are unsupported.
+ * <p>
+ * Replacements use a temporary file in the same directory and require an atomic
+ * move. An unsupported atomic move throws {@link AtomicMoveNotSupportedException}
+ * without a non-atomic fallback. Failed
+ * appends attempt to restore the original file length before releasing the lock;
+ * a rollback failure is attached as a suppressed exception. After an I/O failure,
+ * inspect/reload the file before retrying, especially if rollback or closing the
+ * channel failed. This is not a crash-recovery protocol: writes are not forced to
+ * stable storage and appends are not atomic across process or power failures.
+ */
+public final class TableStore {
+
+ public static final String TABLES_PATH = "DATA/TABLES";
+ public static final String FILE_EXTENSION = ".csv";
+ public static final char SEPARATOR = ';';
+
+ /**
+ * A fixed pool shared by all store instances, without retaining table paths.
+ * Hash collisions only serialize otherwise independent tables.
+ */
+ private static final ReadWriteLock[] TABLE_LOCKS = new ReadWriteLock[256];
+ static {
+ for (int i = 0; i < TABLE_LOCKS.length; i++) {
+ TABLE_LOCKS[i] = new ReentrantReadWriteLock(true);
+ }
+ }
+
+ private final Path tablesDirectory;
+ private final FileOperations files;
+
+ /**
+ * Create a table store rooted at YaCy's data path.
+ *
+ * @param dataPath the YaCy data root containing the {@code DATA} directory
+ */
+ public TableStore(final File dataPath) {
+ this(Objects.requireNonNull(dataPath, "dataPath must not be null").toPath());
+ }
+
+ /**
+ * Create a table store rooted at YaCy's data path.
+ *
+ * @param dataPath the YaCy data root containing the {@code DATA} directory
+ */
+ public TableStore(final Path dataPath) {
+ this(dataPath, new FileOperations());
+ }
+
+ /** Package-private I/O boundary for deterministic write-failure tests. */
+ TableStore(final Path dataPath, final FileOperations files) {
+ Objects.requireNonNull(dataPath, "dataPath must not be null");
+ this.tablesDirectory = dataPath.toAbsolutePath().normalize().resolve(TABLES_PATH);
+ this.files = Objects.requireNonNull(files, "files must not be null");
+ }
+
+ /**
+ * List table names in deterministic order. Names do not include the
+ * {@code .csv} extension.
+ *
+ * @return the table names
+ * @throws IOException when the table directory cannot be accessed
+ */
+ public List<String> listTables() throws IOException {
+ Files.createDirectories(this.tablesDirectory);
+ try (Stream<Path> entries = Files.list(this.tablesDirectory.toRealPath())) {
+ return entries
+ .filter(path -> Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS))
+ .map(path -> path.getFileName().toString())
+ .filter(name -> name.endsWith(FILE_EXTENSION))
+ .map(name -> name.substring(0, name.length() - FILE_EXTENSION.length()))
+ .sorted()
+ .collect(Collectors.toList());
+ }
+ }
+
+ /**
+ * Open a read-only table snapshot.
+ *
+ * @param tableName table name, with or without the {@code .csv} extension
+ * @return the read-only table
+ * @throws IOException when the table cannot be read or is malformed
+ */
+ public Table readTable(final String tableName) throws IOException {
+ return openTable(tableName, Table.AccessMode.READ_ONLY);
+ }
+
+ /**
+ * Open a table with explicit mutation capabilities. All mutations on the
+ * returned table are persisted before the method returns.
+ * Each call returns an independent snapshot: see {@link Table} for reload
+ * and conflict handling when multiple handles refer to the same file.
+ *
+ * @param tableName table name, with or without the {@code .csv} extension
+ * @param accessMode requested access mode
+ * @return a persistent table handle with an initial in-memory snapshot
+ * @throws IOException when the table cannot be read or is malformed
+ */
+ public Table openTable(final String tableName, final Table.AccessMode accessMode) throws IOException {
+ Objects.requireNonNull(accessMode, "accessMode must not be null");
+ final Path tableFile = resolveTable(tableName);
+ return new Table(this, tableFile.getFileName().toString(), accessMode, readTableDataLocked(tableFile));
+ }
+
+ /**
+ * Validate and atomically replace a table.
+ * Writes exactly the supplied handle's snapshot, without reloading or merging
+ * newer stored data. This is an explicit full replacement, even when the
+ * snapshot is stale. Existing handles are not refreshed.
+ *
+ * @param tableName table name, with or without the {@code .csv} extension
+ * @param table table contents, including a non-empty header
+ * @throws IOException when the table cannot be written
+ */
+ public void writeTable(final String tableName, final Table table) throws IOException {
+ Objects.requireNonNull(table, "table must not be null");
+ writeTableData(resolveTable(tableName, true), table.snapshot());
+ }
+
+ /**
+ * Validate and atomically replace a table.
+ * This explicit replacement does not check existing snapshots for conflicts
+ * or refresh open handles; use {@link Table#reload()} to read the replacement.
+ *
+ * @param tableName table name, with or without the {@code .csv} extension
+ * @param header column names
+ * @param rows data rows
+ * @throws IOException when the table cannot be written
+ */
+ public void writeTable(final String tableName, final List<String> header,
+ final List<? extends List<String>> rows) throws IOException {
+ final TableData data = new TableData(header, rows);
+ writeTableData(resolveTable(tableName, true), data);
+ }
+
+ /**
+ * Edit a zero-based data cell and immediately replace the complete file.
+ * The current file is read after acquiring its exclusive lock, preventing
+ * concurrent appends or edits from being overwritten.
+ * Indices address the current stored data. Unlike {@link Table#editCell},
+ * this method has no snapshot to check: the last write to a cell wins and
+ * open handles are not refreshed.
+ *
+ * @param tableName table name, with or without the {@code .csv} extension
+ * @param rowIndex zero-based data row index
+ * @param columnIndex zero-based column index
+ * @param value new cell value
+ * @throws IOException when the table cannot be read or written
+ * @throws IndexOutOfBoundsException when an index is outside the table
+ * @throws IllegalArgumentException when the value is not a valid cell
+ */
+ public void editCell(final String tableName, final int rowIndex, final int columnIndex,
+ final String value) throws IOException {
+ editCellAndRead(tableName, rowIndex, columnIndex, value, null);
+ }
+
+ /**
+ * Validate and append one row without reading or rewriting all data rows.
+ * Uses the current stored header and leaves all open handles unchanged.
+ * Unlike {@link Table#addRow}, no earlier header snapshot is checked.
+ *
+ * @param tableName table name, with or without the {@code .csv} extension
+ * @param row cells to append; the number must match the header
+ * @throws IOException when the table cannot be read or appended
+ * @throws IllegalArgumentException when the row is malformed
+ */
+ public void addRow(final String tableName, final List<String> row) throws IOException {
+ addRow(tableName, row, null);
+ }
+
+ void addRow(final String tableName, final List<String> row, final List<String> expectedHeader) throws IOException {
+ final Path tableFile = resolveTable(tableName);
+ final Lock lock = lockFor(tableFile).writeLock();
+ lock.lock();
+ try {
+ appendRowFile(tableFile, row, expectedHeader);
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ TableData readTableData(final String tableName) throws IOException {
+ return readTableDataLocked(resolveTable(tableName));
+ }
+
+ TableData editCellAndRead(final String tableName, final int rowIndex, final int columnIndex,
+ final String value, final TableData expectedSnapshot) throws IOException {
+ final Path tableFile = resolveTable(tableName);
+ final Lock lock = lockFor(tableFile).writeLock();
+ lock.lock();
+ try {
+ final TableData data = readTableFile(tableFile);
+ if (expectedSnapshot != null && (!data.header.equals(expectedSnapshot.header)
+ || !data.rows.equals(expectedSnapshot.rows))) {
+ throw new ConcurrentModificationException("Table has changed; reload and reselect the cell before editing");
+ }
+ data.rows.get(rowIndex).set(columnIndex, Table.validateCell(value));
+ writeTableFile(tableFile, data);
+ return data.copy();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ private TableData readTableDataLocked(final Path tableFile) throws IOException {
+ final Lock lock = lockFor(tableFile).readLock();
+ lock.lock();
+ try {
+ return readTableFile(tableFile);
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ private TableData readTableFile(final Path tableFile) throws IOException {
+ checkTableFile(tableFile, true);
+
+ final List<String> header;
+ final List<List<String>> rows = new ArrayList<>();
+ try (BufferedReader reader = Files.newBufferedReader(tableFile, StandardCharsets.UTF_8)) {
+ final String headerLine = reader.readLine();
+ if (headerLine == null) {
+ throw malformed(tableFile, "missing header row");
+ }
+ header = splitRow(headerLine);
+
+ String line;
+ int lineNumber = 1;
+ while ((line = reader.readLine()) != null) {
+ lineNumber++;
+ final List<String> row = splitRow(line);
+ if (row.size() != header.size()) {
+ throw malformed(tableFile, "line " + lineNumber + " has " + row.size()
+ + " cells; expected " + header.size());
+ }
+ rows.add(row);
+ }
+ }
+
+ try {
+ return new TableData(header, rows);
+ } catch (final IllegalArgumentException e) {
+ throw malformed(tableFile, e.getMessage());
+ }
+ }
+
+ private void writeTableData(final Path tableFile, final TableData data) throws IOException {
+ final Lock lock = lockFor(tableFile).writeLock();
+ lock.lock();
+ try {
+ writeTableFile(tableFile, data);
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /** Caller must hold the table's write lock. */
+ private void writeTableFile(final Path tableFile, final TableData data) throws IOException {
+ final TableData snapshot = data.copy();
+ checkTableFile(tableFile, false);
+
+ Path temporaryFile = null;
+ try {
+ temporaryFile = Files.createTempFile(tableFile.getParent(), ".table-", ".tmp");
+ try (BufferedWriter writer = this.files.openWriter(temporaryFile)) {
+ writeRow(writer, snapshot.header);
+ for (final List<String> row : snapshot.rows) {
+ writeRow(writer, row);
+ }
+ }
+ this.files.replaceAtomically(temporaryFile, tableFile);
+ } catch (final IOException | RuntimeException | Error failure) {
+ if (temporaryFile != null) {
+ try {
+ this.files.deleteTemporaryFile(temporaryFile);
+ } catch (final IOException cleanupFailure) {
+ failure.addSuppressed(cleanupFailure);
+ }
+ }
+ throw failure;
+ }
+ }
+
+ /** Caller must hold the table's write lock. */
+ private void appendRowFile(final Path tableFile, final List<String> row, final List<String> expectedHeader)
+ throws IOException {
+ checkTableFile(tableFile, true);
+
+ final List<String> header;
+ try (BufferedReader reader = Files.newBufferedReader(tableFile, StandardCharsets.UTF_8)) {
+ final String headerLine = reader.readLine();
+ if (headerLine == null) {
+ throw malformed(tableFile, "missing header row");
+ }
+ try {
+ header = Table.validateHeader(splitRow(headerLine));
+ } catch (final IllegalArgumentException e) {
+ throw malformed(tableFile, e.getMessage());
+ }
+ }
+
+ if (expectedHeader != null && !header.equals(expectedHeader)) {
+ throw new ConcurrentModificationException("Table columns have changed; reload and adapt the row before appending");
+ }
+ final List<String> validatedRow = Table.copyAndValidateRow(row, header.size(), "appended row");
+ final byte[] rowBytes = serializeRow(validatedRow).getBytes(StandardCharsets.UTF_8);
+
+ try (FileChannel channel = FileChannel.open(tableFile, StandardOpenOption.READ, StandardOpenOption.WRITE,
+ LinkOption.NOFOLLOW_LINKS)) {
+ final long size = channel.size();
+ boolean needsLineBreak = false;
+ if (size > 0) {
+ final ByteBuffer lastByte = ByteBuffer.allocate(1);
+ channel.position(size - 1);
+ while (lastByte.hasRemaining() && channel.read(lastByte) >= 0) {
+ // Read the final byte completely.
+ }
+ lastByte.flip();
+ if (lastByte.hasRemaining()) {
+ final byte last = lastByte.get();
+ needsLineBreak = last != '\n' && last != '\r';
+ }
+ }
+
+ channel.position(size);
+ try {
+ if (needsLineBreak) {
+ writeFully(channel, ByteBuffer.wrap(System.lineSeparator().getBytes(StandardCharsets.UTF_8)));
+ }
+ writeFully(channel, ByteBuffer.wrap(rowBytes));
+ } catch (final IOException failure) {
+ try {
+ this.files.truncate(channel, size);
+ } catch (final IOException rollbackFailure) {
+ failure.addSuppressed(rollbackFailure);
+ }
+ throw failure;
+ }
+ }
+ }
+
+ private Path resolveTable(final String tableName) throws IOException {
+ return resolveTable(tableName, false);
+ }
+
+ private Path resolveTable(final String tableName, final boolean createDirectory) throws IOException {
+ Objects.requireNonNull(tableName, "tableName must not be null");
+ if (tableName.isEmpty() || FILE_EXTENSION.equals(tableName)) {
+ throw new IllegalArgumentException("tableName must not be empty");
+ }
+ if (tableName.indexOf('/') >= 0 || tableName.indexOf('\\') >= 0
+ || ".".equals(tableName) || "..".equals(tableName)) {
+ throw new IllegalArgumentException("tableName must be a file name without a path");
+ }
+
+ final String fileName = tableName.endsWith(FILE_EXTENSION) ? tableName : tableName + FILE_EXTENSION;
+ if (createDirectory) Files.createDirectories(this.tablesDirectory);
+ return this.tablesDirectory.toRealPath().resolve(fileName);
+ }
+
+ private static ReadWriteLock lockFor(final Path tableFile) {
+ // Also serialize case variants on case-insensitive file systems, including
+ // first creation. Extra collisions on case-sensitive systems are harmless.
+ final int hash = tableFile.toAbsolutePath().normalize().toString().toLowerCase(Locale.ROOT).hashCode();
+ return TABLE_LOCKS[Math.floorMod(hash, TABLE_LOCKS.length)];
+ }
+
+ private static void checkTableFile(final Path tableFile, final boolean mustExist) throws IOException {
+ final BasicFileAttributes attributes;
+ try {
+ attributes = Files.readAttributes(tableFile, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
+ } catch (final NoSuchFileException missing) {
+ if (mustExist) throw missing;
+ return;
+ }
+ if (!attributes.isRegularFile()) {
+ throw new IOException("Table is not a regular file (symbolic links are unsupported): " + tableFile.getFileName());
+ }
+ if (tableFile.getFileSystem().supportedFileAttributeViews().contains("unix")
+ && ((Number) Files.getAttribute(tableFile, "unix:nlink", LinkOption.NOFOLLOW_LINKS)).longValue() > 1) {
+ throw new IOException("Hard-linked tables are unsupported: " + tableFile.getFileName());
+ }
+ }
+
+ private static List<String> splitRow(final String line) {
+ final String[] cells = line.split(String.valueOf(SEPARATOR), -1);
+ final List<String> row = new ArrayList<>(cells.length);
+ Collections.addAll(row, cells);
+ return row;
+ }
+
+ private static void writeRow(final BufferedWriter writer, final List<String> row) throws IOException {
+ writer.write(serializeRow(row));
+ }
+
+ private static String serializeRow(final List<String> row) {
+ final StringBuilder serialized = new StringBuilder();
+ for (int column = 0; column < row.size(); column++) {
+ if (column > 0) {
+ serialized.append(SEPARATOR);
+ }
+ serialized.append(row.get(column));
+ }
+ return serialized.append(System.lineSeparator()).toString();
+ }
+
+ private void writeFully(final FileChannel channel, final ByteBuffer buffer) throws IOException {
+ while (buffer.hasRemaining()) {
+ this.files.write(channel, buffer);
+ }
+ }
+
+ static class FileOperations {
+ BufferedWriter openWriter(final Path path) throws IOException {
+ return Files.newBufferedWriter(path, StandardCharsets.UTF_8);
+ }
+
+ void replaceAtomically(final Path source, final Path target) throws IOException {
+ Files.move(source, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
+ }
+
+ void deleteTemporaryFile(final Path path) throws IOException {
+ Files.deleteIfExists(path);
+ }
+
+ void write(final FileChannel channel, final ByteBuffer bytes) throws IOException {
+ channel.write(bytes);
+ }
+
+ void truncate(final FileChannel channel, final long size) throws IOException {
+ channel.truncate(size);
+ }
+ }
+
+ private static IOException malformed(final Path tableFile, final String reason) {
+ return new IOException("Malformed table " + tableFile.getFileName() + ": " + reason);
+ }
+
+ static final class TableData {
+
+ final List<String> header;
+ final List<List<String>> rows;
+
+ TableData(final List<String> header, final List<? extends List<String>> rows) {
+ this.header = Table.validateHeader(header);
+ this.rows = new ArrayList<>(rows.size());
+ int rowIndex = 0;
+ for (final List<String> row : rows) {
+ this.rows.add(Table.copyAndValidateRow(row, this.header.size(), "row " + rowIndex));
+ rowIndex++;
+ }
+ }
+
+ private TableData copy() {
+ return new TableData(this.header, this.rows);
+ }
+ }
+}
diff --git a/test/java/net/yacy/data/tables/TableStoreFileAccessTest.java b/test/java/net/yacy/data/tables/TableStoreFileAccessTest.java
new file mode 100644
index 000000000..1bc20afd3
--- /dev/null
+++ b/test/java/net/yacy/data/tables/TableStoreFileAccessTest.java
@@ -0,0 +1,348 @@
+package net.yacy.data.tables;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.AtomicMoveNotSupportedException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.stream.Stream;
+
+import org.junit.Assume;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+public class TableStoreFileAccessTest {
+
+ @Rule
+ public final TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+ private Path root() {
+ return this.temporaryFolder.getRoot().toPath();
+ }
+
+ private Path tableFile() {
+ return root().resolve("DATA/TABLES/people.csv");
+ }
+
+ private TableStore initialStore() throws IOException {
+ final TableStore store = new TableStore(root());
+ store.writeTable("people", Arrays.asList("name", "city"),
+ Collections.singletonList(Arrays.asList("Ada", "London")));
+ return store;
+ }
+
+ private void assertNoTemporaryFiles() throws IOException {
+ try (Stream<Path> files = Files.list(tableFile().getParent())) {
+ assertFalse(files.anyMatch(path -> path.getFileName().toString().startsWith(".table-")));
+ }
+ }
+
+ private static void createSymbolicLink(final Path link, final Path target) throws IOException {
+ try {
+ Files.createSymbolicLink(link, target);
+ } catch (final UnsupportedOperationException | IOException unavailable) {
+ Assume.assumeNoException("Symbolic links unavailable on this test filesystem", unavailable);
+ }
+ }
+
+ @Test
+ public void directoryAliasesSerializeReplacementAndAppend() throws Exception {
+ final Path realRoot = this.temporaryFolder.newFolder("real").toPath();
+ final Path aliasRoot = root().resolve("alias");
+ createSymbolicLink(aliasRoot, realRoot);
+ final TableStore normal = new TableStore(realRoot);
+ normal.writeTable("people", Collections.singletonList("name"),
+ Collections.singletonList(Collections.singletonList("Original")));
+ assertReplacementSerializesAppend(realRoot, aliasRoot, "people");
+ }
+
+ @Test
+ public void caseAliasesSerializeReplacementAndAppend() throws Exception {
+ final TableStore store = new TableStore(root());
+ store.writeTable("people", Collections.singletonList("name"),
+ Collections.singletonList(Collections.singletonList("Original")));
+ final Path uppercase = tableFile().resolveSibling("PEOPLE.csv");
+ Assume.assumeTrue("Requires a case-insensitive filesystem", Files.exists(uppercase));
+ assertTrue(Files.isSameFile(tableFile(), uppercase));
+ assertReplacementSerializesAppend(root(), root(), "PEOPLE");
+ }
+
+ /** Hold a replacement at its commit point while a second store tries to append. */
+ private static void assertReplacementSerializesAppend(final Path writeRoot, final Path appendRoot,
+ final String appendName) throws Exception {
+ final CountDownLatch replacing = new CountDownLatch(1);
+ final CountDownLatch release = new CountDownLatch(1);
+ final CountDownLatch appending = new CountDownLatch(1);
+ final TableStore writer = new TableStore(writeRoot, new TableStore.FileOperations() {
+ @Override
+ void replaceAtomically(final Path source, final Path target) throws IOException {
+ replacing.countDown();
+ try {
+ if (!release.await(10, TimeUnit.SECONDS)) throw new IOException("Test release timed out");
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IOException(e);
+ }
+ super.replaceAtomically(source, target);
+ }
+ });
+ final TableStore appender = new TableStore(appendRoot);
+ final ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ final Future<?> replacement = executor.submit(() -> {
+ writer.writeTable("people", Collections.singletonList("name"),
+ Collections.singletonList(Collections.singletonList("Replacement")));
+ return null;
+ });
+ assertTrue(replacing.await(5, TimeUnit.SECONDS));
+ final Future<?> append = executor.submit(() -> {
+ appending.countDown();
+ appender.addRow(appendName, Collections.singletonList("Appended"));
+ return null;
+ });
+ assertTrue(appending.await(5, TimeUnit.SECONDS));
+ assertThrows(TimeoutException.class, () -> append.get(200, TimeUnit.MILLISECONDS));
+ release.countDown();
+ replacement.get(5, TimeUnit.SECONDS);
+ append.get(5, TimeUnit.SECONDS);
+ assertEquals(Arrays.asList(Collections.singletonList("Replacement"), Collections.singletonList("Appended")),
+ appender.readTable(appendName).getRows());
+ } finally {
+ release.countDown();
+ executor.shutdownNow();
+ assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
+ }
+ }
+
+ @Test
+ public void symbolicTableFilesAreRejectedIncludingDanglingLinks() throws IOException {
+ final TableStore store = initialStore();
+ final Path outside = root().resolve("outside.csv");
+ Files.writeString(outside, "name;city\nGrace;Paris\n", StandardCharsets.UTF_8);
+ final byte[] before = Files.readAllBytes(outside);
+ for (final Path target : Arrays.asList(outside, root().resolve("missing.csv"))) {
+ final Path link = tableFile().resolveSibling("link.csv");
+ createSymbolicLink(link, target);
+ assertThrows(IOException.class, () -> store.readTable("link"));
+ assertThrows(IOException.class, () -> store.addRow("link", Arrays.asList("New", "Row")));
+ assertThrows(IOException.class, () -> store.editCell("link", 0, 0, "Updated"));
+ assertThrows(IOException.class,
+ () -> store.writeTable("link", Collections.singletonList("name"), Collections.emptyList()));
+ assertTrue(Files.isSymbolicLink(link));
+ assertEquals(Collections.singletonList("people"), store.listTables());
+ Files.delete(link);
+ }
+ assertArrayEquals(before, Files.readAllBytes(outside));
+ assertFalse(Files.exists(root().resolve("missing.csv")));
+ assertNoTemporaryFiles();
+ }
+
+ @Test
+ public void hardLinkedTablesAreRejectedWhenLinkCountsAreAvailable() throws IOException {
+ Assume.assumeTrue(root().getFileSystem().supportedFileAttributeViews().contains("unix"));
+ final TableStore store = initialStore();
+ final byte[] before = Files.readAllBytes(tableFile());
+ final Path alias = tableFile().resolveSibling("alias.csv");
+ Files.createLink(alias, tableFile());
+ for (final String name : Arrays.asList("people", "alias")) {
+ assertThrows(IOException.class, () -> store.readTable(name));
+ assertThrows(IOException.class, () -> store.addRow(name, Arrays.asList("New", "Row")));
+ assertThrows(IOException.class, () -> store.editCell(name, 0, 0, "Updated"));
+ assertThrows(IOException.class,
+ () -> store.writeTable(name, Collections.singletonList("name"), Collections.emptyList()));
+ }
+ assertTrue(Files.isSameFile(alias, tableFile()));
+ assertArrayEquals(before, Files.readAllBytes(alias));
+ assertNoTemporaryFiles();
+ }
+
+ @Test
+ public void directoryAtTablePathIsNeverReplaced() throws IOException {
+ final TableStore store = initialStore();
+ final Path directory = tableFile().resolveSibling("directory.csv");
+ Files.createDirectory(directory);
+ assertThrows(IOException.class,
+ () -> store.writeTable("directory", Collections.singletonList("name"), Collections.emptyList()));
+ assertTrue(Files.isDirectory(directory));
+ assertNoTemporaryFiles();
+ }
+
+ @Test
+ public void unsupportedAtomicReplacementLeavesExistingFileAndSnapshotIntact() throws IOException {
+ initialStore();
+ final byte[] before = Files.readAllBytes(tableFile());
+ final TableStore failing = new TableStore(root(), new TableStore.FileOperations() {
+ @Override
+ void replaceAtomically(final Path source, final Path target) throws IOException {
+ throw new AtomicMoveNotSupportedException(source.toString(), target.toString(), "injected");
+ }
+ });
+ final Table table = failing.openTable("people", Table.AccessMode.EDITABLE);
+ final List<List<String>> snapshot = table.getRows();
+ assertThrows(AtomicMoveNotSupportedException.class, () -> table.editCell(0, 0, "Updated"));
+ assertThrows(AtomicMoveNotSupportedException.class,
+ () -> failing.writeTable("new", Collections.singletonList("name"), Collections.emptyList()));
+ assertArrayEquals(before, Files.readAllBytes(tableFile()));
+ assertEquals(snapshot, table.getRows());
+ assertFalse(Files.exists(tableFile().resolveSibling("new.csv")));
+ assertNoTemporaryFiles();
+ }
+
+ @Test
+ public void temporaryWriteAndCloseFailuresPreserveExistingData() throws IOException {
+ initialStore();
+ final byte[] before = Files.readAllBytes(tableFile());
+ for (final boolean failOnClose : new boolean[] {false, true}) {
+ final IOException failure = new IOException("injected temporary-file failure");
+ final TableStore store = new TableStore(root(), new TableStore.FileOperations() {
+ @Override
+ BufferedWriter openWriter(final Path path) throws IOException {
+ return new BufferedWriter(super.openWriter(path)) {
+ @Override
+ public void write(final String text, final int offset, final int length) throws IOException {
+ super.write(text, offset, failOnClose ? length : Math.min(3, length));
+ flush();
+ if (!failOnClose) throw failure;
+ }
+
+ @Override
+ public void close() throws IOException {
+ super.close();
+ if (failOnClose) throw failure;
+ }
+ };
+ }
+ });
+ final Table table = store.openTable("people", Table.AccessMode.EDITABLE);
+ final List<List<String>> snapshot = table.getRows();
+ assertSame(failure, assertThrows(IOException.class, () -> table.editCell(0, 0, "Updated")));
+ assertArrayEquals(before, Files.readAllBytes(tableFile()));
+ assertEquals(snapshot, table.getRows());
+ assertNoTemporaryFiles();
+ }
+ }
+
+ @Test
+ public void cleanupFailureDoesNotHideReplacementFailure() throws IOException {
+ final TableStore normal = initialStore();
+ final byte[] before = Files.readAllBytes(tableFile());
+ final IOException writeFailure = new IOException("replacement failed");
+ final IOException cleanupFailure = new IOException("cleanup failed");
+ final TableStore store = new TableStore(root(), new TableStore.FileOperations() {
+ @Override
+ void replaceAtomically(final Path source, final Path target) throws IOException {
+ throw writeFailure;
+ }
+
+ @Override
+ void deleteTemporaryFile(final Path path) throws IOException {
+ throw cleanupFailure;
+ }
+ });
+ assertSame(writeFailure, assertThrows(IOException.class,
+ () -> store.writeTable("people", Collections.singletonList("name"), Collections.emptyList())));
+ assertArrayEquals(new Throwable[] {cleanupFailure}, writeFailure.getSuppressed());
+ assertArrayEquals(before, Files.readAllBytes(tableFile()));
+ assertEquals(Collections.singletonList("people"), normal.listTables());
+ }
+
+ private static TableStore.FileOperations partialAppendFailure(final IOException failure) {
+ return new TableStore.FileOperations() {
+ @Override
+ void write(final FileChannel channel, final ByteBuffer bytes) throws IOException {
+ if (bytes.remaining() <= 2) {
+ super.write(channel, bytes); // Let any missing final newline reach disk first.
+ return;
+ }
+ final ByteBuffer fragment = bytes.slice();
+ fragment.limit(3);
+ while (fragment.hasRemaining()) channel.write(fragment);
+ throw failure;
+ }
+ };
+ }
+
+ @Test
+ public void partialAppendRollsBackIncludingInsertedNewline() throws IOException {
+ final TableStore normal = initialStore();
+ for (final String ending : Arrays.asList("", "\n", "\r\n")) {
+ Files.writeString(tableFile(), "name;city\nAda;London" + ending, StandardCharsets.UTF_8);
+ final byte[] before = Files.readAllBytes(tableFile());
+ final IOException failure = new IOException("append failed");
+ final TableStore store = new TableStore(root(), partialAppendFailure(failure));
+ final Table table = store.openTable("people", Table.AccessMode.APPEND_ONLY);
+ final List<List<String>> snapshot = table.getRows();
+ assertSame(failure, assertThrows(IOException.class, () -> table.addRow(Arrays.asList("Grace", "Paris"))));
+ assertArrayEquals(before, Files.readAllBytes(tableFile()));
+ assertEquals(snapshot, table.getRows());
+ normal.addRow("people", Arrays.asList("Grace", "Paris"));
+ assertEquals(2, normal.readTable("people").getRows().size());
+ }
+ }
+
+ @Test
+ public void failedRollbackIsReportedWithoutUpdatingSnapshot() throws IOException {
+ initialStore();
+ final long originalSize = Files.size(tableFile());
+ final IOException failure = new IOException("append failed");
+ final IOException rollbackFailure = new IOException("rollback failed");
+ final TableStore.FileOperations partial = partialAppendFailure(failure);
+ final TableStore store = new TableStore(root(), new TableStore.FileOperations() {
+ @Override
+ void write(final FileChannel channel, final ByteBuffer bytes) throws IOException {
+ partial.write(channel, bytes);
+ }
+
+ @Override
+ void truncate(final FileChannel channel, final long size) throws IOException {
+ throw rollbackFailure;
+ }
+ });
+ final Table table = store.openTable("people", Table.AccessMode.APPEND_ONLY);
+ final List<List<String>> snapshot = table.getRows();
+ assertSame(failure, assertThrows(IOException.class, () -> table.addRow(Arrays.asList("Grace", "Paris"))));
+ assertArrayEquals(new Throwable[] {rollbackFailure}, failure.getSuppressed());
+ assertTrue(Files.size(tableFile()) > originalSize);
+ assertEquals(snapshot, table.getRows());
+ assertThrows(IOException.class, table::reload);
+ assertEquals(snapshot, table.getRows());
+ }
+
+ @Test
+ public void missingOrMalformedFilesLeaveOpenSnapshotsUnchanged() throws IOException {
+ final TableStore store = initialStore();
+ final Table table = store.openTable("people", Table.AccessMode.EDITABLE);
+ final List<List<String>> rows = table.getRows();
+ final List<String> header = table.getHeader();
+ Files.delete(tableFile());
+ assertThrows(IOException.class, table::reload);
+ assertThrows(IOException.class, () -> table.editCell(0, 0, "Updated"));
+ assertThrows(IOException.class, () -> table.addRow(Arrays.asList("Grace", "Paris")));
+ assertFalse(Files.exists(tableFile()));
+ Files.write(tableFile(), new byte[] {(byte) 0xC3, 0x28}); // Invalid UTF-8.
+ assertThrows(IOException.class, table::reload);
+ assertEquals(rows, table.getRows());
+ assertEquals(header, table.getHeader());
+ assertNoTemporaryFiles();
+ }
+}
diff --git a/test/java/net/yacy/data/tables/TableStoreTest.java b/test/java/net/yacy/data/tables/TableStoreTest.java
new file mode 100644
index 000000000..0b92a3c88
--- /dev/null
+++ b/test/java/net/yacy/data/tables/TableStoreTest.java
@@ -0,0 +1,382 @@
+package net.yacy.data.tables;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.ConcurrentModificationException;
+import java.util.HashSet;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReadWriteLock;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+public class TableStoreTest {
+
+ @Rule
+ public final TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+ @Test
+ public void writesListsAndReadsTable() throws IOException {
+ final TableStore store = new TableStore(this.temporaryFolder.getRoot());
+ store.writeTable("people", Arrays.asList("name", "city"), Arrays.asList(
+ Arrays.asList("Ada", "London"),
+ Arrays.asList("Grace", "New York")));
+
+ assertEquals(Collections.singletonList("people"), store.listTables());
+ final Table table = store.readTable("people.csv");
+ assertEquals(Table.AccessMode.READ_ONLY, table.getAccessMode());
+ assertEquals(Arrays.asList("name", "city"), table.getHeader());
+ assertEquals(Arrays.asList(
+ Arrays.asList("Ada", "London"),
+ Arrays.asList("Grace", "New York")), table.getRows());
+
+ final File csvFile = new File(this.temporaryFolder.getRoot(), "DATA/TABLES/people.csv");
+ assertEquals("name;city\nAda;London\nGrace;New York\n",
+ Files.readString(csvFile.toPath(), StandardCharsets.UTF_8).replace("\r\n", "\n"));
+ }
+
+ @Test
+ public void enforcesAccessModesAndPersistsMutationsImmediately() throws IOException {
+ final TableStore store = new TableStore(this.temporaryFolder.getRoot());
+ store.writeTable("people", Arrays.asList("name", "city"),
+ Collections.singletonList(Arrays.asList("Ada", "London")));
+
+ final Table readOnly = store.readTable("people");
+ assertThrows(IllegalStateException.class, () -> readOnly.addRow(Arrays.asList("Grace", "New York")));
+ assertThrows(IllegalStateException.class, () -> readOnly.editCell(0, 1, "Paris"));
+
+ final Path tableFile = this.temporaryFolder.getRoot().toPath().resolve("DATA/TABLES/people.csv");
+ final Object fileKeyBeforeAppend = Files.readAttributes(tableFile, BasicFileAttributes.class).fileKey();
+ final Table appendOnly = store.openTable("people", Table.AccessMode.APPEND_ONLY);
+ appendOnly.addRow(Arrays.asList("Grace", "New York"));
+ final Object fileKeyAfterAppend = Files.readAttributes(tableFile, BasicFileAttributes.class).fileKey();
+ if (fileKeyBeforeAppend != null && fileKeyAfterAppend != null) {
+ assertEquals("Appending must not replace the table file", fileKeyBeforeAppend, fileKeyAfterAppend);
+ }
+ assertThrows(IllegalStateException.class, () -> appendOnly.editCell(0, 1, "Paris"));
+ assertEquals(2, store.readTable("people").getRows().size());
+
+ final Table editable = store.openTable("people", Table.AccessMode.EDITABLE);
+ editable.editCell(0, 1, "Paris");
+ editable.addRow(Arrays.asList("Katherine", "Hampton"));
+
+ assertEquals(Arrays.asList(
+ Arrays.asList("Ada", "Paris"),
+ Arrays.asList("Grace", "New York"),
+ Arrays.asList("Katherine", "Hampton")), store.readTable("people").getRows());
+ }
+
+ @Test
+ public void reloadRefreshesSnapshotsAfterConcurrentChanges() throws IOException {
+ final TableStore store = new TableStore(this.temporaryFolder.getRoot());
+ store.writeTable("people", Collections.singletonList("name"),
+ Collections.singletonList(Collections.singletonList("Ada")));
+ final Table snapshot = store.readTable("people");
+
+ store.addRow("people", Collections.singletonList("Grace"));
+ assertEquals(1, snapshot.getRows().size());
+ snapshot.reload();
+ assertEquals(2, snapshot.getRows().size());
+ }
+
+ @Test
+ public void concurrentHandlesKeepLocalSnapshotsAndRejectStaleRowIndices() throws IOException {
+ final TableStore firstStore = new TableStore(this.temporaryFolder.getRoot());
+ final TableStore secondStore = new TableStore(this.temporaryFolder.getRoot());
+ final List<String> header = Collections.singletonList("name");
+ final List<String> ada = Collections.singletonList("Ada");
+ final List<String> grace = Collections.singletonList("Grace");
+ final List<String> katherine = Collections.singletonList("Katherine");
+ firstStore.writeTable("people", header, Collections.singletonList(ada));
+ final Table first = firstStore.openTable("people", Table.AccessMode.EDITABLE);
+ final Table second = secondStore.openTable("people", Table.AccessMode.EDITABLE);
+ final List<List<String>> originalSnapshot = second.getRows();
+
+ first.addRow(grace);
+ second.addRow(katherine);
+ assertEquals(Arrays.asList(ada, grace), first.getRows());
+ assertEquals(Arrays.asList(ada, katherine), second.getRows());
+ final List<List<String>> persisted = Arrays.asList(ada, grace, katherine);
+ assertEquals(persisted, firstStore.readTable("people").getRows());
+
+ // Row 1 in the second handle is Katherine, but row 1 on disk is Grace.
+ assertThrows(ConcurrentModificationException.class, () -> second.editCell(1, 0, "Updated"));
+ assertEquals(persisted, firstStore.readTable("people").getRows());
+ assertEquals(Arrays.asList(ada, katherine), second.getRows());
+ second.reload();
+ second.editCell(2, 0, "Updated");
+ assertEquals(Arrays.asList(ada, grace, Collections.singletonList("Updated")), second.getRows());
+ assertEquals(second.getRows(), firstStore.readTable("people").getRows());
+ assertEquals(Arrays.asList(ada, grace), first.getRows());
+ first.reload();
+ assertEquals(second.getRows(), first.getRows());
+ assertEquals(Collections.singletonList(ada), originalSnapshot);
+ }
+
+ @Test
+ public void staleCellEditsRequireReloadAfterAnotherHandleWrites() throws IOException {
+ final TableStore store = new TableStore(this.temporaryFolder.getRoot());
+ store.writeTable("people", Arrays.asList("name", "city"),
+ Collections.singletonList(Arrays.asList("Ada", "London")));
+ final Table first = store.openTable("people", Table.AccessMode.EDITABLE);
+ final Table second = store.openTable("people", Table.AccessMode.EDITABLE);
+ first.editCell(0, 1, "Paris");
+ assertThrows(ConcurrentModificationException.class, () -> second.editCell(0, 1, "Rome"));
+ assertEquals(Collections.singletonList(Arrays.asList("Ada", "London")), second.getRows());
+ assertEquals(first.getRows(), store.readTable("people").getRows());
+ second.reload();
+ second.editCell(0, 1, "Rome");
+ assertEquals(Collections.singletonList(Arrays.asList("Ada", "Rome")), store.readTable("people").getRows());
+ }
+
+ @Test
+ public void competingHandleEditsAllowExactlyOneWriterUntilReload() throws Exception {
+ final TableStore firstStore = new TableStore(this.temporaryFolder.getRoot());
+ final TableStore secondStore = new TableStore(this.temporaryFolder.getRoot());
+ firstStore.writeTable("people", Collections.singletonList("name"),
+ Collections.singletonList(Collections.singletonList("Original")));
+ final Table first = firstStore.openTable("people", Table.AccessMode.EDITABLE);
+ final Table second = secondStore.openTable("people", Table.AccessMode.EDITABLE);
+ final ExecutorService executor = Executors.newFixedThreadPool(2);
+ final CountDownLatch start = new CountDownLatch(1);
+ try {
+ final Future<Boolean> firstEdit = executor.submit(() -> {
+ start.await();
+ try {
+ first.editCell(0, 0, "First");
+ return true;
+ } catch (final ConcurrentModificationException expected) {
+ return false;
+ }
+ });
+ final Future<Boolean> secondEdit = executor.submit(() -> {
+ start.await();
+ try {
+ second.editCell(0, 0, "Second");
+ return true;
+ } catch (final ConcurrentModificationException expected) {
+ return false;
+ }
+ });
+ start.countDown();
+ final boolean firstWon = firstEdit.get(20, TimeUnit.SECONDS);
+ final boolean secondWon = secondEdit.get(20, TimeUnit.SECONDS);
+ assertTrue("Exactly one handle may edit the original snapshot", firstWon ^ secondWon);
+ final Table winner = firstWon ? first : second;
+ final Table loser = firstWon ? second : first;
+ assertEquals(winner.getRows(), firstStore.readTable("people").getRows());
+ assertEquals(Collections.singletonList(Collections.singletonList("Original")), loser.getRows());
+ loser.reload();
+ assertEquals(winner.getRows(), loser.getRows());
+ } finally {
+ executor.shutdownNow();
+ assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
+ }
+ }
+
+ @Test
+ public void replacedTableRequiresReloadBeforeEditingEvenWithTheSameHeader() throws IOException {
+ final TableStore store = new TableStore(this.temporaryFolder.getRoot());
+ final List<String> header = Arrays.asList("name", "city");
+ store.writeTable("people", header, Collections.singletonList(Arrays.asList("Ada", "London")));
+ final Table table = store.openTable("people", Table.AccessMode.EDITABLE);
+ final List<List<String>> replacement = Collections.singletonList(Arrays.asList("Grace", "New York"));
+ store.writeTable("people", header, replacement);
+ assertThrows(ConcurrentModificationException.class, () -> table.editCell(0, 1, "Paris"));
+ assertEquals(replacement, store.readTable("people").getRows());
+ table.reload();
+ table.editCell(0, 1, "Paris");
+ assertEquals(Collections.singletonList(Arrays.asList("Grace", "Paris")), table.getRows());
+ }
+
+ @Test
+ public void changedColumnsRejectHandleMutationsUntilReload() throws IOException {
+ final TableStore store = new TableStore(this.temporaryFolder.getRoot());
+ for (final List<String> changedHeader : Arrays.asList(
+ Arrays.asList("city", "name"), Arrays.asList("name", "country"),
+ Arrays.asList("name", "city", "country"), Collections.singletonList("name"))) {
+ final List<String> originalHeader = Arrays.asList("name", "city");
+ store.writeTable("people", originalHeader, Collections.emptyList());
+ final Table editable = store.openTable("people", Table.AccessMode.EDITABLE);
+ final Table appendOnly = store.openTable("people", Table.AccessMode.APPEND_ONLY);
+ store.writeTable("people", changedHeader, Collections.emptyList());
+ final Path file = this.temporaryFolder.getRoot().toPath().resolve("DATA/TABLES/people.csv");
+ final String before = Files.readString(file, StandardCharsets.UTF_8);
+ assertThrows(ConcurrentModificationException.class,
+ () -> editable.addRow(Arrays.asList("Ada", "London")));
+ assertThrows(ConcurrentModificationException.class,
+ () -> appendOnly.addRow(Arrays.asList("Grace", "New York")));
+ assertThrows(ConcurrentModificationException.class, () -> editable.editCell(0, 0, "Updated"));
+ assertEquals(before, Files.readString(file, StandardCharsets.UTF_8));
+ assertEquals(originalHeader, editable.getHeader());
+ assertEquals(originalHeader, appendOnly.getHeader());
+ assertTrue(editable.getRows().isEmpty());
+ assertTrue(appendOnly.getRows().isEmpty());
+
+ appendOnly.reload();
+ assertEquals(changedHeader, appendOnly.getHeader());
+ final List<String> row = Collections.nCopies(changedHeader.size(), "value");
+ appendOnly.addRow(row);
+ assertEquals(Collections.singletonList(row), store.readTable("people").getRows());
+ editable.reload();
+ editable.editCell(0, 0, "Updated");
+ assertEquals("Updated", store.readTable("people").getRows().get(0).get(0));
+ }
+ }
+
+ @Test
+ public void storeOperationsUseCurrentDataAndSnapshotExportExplicitlyReplacesIt() throws IOException {
+ final TableStore store = new TableStore(this.temporaryFolder.getRoot());
+ store.writeTable("people", Collections.singletonList("name"),
+ Collections.singletonList(Collections.singletonList("Ada")));
+ final Table original = store.readTable("people");
+ store.writeTable("people", Arrays.asList("name", "city"),
+ Collections.singletonList(Arrays.asList("Grace", "New York")));
+ store.addRow("people", Arrays.asList("Katherine", "Hampton"));
+ store.editCell("people", 0, 1, "Paris");
+ assertEquals(Arrays.asList(Arrays.asList("Grace", "Paris"), Arrays.asList("Katherine", "Hampton")),
+ store.readTable("people").getRows());
+ assertEquals(Collections.singletonList("name"), original.getHeader());
+ // Export is an explicit complete replacement, including when its source snapshot is stale.
+ store.writeTable("people", original);
+ assertEquals(original.getHeader(), store.readTable("people").getHeader());
+ assertEquals(original.getRows(), store.readTable("people").getRows());
+ }
+
+ @Test
+ public void rejectsSemicolonsThroughAllMutationPaths() throws IOException {
+ final TableStore store = new TableStore(this.temporaryFolder.getRoot());
+ assertThrows(IllegalArgumentException.class, () -> store.writeTable("invalid-header",
+ Arrays.asList("name", "ci;ty"), Collections.emptyList()));
+
+ store.writeTable("people", Arrays.asList("name", "city"),
+ Collections.singletonList(Arrays.asList("Ada", "London")));
+ final Table appendOnly = store.openTable("people", Table.AccessMode.APPEND_ONLY);
+ final Table editable = store.openTable("people", Table.AccessMode.EDITABLE);
+ assertThrows(IllegalArgumentException.class,
+ () -> appendOnly.addRow(Arrays.asList("Grace;Hopper", "New York")));
+ assertThrows(IllegalArgumentException.class, () -> editable.editCell(0, 1, "Paris;France"));
+ assertThrows(IllegalArgumentException.class,
+ () -> store.addRow("people", Arrays.asList("Grace", "New;York")));
+ }
+
+ @Test
+ public void boundsLockCountAcrossManyMissingTables() throws Exception {
+ final Path root = this.temporaryFolder.getRoot().toPath();
+ final TableStore store = new TableStore(root);
+ store.listTables(); // Ensure missing-file reads reach the shared locking path.
+ // Lock identities expose retained synchronization resources without relying on GC or heap-size estimates.
+ final Method lockFor = TableStore.class.getDeclaredMethod("lockFor", Path.class);
+ lockFor.setAccessible(true);
+ final Set<ReadWriteLock> locks = Collections.newSetFromMap(new IdentityHashMap<>());
+ final Path firstTable = root.resolve("DATA/TABLES/missing-0.csv");
+ final ReadWriteLock firstLock = (ReadWriteLock) lockFor.invoke(null, firstTable);
+ for (int i = 0; i < 4096; i++) {
+ final String name = "missing-" + i;
+ assertThrows(IOException.class, () -> store.readTable(name));
+ locks.add((ReadWriteLock) lockFor.invoke(null, root.resolve("DATA/TABLES/" + name + ".csv")));
+ }
+ assertTrue("Distinct table names must use at most 256 shared locks, got " + locks.size(),
+ locks.size() <= 256);
+ assertSame("A table's lock must remain stable after other lookups", firstLock,
+ lockFor.invoke(null, firstTable));
+ }
+
+ @Test
+ public void serializesConcurrentAppendsAndEditsAcrossStoreInstances() throws Exception {
+ final TableStore firstStore = new TableStore(this.temporaryFolder.getRoot());
+ final TableStore secondStore = new TableStore(this.temporaryFolder.getRoot().toPath().resolve("unused/.."));
+ firstStore.writeTable("events", Arrays.asList("source", "value"),
+ Collections.singletonList(Arrays.asList("root", "initial")));
+
+ final int appenderCount = 4;
+ final int rowsPerAppender = 40;
+ final ExecutorService executor = Executors.newFixedThreadPool(appenderCount + 1);
+ final CountDownLatch start = new CountDownLatch(1);
+ final Future<?>[] futures = new Future<?>[appenderCount + 1];
+ try {
+ for (int thread = 0; thread < appenderCount; thread++) {
+ final int threadIndex = thread;
+ futures[thread] = executor.submit(() -> {
+ start.await();
+ final TableStore store = threadIndex % 2 == 0 ? firstStore : secondStore;
+ for (int row = 0; row < rowsPerAppender; row++) {
+ store.addRow(threadIndex % 2 == 0 ? "events" : "events.csv",
+ Arrays.asList("thread-" + threadIndex, "row-" + row));
+ }
+ return null;
+ });
+ }
+ futures[appenderCount] = executor.submit(() -> {
+ start.await();
+ for (int edit = 0; edit < 10; edit++) {
+ secondStore.editCell("events", 0, 1, "edit-" + edit);
+ }
+ return null;
+ });
+
+ start.countDown();
+ for (final Future<?> future : futures) {
+ future.get(20, TimeUnit.SECONDS);
+ }
+ } finally {
+ executor.shutdownNow();
+ assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
+ }
+
+ final List<List<String>> rows = firstStore.readTable("events").getRows();
+ assertEquals(1 + appenderCount * rowsPerAppender, rows.size());
+ assertEquals(Arrays.asList("root", "edit-9"), rows.get(0));
+ final Set<String> appendedRows = new HashSet<>();
+ for (int row = 1; row < rows.size(); row++) {
+ appendedRows.add(rows.get(row).get(0) + ":" + rows.get(row).get(1));
+ }
+ assertEquals(appenderCount * rowsPerAppender, appendedRows.size());
+ }
+
+ @Test
+ public void rejectsMissingHeaderAndRowsWithWrongWidth() throws IOException {
+ final File tablesDirectory = new File(this.temporaryFolder.getRoot(), "DATA/TABLES");
+ Files.createDirectories(tablesDirectory.toPath());
+ Files.writeString(new File(tablesDirectory, "empty.csv").toPath(), "", StandardCharsets.UTF_8);
+ Files.writeString(new File(tablesDirectory, "wide.csv").toPath(), "a;b\n1;2;3\n",
+ StandardCharsets.UTF_8);
+
+ final TableStore store = new TableStore(this.temporaryFolder.getRoot());
+ assertThrows(IOException.class, () -> store.readTable("empty"));
+ assertThrows(IOException.class, () -> store.readTable("wide"));
+ assertThrows(IllegalArgumentException.class, () -> store.writeTable("no-header",
+ Collections.emptyList(), Collections.emptyList()));
+ assertThrows(IllegalArgumentException.class, () -> store.writeTable("wrong-width",
+ Arrays.asList("a", "b"), Collections.singletonList(Collections.singletonList("1"))));
+ }
+
+ @Test
+ public void rejectsPathsAsTableNames() {
+ final TableStore store = new TableStore(this.temporaryFolder.getRoot());
+ assertThrows(IllegalArgumentException.class, () -> store.readTable("../outside"));
+ assertThrows(IllegalArgumentException.class, () -> store.readTable("nested/table"));
+ assertThrows(IllegalArgumentException.class, () -> store.readTable("nested\\table"));
+ assertThrows(IllegalArgumentException.class, () -> store.readTable(".csv"));
+ }
+}