이 페이지는 사람의 검토를 기다리는 기계 번역입니다. 오류가 있을 수 있습니다.
데이터를 커밋하기 전에 드라이런으로 로드 검증하기
이 레시피는 데이터를 커밋하기 전에 비동기 가져오기 엔드포인트를 부작용 없는 검증 도구로 사용하는 방법을 보여 줍니다. 흐름은 대량 가져오기 레시피와 동일하며(시작, 업로드, 커밋, 폴링), 매개변수 하나만 바뀝니다: dryRun: true. 워커는 전체 검증 파이프라인을 실행하고, 검증된 행을 성공 합계에 포함하지만, 행을 기록하지는 않습니다.
사용 시점
드라이런은 생성한 파일을 일일 제출에 믿고 쓰기 전에 형식이 올바른지 알고 싶을 때 적합한 도구입니다. 일반적인 용도는 다음과 같습니다.
- 대출 테이프 내보내기를 처음 연결할 때 JSON 형식이 Waafir의 기대와 일치하는지 확인하는 경우.
- 새 파일의 나머지를 제출하기 전에 처음 100개 행으로 야간 카나리 실행을 하는 경우.
- 자사 측 내부 스키마가 변경된 후, 전송 형식이 여전히 문제없이 파싱되는지 확인하는 경우.
드라이런은 실제 수집 경로와 같은 검증기를 실행하므로, 드라이런을 통과하면 같은 파일을 실제로 제출했을 때 성공적으로 반영된다는 강력한 보장이 됩니다. 다만 비대칭성이 있습니다. 드라이런은 행을 기록하지 않으므로 데이터베이스 고유성 제약 조건을 실행하지 않습니다. 따라서 드라이런이 받아들인 중복 외부 ID 때문에 실제 실행이 실패할 수 있습니다. 그 보장이 필요하다면 실제 실행 후 외부 ID로 대사하세요.
레시피
# curl — dry-run validation
set -euo pipefail
PAT="${WAAFIR_PAT}"
BASE_URL="${WAAFIR_BASE_URL:-https://app.waafir.io}"
NDJSON_FILE="loans-canary.ndjson"
# Step 1 — start an import with dryRun=true. The query parameter and
# the body field are both accepted; the query is the curl-friendly form.
START=$(curl -fsS -X POST "${BASE_URL}/api/v1/monitoring/loan/imports?dryRun=true" \
-H "Authorization: Bearer ${PAT}" \
-H "Content-Type: application/json" \
-d "$(cat <<JSON
{
"kind": "loan",
"filename": "${NDJSON_FILE}",
"sizeBytes": $(stat -c%s "${NDJSON_FILE}")
}
JSON
)")
IMPORT_ID=$(echo "$START" | jq -r .importId)
UPLOAD_URL=$(echo "$START" | jq -r .uploadUrl)
# Step 2 — upload the file, applying the signed-in headers the start
# response returned (same shape as a real import — see the
# async-import recipe for the full rationale).
HEADER_ARGS=$(echo "$START" | jq -r '.headers | to_entries[] | "-H \"\(.key): \(.value)\""')
eval curl -fsS -X PUT --data-binary @"\"${NDJSON_FILE}\"" $HEADER_ARGS "\"${UPLOAD_URL}\""
# Step 3 — commit; the worker enqueues but the row processor short-circuits.
curl -fsS -X POST "${BASE_URL}/api/v1/monitoring/loan/imports/${IMPORT_ID}/commit" \
-H "Authorization: Bearer ${PAT}"
# Step 4 — poll. Terminal status + dryRun:true means the file is structurally valid.
while :; do
BODY=$(curl -fsS "${BASE_URL}/api/v1/monitoring/loan/imports/${IMPORT_ID}" \
-H "Authorization: Bearer ${PAT}")
STATUS=$(echo "$BODY" | jq -r .status)
echo "dry-run ${IMPORT_ID}: ${STATUS}"
case "${STATUS}" in
succeeded|partial|failed|cancelled) break ;;
esac
sleep 5
done
# At terminal, inspect the row counts. `dryRun: true` should be present.
echo "$BODY" | jq '{status, dryRun, rowCountProcessed, rowCountSucceeded, rowCountFailed}'// TypeScript — dry-run validation
import { readFileSync, statSync } from "node:fs";
const PAT = process.env.WAAFIR_PAT!;
const BASE_URL = process.env.WAAFIR_BASE_URL ?? "https://app.waafir.io";
const NDJSON_FILE = "loans-canary.ndjson";
const auth = { Authorization: `Bearer ${PAT}` };
// Step 1 — start with dryRun=true via the body. (?dryRun=true is also accepted.)
const startRes = await fetch(`${BASE_URL}/api/v1/monitoring/loan/imports`, {
method: "POST",
headers: { ...auth, "Content-Type": "application/json" },
body: JSON.stringify({
kind: "loan",
filename: NDJSON_FILE,
sizeBytes: statSync(NDJSON_FILE).size,
dryRun: true,
}),
});
if (!startRes.ok) throw new Error(`start failed: ${startRes.status} ${await startRes.text()}`);
const { importId, uploadUrl, headers: uploadHeaders } = (await startRes.json()) as {
importId: string;
uploadUrl: string;
headers: Record<string, string>;
};
// Step 2 — upload, applying the signed-in headers.
const putRes = await fetch(uploadUrl, {
method: "PUT",
headers: uploadHeaders,
body: readFileSync(NDJSON_FILE),
});
if (!putRes.ok) throw new Error(`upload failed: ${putRes.status}`);
// Step 3 — commit.
const commitRes = await fetch(`${BASE_URL}/api/v1/monitoring/loan/imports/${importId}/commit`, {
method: "POST",
headers: auth,
});
if (!commitRes.ok) throw new Error(`commit failed: ${commitRes.status} ${await commitRes.text()}`);
// Step 4 — poll until terminal.
const TERMINAL = new Set(["succeeded", "partial", "failed", "cancelled"]);
let final: { status: string; dryRun: boolean; rowCountProcessed: number; rowCountSucceeded: number; rowCountFailed: number };
while (true) {
const statusRes = await fetch(`${BASE_URL}/api/v1/monitoring/loan/imports/${importId}`, { headers: auth });
final = (await statusRes.json()) as typeof final;
console.log(`dry-run ${importId}: ${final.status}`);
if (TERMINAL.has(final.status)) break;
await new Promise((r) => setTimeout(r, 5_000));
}
console.log({
status: final.status,
dryRun: final.dryRun,
rowCountProcessed: final.rowCountProcessed,
rowCountSucceeded: final.rowCountSucceeded,
rowCountFailed: final.rowCountFailed,
});# python — dry-run validation
import os
import time
import requests
from pathlib import Path
PAT = os.environ["WAAFIR_PAT"]
BASE_URL = os.environ.get("WAAFIR_BASE_URL", "https://app.waafir.io")
NDJSON_FILE = Path("loans-canary.ndjson")
auth = {"Authorization": f"Bearer {PAT}"}
# Step 1 — start with dryRun=True. The body field is the structured form;
# `?dryRun=true` on the query string is equivalent for curl ergonomics.
start = requests.post(
f"{BASE_URL}/api/v1/monitoring/loan/imports",
headers={**auth, "Content-Type": "application/json"},
json={
"kind": "loan",
"filename": NDJSON_FILE.name,
"sizeBytes": NDJSON_FILE.stat().st_size,
"dryRun": True,
},
timeout=30,
)
start.raise_for_status()
payload = start.json()
import_id = payload["importId"]
upload_url = payload["uploadUrl"]
upload_headers = payload["headers"]
# Step 2 — upload, applying the signed-in headers.
with NDJSON_FILE.open("rb") as fh:
requests.put(upload_url, data=fh, headers=upload_headers, timeout=300).raise_for_status()
# Step 3 — commit.
requests.post(
f"{BASE_URL}/api/v1/monitoring/loan/imports/{import_id}/commit",
headers=auth,
timeout=30,
).raise_for_status()
# Step 4 — poll until terminal.
terminal = {"succeeded", "partial", "failed", "cancelled"}
while True:
body = requests.get(
f"{BASE_URL}/api/v1/monitoring/loan/imports/{import_id}",
headers=auth,
timeout=30,
).json()
print(f"dry-run {import_id}: {body['status']}")
if body["status"] in terminal:
break
time.sleep(5)
print({
"status": body["status"],
"dryRun": body["dryRun"],
"rowCountProcessed": body["rowCountProcessed"],
"rowCountSucceeded": body["rowCountSucceeded"],
"rowCountFailed": body["rowCountFailed"],
})확인할 사항
최종 상태 객체에는 dryRun: true가 포함되므로 워커가 드라이런 모드로 실행되었는지 확인할 수 있습니다. 드라이런에서 행 수는 다음과 같은 특정한 의미를 가집니다.
rowCountSucceeded는 검증을 통과한 행 수입니다. 실제 실행이었다면 실제 행으로 반영되었을 수와 정확히 같습니다.rowCountFailed는 검증에 실패한 행 수입니다. 부분 실패 검사 레시피로 살펴보세요. 페이지 단위 오류 엔드포인트는 드라이런에서도 동일하게 작동합니다.rowCountProcessed는 그 합계로, 워커가 검토한 모든 행입니다.
드라이런에서 실패한 행이 0개라면, 같은 파일을 (dryRun: true 없이) 실제로 제출했을 때 위에서 언급한 데이터베이스 고유성 비대칭성을 제외하면 문제없이 반영됩니다.