diff --git a/README.md b/README.md index dbd0dd6..06ac524 100644 --- a/README.md +++ b/README.md @@ -199,7 +199,7 @@ 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. +Measurements are stored in the `data` folder next to your script (e.g. `data/data.csv`). Each measurement is appended to the file (also for `json` and `xml`, where it is inserted before the closing `]` or ``), 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. The files keep the same format as written by earlier versions. 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 diff --git a/docs/getting_started.rst b/docs/getting_started.rst index dbd3a6c..2b0fb05 100644 --- a/docs/getting_started.rst +++ b/docs/getting_started.rst @@ -68,7 +68,7 @@ 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. +Measurements are stored in the ``data`` folder next to your script (e.g. ``data/data.csv``). Each measurement is appended to the file (also for ``json`` and ``xml``, where it is inserted before the closing ``]`` or ````), 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. The files keep the same format as written by earlier versions. 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: diff --git a/succulent/processing.py b/succulent/processing.py index df784bb..b8822b7 100644 --- a/succulent/processing.py +++ b/succulent/processing.py @@ -457,9 +457,9 @@ def load(self, path): 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). + Used when a file is new, when the stored columns do not include all + configured columns (e.g. after a column was added to the + configuration), or when a json or xml file does not look as expected. Args: path (str): Path to the data file. @@ -595,6 +595,217 @@ def append_sqlite(self, path, row): finally: conn.close() + # Bytes read from the start of a JSON or XML file to find the stored + # columns, and from its end to find where the next row goes + HEAD_LIMIT = 1024 * 1024 + TAIL_BYTES = 4096 + + def stored_tail(self, path, closing): + """Find where a new row can be inserted at the end of a JSON or XML file. + + Only the last bytes of the file are read. + + Args: + path (str): Path to the data file. + closing (bytes): The closing text of the file (``]`` or ````). + + Returns: + tuple or None: The position of ``closing`` and the bytes after it, + or None if the end of the file does not look as expected. + """ + size = os.path.getsize(path) + start = max(0, size - self.TAIL_BYTES) + with open(path, 'rb') as f: + f.seek(start) + tail = f.read() + position = tail.rfind(closing) + if position < 0 or tail[position + len(closing):].strip(): + return None + return start + position, tail[position + len(closing):] + + def json_columns(self, path): + """Read the column names of a JSON file from its first record. + + Only the start of the file is read. + + Args: + path (str): Path to the JSON file. + + Returns: + list or None: The keys of the first record, or None if the file + does not start with a JSON array of objects. + """ + decoder = json.JSONDecoder() + size = 65536 + while True: + with open(path, 'rb') as f: + head = f.read(size) + try: + text = head.decode('utf-8') + except UnicodeDecodeError as err: + # A multi-byte character cut at the end of the chunk + text = head[:err.start].decode('utf-8', errors='ignore') + index = len(text) - len(text.lstrip()) + if not text[index:index + 1] == '[': + return None + index += 1 + while index < len(text) and text[index].isspace(): + index += 1 + try: + record, _ = decoder.raw_decode(text, index) + except json.JSONDecodeError: + if len(head) < size or size >= self.HEAD_LIMIT: + return None + size *= 4 + continue + return list(record) if isinstance(record, dict) else None + + def xml_columns(self, path): + """Read the column names of an XML file from its first row. + + The file is parsed incrementally and only up to the first row. + + Args: + path (str): Path to the XML file. + + Returns: + list or None: The element names of the first row, or None if the + file is not a ```` element with ```` elements. + """ + try: + with open(path, 'rb') as f: + depth = 0 + for event, element in ET.iterparse(f, events=('start', 'end')): + if event == 'start': + if depth == 0 and element.tag != 'data': + return None + depth += 1 + continue + depth -= 1 + if depth == 1: + return [child.tag for child in element] if element.tag == 'row' else None + except ET.ParseError: + return None + return None + + def append_json(self, path, row): + """Append a row to the JSON file without reading the stored data. + + The new record is written in the same format as before (as by + ``DataFrame.to_json(orient='records', indent=4)``) just before the + closing ``]``, so the file stays a valid JSON array and is the same + as if it had been written again. Only the first record and the end + of the file are read. If the file is new, its columns differ, or it + does not look as expected, it is written again (see :meth:`rewrite`). + + Args: + path (str): Path to the JSON file. + row (pandas.DataFrame): The new row. + + Returns: + None + """ + if not os.path.exists(path) or os.path.getsize(path) == 0: + self.rewrite(path, row) + return + + columns = self.json_columns(path) + tail = self.stored_tail(path, b']') + if (columns is None or tail is None or not set(row.columns) <= set(columns) + or len(set(columns)) != len(columns)): + self.rewrite(path, row) + return + + position, after = tail + with open(path, 'rb') as f: + f.seek(max(0, position - 64)) + before = f.read(position - max(0, position - 64)).rstrip() + if not before.endswith(b'}'): + self.rewrite(path, row) + return + + row = row.reindex(columns=columns) + # '[\n' + record + '\n]' for a single row + record = row.to_json(orient='records', indent=4)[2:-2] + self.insert_before(path, position, b',\n' + record.encode('utf-8') + b'\n', b']' + after, + strip_before=True) + self.df = row.reset_index(drop=True) + + def append_xml(self, path, row): + """Append a row to the XML file without reading the stored data. + + The new ```` is written in the same format as before (as by + ``DataFrame.to_xml(index=False)``) just before the closing + ````, so the file stays valid XML and is the same as if it had + been written again. Only the first row and the end of the file are + read. If the file is new, its columns differ, or it does not look as + expected, it is written again (see :meth:`rewrite`). + + Args: + path (str): Path to the XML file. + row (pandas.DataFrame): The new row. + + Returns: + None + """ + if not os.path.exists(path) or os.path.getsize(path) == 0: + self.rewrite(path, row) + return + + columns = self.xml_columns(path) + tail = self.stored_tail(path, b'') + if (columns is None or tail is None or not set(row.columns) <= set(columns) + or len(set(columns)) != len(columns)): + self.rewrite(path, row) + return + + position, after = tail + with open(path, 'rb') as f: + f.seek(max(0, position - 64)) + before = f.read(position - max(0, position - 64)).rstrip() + if not before.endswith(b''): + self.rewrite(path, row) + return + + row = row.reindex(columns=columns) + text = row.to_xml(index=False) + block = text[text.index('') + len('\n'):text.rindex('\n')] + self.insert_before(path, position, b'\n' + block.encode('utf-8') + b'\n', b'' + after, + strip_before=True) + self.df = row.reset_index(drop=True) + + @staticmethod + def insert_before(path, position, text, ending, strip_before=False): + """Write ``text`` and ``ending`` at ``position`` of a file. + + Everything from ``position`` on is replaced. With ``strip_before``, + whitespace just before ``position`` is replaced as well, so the new + text follows the previous content directly. Line endings in ``text`` + follow the file (``\\r\\n`` if the file uses them). + + Args: + path (str): Path to the file. + position (int): Where to write. + text (bytes): The text to insert. + ending (bytes): The text that ends the file. + strip_before (bool): Also replace whitespace before ``position``. + + Returns: + None + """ + with open(path, 'r+b') as f: + start = max(0, position - 64) + f.seek(start) + chunk = f.read(position - start) + if strip_before: + position = start + len(chunk.rstrip()) + # Use the file's line endings (e.g. \r\n if it was written on Windows) + if b'\r\n' in chunk: + text = text.replace(b'\r\n', b'\n').replace(b'\n', b'\r\n') + f.seek(position) + f.write(text + ending) + f.truncate() + def process(self, req): """Process the incoming request and store the data accordingly. @@ -651,7 +862,7 @@ def process(self, req): data['timestamp'] = now.strftime('%Y-%m-%d %H:%M:%S') # Store data to device: append the new row instead of rewriting - # the whole file (csv, sqlite), so storing takes the same time + # the whole file, 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 @@ -660,8 +871,10 @@ def process(self, req): self.append_csv(path, row) elif self.format == 'sqlite': self.append_sqlite(path, row) + elif self.format == 'json': + self.append_json(path, row) else: - self.rewrite(path, row) + self.append_xml(path, row) if self.format == 'image': # Retrieve image from request diff --git a/tests/test_storage.py b/tests/test_storage.py index ee6a163..6be66e4 100644 --- a/tests/test_storage.py +++ b/tests/test_storage.py @@ -1,3 +1,4 @@ +import json import multiprocessing import os import shutil @@ -5,6 +6,7 @@ import tempfile import threading import unittest +import xml.etree.ElementTree as ET from unittest import mock import pandas as pd @@ -209,6 +211,154 @@ def test_data_endpoint(self): self.assertEqual([r['sensor'] for r in data], ['a', 'b']) +class DocumentAppendMixin: + """Shared tests for the JSON and XML formats (one document per file).""" + + FORMAT = None + READER = None # pandas reader that would read the whole file + + def setUp(self): + self.api, self.client = self.make_api(format=self.FORMAT) + + def full_write(self, rows, path): + df = pd.DataFrame(rows, dtype=object) + if self.FORMAT == 'json': + df.to_json(path, orient='records', indent=4) + else: + df.to_xml(path, index=False) + + def stored(self): + with open(self.path(self.api), 'rb') as f: + return f.read() + + def test_same_file_as_writing_everything_again(self): + rows = [ + {'temperature': 20.5, 'humidity': None, 'sensor': 'a'}, + {'temperature': 21.5, 'humidity': 40, 'sensor': 'b <&> "č" ] }'}, + {'temperature': None, 'humidity': 41.25, 'sensor': 'ž' * 20000}, + {'temperature': -3.5, 'humidity': None, 'sensor': None}, + ] + for row in rows: + self.post(self.client, **{k: v for k, v in row.items() if v is not None}) + reference = os.path.join(self.api.processing.directory, 'reference') + self.full_write(rows, reference) + with open(reference, 'rb') as f: + self.assertEqual(self.stored(), f.read()) + + data = self.client.get('/data').get_json()['data'] + self.assertEqual([r['temperature'] for r in data], [20.5, 21.5, None, -3.5]) + + def test_stored_data_is_not_read(self): + self.post(self.client, temperature=20) + with mock.patch(f'succulent.processing.pd.{self.READER}') as read: + self.post(self.client, temperature=21) + self.post(self.client, temperature=22) + read.assert_not_called() + data = self.client.get('/data').get_json()['data'] + self.assertEqual([r['temperature'] for r in data], [20, 21, 22]) + + def test_file_from_older_version(self): + # Written as a whole by pandas, as older versions did on every measurement + os.makedirs(self.api.processing.directory, exist_ok=True) + self.full_write([{'temperature': 20.0, 'humidity': 40.0, 'sensor': 'a'}], self.path(self.api)) + 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 test_new_column_in_configuration(self): + self.post(self.client, temperature=20) + config = dict(CONFIG, timestamp=True, data=CONFIG['data'] + [{'name': 'light'}]) + api, client = self.make_api(config, format=self.FORMAT, clear=False) + self.post(client, temperature=21, light=300) + self.post(client, temperature=22, light=310) + data = client.get('/data').get_json()['data'] + self.assertEqual([r['light'] for r in data], [None, 300, 310]) + self.assertIsNone(data[0]['timestamp']) + self.assertIsNotNone(data[2]['timestamp']) + + 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, format=self.FORMAT, clear=False) + with mock.patch(f'succulent.processing.pd.{self.READER}') as read: + self.post(client, temperature=21) + read.assert_not_called() + data = client.get('/data').get_json()['data'] + self.assertEqual([r['sensor'] for r in data], ['a', None]) + + def test_unexpected_end_of_file_is_rewritten(self): + self.post(self.client, temperature=20) + with open(self.path(self.api), 'ab') as f: + f.write(b'\n\n \n') # trailing whitespace is fine + self.post(self.client, temperature=21) + self.assertEqual(len(self.client.get('/data').get_json()['data']), 2) + + def test_windows_line_endings(self): + os.makedirs(self.api.processing.directory, exist_ok=True) + path = self.path(self.api) + self.full_write([{'temperature': 20.0, 'humidity': None, 'sensor': 'a'}], path) + with open(path, 'rb') as f: + content = f.read().replace(b'\n', b'\r\n') + with open(path, 'wb') as f: + f.write(content) + self.post(self.client, temperature=21, sensor='b') + stored = self.stored() + self.assertNotIn(b'\n', stored.replace(b'\r\n', b'')) + data = self.client.get('/data').get_json()['data'] + self.assertEqual([r['sensor'] for r in data], ['a', 'b']) + + 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(len(self.client.get('/data').get_json()['data']), 1) + + +class TestJsonAppend(DocumentAppendMixin, StorageTestCase): + FORMAT = 'json' + READER = 'read_json' + + def test_compact_json_file(self): + # A valid JSON array written without indentation, e.g. by another tool + os.makedirs(self.api.processing.directory, exist_ok=True) + with open(self.path(self.api), 'w') as f: + f.write('[{"temperature":20,"humidity":null,"sensor":"a"}]') + self.post(self.client, temperature=21, sensor='b') + with open(self.path(self.api)) as f: + records = json.load(f) + self.assertEqual([r['sensor'] for r in records], ['a', 'b']) + + def test_nested_values_in_first_record(self): + self.post(self.client, sensor={'id': 1, 'tags': ['a', '}']}) + with mock.patch('succulent.processing.pd.read_json') as read: + self.post(self.client, sensor='b') + read.assert_not_called() + with open(self.path(self.api)) as f: + records = json.load(f) + self.assertEqual(records[0]['sensor'], {'id': 1, 'tags': ['a', '}']}) + self.assertEqual(records[1]['sensor'], 'b') + + def test_not_an_array_is_rewritten(self): + os.makedirs(self.api.processing.directory, exist_ok=True) + with open(self.path(self.api), 'w') as f: + f.write('[]') + self.post(self.client, temperature=21) + with open(self.path(self.api)) as f: + self.assertEqual(len(json.load(f)), 1) + + +class TestXmlAppend(DocumentAppendMixin, StorageTestCase): + FORMAT = 'xml' + READER = 'read_xml' + + def test_file_stays_valid_xml(self): + for i in range(3): + self.post(self.client, temperature=20 + i, sensor=f'') + root = ET.parse(self.path(self.api)).getroot() + self.assertEqual(root.tag, 'data') + self.assertEqual([row.find('sensor').text for row in root], ['', '', '']) + + def store_in_process(config_path, fmt, number, count): """Send measurements from a separate process (like a gunicorn worker).""" from succulent.api import SucculentAPI