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

+4 -1
View File
@@ -2486,7 +2486,10 @@ read-only count of source folders and messages before copying. The size
is shown only when the source reports it for every folder. Partial is shown only when the source reports it for every folder. Partial
inventories identify how many folders were counted. Counts describe the inventories identify how many folders were counted. Counts describe the
source at the time of the check and include mail already copied on prior source at the time of the check and include mail already copied on prior
passes. Confirmation starts a new copy pass with the same source passes. On a subsequent pass, the preview can count messages after a
matching checkpoint in a bounded UID range. It leaves the estimate
unavailable for folders where it cannot do so reliably. Confirmation
starts a new copy pass with the same source
credentials and uses the existing checkpoints. The preview expires after credentials and uses the existing checkpoints. The preview expires after
30 minutes. Use **Import without preview** if you do not need an 30 minutes. Use **Import without preview** if you do not need an
inventory or your provider does not supply usable folder counts. inventory or your provider does not supply usable folder counts.
+8
View File
@@ -131,6 +131,14 @@ Show a blocked prerequisite beside the resource that needs it. Put the
reason and retry action there for operators with the relevant permission. reason and retry action there for operators with the relevant permission.
Give customers a short next step without showing internal service details. Give customers a short next step without showing internal service details.
### Import previews
Separate a read-only preview from the action that starts a copy. Identify
the source and destination, show the snapshot totals first, and put the
per-folder or per-item breakdown below. Label partial counts and missing
estimates explicitly. Distinguish the full source inventory from work
remaining after a checkpoint. Do not display credentials or source content.
## Review a UI change ## Review a UI change
Compare the result with a Core page that serves the same purpose. In light Compare the result with a Core page that serves the same purpose. In light
+70 -10
View File
@@ -26,7 +26,9 @@ from .resource_requests import lock_hosting_account
LIFETIME = timedelta(minutes=30) LIFETIME = timedelta(minutes=30)
INSPECT_SECONDS = 70 INSPECT_SECONDS = 70
MAX_FOLDERS = 1000 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." EXPIRED = "The preview expired. Enter the source password to check again."
UNAVAILABLE = "This mailbox is no longer available for preview." UNAVAILABLE = "This mailbox is no longer available for preview."
@@ -162,7 +164,8 @@ def authorized_mailbox(preview):
def folder_status(client, name, include_size): 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: try:
result, rows = client.status(imap.quote(name), attributes) result, rows = client.status(imap.quote(name), attributes)
except imaplib.IMAP4.abort: except imaplib.IMAP4.abort:
@@ -172,14 +175,45 @@ def folder_status(client, name, include_size):
if result != "OK" and include_size: if result != "OK" and include_size:
return folder_status(client, name, False) return folder_status(client, name, False)
if result != "OK" or not rows or not isinstance(rows[0], bytes): 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. # Match attributes after the folder name, which may contain spaces.
fields = rows[0].rsplit(b"(", 1)[-1] fields = rows[0].rsplit(b"(", 1)[-1]
values = {key: int(count) for key, count in STAT.findall(fields)} return {key: int(count) for key, count in STAT.findall(fields)}
return values.get(b"MESSAGES"), values.get(b"SIZE")
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 deadline = monotonic() + INSPECT_SECONDS
caps = {cap.upper() for cap in client.capabilities} caps = {cap.upper() for cap in client.capabilities}
include_size = bool({"STATUS=SIZE", "IMAP4REV2"} & caps) include_size = bool({"STATUS=SIZE", "IMAP4REV2"} & caps)
@@ -187,12 +221,19 @@ def inventory(client, mapping):
for source_name, _ in mapping[:MAX_FOLDERS]: for source_name, _ in mapping[:MAX_FOLDERS]:
if monotonic() >= deadline: if monotonic() >= deadline:
break break
count, size = folder_status(client, source_name, include_size) status = folder_status(client, source_name, include_size)
folders.append( folders.append(
{ {
"name": imports.display_name(source_name), "name": imports.display_name(source_name),
"count": count, "count": status.get(b"MESSAGES"),
"bytes": size, "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] 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) if complete and all(folder["bytes"] is not None for folder in readable)
else None, else None,
"complete": complete, "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() @sensitive_variables()
def run_preview(preview): def run_preview(preview):
mailbox = authorized_mailbox(preview) mailbox = authorized_mailbox(preview)
@@ -243,4 +303,4 @@ def run_preview(preview):
raise imap.MailboxImportError( raise imap.MailboxImportError(
"The source has no selectable folders to copy." "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 %} {% elif preview.problem %}
<p class="section-text" role="status">{{ preview.problem }}</p> <p class="section-text" role="status">{{ preview.problem }}</p>
{% else %} {% 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> <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"> <dl class="details section-text">
<div><dt>Folders counted</dt><dd>{{ preview.report.readable }} of {{ preview.report.total_folders }}</dd></div> <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> <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> <div><dt>Source size</dt><dd>{% if preview.report.bytes is not None %}{{ preview.report.bytes|filesizeformat }}{% else %}Not available{% endif %}</dd></div>
</dl> </dl>
{% if not preview.report.complete %} {% if not preview.report.complete %}
@@ -90,13 +95,14 @@
{% endif %} {% endif %}
<div class="table-scroll"> <div class="table-scroll">
<table> <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> <tbody>
{% for folder in preview.report.folders %} {% for folder in preview.report.folders %}
<tr> <tr>
<th scope="row">{{ folder.name }}</th> <th scope="row">{{ folder.name }}</th>
<td>{{ folder.count|default_if_none:"Not available" }}</td> <td>{{ folder.count|default_if_none:"Not available" }}</td>
<td>{% if folder.bytes is not None %}{{ folder.bytes|filesizeformat }}{% else %}Not available{% endif %}</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> </tr>
{% endfor %} {% endfor %}
</tbody> </tbody>
@@ -234,6 +234,37 @@ class MailboxImportTests(TestCase):
source.fetch.assert_not_called() source.fetch.assert_not_called()
source.append.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): def test_preview_expires_without_queuing_an_import(self):
self.sign_in(self.customer) self.sign_in(self.customer)
self.client.post(self.url(), self.data(action="preview")) self.client.post(self.url(), self.data(action="preview"))