From f10fcb7806be63820cefaac018eec4c2773a6e71 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 08:05:48 +0000 Subject: [PATCH] perf: append measurements to CSV and SQLite instead of rewriting Every measurement read the whole data file, added one row and wrote the whole file again, so storing became slower as data grew (e.g. 184 ms per measurement with 100,000 CSV rows), all data was kept in memory, and concurrent requests could lose measurements. - CSV: only the header is read and the row is appended (about 3 ms per measurement with 1,000,000 rows). If the header lacks a configured column (e.g. a column was added, or timestamps enabled later), the file is rewritten once with the new column - SQLite: rows are inserted; missing columns are added with ALTER TABLE. New tables have untyped columns, so values keep their type (a first measurement with a missing value no longer makes a column text). Lists and objects are stored as JSON - JSON and XML still rewrite the file (to be changed separately) - Lock the stored data while writing and reading (lock file next to the data file, works between threads and processes on Linux, macOS and Windows), so concurrent measurements, also from several gunicorn workers, are all stored, and /data, /export and /explore never read a half-written row - Values are stored as sent (e.g. 21 no longer becomes 21.0), and earlier rows are no longer changed by later measurements - Fix a 500 error when several processes create the data folder at the same time - Keep only the last stored row in memory after a measurement - Document the storage and the lock file, and add tests Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VCvw8haRnmyrVKrLkz5Yf8 --- README.md | 2 + docs/getting_started.rst | 2 + succulent/explore.py | 19 +-- succulent/processing.py | 314 ++++++++++++++++++++++++++++++--------- tests/test_storage.py | 307 ++++++++++++++++++++++++++++++++++++++ 5 files changed, 556 insertions(+), 88 deletions(-) create mode 100644 tests/test_storage.py diff --git a/README.md b/README.md index e3ab658..dbd0dd6 100644 --- a/README.md +++ b/README.md @@ -199,6 +199,8 @@ data: max: # Maximum value (optional) ``` +Measurements are stored in the `data` folder next to your script (e.g. `data/data.csv`). With the `csv` and `sqlite` formats, each measurement is appended to the file, so storing it takes the same time however much data is already stored, which keeps succulent fast on limited hardware such as a Raspberry Pi. Measurements that arrive at the same time, also from several server processes (e.g. gunicorn workers), are all stored. A small lock file (e.g. `data/.data.csv.lock`) is used for this; it can be ignored. + To collect images, create a `configuration.yml` file in the root directory and define the following: ```yml data: diff --git a/docs/getting_started.rst b/docs/getting_started.rst index 96607f9..dbd3a6c 100644 --- a/docs/getting_started.rst +++ b/docs/getting_started.rst @@ -68,6 +68,8 @@ In the root directory, create a ``configuration.yml`` file and define the follow min: # Minimum value (optional) max: # Maximum value (optional) +Measurements are stored in the ``data`` folder next to your script (e.g. ``data/data.csv``). With the ``csv`` and ``sqlite`` formats, each measurement is appended to the file, so storing it takes the same time however much data is already stored, which keeps succulent fast on limited hardware such as a Raspberry Pi. Measurements that arrive at the same time, also from several server processes (e.g. gunicorn workers), are all stored. A small lock file (e.g. ``data/.data.csv.lock``) is used for this; it can be ignored. + To collect images, create a ``configuration.yml`` file in the root directory and define the following: .. code:: yaml diff --git a/succulent/explore.py b/succulent/explore.py index 09c6bd8..53f93d9 100644 --- a/succulent/explore.py +++ b/succulent/explore.py @@ -15,7 +15,6 @@ import math import os import secrets -import sqlite3 from datetime import datetime, timedelta import numpy as np @@ -292,21 +291,9 @@ def load(self): pandas.DataFrame: The stored data (empty if there is none yet). """ path = os.path.join(self.processing.directory, f'data.{self.processing.format}') - if not os.path.exists(path): - return pd.DataFrame() - - fmt = self.processing.format - if fmt == 'csv': - return pd.read_csv(path, sep=',') - if fmt == 'json': - return pd.read_json(path, orient='records') - if fmt == 'xml': - return pd.read_xml(path) - conn = sqlite3.connect(path) - try: - return pd.read_sql_query('SELECT * FROM data', conn) - finally: - conn.close() + # Locked, so a measurement being written is never read half-way + with self.processing.storage_lock(): + return self.processing.load(path) def bounds(self): """Map each column with a boundary to its minimum and maximum. diff --git a/succulent/processing.py b/succulent/processing.py index d14ec29..df784bb 100644 --- a/succulent/processing.py +++ b/succulent/processing.py @@ -1,8 +1,11 @@ import os import re import hmac +import json +import time import sqlite3 import inspect +from contextlib import contextmanager import xml.etree.ElementTree as ET import pandas as pd from datetime import datetime @@ -26,7 +29,8 @@ class Processing: timestamp (bool): Enable timestamp storage for the data collection. enable_results (bool): Enable access to the collected data via the API. enable_export (bool): Enable collected data export via the API. - df (pandas.DataFrame): The DataFrame to hold the data (for 'csv', 'json', and 'sqlite' formats). + df (pandas.DataFrame): The data for the table formats: after a measurement, the stored row + (all data only when the file had to be rewritten); after /data or /export, all data. key (str): The key to retrieve the image file from the request (for 'image' format). allowed_extensions (list): File extensions accepted for uploaded images (for 'image' format). @@ -379,6 +383,218 @@ def authorised(self, req): ] return any(matches) + @contextmanager + def storage_lock(self, timeout=30): + """Lock the stored data while it is written or read. + + Uses a lock file next to the data file, so it works between threads + and between processes (e.g. several gunicorn workers), on Linux, + macOS and Windows. + + Args: + timeout (float): Seconds to wait for the lock (Windows only; + elsewhere the wait is not limited). + + Raises: + TimeoutError: The lock was not released in time. + + Yields: + None + """ + os.makedirs(self.directory, exist_ok=True) + lock_path = os.path.join(self.directory, f'.data.{self.format}.lock') + with open(lock_path, 'a+b') as handle: + if os.name == 'nt': + import msvcrt + deadline = time.monotonic() + timeout + while True: + try: + handle.seek(0) + msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1) + break + except OSError: + if time.monotonic() > deadline: + raise TimeoutError('The stored data is locked by another request.') from None + time.sleep(0.02) + try: + yield + finally: + handle.seek(0) + msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1) + else: + import fcntl + fcntl.flock(handle, fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(handle, fcntl.LOCK_UN) + + def load(self, path): + """Read all stored data of a table format. + + Args: + path (str): Path to the data file. + + Returns: + pandas.DataFrame: The stored data (empty if there is none). + """ + if not os.path.exists(path) or os.path.getsize(path) == 0: + return pd.DataFrame() + if self.format == 'csv': + return pd.read_csv(path, sep=',') + if self.format == 'json': + return pd.read_json(path, orient='records') + if self.format == 'xml': + return pd.read_xml(path) + if self.format == 'sqlite': + conn = sqlite3.connect(path) + try: + return pd.read_sql_query('SELECT * FROM data', conn) + finally: + conn.close() + raise ValueError(f'Invalid file type: {self.format}') + + def rewrite(self, path, row): + """Store a row by reading all data and writing the whole file again. + + Used for the json and xml formats, and for csv and sqlite when the + stored columns do not include all configured columns (e.g. after a + column was added to the configuration). + + Args: + path (str): Path to the data file. + row (pandas.DataFrame): The new row. + + Returns: + None + """ + existing = self.load(path) + if existing.empty and not len(existing.columns): + existing = pd.DataFrame(columns=self.columns) + self.df = pd.concat([existing, row], ignore_index=True) + + if self.format == 'csv': + self.df.to_csv(path, sep=',', index=False) + elif self.format == 'json': + self.df.to_json(path, orient='records', indent=4) + elif self.format == 'xml': + self.df.to_xml(path, index=False) + elif self.format == 'sqlite': + conn = sqlite3.connect(path) + try: + self.df.to_sql('data', conn, if_exists='replace', index=False) + finally: + conn.close() + + def append_csv(self, path, row): + """Append a row to the CSV file without reading the stored data. + + Only the header is read. If the file is new or empty, it is created + with a header. If the header lacks a configured column, the file is + rewritten once with the new column (see :meth:`rewrite`). + + Args: + path (str): Path to the CSV file. + row (pandas.DataFrame): The new row. + + Returns: + None + """ + if not os.path.exists(path) or os.path.getsize(path) == 0: + row.to_csv(path, sep=',', index=False) + self.df = row.reset_index(drop=True) + return + + try: + header = list(pd.read_csv(path, sep=',', nrows=0).columns) + except (pd.errors.EmptyDataError, pd.errors.ParserError): + header = [] + if not header or not set(row.columns) <= set(header) or len(set(header)) != len(header): + self.rewrite(path, row) + return + + # Same order as the file; stored columns no longer configured stay empty + row = row.reindex(columns=header) + + # Make sure the new row starts on its own line + with open(path, 'rb') as f: + f.seek(-1, os.SEEK_END) + ends_with_newline = f.read(1) == b'\n' + if not ends_with_newline: + with open(path, 'a', newline='') as f: + f.write(os.linesep) + + row.to_csv(path, sep=',', index=False, header=False, mode='a') + self.df = row.reset_index(drop=True) + + @staticmethod + def quote_identifier(name): + """Quote a column name for use in an SQL statement. + + Args: + name (str): The column name. + + Returns: + str: The quoted name. + """ + return '"' + str(name).replace('"', '""') + '"' + + @staticmethod + def sqlite_value(value): + """Convert a value to a type SQLite can store. + + Args: + value: A value from the request. + + Returns: + The value as None, int, float, str or bytes. + """ + if value is None: + return None + if isinstance(value, float) and value != value: + return None + if isinstance(value, (bool, int, float, str, bytes)): + return value + if isinstance(value, (list, dict)): + return json.dumps(value) + if pd.isna(value): + return None + return str(value) + + def append_sqlite(self, path, row): + """Insert a row into the SQLite table without reading the stored data. + + If the table is new, it is created. If it lacks a configured column, + the column is added (``ALTER TABLE``). New columns have no declared + type, so each value keeps the type it was sent with (a first + measurement with a missing value does not make the column text). + + Args: + path (str): Path to the SQLite database. + row (pandas.DataFrame): The new row. + + Returns: + None + """ + conn = sqlite3.connect(path, timeout=30) + try: + columns = [info[1] for info in conn.execute('PRAGMA table_info(data)')] + with conn: + if not columns: + names = ', '.join(self.quote_identifier(c) for c in row.columns) + conn.execute(f'CREATE TABLE data ({names})') + columns = list(row.columns) + for column in row.columns: + if column not in columns: + conn.execute(f'ALTER TABLE data ADD COLUMN {self.quote_identifier(column)}') + names = ', '.join(self.quote_identifier(c) for c in row.columns) + marks = ', '.join('?' for _ in row.columns) + values = [self.sqlite_value(v) for v in row.iloc[0].tolist()] + conn.execute(f'INSERT INTO data ({names}) VALUES ({marks})', values) + self.df = row.reset_index(drop=True) + finally: + conn.close() + def process(self, req): """Process the incoming request and store the data accordingly. @@ -397,8 +613,8 @@ def process(self, req): now = datetime.now() # Directory preparation - if not os.path.exists(self.directory): - os.makedirs(self.directory) + # exist_ok: several processes may create it at the same time + os.makedirs(self.directory, exist_ok=True) # Password check if not self.authorised(req): @@ -410,24 +626,6 @@ def process(self, req): self.directory, f'data.{self.format}' ) - # Load existing data - if os.path.exists(path): - if self.format == 'csv': - self.df = pd.read_csv(path, sep=',') - elif self.format == 'json': - self.df = pd.read_json(path, orient='records') - elif self.format == 'sqlite': - conn = sqlite3.connect(path) - self.df = pd.read_sql_query('SELECT * FROM data', conn) - conn.close() - elif self.format == 'xml': - self.df = pd.read_xml(path) - else: - raise ValueError(f'Invalid file type: {self.format}') - # Initialise new data - else: - self.df = pd.DataFrame(columns=self.columns) - # Parse data from request (once, before checking the columns) values = self.request_values(req) @@ -444,28 +642,26 @@ def process(self, req): else: data[column] = value - # Convert data to Series - data = pd.Series(data, index=self.columns) + # Convert data to Series (object dtype, so values are stored as + # sent, e.g. 21 stays 21 instead of becoming 21.0) + data = pd.Series(data, index=self.columns, dtype=object) # Timestamp if self.timestamp: data['timestamp'] = now.strftime('%Y-%m-%d %H:%M:%S') - # Merge data - self.df = pd.concat( - [self.df, data.to_frame().T], ignore_index=True) - - # Store data to device - if self.format == 'csv': - self.df.to_csv(path, sep=',', index=False) - elif self.format == 'json': - self.df.to_json(path, orient='records', indent=4) - elif self.format == 'xml': - self.df.to_xml(path, index=False) - elif self.format == 'sqlite': - conn = sqlite3.connect(path) - self.df.to_sql('data', conn, if_exists='replace', index=False) - conn.close() + # Store data to device: append the new row instead of rewriting + # the whole file (csv, sqlite), so storing takes the same time + # however much data is stored. Concurrent requests and readers + # are serialised by a lock. + row = data.to_frame().T + with self.storage_lock(): + if self.format == 'csv': + self.append_csv(path, row) + elif self.format == 'sqlite': + self.append_sqlite(path, row) + else: + self.rewrite(path, row) if self.format == 'image': # Retrieve image from request @@ -523,23 +719,10 @@ def data(self, req): self.directory, f'data.{self.format}' ) - # Load existing data - if os.path.exists(path): - if self.format == 'csv': - self.df = pd.read_csv(path, sep=',') - elif self.format == 'json': - self.df = pd.read_json(path, orient='records') - elif self.format == 'sqlite': - conn = sqlite3.connect(path) - self.df = pd.read_sql_query('SELECT * FROM data', conn) - conn.close() - elif self.format == 'xml': - self.df = pd.read_xml(path) - else: - raise ValueError(f'Invalid file type: {self.format}') - else: - # No stored data (e.g. file removed): do not reuse stale data - self.df = pd.DataFrame() + # Load existing data (empty if the file was removed: do not + # reuse stale data), locked so a row being written is not read + with self.storage_lock(): + self.df = self.load(path) # Check if data is available if self.df.empty: @@ -572,23 +755,10 @@ def export(self, req): self.directory, f'data.{self.format}' ) - # Load existing data - if os.path.exists(path): - if self.format == 'csv': - self.df = pd.read_csv(path, sep=',') - elif self.format == 'json': - self.df = pd.read_json(path, orient='records') - elif self.format == 'sqlite': - conn = sqlite3.connect(path) - self.df = pd.read_sql_query('SELECT * FROM data', conn) - conn.close() - elif self.format == 'xml': - self.df = pd.read_xml(path) - else: - raise ValueError(f'Invalid file type: {self.format}') - else: - # No stored data (e.g. file removed): do not reuse stale data - self.df = pd.DataFrame() + # Load existing data (empty if the file was removed: do not + # reuse stale data), locked so a row being written is not read + with self.storage_lock(): + self.df = self.load(path) # Check if data is available if self.df.empty: diff --git a/tests/test_storage.py b/tests/test_storage.py new file mode 100644 index 0000000..ee6a163 --- /dev/null +++ b/tests/test_storage.py @@ -0,0 +1,307 @@ +import multiprocessing +import os +import shutil +import sqlite3 +import tempfile +import threading +import unittest +from unittest import mock + +import pandas as pd +import yaml + +from succulent.api import SucculentAPI + + +CONFIG = { + 'data': [ + {'name': 'temperature', 'min': -20, 'max': 60}, + {'name': 'humidity'}, + {'name': 'sensor'}, + ], + 'results': [{'enable': True}], +} + + +class StorageTestCase(unittest.TestCase): + """Base class: builds an API from a configuration dictionary.""" + + def make_api(self, config=None, format='csv', clear=True): + handle, path = tempfile.mkstemp(suffix='.yml') + with os.fdopen(handle, 'w') as f: + yaml.safe_dump(config or CONFIG, f) + self.addCleanup(os.remove, path) + api = SucculentAPI(config=path, format=format) + if clear: + shutil.rmtree(api.processing.directory, ignore_errors=True) + self.addCleanup(shutil.rmtree, api.processing.directory, True) + return api, api.app.test_client() + + def path(self, api): + return os.path.join(api.processing.directory, f'data.{api.processing.format}') + + def post(self, client, **values): + response = client.post('/measure', json=values) + self.assertEqual(response.status_code, 200, response.get_json()) + return response + + +class TestCsvAppend(StorageTestCase): + + def setUp(self): + self.api, self.client = self.make_api() + + def read(self): + with open(self.path(self.api), newline='') as f: + return f.read().splitlines() + + def test_rows_are_appended(self): + self.post(self.client, temperature=20, humidity=40, sensor='a') + self.post(self.client, temperature=21.5, sensor='b') + self.post(self.client, humidity=42) + self.assertEqual(self.read(), [ + 'temperature,humidity,sensor', + '20,40,a', + '21.5,,b', + ',42,', + ]) + + def test_stored_data_is_not_read(self): + self.post(self.client, temperature=20) + real = pd.read_csv + calls = [] + + def spy(*args, **kwargs): + calls.append(kwargs.get('nrows')) + return real(*args, **kwargs) + + with mock.patch('succulent.processing.pd.read_csv', side_effect=spy): + self.post(self.client, temperature=21) + # Only the header is read + self.assertEqual(calls, [0]) + + def test_earlier_values_are_not_changed(self): + # Before, the whole file was read and written again on every + # measurement, so e.g. "007" became 7 and 20 became 20.0 + self.post(self.client, temperature=20, sensor='007') + self.post(self.client, temperature=21.5, sensor='008') + self.post(self.client, sensor='009') + self.assertEqual(self.read()[1:], ['20,,007', '21.5,,008', ',,009']) + + def test_new_column_in_configuration(self): + self.post(self.client, temperature=20) + config = dict(CONFIG, data=CONFIG['data'] + [{'name': 'light'}]) + api, client = self.make_api(config, clear=False) + self.post(client, temperature=21, light=300) + self.post(client, temperature=22, light=310) + self.assertEqual(self.read(), [ + 'temperature,humidity,sensor,light', + '20,,,', + '21,,,300', + '22,,,310', + ]) + + def test_timestamp_enabled_later(self): + self.post(self.client, temperature=20) + api, client = self.make_api(dict(CONFIG, timestamp=True), clear=False) + self.post(client, temperature=21) + lines = self.read() + self.assertEqual(lines[0], 'temperature,humidity,sensor,timestamp') + self.assertEqual(lines[1], '20,,,') + self.assertRegex(lines[2], r'^21,,,\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$') + + def test_column_removed_from_configuration(self): + self.post(self.client, temperature=20, sensor='a') + config = dict(CONFIG, data=CONFIG['data'][:2]) + api, client = self.make_api(config, clear=False) + self.post(client, temperature=21) + # The stored column stays, empty for new rows + self.assertEqual(self.read(), ['temperature,humidity,sensor', '20,,a', '21,,']) + + def test_file_without_trailing_newline(self): + os.makedirs(self.api.processing.directory, exist_ok=True) + with open(self.path(self.api), 'w', newline='') as f: + f.write('temperature,humidity,sensor\n20,40,a') + self.post(self.client, temperature=21) + self.assertEqual(self.read(), ['temperature,humidity,sensor', '20,40,a', '21,,']) + + def test_empty_file(self): + os.makedirs(self.api.processing.directory, exist_ok=True) + open(self.path(self.api), 'w').close() + self.post(self.client, temperature=21) + self.assertEqual(self.read(), ['temperature,humidity,sensor', '21,,']) + + def test_values_with_commas_and_quotes(self): + self.post(self.client, sensor='a, "b"') + self.post(self.client, sensor='c') + data = self.client.get('/data').get_json()['data'] + self.assertEqual([row['sensor'] for row in data], ['a, "b"', 'c']) + + def test_last_row_is_kept_in_memory(self): + self.post(self.client, temperature=20) + self.post(self.client, temperature=21) + self.assertEqual(len(self.api.processing.df), 1) + self.assertEqual(self.api.processing.df.iloc[-1]['temperature'], 21) + + +class TestSqliteAppend(StorageTestCase): + + def setUp(self): + self.api, self.client = self.make_api(format='sqlite') + + def rows(self, api=None): + conn = sqlite3.connect(self.path(api or self.api)) + try: + cursor = conn.execute('SELECT * FROM data') + return [d[0] for d in cursor.description], cursor.fetchall() + finally: + conn.close() + + def test_rows_are_inserted(self): + self.post(self.client, temperature=20, humidity=40, sensor='a') + self.post(self.client, temperature=21.5, sensor='b') + columns, rows = self.rows() + self.assertEqual(columns, ['temperature', 'humidity', 'sensor']) + self.assertEqual(rows, [(20, 40, 'a'), (21.5, None, 'b')]) + + def test_stored_data_is_not_read(self): + self.post(self.client, temperature=20) + with mock.patch('succulent.processing.pd.read_sql_query') as read: + self.post(self.client, temperature=21) + read.assert_not_called() + self.assertEqual(len(self.rows()[1]), 2) + + def test_new_column_in_configuration(self): + self.post(self.client, temperature=20) + config = dict(CONFIG, timestamp=True, data=CONFIG['data'] + [{'name': 'light "lux"'}]) + api, client = self.make_api(config, format='sqlite', clear=False) + self.post(client, temperature=21, **{'light "lux"': 300}) + columns, rows = self.rows(api) + self.assertEqual(columns, ['temperature', 'humidity', 'sensor', 'light "lux"', 'timestamp']) + self.assertEqual(rows[0], (20, None, None, None, None)) + self.assertEqual(rows[1][:4], (21, None, None, 300)) + + def test_lists_and_objects_are_stored_as_json(self): + self.post(self.client, sensor={'id': 7, 'tags': ['a', 'b']}) + self.post(self.client, sensor=[1, 2]) + self.assertEqual([r[2] for r in self.rows()[1]], ['{"id": 7, "tags": ["a", "b"]}', '[1, 2]']) + + def test_first_value_missing_keeps_numbers(self): + self.post(self.client, sensor='a') + self.post(self.client, temperature=21.5, humidity=40) + self.assertEqual(self.rows()[1][1], (21.5, 40, None)) + data = self.client.get('/data').get_json()['data'] + self.assertEqual(data[1]['temperature'], 21.5) + + def test_existing_database_from_older_version(self): + # Table created by pandas (with declared types), as before + os.makedirs(self.api.processing.directory, exist_ok=True) + conn = sqlite3.connect(self.path(self.api)) + pd.DataFrame([{'temperature': 20.0, 'humidity': 40.0, 'sensor': 'a'}]).to_sql('data', conn, index=False) + conn.close() + self.post(self.client, temperature=21, sensor='b') + self.assertEqual(self.rows()[1], [(20.0, 40.0, 'a'), (21.0, None, 'b')]) + + def test_data_endpoint(self): + self.post(self.client, temperature=20, sensor='a') + self.post(self.client, temperature=21, sensor='b') + data = self.client.get('/data').get_json()['data'] + self.assertEqual([r['sensor'] for r in data], ['a', 'b']) + + +def store_in_process(config_path, fmt, number, count): + """Send measurements from a separate process (like a gunicorn worker).""" + from succulent.api import SucculentAPI + client = SucculentAPI(config=config_path, format=fmt).app.test_client() + failed = 0 + for i in range(count): + response = client.post('/measure', json={'temperature': number, 'humidity': i}) + failed += response.status_code != 200 + return failed + + +class TestConcurrentWrites(StorageTestCase): + """Measurements sent at the same time must all be stored.""" + + THREADS = 8 + PER_THREAD = 15 + + def run_threads(self, api): + errors = [] + + def worker(n): + client = api.app.test_client() + for i in range(self.PER_THREAD): + response = client.post('/measure', json={'temperature': n, 'humidity': i}) + if response.status_code != 200: + errors.append(response.get_json()) + + threads = [threading.Thread(target=worker, args=(n,)) for n in range(self.THREADS)] + for t in threads: + t.start() + for t in threads: + t.join() + self.assertEqual(errors, []) + + def test_all_rows_are_stored(self): + for fmt in ['csv', 'sqlite', 'json', 'xml']: + with self.subTest(format=fmt): + api, client = self.make_api(format=fmt) + self.run_threads(api) + data = client.get('/data').get_json()['data'] + self.assertEqual(len(data), self.THREADS * self.PER_THREAD) + pairs = {(int(r['temperature']), int(r['humidity'])) for r in data} + self.assertEqual(len(pairs), self.THREADS * self.PER_THREAD) + shutil.rmtree(api.processing.directory, ignore_errors=True) + + def test_all_rows_are_stored_from_several_processes(self): + processes, per_process = 4, 20 + for fmt in ['csv', 'sqlite', 'json', 'xml']: + with self.subTest(format=fmt): + handle, config_path = tempfile.mkstemp(suffix='.yml') + with os.fdopen(handle, 'w') as f: + yaml.safe_dump(CONFIG, f) + self.addCleanup(os.remove, config_path) + api = SucculentAPI(config=config_path, format=fmt) + shutil.rmtree(api.processing.directory, ignore_errors=True) + self.addCleanup(shutil.rmtree, api.processing.directory, True) + + context = multiprocessing.get_context('spawn') + with context.Pool(processes) as pool: + failed = pool.starmap(store_in_process, + [(config_path, fmt, n, per_process) for n in range(processes)]) + self.assertEqual(sum(failed), 0) + + data = api.app.test_client().get('/data').get_json()['data'] + pairs = {(int(r['temperature']), int(r['humidity'])) for r in data} + self.assertEqual(len(data), processes * per_process) + self.assertEqual(len(pairs), processes * per_process) + shutil.rmtree(api.processing.directory, ignore_errors=True) + + def test_reading_while_writing(self): + api, client = self.make_api() + self.post(client, temperature=1) + failures = [] + stop = threading.Event() + + def reader(): + reader_client = api.app.test_client() + while not stop.is_set(): + response = reader_client.get('/data') + if response.status_code != 200: + failures.append(response.get_json()) + + threads = [threading.Thread(target=reader) for _ in range(2)] + for t in threads: + t.start() + try: + self.run_threads(api) + finally: + stop.set() + for t in threads: + t.join() + self.assertEqual(failures, []) + + +if __name__ == '__main__': + unittest.main()