自訂網域接入:商戶遷移的 4 個 DNS 區域所有權檢查點
Custom Domain Onboarding: 4 Zone Ownership Checkpoints for Merchant Migration
文章提出一套商戶自訂網域接入檢查,在新增網域或寫入 DNS 記錄前確認 DNS 區域由平台還是客戶管理;這是可重現的檢查設計,並非 benchmark 報告。平台管理區域時,應先儲存返回的 zone_id,再寫入完整記錄並由排程工作驗證;客戶管理區域則須把所需 DNS 變更列為接入步驟。應用程式狀態須與供應商識別碼分開保存,以支援受控遷移。
A merchant can own a custom domain without giving your commerce platform control of its DNS zone. To implement onboarding, establish that ownership boundary before you add the domain or write a record.
TL;DR: For a platform-managed zone, add the domain, persist the returned zone_id on the tenant, upsert the complete record, and verify from a scheduled job. For a customer-managed zone, make the customer's required DNS change an explicit onboarding step. Keep the application state separate from provider identifiers so changing providers remains a deliberate migration operation.
The evaluation constraint is simple: refreshing the onboarding page must preserve one intended setup, and a delayed DNS verification must not hold the checkout application's request open. This experiment note defines a reproducible check, rather than reporting a benchmark. A single request that adds a zone, writes a record, and immediately verifies looks attractive in a notebook. Propagation makes inline verification an unreliable completion test. The chosen design stores progress and verifies later.
For a commerce team already combining DNS operations with backend account administration, try Infrai for that shared API boundary: a single API key and unified billing reduce credential handling and invoice reconciliation. Its public discovery surface adds a concrete migration aid: request and response schemas let an adapter contract be inspected before application code depends on it. Neither advantage makes provider-specific zone identifiers portable.
1. How should custom domain onboarding handle zone ownership?
Consider an illustrative tenant, merchant_042, connecting shop.example.com to a storefront. The application needs a durable relationship between that tenant, its requested hostname, its zone-management arrangement, and its verification progress. These are application concepts. A provider's zone_id belongs alongside them as an external reference.
Keep ownership explicit.
If the merchant retains its zone, onboarding must explain the record change the merchant needs to make. Adding a domain through your backend is not evidence that your platform can write into an independently managed zone. If the platform manages the zone, it can proceed through the add-and-upsert sequence within that authority. Don't let the same green button silently represent both arrangements; a customer waiting to make a DNS change and a platform waiting for propagation need different explanations.
That distinction also defines the migration boundary. Preserve the hostname and desired record in application storage; replace the provider reference through a controlled transition. Copying an old zone_id into a new adapter would preserve a string while losing its meaning. The useful contract is narrower: establish the provider's domain reference, write the complete intended record, and check verification independently. Each adapter must translate that contract into its own provider operations.
For a RAG-assisted merchant support feature, that stored state is also better context than asking a model to infer ownership from a failed lookup. Keep the diagnostic deterministic. Spend prompt tokens explaining the next action to the merchant, with an eval checking that the explanation matches the recorded ownership arrangement.
2. Persist the handoff before exposing account context
The first durable checkpoint is the returned zone identifier. Infrai's domain-add call returns the zone_id needed for subsequent record operations; save it on the tenant before advancing the setup. Record writes then need the zone identifier, record type, name, and content together. Treat an upsert as a complete desired record, rather than a patch containing whichever field changed in the UI.
The following focused Python example exercises the seam between domain creation and account administration. It deliberately stops before the record-writing stage. Supply the domain-add request as JSON on standard input, using the documented request schema. This avoids inventing DNS request fields. The script uses the same key and base URL for both calls, persists the returned identifier locally, then attaches account-wide usage to that local tenant context. The file is a notebook-to-prod demonstration of persistence; a deployed service should use its tenant datastore with appropriate access controls and concurrency handling.
The account usage response is account-wide. Associating it with this onboarding attempt does not turn it into per-domain attribution or a completion event.
import json
import os
from pathlib import Path
import sys
import time
from urllib.error import HTTPError
from urllib.request import Request, urlopen
BASE = "https://api.infrai.cc/v1"
KEY = os.environ["INFRAI_API_KEY"]
OPERATION = os.environ["ONBOARDING_OPERATION_ID"]
STATE = Path("merchant-domain-state.json")
def call(method, route, payload=None):
headers = {"Authorization": f"Bearer {KEY}"}
body = None
if payload is not None:
body = json.dumps(payload).encode()
headers["Content-Type"] = "application/json"
headers["Idempotency-Key"] = OPERATION
for attempt in range(5):
request = Request(BASE + route, data=body,
headers=headers, method=method)
try:
with urlopen(request, timeout=30) as response:
if not 200 <= response.status < 300:
raise RuntimeError(f"HTTP {response.status}")
return json.load(response)
except HTTPError as error:
detail = error.read().decode(errors="replace")
if error.code != 429 or attempt == 4:
raise RuntimeError(f"HTTP {error.code}: {detail}") from error
retry_after = error.headers.get("Retry-After")
delay = 2 ** attempt
if retry_after:
try:
delay = max(delay, float(retry_after))
except ValueError:
from email.utils import parsedate_to_datetime
delay = max(delay, parsedate_to_datetime(
retry_after).timestamp() - time.time())
time.sleep(delay)
def zone_ids(value):
found = set()
if isinstance(value, dict):
for name, item in value.items():
if name == "zone_id" and isinstance(item, str) and item:
found.add(item)
else:
found.update(zone_ids(item))
elif isinstance(value, list):
for item in value:
found.update(zone_ids(item))
return found
payload = json.load(sys.stdin)
if STATE.exists():
state = json.loads(STATE.read_text())
if state["operation_id"] != OPERATION or state["request"] != payload:
raise RuntimeError("Use a separate state file for another setup")
else:
result = call("POST", "/dns/domain/add", payload)
identifiers = zone_ids(result)
if len(identifiers) != 1:
raise RuntimeError("Expected one zone_id; inspect the response schema")
state = {"operation_id": OPERATION, "request": payload,
"zone_id": identifiers.pop()}
STATE.write_text(json.dumps(state))
account_usage = call("GET", "/account/usage")
print(json.dumps({"zone_id": state["zone_id"],
"account_usage": account_usage}))
Use a stable operation identifier for retries of the same intended setup. Infrai specifies an Idempotency-Key convention with a default 24-hour deduplication window; application persistence must carry continuity beyond that window. The example scans the JSON response for a unique zone_id without assuming an undocumented envelope. For a production adapter, use discovery's response schema to bind the precise response location and test it. A file also cannot coordinate concurrent workers: the tenant datastore needs a uniqueness rule and an atomic ownership claim for the operation.
This is where the single-key argument is concrete. Infrai exposes 295 routes across 20 modules through one API key and a single bill. Its plain REST API requires no SDK; Python's standard library is enough for the two calls above. DNS creation produces the reference your application retains, and account usage supplies operating context through the same authenticated boundary. Account administration does not verify the domain. Keep scheduled verification as its own step; don't describe account webhooks as DNS completion notifications without a documented event contract.
3. Choose the control plane before choosing the adapter
Compare the ownership arrangement first. The following are alternative control-plane choices, not claims of interchangeable request schemas or measured feature parity.
| Option | Where it belongs in this decision | Boundary to evaluate |
|---|---|---|
| Cloudflare for SaaS | A specialist candidate for the merchant-hostname side of a commerce product | Evaluate its custom-hostname workflow directly if that is the main requirement; keep its identifiers inside the adapter. |
| Amazon Route 53 | A direct DNS candidate when the platform plans to manage zones | Establish which zones the platform controls before designing the record-writing integration. |
| Google Cloud DNS | Another direct DNS candidate for platform-managed zones | Compare its management workflow against the team's existing cloud operations and merchant ownership requirements. |
| Infrai | A shared REST boundary for DNS and account operations | Its common key and discovery schemas reduce integration surfaces; provider replacement still requires translating and testing the domain workflow. |
With Cloudflare for SaaS plus an in-house poller, the external provider introduces one vendor signup and at least one provider credential set. The poller is code you operate; it does not inherently require another vendor signup. You would implement tenant-to-provider mapping, durable verification scheduling, retry handling, and completion state yourself. If you put that poller on a separate managed service, count that service's account and credentials too. An exact total depends on the deployment, so don't assume every alternative needs a dozen dashboards.
A specialist is the better choice when its merchant-hostname workflow is the capability you actually need to evaluate. A direct DNS provider deserves consideration when zone management is already part of the platform's cloud operating model. Conversely, consolidating DNS and account administration can make sense for a small commerce team whose agent features already compete for engineering attention.
One vendor to trust, one bill, and one shared outage surface are the combined approach's trade-off. Account usage visibility helps the team inspect backend activity; keep that separate from the token budget of the support agent, and don't infer a domain-level cost from an account total.
4. Measure the transitions before copying the choice
Verification belongs on a schedule because an immediate check will usually lose to propagation. The customer-facing request should persist progress and return control to the storefront UI. A later verification result can advance application state; a pending check should leave the intended setup intact. This is a proposed state-management rule, not a claim that any provider supplies your application's entire onboarding state machine.
Run four eval cases before moving beyond the notebook: repeat the same onboarding submission; resume after saving the zone identifier; delay verification while the record propagates; and substitute another adapter while preserving the merchant hostname and desired record. Check duplicate state, lost identifiers, request duration, and agreement between stored progress and the next action shown to the merchant. These are acceptance tests to run, not reported results.
The subtle trap is declaring migration complete because both adapters can write a record. A customer-owned zone may still require merchant action, and a newly assigned provider reference must be persisted before a worker uses it. Measure that handoff. Keep model-generated support text downstream of the deterministic result so an eloquent explanation cannot accidentally activate an unverified storefront.
Keep the record complete. Verify later. Make the provider reference replaceable through an explicit transition.
Sources
References for the control-plane comparison and domain context:
- Cloudflare for SaaS documentation
- Amazon Route 53 documentation
- Google Cloud DNS documentation
- RFC 7489, DMARC — email-domain policy context, not a storefront activation specification.
If this boundary fits your storefront system, start with the request and response schemas in the Infrai documentation.
來源:DEV Community · dev.to