diff --git a/docs/command_reference.md b/docs/command_reference.md index 97fc21e8..6fb9a99a 100644 --- a/docs/command_reference.md +++ b/docs/command_reference.md @@ -375,8 +375,15 @@ Gotchas: matches does it read the file's fingerprint: 64 KiB from its start, middle and end. Files uploaded with earlier versions were recorded by checksum instead, so they are not found, and are uploaded once more. - A file of the same size as an uploaded file that differs from it only outside these three blocks is taken as - uploaded. Captures from cameras don't differ that way; `--reupload` uploads such a file anyway. -- An interrupted upload resumes where it stopped the next time you upload the same files. + uploaded. Captures from cameras don't differ that way; `--reupload` uploads such a file anyway, and + `--reupload --noresume` such a video (see below). +- An interrupted upload resumes where it stopped the next time you upload the same files. A video is not read + whole to find its interrupted upload, which is keyed by the fingerprint of the video, where its frames are in it, + and the track uploaded with it: `upload` reads it once, while uploading it. A video changed in place outside the + three blocks, with its frames where they were, is taken as the one uploaded before: its interrupted upload + resumes with the bytes uploaded before the change, and `--reupload` finishes its earlier upload again. Specify + `--noresume` to upload it from the start. Interrupted video uploads of earlier versions start over, and so do + those of a video edited in other ways since, even only in metadata that is not uploaded. - `--organization_key` takes a numeric ID. Organization names are 2 to 32 letters, digits, `-` and `_`, starting with a letter, and are case-sensitive. Saving a name again with another ID replaces it. - An image that fails to upload fails its whole sequence. The other sequences, videos and zip files carry on, and diff --git a/mapillary_tools/fingerprint.py b/mapillary_tools/fingerprint.py index 0a2668e0..7f5387fb 100644 --- a/mapillary_tools/fingerprint.py +++ b/mapillary_tools/fingerprint.py @@ -4,7 +4,8 @@ # LICENSE file in the root directory of this source tree. """ -Fingerprints identify files in the upload history without reading them whole. +Fingerprints identify files in the upload history without reading them whole, +and key interrupted video uploads (see uploader._stream_key()). A fingerprint is a BLAKE2b hash of the file size and of three blocks of the file: at the start, in the middle and at the end. A file no larger than the @@ -20,7 +21,7 @@ from __future__ import annotations import hashlib -import os +import io import typing as T from pathlib import Path @@ -35,16 +36,25 @@ def fingerprint_file(path: Path) -> str: """Return the fingerprint of the file, as 32 hexadecimal digits""" - hasher = hashlib.blake2b(digest_size=16, person=_PERSONALIZATION) with path.open("rb") as fp: - size = os.fstat(fp.fileno()).st_size - hasher.update(size.to_bytes(8, "little")) - if size <= 3 * BLOCK_SIZE: - hasher.update(fp.read()) - else: - for offset in (0, (size - BLOCK_SIZE) // 2, size - BLOCK_SIZE): - fp.seek(offset) - hasher.update(fp.read(BLOCK_SIZE)) + return fingerprint_fp(fp) + + +def fingerprint_fp(fp: T.BinaryIO) -> str: + """ + Return the fingerprint of the content of a seekable binary stream, such + as an open file, as 32 hexadecimal digits + """ + hasher = hashlib.blake2b(digest_size=16, person=_PERSONALIZATION) + size = fp.seek(0, io.SEEK_END) + hasher.update(size.to_bytes(8, "little")) + if size <= 3 * BLOCK_SIZE: + fp.seek(0) + hasher.update(fp.read()) + else: + for offset in (0, (size - BLOCK_SIZE) // 2, size - BLOCK_SIZE): + fp.seek(offset) + hasher.update(fp.read(BLOCK_SIZE)) return hasher.hexdigest() diff --git a/mapillary_tools/mp4/io_utils.py b/mapillary_tools/mp4/io_utils.py index 5ade6f88..c94bb757 100644 --- a/mapillary_tools/mp4/io_utils.py +++ b/mapillary_tools/mp4/io_utils.py @@ -27,6 +27,11 @@ def __init__(self, streams: T.Sequence[io.IOBase]): self._offset_after_seek_end = 0 self._idx = 0 + @property + def streams(self) -> T.Sequence[io.IOBase]: + """The streams chained, in order""" + return self._streams + def _seek_next_stream(self) -> None: """ seek to the end of the current stream, and seek to the beginning of the next stream @@ -144,6 +149,19 @@ def __init__(self, source: T.BinaryIO, offset: int, size: int) -> None: self._rel_offset = 0 self._size = size + @property + def source(self) -> T.BinaryIO: + return self._source + + @property + def offset(self) -> int: + """Where the slice starts in the source""" + return self._begin_offset + + @property + def size(self) -> int: + return self._size + def read(self, n: int = -1) -> bytes: if self._rel_offset < self._size: self._source.seek(self._begin_offset + self._rel_offset, io.SEEK_SET) diff --git a/mapillary_tools/uploader.py b/mapillary_tools/uploader.py index 7865c5ee..8e676b42 100644 --- a/mapillary_tools/uploader.py +++ b/mapillary_tools/uploader.py @@ -38,6 +38,7 @@ config, constants, exif_write, + fingerprint, geo, history, telemetry, @@ -48,7 +49,7 @@ ) from .camm import camm_builder, camm_parser from .gpmf import gpmf_parser -from .mp4 import simple_mp4_builder +from .mp4 import io_utils, simple_mp4_builder from .serializer.description import ( desc_file_to_exif, DescriptionJSONSerializer, @@ -1117,8 +1118,7 @@ def _gen_session_key(self, fp: T.IO[bytes], progress: dict[str, T.Any]) -> str: # to prevent resuming from previous uploads session_key = f"{_prefixed_uuid4()}" else: - fp.seek(0, io.SEEK_SET) - session_key = utils.md5sum_fp(fp).hexdigest() + session_key = _stream_key(fp) filetype = progress.get("file_type") if filetype is not None: @@ -1361,6 +1361,42 @@ def _parse_retry_after_from_header(resp: requests.Response) -> int | None: } +def _stream_key(fp: T.IO[bytes]) -> str: + """ + A key of the stream, to resume its upload where it stopped (see + upload_api_v4): a checksum of the stream. A stream chained from slices of + files, as that of a video with its CAMM track (see + simple_mp4_builder.transform_mp4()), is keyed by the fingerprints of the + files (see fingerprint.py), where the slices are in them, and the checksum + of its other bytes, instead of the bytes of the slices: the video is then + read once, to upload it, rather than once for its checksum and once more + to upload it. A file changed in place outside the blocks of its + fingerprint, with its slices where they were, gives the same key, and the + upload of the file before the change resumes; a file changed only outside + the slices, such as in metadata that is not uploaded, may give another. + """ + if not isinstance(fp, io_utils.ChainedIO): + fp.seek(0, io.SEEK_SET) + return utils.md5sum_fp(fp).hexdigest() + + md5 = hashlib.md5() + source_fingerprints: dict[int, str] = {} + for stream in fp.streams: + if isinstance(stream, io_utils.SlicedIO): + source = id(stream.source) + if source not in source_fingerprints: + source_fingerprints[source] = fingerprint.fingerprint_fp(stream.source) + md5.update( + f"slice {source_fingerprints[source]} {stream.offset} {stream.size}\n".encode() + ) + else: + stream.seek(0, io.SEEK_SET) + data = stream.read() + md5.update(f"bytes {len(data)}\n".encode()) + md5.update(data) + return md5.hexdigest() + + def _suffix_session_key( key: str, filetype: api_v4.ClusterFileType | types.FileType ) -> str: diff --git a/tests/integration/fixtures.py b/tests/integration/fixtures.py index b9d59ee8..30aab70c 100644 --- a/tests/integration/fixtures.py +++ b/tests/integration/fixtures.py @@ -7,6 +7,7 @@ import json import os +import re import shlex import shutil import subprocess @@ -220,12 +221,10 @@ def validate_and_extract_zip(zip_path: Path) -> list[dict]: def validate_and_extract_camm(video_path: Path) -> list[dict]: - with video_path.open("rb") as fp: - upload_md5sum = utils.md5sum_fp(fp).hexdigest() - - assert f"mly_tools_{upload_md5sum}.mp4" == video_path.name, ( - video_path.name, - upload_md5sum, + # Keyed by the fingerprint of the source video, not by a checksum of the + # upload (see uploader._stream_key) + assert re.fullmatch(r"mly_tools_[0-9a-f]{32}\.mp4", video_path.name), ( + video_path.name ) return run_process_for_descs( diff --git a/tests/unit/test_check_upload_history.py b/tests/unit/test_check_upload_history.py index 1bfa441d..57ff9ffb 100644 --- a/tests/unit/test_check_upload_history.py +++ b/tests/unit/test_check_upload_history.py @@ -609,8 +609,8 @@ def _upload(reupload: bool = False): _upload() assert session_keys == [str(video_path)] - # The video is read in full once, for the session key: not for a checksum - assert [read for read in reads if read.startswith("md5:")] == ["md5:"] + # The video is read in full for neither a checksum nor the session key + assert [read for read in reads if read.startswith("md5:")] == [] assert _uploaded_files(upload_path) for name in _uploaded_files(upload_path): diff --git a/tests/unit/test_upload_session_key.py b/tests/unit/test_upload_session_key.py new file mode 100644 index 00000000..62cc769d --- /dev/null +++ b/tests/unit/test_upload_session_key.py @@ -0,0 +1,139 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +""" +An upload is keyed by its content, to resume it where it stopped. A video with +its CAMM track is keyed without reading it whole: it is read once, to upload +it. +""" + +from __future__ import annotations + +import hashlib +import io +import shutil +import typing as T +from pathlib import Path + +from mapillary_tools import fingerprint, geo, types, uploader +from mapillary_tools.camm import camm_builder, camm_parser +from mapillary_tools.mp4 import io_utils, simple_mp4_builder + +from ..integration.fixtures import setup_upload # noqa: F401 + +_VIDEO = ( + Path(__file__).resolve().parent.parent.joinpath("data", "gopro_data", "hero8.mp4") +) + + +class _CountingFile(io.BufferedReader): + """A file that counts the bytes read from it""" + + bytes_read = 0 + + def read(self, size: int | None = -1) -> bytes: + data = super().read(size) + self.bytes_read += len(data) + return data + + +def _points(lat: float = 37.0) -> list[geo.Point]: + return [ + geo.Point(time=t, lat=lat + t / 10_000, lon=-122.0, alt=None, angle=None) + for t in range(5) + ] + + +def _key(path: Path, points: T.Sequence[geo.Point] | None = None) -> tuple[str, int]: + """The key of the upload of the video with the points, and the bytes read for it""" + with _CountingFile(io.FileIO(path, "rb")) as fp: + stream = simple_mp4_builder.transform_mp4( + fp, + camm_builder.camm_sample_generator2( + camm_parser.CAMMInfo(mini_gps=list(points or _points())) + ), + ) + fp.bytes_read = 0 + return uploader._stream_key(stream), fp.bytes_read + + +def test_video_read_for_its_fingerprint_only(): + key, bytes_read = _key(_VIDEO) + + assert len(key) == 32 + assert _VIDEO.stat().st_size > 1_000_000 + assert bytes_read == 3 * fingerprint.BLOCK_SIZE + + +def test_same_video_same_key(tmp_path: Path): + copy = tmp_path / "copy.mp4" + shutil.copyfile(_VIDEO, copy) + + # Also under another name, as a resumed upload of a copied file + assert _key(copy)[0] == _key(_VIDEO)[0] + + +def test_another_track_another_key(): + assert _key(_VIDEO, _points(lat=38.0))[0] != _key(_VIDEO)[0] + + +def test_another_fingerprint_another_key(tmp_path: Path): + changed = tmp_path / "changed.mp4" + data = bytearray(_VIDEO.read_bytes()) + # A byte of the samples in the middle block of the fingerprint, the same + # size + data[(len(data) - fingerprint.BLOCK_SIZE) // 2 + 100] ^= 0xFF + changed.write_bytes(bytes(data)) + + assert fingerprint.fingerprint_file(changed) != fingerprint.fingerprint_file(_VIDEO) + assert _key(changed)[0] != _key(_VIDEO)[0] + + +def _slices_key(fp: T.BinaryIO, *slices: tuple[int, int]) -> str: + return uploader._stream_key( + io_utils.ChainedIO( + [ + io.BytesIO(b"the same header"), + *(io_utils.SlicedIO(fp, offset, size) for offset, size in slices), + ] + ) + ) + + +def test_slices_keyed_by_where_they_are(): + # As the pieces of a video with a track that does not move, whose CAMM + # samples are the same: only where their samples are tells them apart + with _VIDEO.open("rb") as fp: + key = _slices_key(fp, (1000, 500), (2000, 500)) + + assert _slices_key(fp, (1000, 500), (2000, 500)) == key + assert _slices_key(fp, (1000, 500), (3000, 500)) != key + assert _slices_key(fp, (1000, 500), (2000, 600)) != key + assert _slices_key(fp, (1000, 500)) != key + + +def test_other_streams_keyed_by_their_checksum(): + data = b"a zip file, or any upload that is not chained from slices of files" + + assert uploader._stream_key(io.BytesIO(data)) == hashlib.md5(data).hexdigest() + + +def test_video_uploaded_under_its_key(setup_upload): + metadata = types.VideoMetadata(_VIDEO, types.FileType.VIDEO, points=_points()) + mly_uploader = uploader.Uploader( + uploader.UploadOptions( + {"user_upload_token": "YOUR_USER_ACCESS_TOKEN"}, dry_run=True + ) + ) + + ((_, result),) = uploader.VideoUploader.upload_videos(mly_uploader, [metadata]) + + assert result.error is None + with uploader.VideoUploader.build_camm_stream(metadata) as camm_fp: + key = uploader._stream_key(camm_fp) + camm_fp.seek(0) + expected = camm_fp.read() + uploaded = Path(setup_upload) / f"mly_tools_{key}.mp4" + assert uploaded.read_bytes() == expected