Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

rocketchat: Do not load attachment table into memory.

Alex Vandiver8c7e8764451d
diff --git a/zerver/data_import/rocketchat.py b/zerver/data_import/rocketchat.py
index cabc16e0d3a..3e2d1eadd06 100644
--- a/zerver/data_import/rocketchat.py
+++ b/zerver/data_import/rocketchat.py
@@ -2,7 +2,7 @@ import logging
import os
import uuid
from collections import defaultdict
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from typing import Any
import bson
@@ -386,10 +386,11 @@ def process_message_attachment(
user_id: int,
zerver_attachment: list[ZerverFieldsT],
uploads_list: list[UploadRecordData],
- upload_id_to_upload_data_map: dict[str, dict[str, Any]],
+ attachment_lookup: Callable[[str], None | tuple[dict[str, Any], Iterator[bytes]]],
output_dir: str,
) -> tuple[str, bool]:
- if upload["_id"] not in upload_id_to_upload_data_map: # nocoverage
+ attachment_data = attachment_lookup(upload["_id"])
+ if attachment_data is None:
logging.info("Skipping unknown attachment of message_id: %s", message_id)
return "", False
@@ -397,7 +398,7 @@ def process_message_attachment(
logging.info("Skipping attachment without type of message_id: %s", message_id)
return "", False
- upload_file_data = upload_id_to_upload_data_map[upload["_id"]]
+ upload_file_data, content_iterator = attachment_data
file_name = upload["name"]
file_ext = f".{upload['type'].split('/')[-1]}"
@@ -415,18 +416,18 @@ def process_message_attachment(
logging.info("Replacing too long attachment name with random uuid: %s", file_name)
sanitized_name = uuid.uuid4().hex
- attachment_data = get_attachment_path_and_content(
+ attachment_link = get_attachment_path_and_content(
link_name=file_name, filename=file_name, realm_id=realm_id
)
# Build the attachment from chunks and save it to s3_path.
- file_out_path = os.path.join(output_dir, "uploads", attachment_data.path_id)
+ file_out_path = os.path.join(output_dir, "uploads", attachment_link.path_id)
os.makedirs(os.path.dirname(file_out_path), exist_ok=True)
with open(file_out_path, "wb") as upload_file:
- upload_file.write(b"".join(upload_file_data["chunk"]))
+ upload_file.writelines(content_iterator)
attachment_content = (
- f"{upload_file_data.get('description', '')}\n\n{attachment_data.markdown_link}"
+ f"{upload_file_data.get('description', '')}\n\n{attachment_link.markdown_link}"
)
fileinfo = {
@@ -439,9 +440,9 @@ def process_message_attachment(
UploadRecordData(
content_type=upload["type"],
last_modified=fileinfo["created"],
- path=attachment_data.path_id,
+ path=attachment_link.path_id,
realm_id=realm_id,
- s3_path=attachment_data.path_id,
+ s3_path=attachment_link.path_id,
size=fileinfo["size"],
user_profile_id=user_id,
)
@@ -452,7 +453,7 @@ def process_message_attachment(
message_ids={message_id},
user_id=user_id,
fileinfo=fileinfo,
- s3_path=attachment_data.path_id,
+ s3_path=attachment_link.path_id,
zerver_attachment=zerver_attachment,
)
@@ -469,7 +470,7 @@ def process_raw_message_batch(
total_reactions: list[ZerverFieldsT],
uploads_list: list[UploadRecordData],
zerver_attachment: list[ZerverFieldsT],
- upload_id_to_upload_data_map: dict[str, dict[str, Any]],
+ attachment_lookup: Callable[[str], None | tuple[dict[str, Any], Iterator[bytes]]],
) -> None:
def fix_mentions(
content: str, mention_user_ids: set[int], rc_channel_mention_data: list[dict[str, str]]
@@ -532,7 +533,7 @@ def process_raw_message_batch(
user_id=sender_user_id,
uploads_list=uploads_list,
zerver_attachment=zerver_attachment,
- upload_id_to_upload_data_map=upload_id_to_upload_data_map,
+ attachment_lookup=attachment_lookup,
output_dir=output_dir,
)
@@ -626,7 +627,7 @@ def process_messages(
total_reactions: list[ZerverFieldsT],
uploads_list: list[UploadRecordData],
zerver_attachment: list[ZerverFieldsT],
- upload_id_to_upload_data_map: dict[str, dict[str, Any]],
+ attachment_lookup: Callable[[str], None | tuple[dict[str, Any], Iterator[bytes]]],
output_dir: str,
) -> None:
private_channels_set = {
@@ -826,31 +827,10 @@ def process_messages(
total_reactions=total_reactions,
uploads_list=uploads_list,
zerver_attachment=zerver_attachment,
- upload_id_to_upload_data_map=upload_id_to_upload_data_map,
+ attachment_lookup=attachment_lookup,
)
-def map_upload_id_to_upload_data(
- upload_data: dict[str, list[dict[str, Any]]],
-) -> dict[str, dict[str, Any]]:
- upload_id_to_upload_data_map: dict[str, dict[str, Any]] = {}
-
- for upload in upload_data["upload"]:
- upload_id_to_upload_data_map[upload["_id"]] = {**upload, "chunk": []}
-
- for chunk in sorted(upload_data["chunk"], key=lambda c: c["n"]):
- if chunk["files_id"] not in upload_id_to_upload_data_map: # nocoverage
- logging.info("Skipping chunk %s without metadata", chunk["files_id"])
- # It's unclear why this apparent data corruption in the
- # Rocket.Chat database is possible, but empirically, some
- # chunks don't have any associated metadata.
- continue
-
- upload_id_to_upload_data_map[chunk["files_id"]]["chunk"].append(chunk["data"])
-
- return upload_id_to_upload_data_map
-
-
def map_receiver_id_to_recipient_id(
zerver_recipient: list[ZerverFieldsT],
stream_id_to_recipient_id: dict[int, int],
@@ -953,9 +933,6 @@ def rocketchat_data_to_dict(
export. Defaults to fetching everything, which is convenient for tests, but
we prefer to fetch only those sections that are needed for a given stage to
provide a faster debug cycle for metadata data corruption issues.
-
- TODO: Ideally, we'd read the big data sets, like messages and
- uploads, with a streaming BSON parser, or pre-paginate the data.
"""
rocketchat_data: dict[str, Any] = {}
@@ -1016,26 +993,6 @@ def rocketchat_data_to_dict(
fcache.read(), bson_codec_options
)
- if sections is None or "upload" in sections:
- rocketchat_data["upload"] = {"upload": [], "file": [], "chunk": []}
- with open(os.path.join(rocketchat_data_dir, "rocketchat_uploads.bson"), "rb") as fcache:
- rocketchat_data["upload"]["upload"] = bson.decode_all(fcache.read(), bson_codec_options)
-
- if rocketchat_data["upload"]["upload"]:
- with open(
- os.path.join(rocketchat_data_dir, "rocketchat_uploads.files.bson"), "rb"
- ) as fcache:
- rocketchat_data["upload"]["file"] = bson.decode_all(
- fcache.read(), bson_codec_options
- )
-
- with open(
- os.path.join(rocketchat_data_dir, "rocketchat_uploads.chunks.bson"), "rb"
- ) as fcache:
- rocketchat_data["upload"]["chunk"] = bson.decode_all(
- fcache.read(), bson_codec_options
- )
-
return rocketchat_data
@@ -1175,38 +1132,71 @@ def do_convert_data(rocketchat_data_dir: str, output_dir: str) -> None:
uploads_list: list[UploadRecordData] = []
zerver_attachment: list[ZerverFieldsT] = []
- rocketchat_upload_data = rocketchat_data_to_dict(rocketchat_data_dir, ["upload"])["upload"]
- upload_id_to_upload_data_map = map_upload_id_to_upload_data(rocketchat_upload_data)
-
def message_stream() -> Iterator[dict[str, Any]]:
with open(f"{rocketchat_data_dir}/rocketchat_message.bson", "rb") as message_file:
yield from KeyValueBSONInput(fh=message_file)
- process_messages(
- realm_id=realm_id,
- rocketchat_messages=message_stream(),
- subscriber_map=subscriber_map,
- username_to_user_id_map=username_to_user_id_map,
- user_id_mapper=user_id_mapper,
- user_handler=user_handler,
- user_id_to_recipient_id=user_id_to_recipient_id,
- stream_id_mapper=stream_id_mapper,
- stream_id_to_recipient_id=stream_id_to_recipient_id,
- direct_message_group_id_mapper=direct_message_group_id_mapper,
- direct_message_group_id_to_recipient_id=direct_message_group_id_to_recipient_id,
- thread_id_mapper=thread_id_mapper,
- room_id_to_room_map=room_id_to_room_map,
- dsc_id_to_dsc_map=dsc_id_to_dsc_map,
- direct_id_to_direct_map=direct_id_to_direct_map,
- direct_message_group_id_to_direct_message_group_map=direct_message_group_id_to_direct_message_group_map,
- livechat_id_to_livechat_map=livechat_id_to_livechat_map,
- zerver_realmemoji=zerver_realmemoji,
- total_reactions=total_reactions,
- uploads_list=uploads_list,
- zerver_attachment=zerver_attachment,
- upload_id_to_upload_data_map=upload_id_to_upload_data_map,
- output_dir=output_dir,
- )
+ with (
+ open(os.path.join(rocketchat_data_dir, "rocketchat_uploads.bson"), "rb") as uploads_fh,
+ open(
+ os.path.join(rocketchat_data_dir, "rocketchat_uploads.chunks.bson"), "rb"
+ ) as chunks_fh,
+ ):
+
+ def attachment_lookup(file_id: str) -> None | tuple[dict[str, Any], Iterator[bytes]]:
+ uploads_fh.seek(0)
+ uploads = [
+ doc
+ for doc in KeyValueBSONInput(fh=uploads_fh, fast_string_prematch=file_id.encode())
+ if doc.get("_id") == file_id
+ ]
+ if len(uploads) == 0: # nocoverage
+ return None
+ if len(uploads) > 1: # nocoverage
+ logging.info(
+ "Found %d metadata entries for upload %s, using first", len(uploads), file_id
+ )
+
+ def iterate_chunks() -> Iterator[bytes]:
+ chunks_fh.seek(0)
+ matching = [
+ chunk
+ for chunk in KeyValueBSONInput(
+ fh=chunks_fh, fast_string_prematch=file_id.encode()
+ )
+ if chunk.get("files_id") == file_id
+ ]
+ matching.sort(key=lambda c: c.get("n", 0))
+ for chunk in matching:
+ yield chunk.get("data", b"")
+
+ return uploads[0], iterate_chunks()
+
+ process_messages(
+ realm_id=realm_id,
+ rocketchat_messages=message_stream(),
+ subscriber_map=subscriber_map,
+ username_to_user_id_map=username_to_user_id_map,
+ user_id_mapper=user_id_mapper,
+ user_handler=user_handler,
+ user_id_to_recipient_id=user_id_to_recipient_id,
+ stream_id_mapper=stream_id_mapper,
+ stream_id_to_recipient_id=stream_id_to_recipient_id,
+ direct_message_group_id_mapper=direct_message_group_id_mapper,
+ direct_message_group_id_to_recipient_id=direct_message_group_id_to_recipient_id,
+ thread_id_mapper=thread_id_mapper,
+ room_id_to_room_map=room_id_to_room_map,
+ dsc_id_to_dsc_map=dsc_id_to_dsc_map,
+ direct_id_to_direct_map=direct_id_to_direct_map,
+ direct_message_group_id_to_direct_message_group_map=direct_message_group_id_to_direct_message_group_map,
+ livechat_id_to_livechat_map=livechat_id_to_livechat_map,
+ zerver_realmemoji=zerver_realmemoji,
+ total_reactions=total_reactions,
+ uploads_list=uploads_list,
+ zerver_attachment=zerver_attachment,
+ attachment_lookup=attachment_lookup,
+ output_dir=output_dir,
+ )
realm["zerver_reaction"] = total_reactions
realm["zerver_userprofile"] = user_handler.get_all_users()
realm["sort_by_date"] = True
diff --git a/zerver/tests/test_rocketchat_importer.py b/zerver/tests/test_rocketchat_importer.py
index 3e9bc805b98..5484c3d47c5 100644
--- a/zerver/tests/test_rocketchat_importer.py
+++ b/zerver/tests/test_rocketchat_importer.py
@@ -21,7 +21,6 @@ from zerver.data_import.rocketchat import (
convert_stream_subscription_data,
do_convert_data,
map_receiver_id_to_recipient_id,
- map_upload_id_to_upload_data,
map_user_id_to_user,
map_username_to_user_id,
process_message_attachment,
@@ -43,7 +42,7 @@ class RocketChatImporter(ZulipTestCase):
def test_rocketchat_data_to_dict(self) -> None:
fixture_dir_name = self.fixture_file_name("", "rocketchat_fixtures")
rocketchat_data = rocketchat_data_to_dict(fixture_dir_name)
- self.assert_length(rocketchat_data, 6)
+ self.assert_length(rocketchat_data, 5)
self.assert_length(rocketchat_data["user"], 6)
self.assertEqual(rocketchat_data["user"][2]["username"], "harry.potter")
@@ -56,9 +55,6 @@ class RocketChatImporter(ZulipTestCase):
self.assert_length(rocketchat_data["custom_emoji"]["emoji"], 3)
self.assertEqual(rocketchat_data["custom_emoji"]["emoji"][0]["name"], "tick")
- self.assert_length(rocketchat_data["upload"]["upload"], 4)
- self.assertEqual(rocketchat_data["upload"]["upload"][0]["name"], "harry-ron.jpg")
-
def test_map_user_id_to_user(self) -> None:
fixture_dir_name = self.fixture_file_name("", "rocketchat_fixtures")
rocketchat_data = rocketchat_data_to_dict(fixture_dir_name)
@@ -739,31 +735,6 @@ class RocketChatImporter(ZulipTestCase):
zerver_recipient[12]["id"],
)
- def test_map_upload_id_to_upload_data(self) -> None:
- fixture_dir_name = self.fixture_file_name("", "rocketchat_fixtures")
- rocketchat_data = rocketchat_data_to_dict(fixture_dir_name)
-
- upload_id_to_upload_data_map = map_upload_id_to_upload_data(rocketchat_data["upload"])
-
- self.assert_length(rocketchat_data["upload"]["upload"], 4)
- self.assert_length(upload_id_to_upload_data_map, 4)
-
- upload_id = rocketchat_data["upload"]["upload"][0]["_id"]
- upload_name = rocketchat_data["upload"]["upload"][0]["name"]
- self.assertEqual(upload_id_to_upload_data_map[upload_id]["name"], upload_name)
- self.assert_length(upload_id_to_upload_data_map[upload_id]["chunk"], 1)
-
- # Verify multi-chunk files have chunks in correct order.
- # The fixture's PDF (4BoikTP2ZZkE5RsGh) has chunks stored as
- # n=0, n=2, n=1 in the BSON file; they must be reassembled as
- # n=0, n=1, n=2.
- pdf_upload_id = "4BoikTP2ZZkE5RsGh"
- pdf_chunks = upload_id_to_upload_data_map[pdf_upload_id]["chunk"]
- self.assert_length(pdf_chunks, 3)
- self.assertEqual(len(pdf_chunks[0]), 261120)
- self.assertEqual(len(pdf_chunks[1]), 261120)
- self.assertEqual(len(pdf_chunks[2]), 47300)
-
def test_build_reactions(self) -> None:
fixture_dir_name = self.fixture_file_name("", "rocketchat_fixtures")
rocketchat_data = rocketchat_data_to_dict(fixture_dir_name)
@@ -869,8 +840,32 @@ class RocketChatImporter(ZulipTestCase):
zerver_attachments: list[ZerverFieldsT] = []
uploads_list: list[UploadRecordData] = []
- upload_id_to_upload_data_map = map_upload_id_to_upload_data(rocketchat_data["upload"])
-
+ attachment_mock = mock.MagicMock()
+ attachment_mock.return_value = (
+ {
+ "_id": "MmgXWQbD3hXYyGSai",
+ "name": "harry-ron.jpg",
+ "size": 149467,
+ "type": "image/jpeg",
+ "rid": "7scLEFgSgYXDqQwRM",
+ "userId": "LdBZ7kPxtKESyHPEe",
+ "store": "GridFS:Uploads",
+ "_updatedAt": datetime(2021, 7, 30, 22, 3, 11, 351000, tzinfo=timezone.utc),
+ "instanceId": "tYveC9XFjoWEn68mx",
+ "identify": {"format": "jpeg", "size": {"width": 1500, "height": 750}},
+ "complete": True,
+ "etag": "Hp6BwNq6mjqmSe4GH",
+ "path": "/ufs/GridFS:Uploads/MmgXWQbD3hXYyGSai/harry-ron.jpg",
+ "progress": 1,
+ "token": "08397aB979",
+ "uploadedAt": datetime(2021, 7, 30, 22, 3, 12, 675000, tzinfo=timezone.utc),
+ "uploading": False,
+ "url": "http://localhost:3000/ufs/GridFS:Uploads/MmgXWQbD3hXYyGSai/harry-ron.jpg",
+ "description": "Just a random pic!",
+ "typeGroup": "image",
+ },
+ iter([b"moose\n", b"thing\n"]),
+ )
process_message_attachment(
upload={"_id": "MmgXWQbD3hXYyGSai", "name": "harry-ron.jpg", "type": "image/jpeg"},
realm_id=3,
@@ -878,7 +873,7 @@ class RocketChatImporter(ZulipTestCase):
user_id=3,
zerver_attachment=zerver_attachments,
uploads_list=uploads_list,
- upload_id_to_upload_data_map=upload_id_to_upload_data_map,
+ attachment_lookup=attachment_mock,
output_dir=output_dir,
)
@@ -937,6 +932,115 @@ class RocketChatImporter(ZulipTestCase):
for um in dm_ums:
self.assertTrue(um["flags_mask"] & 2048)
+ def test_attachment_lookup_found(self) -> None:
+ """Test that attachment_lookup correctly finds uploads and streams chunks
+ from the BSON fixture files, matching the behavior of the streaming
+ attachment_lookup closure in do_convert_data."""
+ from collections.abc import Iterator
+
+ from bsonstream import KeyValueBSONInput
+
+ fixture_dir_name = self.fixture_file_name("", "rocketchat_fixtures")
+ uploads_path = os.path.join(fixture_dir_name, "rocketchat_uploads.bson")
+ chunks_path = os.path.join(fixture_dir_name, "rocketchat_uploads.chunks.bson")
+
+ with (
+ open(uploads_path, "rb") as uploads_fh,
+ open(chunks_path, "rb") as chunks_fh,
+ ):
+
+ def attachment_lookup(
+ file_id: str,
+ ) -> None | tuple[dict[str, Any], Iterator[bytes]]:
+ uploads_fh.seek(0)
+ uploads = [
+ doc
+ for doc in KeyValueBSONInput(
+ fh=uploads_fh, fast_string_prematch=file_id.encode()
+ )
+ if doc.get("_id") == file_id
+ ]
+ if len(uploads) == 0:
+ return None
+ self.assert_length(uploads, 1)
+
+ chunks_fh.seek(0)
+ matching = [
+ chunk
+ for chunk in KeyValueBSONInput(
+ fh=chunks_fh, fast_string_prematch=file_id.encode()
+ )
+ if chunk.get("files_id") == file_id
+ ]
+ matching.sort(key=lambda c: c.get("n", 0))
+
+ def iterate_chunks() -> Iterator[bytes]:
+ for chunk in matching:
+ yield chunk.get("data", b"")
+
+ return uploads[0], iterate_chunks()
+
+ # Known upload: harry-ron.jpg has one chunk
+ result = attachment_lookup("MmgXWQbD3hXYyGSai")
+ assert result is not None
+ upload_meta, chunk_iter = result
+ self.assertEqual(upload_meta["name"], "harry-ron.jpg")
+ self.assertEqual(upload_meta["size"], 149467)
+ chunks = list(chunk_iter)
+ self.assert_length(chunks, 1)
+ self.assertEqual(len(chunks[0]), 149467)
+
+ # Known upload: Hogwarts Curriculum.pdf has multiple chunks.
+ # The fixture stores these as n=0, n=2, n=1 in the BSON file;
+ # they must be yielded in n=0, n=1, n=2 order.
+ result = attachment_lookup("4BoikTP2ZZkE5RsGh")
+ assert result is not None
+ upload_meta, chunk_iter = result
+ self.assertEqual(upload_meta["name"], "Hogwarts Curriculum.pdf")
+ chunks = list(chunk_iter)
+ self.assert_length(chunks, 3)
+ self.assertEqual(len(chunks[0]), 261120)
+ self.assertEqual(len(chunks[1]), 261120)
+ self.assertEqual(len(chunks[2]), 47300)
+ self.assertEqual(sum(len(c) for c in chunks), upload_meta["size"])
+
+ # Unknown upload: returns None
+ result = attachment_lookup("nonexistent_id")
+ self.assertIsNone(result)
+
+ def test_process_message_attachment_unknown(self) -> None:
+ """Test that process_message_attachment handles an unknown attachment
+ (attachment_lookup returns None) by returning empty content."""
+
+ output_dir = self.make_import_output_dir("mattermost")
+
+ zerver_attachments: list[ZerverFieldsT] = []
+ uploads_list: list[UploadRecordData] = []
+
+ attachment_mock = mock.MagicMock()
+ attachment_mock.return_value = None
+
+ with self.assertLogs(level="INFO") as info_log:
+ content, has_image = process_message_attachment(
+ upload={"_id": "unknown_id", "name": "missing.jpg", "type": "image/jpeg"},
+ realm_id=3,
+ message_id=42,
+ user_id=3,
+ zerver_attachment=zerver_attachments,
+ uploads_list=uploads_list,
+ attachment_lookup=attachment_mock,
+ output_dir=output_dir,
+ )
+
+ self.assertEqual(content, "")
+ self.assertFalse(has_image)
+ self.assert_length(zerver_attachments, 0)
+ self.assert_length(uploads_list, 0)
+ self.assertIn(
+ "INFO:root:Skipping unknown attachment of message_id: 42",
+ info_log.output,
+ )
+
def read_file(self, team_output_dir: str, output_file: str) -> Any:
full_path = os.path.join(team_output_dir, output_file)
with open(full_path, "rb") as f: