|
| 1 | +import logging |
1 | 2 | from collections.abc import Callable, Iterator |
2 | 3 | from functools import partial |
3 | 4 | from typing import Any |
| 5 | +from constance import config |
4 | 6 | from uuid import UUID, uuid4 |
5 | 7 |
|
| 8 | +from django.core import signing |
6 | 9 | from django.db import IntegrityError, transaction |
7 | | - |
8 | | -from country_workspace.contrib.dedup_engine import REJECTABLE_DEDUPLICATION_SET_STATES, make_dedup_client |
| 10 | +from django.urls import reverse |
| 11 | +from strategy_field.utils import fqn |
| 12 | + |
| 13 | +from country_workspace.contrib.dedup_engine import ( |
| 14 | + REJECTABLE_DEDUPLICATION_SET_STATES, |
| 15 | + DedupResponseStatus, |
| 16 | + DeduplicationSetState, |
| 17 | + make_dedup_client, |
| 18 | +) |
9 | 19 | from country_workspace.contrib.hope.exceptions import HopePushError |
10 | 20 | from country_workspace.exceptions import RemoteError, RemoteUnavailableError |
11 | 21 | from country_workspace.models import AsyncJob, Rdp |
|
20 | 30 | qs_households, |
21 | 31 | qs_individuals_by_household_pks, |
22 | 32 | qs_individuals_by_pks, |
| 33 | + qs_individuals_for_rdp, |
23 | 34 | rdp_for_dedup, |
24 | 35 | rdp_for_push, |
25 | 36 | release_rdp_dedup_settings_lock, |
|
28 | 39 | workflow_config_for_rdp, |
29 | 40 | ) |
30 | 41 |
|
| 42 | +_DEDUP_CALLBACK_SIGN_KEY = "dedup_callback" |
| 43 | +_DEDUP_CALLBACK_MAX_AGE = 60 * 60 * 96 # 96 hours |
| 44 | + |
| 45 | +logger = logging.getLogger(__name__) |
| 46 | + |
31 | 47 |
|
32 | 48 | def _require_policy_check(check: Callable[[], ActionCheck]) -> None: |
33 | 49 | try: |
@@ -78,6 +94,210 @@ def create_rdp_core(job: AsyncJob) -> dict[str, Any]: |
78 | 94 | return {"rdp_id": rdp.id, "rdp_str": str(rdp)} |
79 | 95 |
|
80 | 96 |
|
| 97 | +def _build_dedup_callback_url(rdp_id: int, job_id: int) -> str: |
| 98 | + """Build an absolute, signed callback URL for the dedup engine to call when dedup finishes.""" |
| 99 | + token = signing.dumps( |
| 100 | + {"rdp_id": rdp_id, "job_id": job_id}, |
| 101 | + key=_DEDUP_CALLBACK_SIGN_KEY, |
| 102 | + ) |
| 103 | + path = reverse("dedup_callback", kwargs={"signed_token": token}) |
| 104 | + base = config.APP_BASE_URL.rstrip("/") |
| 105 | + return f"{base}{path}" |
| 106 | + |
| 107 | + |
| 108 | +def create_rdp_and_start_dedup_core(job: AsyncJob) -> dict[str, Any]: |
| 109 | + """Create an RDP, upload images to the dedup engine, and start deduplication. |
| 110 | +
|
| 111 | + The dedup engine will call back the notification URL when deduplication finishes. |
| 112 | + The push to HOPE is deferred until the callback is received and the findings |
| 113 | + threshold is evaluated. |
| 114 | + """ |
| 115 | + create_result = create_rdp_core(job) |
| 116 | + rdp_id = create_result["rdp_id"] |
| 117 | + |
| 118 | + with transaction.atomic(): |
| 119 | + _check, rdp = claim_rdp_deduplication(rdp_id) |
| 120 | + if rdp is None: |
| 121 | + raise HopePushError({"errors": ["RDP: could not claim deduplication set."], "rdp_id": rdp_id}) |
| 122 | + |
| 123 | + job.refresh_from_db() |
| 124 | + |
| 125 | + callback_url = _build_dedup_callback_url(rdp_id=rdp_id, job_id=job.pk) |
| 126 | + processor = DedupProcessor(rdp) |
| 127 | + processor.run(notification_url=callback_url) |
| 128 | + |
| 129 | + if processor.has_errors: |
| 130 | + raise HopePushError({**processor.total, "rdp_id": rdp_id}) |
| 131 | + |
| 132 | + with transaction.atomic(): |
| 133 | + locked = lock_rdp_for_update(pk=rdp_id) |
| 134 | + locked.status = Rdp.PushStatus.DEDUP_PENDING |
| 135 | + locked.save(update_fields=["status"]) |
| 136 | + |
| 137 | + return {**create_result, "dedup_pending": True} |
| 138 | + |
| 139 | + |
| 140 | +def create_and_push_rdp_core(job: AsyncJob) -> dict[str, Any]: |
| 141 | + """Create an RDP and start deduplication; the push to HOPE is deferred. |
| 142 | +
|
| 143 | + Push to HOPE is only available for programs with biometric deduplication |
| 144 | + enabled. Deduplication is started first and the push is deferred until the |
| 145 | + dedup engine calls back the notification URL and the findings threshold is |
| 146 | + evaluated. |
| 147 | + """ |
| 148 | + rdp_program = job.program |
| 149 | + if not (rdp_program and rdp_program.biometric_deduplication_enabled): |
| 150 | + raise HopePushError({"errors": ["RDP: push to HOPE requires biometric deduplication for this program."]}) |
| 151 | + return create_rdp_and_start_dedup_core(job) |
| 152 | + |
| 153 | + |
| 154 | +def _lock_and_fail_rdp(rdp_id: int, *, reason: str) -> None: |
| 155 | + with transaction.atomic(): |
| 156 | + locked = lock_rdp_for_update(pk=rdp_id) |
| 157 | + if locked.status == Rdp.PushStatus.DEDUP_PENDING: |
| 158 | + set_rdp_push_status(rdp=locked, status=Rdp.PushStatus.FAILURE, hope_rdi_id="N/A") |
| 159 | + logger.warning( |
| 160 | + "dedup_callback_handle: rdp_id=%s marked FAILURE (%s)", |
| 161 | + rdp_id, |
| 162 | + reason, |
| 163 | + ) |
| 164 | + else: |
| 165 | + logger.info( |
| 166 | + "dedup_callback_handle: rdp_id=%s skip FAILURE (%s); status=%s", |
| 167 | + rdp_id, |
| 168 | + reason, |
| 169 | + locked.status, |
| 170 | + ) |
| 171 | + |
| 172 | + |
| 173 | +def _handle_deduplicated(rdp: Rdp, rdp_id: int, findings_count: int) -> None: |
| 174 | + origin_job = AsyncJob.objects.filter(rdp_id=rdp_id).order_by("-id").first() |
| 175 | + max_findings_percent: int = origin_job.config.get("max_dedup_findings_percent", 0) if origin_job else 0 |
| 176 | + |
| 177 | + total_individuals = qs_individuals_for_rdp(rdp=rdp).count() |
| 178 | + findings_rate = findings_count / total_individuals * 100 if total_individuals > 0 else float(findings_count) |
| 179 | + |
| 180 | + logger.info( |
| 181 | + "dedup_callback_handle: rdp_id=%s DEDUPLICATED findings_count=%s total_individuals=%s " |
| 182 | + "findings_rate=%.2f%% max_dedup_findings_percent=%s", |
| 183 | + rdp_id, |
| 184 | + findings_count, |
| 185 | + total_individuals, |
| 186 | + findings_rate, |
| 187 | + max_findings_percent, |
| 188 | + ) |
| 189 | + |
| 190 | + if findings_rate > max_findings_percent: |
| 191 | + _lock_and_fail_rdp( |
| 192 | + rdp_id, |
| 193 | + reason=f"findings_rate {findings_rate:.2f}% exceeds threshold {max_findings_percent}%", |
| 194 | + ) |
| 195 | + return |
| 196 | + |
| 197 | + with transaction.atomic(): |
| 198 | + locked = lock_rdp_for_update(pk=rdp_id) |
| 199 | + if locked.status != Rdp.PushStatus.DEDUP_PENDING: |
| 200 | + logger.warning( |
| 201 | + "dedup_callback_handle: rdp_id=%s skip push queue; status changed to %s", |
| 202 | + rdp_id, |
| 203 | + locked.status, |
| 204 | + ) |
| 205 | + return |
| 206 | + locked.status = Rdp.PushStatus.PENDING |
| 207 | + locked.save(update_fields=["status"]) |
| 208 | + |
| 209 | + push_job = AsyncJob.objects.create( |
| 210 | + description=f"Push RDP {rdp_id} to HOPE (post-dedup)", |
| 211 | + type=AsyncJob.JobType.TASK, |
| 212 | + owner=rdp.pushed_by, |
| 213 | + action=fqn(push_existing_rdp_core), |
| 214 | + program=rdp.program, |
| 215 | + rdp=rdp, |
| 216 | + config={"rdp_id": rdp_id}, |
| 217 | + ) |
| 218 | + push_job.queue() |
| 219 | + logger.info( |
| 220 | + "dedup_callback_handle: rdp_id=%s status DEDUP_PENDING→PENDING; queued push job_id=%s", |
| 221 | + rdp_id, |
| 222 | + push_job.pk, |
| 223 | + ) |
| 224 | + |
| 225 | + |
| 226 | +def dedup_callback_handle(rdp_id: int) -> None: |
| 227 | + """Handle a dedup engine callback for the given RDP. |
| 228 | +
|
| 229 | + Fetches the current deduplication set state from the engine. Only acts on |
| 230 | + terminal states (``DEDUPLICATED``, ``DEDUPLICATION_FAILED``, |
| 231 | + ``ENCODING_FAILED``). For intermediate states the function returns |
| 232 | + immediately so the engine can call again after the next state transition. |
| 233 | +
|
| 234 | + When dedup is successful and findings are within the configured threshold, |
| 235 | + a ``push_existing_rdp_core`` async job is queued. Otherwise the RDP is |
| 236 | + marked as ``FAILURE``. |
| 237 | + """ |
| 238 | + try: |
| 239 | + rdp = rdp_for_push(pk=rdp_id) |
| 240 | + except Rdp.DoesNotExist: |
| 241 | + logger.warning("dedup_callback_handle: rdp_id=%s not found", rdp_id) |
| 242 | + return |
| 243 | + |
| 244 | + if rdp.status != Rdp.PushStatus.DEDUP_PENDING: |
| 245 | + logger.info( |
| 246 | + "dedup_callback_handle: rdp_id=%s skip; status=%s (expected DEDUP_PENDING)", |
| 247 | + rdp_id, |
| 248 | + rdp.status, |
| 249 | + ) |
| 250 | + return |
| 251 | + |
| 252 | + if not rdp.deduplication_set_id: |
| 253 | + logger.warning("dedup_callback_handle: rdp_id=%s missing deduplication_set_id", rdp_id) |
| 254 | + _lock_and_fail_rdp(rdp_id, reason="missing deduplication_set_id") |
| 255 | + return |
| 256 | + |
| 257 | + logger.info( |
| 258 | + "dedup_callback_handle: rdp_id=%s deduplication_set_id=%s; fetching remote status", |
| 259 | + rdp_id, |
| 260 | + rdp.deduplication_set_id, |
| 261 | + ) |
| 262 | + |
| 263 | + status = get_rdp_policy(rdp).deduplication_status(rdp) |
| 264 | + if status is None: |
| 265 | + logger.warning( |
| 266 | + "dedup_callback_handle: rdp_id=%s dedup engine returned no status; leaving DEDUP_PENDING", |
| 267 | + rdp_id, |
| 268 | + ) |
| 269 | + return |
| 270 | + |
| 271 | + if status.response_status != DedupResponseStatus.OK: |
| 272 | + logger.warning( |
| 273 | + "dedup_callback_handle: rdp_id=%s dedup engine status unavailable (%s); leaving DEDUP_PENDING", |
| 274 | + rdp_id, |
| 275 | + status.response_status, |
| 276 | + ) |
| 277 | + return |
| 278 | + |
| 279 | + dedup_state = status.deduplication_set_status |
| 280 | + terminal_failure_states = {DeduplicationSetState.DEDUPLICATION_FAILED, DeduplicationSetState.ENCODING_FAILED} |
| 281 | + |
| 282 | + logger.info( |
| 283 | + "dedup_callback_handle: rdp_id=%s remote_state=%s findings_count=%s", |
| 284 | + rdp_id, |
| 285 | + dedup_state, |
| 286 | + status.findings_count, |
| 287 | + ) |
| 288 | + |
| 289 | + if dedup_state in terminal_failure_states: |
| 290 | + _lock_and_fail_rdp(rdp_id, reason=f"dedup engine state {dedup_state}") |
| 291 | + elif dedup_state == DeduplicationSetState.DEDUPLICATED: |
| 292 | + _handle_deduplicated(rdp, rdp_id, status.findings_count) |
| 293 | + else: |
| 294 | + logger.info( |
| 295 | + "dedup_callback_handle: rdp_id=%s intermediate state %s; waiting for next callback", |
| 296 | + rdp_id, |
| 297 | + dedup_state, |
| 298 | + ) |
| 299 | + |
| 300 | + |
81 | 301 | def claim_rdp_deduplication(rdp_id: int) -> tuple[ActionCheck, Rdp | None]: |
82 | 302 | rdp = rdp_for_dedup(pk=rdp_id) |
83 | 303 | policy = get_rdp_policy(rdp) |
|
0 commit comments