Waafir
이 페이지는 사람의 검토를 기다리는 기계 번역입니다. 오류가 있을 수 있습니다.

진행 중인 가져오기 취소하기

이 레시피는 아직 처리 중인 비동기 가져오기를 취소하는 방법을 보여 줍니다. 워커는 배치 경계마다 취소 요청이 있는지 확인하며, 요청을 발견하면 진행 중인 배치가 끝나는 지점에서 멈추고 상태를 cancelled로 전환합니다. 취소 전에 완료된 행은 반영된 상태로 유지되며, 나중에 정리해야 할 일부만 기록된 배치는 없습니다.

취소해야 하는 경우

진행 도중에 가져오기가 잘못되었다는 것을 알게 되었을 때 취소 엔드포인트가 적합한 도구입니다. 잘못된 파일, 잘못된 포트폴리오, 오래된 스냅샷, 잘못된 날짜 등이 해당합니다. 일반적인 계기는 다음과 같습니다.

  • 모니터링 대시보드에서 가져오기에 잘못된 파일이 지정된 것을 발견한 경우.
  • 먼저 드라이런을 하려 했는데 프로덕션 포트폴리오를 대상으로 수백만 행의 백필을 시작한 경우.
  • 업로드가 완료된 후 업스트림 시스템이 파일을 손상된 것으로 표시한 경우.

취소는 dryRun: true를 대체하지 않습니다(드라이런 레시피 참조). 실제 가져오기가 실행되기 시작하면, 취소 시점 이전에 성공한 행은 커밋됩니다. Waafir가 일부만 기록된 배치를 남기지 않는다는 점은 믿을 수 있지만, 이미 커밋된 행을 되돌릴 수는 없습니다. 올바른 패턴은 잘못 반영된 내용을 조정하는 수정 가져오기를 후속으로 실행하는 것입니다.

배치 경계 보장

워커는 행을 200개 단위 배치로 처리합니다. 각 배치가 끝나면 가져오기 상태를 확인하고, 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 필드는 취소 전에 커밋된 행 수입니다. 반영된 항목의 확정 목록이 필요하다면 외부 ID로 해당 행을 대사하세요(대사 레시피 참조).

같은 가져오기에 두 번째 DELETE를 보내면 취소를 다시 실행하지 않고 기존 최종 상태를 반환합니다. 이 엔드포인트는 멱등합니다. 이미 최종 상태에 있는 가져오기(이미 succeeded, partial 또는 failed에 도달한 가져오기)를 취소하면 아무 작업도 하지 않고 기존 상태를 반환합니다.