Report incremental mailbox import estimates when checkpoints match

This commit is contained in:
parkel committed 2026-12-04 14:03:44 +01:00
1 parent f0665b2028
commit 898bb47877
5 files changed
+120 -12

No files matched your search

+70 -10
View File
@@ -26,7 +26,9 @@ from .resource_requests import lock_hosting_account
LIFETIME = timedelta(minutes=30)
INSPECT_SECONDS = 70
MAX_FOLDERS = 1000
STAT = re.compile(rb"\b(MESSAGES|SIZE) ([0-9]{1,18})(?=[ )])")
STAT = re.compile(
rb"\b(MESSAGES|SIZE|UIDNEXT|UIDVALIDITY) ([0-9]{1,18})(?=[ )])"
)
EXPIRED = "The preview expired. Enter the source password to check again."
UNAVAILABLE = "This mailbox is no longer available for preview."
@@ -162,7 +164,8 @@ def authorized_mailbox(preview):
def folder_status(client, name, include_size):
attributes = "(MESSAGES SIZE)" if include_size else "(MESSAGES)"
attributes = "(MESSAGES UIDNEXT UIDVALIDITY"
attributes += " SIZE)" if include_size else ")"
try:
result, rows = client.status(imap.quote(name), attributes)
except imaplib.IMAP4.abort:
@@ -172,14 +175,45 @@ def folder_status(client, name, include_size):
if result != "OK" and include_size:
return folder_status(client, name, False)
if result != "OK" or not rows or not isinstance(rows[0], bytes):
return None, None
return {}
# Match attributes after the folder name, which may contain spaces.
fields = rows[0].rsplit(b"(", 1)[-1]
values = {key: int(count) for key, count in STAT.findall(fields)}
return values.get(b"MESSAGES"), values.get(b"SIZE")
return {key: int(count) for key, count in STAT.findall(fields)}
def inventory(client, mapping):
def messages_after_checkpoint(client, name, status, checkpoint, deadline):
count = status.get(b"MESSAGES")
if checkpoint is None:
return count
validity = status.get(b"UIDVALIDITY")
next_uid = status.get(b"UIDNEXT")
if (
count is None
or next_uid is None
or not validity
or validity != checkpoint.source_validity
or checkpoint.pending
):
return None
if not checkpoint.last_uid:
return count
first = checkpoint.last_uid + 1
if next_uid <= first:
return 0
if next_uid - first > imports.UID_WINDOW or monotonic() >= deadline:
return None
try:
actual_validity, actual_next = imap.select(client, name, readonly=True)
if actual_validity == validity and actual_next == next_uid:
return len(imap.search_uids(client, first, last=next_uid - 1))
except imaplib.IMAP4.abort:
raise
except (imap.MailboxImportError, imaplib.IMAP4.error):
pass
return None
def inventory(client, mapping, checkpoints=None):
deadline = monotonic() + INSPECT_SECONDS
caps = {cap.upper() for cap in client.capabilities}
include_size = bool({"STATUS=SIZE", "IMAP4REV2"} & caps)
@@ -187,12 +221,19 @@ def inventory(client, mapping):
for source_name, _ in mapping[:MAX_FOLDERS]:
if monotonic() >= deadline:
break
count, size = folder_status(client, source_name, include_size)
status = folder_status(client, source_name, include_size)
folders.append(
{
"name": imports.display_name(source_name),
"count": count,
"bytes": size,
"count": status.get(b"MESSAGES"),
"bytes": status.get(b"SIZE"),
"remaining": messages_after_checkpoint(
client,
source_name,
status,
(checkpoints or {}).get(imports.folder_key(source_name)),
deadline,
),
}
)
readable = [folder for folder in folders if folder["count"] is not None]
@@ -206,9 +247,28 @@ def inventory(client, mapping):
if complete and all(folder["bytes"] is not None for folder in readable)
else None,
"complete": complete,
"incremental": bool(checkpoints),
"remaining": sum(folder["remaining"] for folder in folders)
if complete
and all(folder["remaining"] is not None for folder in folders)
else None,
}
def checkpoints_for(preview):
job = MailboxImport.objects.filter(
mailbox=preview.mailbox,
finished_at__isnull=False,
source_host=preview.source_host,
source_user=preview.source_user,
target_host=preview.target_host,
target_user=preview.target_user,
).first()
if not job:
return {}
return {folder.source_key: folder for folder in job.folders.all()}
@sensitive_variables()
def run_preview(preview):
mailbox = authorized_mailbox(preview)
@@ -243,4 +303,4 @@ def run_preview(preview):
raise imap.MailboxImportError(
"The source has no selectable folders to copy."
)
return inventory(source, mapping)
return inventory(source, mapping, checkpoints_for(preview))
@@ -79,10 +79,15 @@
{% elif preview.problem %}
<p class="section-text" role="status">{{ preview.problem }}</p>
{% else %}
<dl class="details section-text">
<div><dt>Source</dt><dd>{{ preview.source_user }} at {{ preview.source_host }}</dd></div>
<div><dt>Destination</dt><dd>{{ preview.target_user }}</dd></div>
</dl>
<p class="section-text">Source snapshot. These counts include previously copied messages. The import skips messages recorded at its checkpoints.</p>
<dl class="details section-text">
<div><dt>Folders counted</dt><dd>{{ preview.report.readable }} of {{ preview.report.total_folders }}</dd></div>
<div><dt>Messages in counted folders</dt><dd>{{ preview.report.messages }}</dd></div>
{% if preview.report.incremental %}<div><dt>Messages after previous checkpoints</dt><dd>{{ preview.report.remaining|default_if_none:"Not available" }}</dd></div>{% endif %}
<div><dt>Source size</dt><dd>{% if preview.report.bytes is not None %}{{ preview.report.bytes|filesizeformat }}{% else %}Not available{% endif %}</dd></div>
</dl>
{% if not preview.report.complete %}
@@ -90,13 +95,14 @@
{% endif %}
<div class="table-scroll">
<table>
<thead><tr><th scope="col">Source folder</th><th scope="col">Messages</th><th scope="col">Source size</th></tr></thead>
<thead><tr><th scope="col">Source folder</th><th scope="col">Messages</th><th scope="col">Source size</th>{% if preview.report.incremental %}<th scope="col">After checkpoint</th>{% endif %}</tr></thead>
<tbody>
{% for folder in preview.report.folders %}
<tr>
<th scope="row">{{ folder.name }}</th>
<td>{{ folder.count|default_if_none:"Not available" }}</td>
<td>{% if folder.bytes is not None %}{{ folder.bytes|filesizeformat }}{% else %}Not available{% endif %}</td>
{% if preview.report.incremental %}<td>{{ folder.remaining|default_if_none:"Not available" }}</td>{% endif %}
</tr>
{% endfor %}
</tbody>
@@ -234,6 +234,37 @@ class MailboxImportTests(TestCase):
source.fetch.assert_not_called()
source.append.assert_not_called()
def test_preview_separates_incremental_work_from_source_count(self):
names = [b"Archive.2020", b"Archive.2021", b"INBOX"]
source = Mock(capabilities=("IMAP4REV1",))
source.status.side_effect = [
(
"OK",
[b'"Archive.2020" (MESSAGES 999 UIDNEXT 1001 UIDVALIDITY 1)'],
),
("OK", [b'"Archive.2021" (MESSAGES 12 UIDNEXT 21 UIDVALIDITY 5)']),
("OK", [b'"INBOX" (MESSAGES 3 UIDNEXT 4 UIDVALIDITY 2)']),
]
first = Mock(last_uid=1000, source_validity=1, pending={})
second = Mock(last_uid=12, source_validity=5, pending={})
with (
patch.object(imap, "select", return_value=(5, 21)) as select,
patch.object(imap, "search_uids", return_value=[14, 17]) as search,
):
report = preview.inventory(
source,
[(name, name) for name in names],
{
imports.folder_key(names[0]): first,
imports.folder_key(names[1]): second,
},
)
select.assert_called_once_with(source, names[1], readonly=True)
search.assert_called_once_with(source, 13, last=20)
self.assertEqual(report["messages"], 1014)
self.assertTrue(report["incremental"])
self.assertEqual(report["remaining"], 5)
def test_preview_expires_without_queuing_an_import(self):
self.sign_in(self.customer)
self.client.post(self.url(), self.data(action="preview"))