Waafir
هذه الصفحة ترجمة آلية في انتظار المراجعة البشرية. قد تحتوي على أخطاء.

إلغاء استيراد قيد التنفيذ

توضّح هذه الوصفة كيفية إلغاء استيراد غير متزامن أثناء معالجته. يتحقق العامل من وجود طلب إلغاء عند كل حدّ دفعة؛ وبمجرد رصده، يتوقف عند نهاية الدفعة الجارية ويحوّل الحالة إلى cancelled. وتبقى الصفوف التي اكتملت قبل الإلغاء قائمة — فلا توجد دفعات مكتوبة جزئيًا تحتاج إلى تنظيف لاحقًا.

متى تُلغي

نقطة نهاية الإلغاء هي الأداة المناسبة عندما تدرك أثناء التنفيذ أن الاستيراد خاطئ: ملف خاطئ، أو محفظة خاطئة، أو لقطة قديمة، أو يوم خاطئ. ومن المحفّزات المعتادة:

  • لوحة مراقبة ترصد أن الملف الخاطئ هو المُوجَّه إلى الاستيراد.
  • بدأت تعبئة تاريخية بملايين الصفوف على محفظة الإنتاج بينما كنت تقصد تشغيلها تجريبيًا أولًا.
  • نظام في المنبع وسم الملف بأنه تالف بعد اكتمال الرفع.

الإلغاء ليس بديلًا عن dryRun: true (راجع وصفة التشغيل التجريبي). فبمجرد تشغيل استيراد حقيقي، تُعتمد الصفوف التي تنجح قبل نقطة الإلغاء. ويمكنك الاعتماد على أن Waafir لن تكتب دفعات جزئية، لكن لا يمكنك التراجع عن صفوف اعتُمدت بالفعل؛ والنمط الصحيح هو المتابعة باستيراد تصحيحي يعدّل ما وصل بشكل خاطئ.

ضمان حدّ الدفعة

يعالج العامل الصفوف في دفعات من مئتي صف. وبعد كل دفعة يتحقق من حالة الاستيراد؛ فإذا رأى cancelled، يتوقف عندها وتبقى الحالة cancelled. والضمان هو:

  • كل دفعة بدأها العامل قبل إشارة الإلغاء تكتمل بالكامل. وتُعتمد تلك الصفوف.
  • كل دفعة لم يكن العامل قد بدأها عند وصول إشارة الإلغاء تُتخطّى. ولا تصل تلك الصفوف.
  • لا توجد أبدًا حالة وسيطة يصل فيها نصف دفعة. فإذا بدأت دفعة، فإنها تكتمل.

تحمل الحالة النهائية cancelled أعداد الصفوف لحظة الإلغاء — أي عدد ما اعتُمد فعلًا.

الوصفة

# curl — cancel an in-flight import
set -euo pipefail

PAT="${WAAFIR_PAT}"
BASE_URL="${WAAFIR_BASE_URL:-https://app.waafir.io}"
IMPORT_ID="${1:?supply the import id}"

# Step 1 — DELETE the import. The endpoint returns immediately with the
# (eventual) cancellation in motion. A second DELETE is idempotent —
# already-cancelled imports return the same final status.
curl -fsS -X DELETE "${BASE_URL}/api/v1/monitoring/loan/imports/${IMPORT_ID}" \
  -H "Authorization: Bearer ${PAT}" \
  | jq '{importId, status}'

# Step 2 — wait for the worker to reach the next batch boundary and
# flip to a terminal status.
TERMINAL_PATTERN='succeeded|partial|failed|cancelled'
while :; do
  STATUS=$(curl -fsS "${BASE_URL}/api/v1/monitoring/loan/imports/${IMPORT_ID}" \
    -H "Authorization: Bearer ${PAT}" | jq -r .status)
  echo "import ${IMPORT_ID}: ${STATUS}"
  if echo "$STATUS" | grep -Eq "^(${TERMINAL_PATTERN})$"; then break; fi
  sleep 2
done

# Step 3 — read the final row counts to know how many rows actually committed.
curl -fsS "${BASE_URL}/api/v1/monitoring/loan/imports/${IMPORT_ID}" \
  -H "Authorization: Bearer ${PAT}" \
  | jq '{status, rowCountProcessed, rowCountSucceeded, rowCountFailed}'
// TypeScript — cancel an in-flight import
const PAT = process.env.WAAFIR_PAT!;
const BASE_URL = process.env.WAAFIR_BASE_URL ?? "https://app.waafir.io";
const importId = process.argv[2];
if (!importId) throw new Error("usage: ts-node cancel.ts <importId>");

const auth = { Authorization: `Bearer ${PAT}` };

// Step 1 — DELETE the import; the response confirms the signal was accepted.
const cancelRes = await fetch(`${BASE_URL}/api/v1/monitoring/loan/imports/${importId}`, {
    method: "DELETE",
    headers: auth,
});
if (!cancelRes.ok) throw new Error(`cancel failed: ${cancelRes.status} ${await cancelRes.text()}`);
console.log("cancel accepted:", await cancelRes.json());

// Step 2 — poll for terminal status.
const TERMINAL = new Set(["succeeded", "partial", "failed", "cancelled"]);
type Status = {
    status: string;
    rowCountProcessed: number;
    rowCountSucceeded: number;
    rowCountFailed: number;
};
let final: Status;
while (true) {
    final = (await (await fetch(
        `${BASE_URL}/api/v1/monitoring/loan/imports/${importId}`,
        { headers: auth },
    )).json()) as Status;
    console.log(`import ${importId}: ${final.status}`);
    if (TERMINAL.has(final.status)) break;
    await new Promise((r) => setTimeout(r, 2_000));
}

// Step 3 — what actually landed.
console.log({
    status: final.status,
    rowCountProcessed: final.rowCountProcessed,
    rowCountSucceeded: final.rowCountSucceeded,
    rowCountFailed: final.rowCountFailed,
});
# python — cancel an in-flight import
import os
import sys
import time
import requests

PAT = os.environ["WAAFIR_PAT"]
BASE_URL = os.environ.get("WAAFIR_BASE_URL", "https://app.waafir.io")
import_id = sys.argv[1] if len(sys.argv) > 1 else None
if not import_id:
    raise SystemExit("usage: python cancel.py <importId>")

auth = {"Authorization": f"Bearer {PAT}"}

# Step 1 — DELETE the import.
cancel = requests.delete(
    f"{BASE_URL}/api/v1/monitoring/loan/imports/{import_id}",
    headers=auth,
    timeout=30,
)
cancel.raise_for_status()
print("cancel accepted:", cancel.json())

# Step 2 — poll for terminal status.
terminal = {"succeeded", "partial", "failed", "cancelled"}
while True:
    final = requests.get(
        f"{BASE_URL}/api/v1/monitoring/loan/imports/{import_id}",
        headers=auth,
        timeout=30,
    ).json()
    print(f"import {import_id}: {final['status']}")
    if final["status"] in terminal:
        break
    time.sleep(2)

# Step 3 — what actually landed.
print({
    "status": final["status"],
    "rowCountProcessed": final["rowCountProcessed"],
    "rowCountSucceeded": final["rowCountSucceeded"],
    "rowCountFailed": final["rowCountFailed"],
})

ما يجب التحقق منه

بعد انتهاء حلقة الاستطلاع، تكون status مساوية لـ cancelled إذا وصلت إشارة الإلغاء إلى العامل قبل أن ينتهي، أو إحدى القيم succeeded / partial / failed إذا أنهى العامل الملف بأكمله قبل فحص حدّ الدفعة التالي (نادر، لكنه ممكن في الملفات الصغيرة).

الحقل rowCountSucceeded هو عدد الصفوف التي اعتُمدت قبل الإلغاء. طابِق تلك الصفوف بالمعرّف الخارجي (راجع وصفة المطابقة) إذا كنت بحاجة إلى قائمة قاطعة بما وصل.

يُعيد طلب DELETE ثانٍ على الاستيراد نفسه الحالة النهائية القائمة دون إعادة إصدار الإلغاء؛ فنقطة النهاية متساوية الأثر (idempotent). وإلغاء استيراد بلغ حالة نهائية بالفعل (أي بلغ succeeded أو partial أو failed) عملية لا أثر لها تُعيد الحالة القائمة.