انتقل إلى المحتوى الرئيسي

أمثلة على تكامل SDK

توفر هذه الصفحة أنماط تكامل جاهزة للإنتاج لواجهات برمجة تطبيقات AuroraSOC.

متى تستخدم هذه الصفحة

استخدم هذه الصفحة عند إنشاء عمليات تكامل الخدمة أو عمال التشغيل الآلي أو أغلفة SDK الداخلية.

أهداف التصميم لتكاملات العملاء

  1. مركزية الحصول على الرمز المميز وتحديثه
  2. تطبيع عمليات إعادة المحاولة للأخطاء العابرة (429، 503، المحدد 500)
  3. فرض التحقق من صحة الطلب/الاستجابة على الحدود
  4. قم بإصدار القياس عن بعد لوقت الاستجابة والفشل وعدد مرات إعادة المحاولة

عميل بايثون المرجعي (httpx)

from __future__ import annotations

import asyncio
from dataclasses import dataclass

import httpx


@dataclass
class AuroraClient:
base_url: str
username: str
password: str
timeout_s: float = 20.0

def __post_init__(self) -> None:
self._token: str | None = None
self._client = httpx.AsyncClient(timeout=self.timeout_s)

async def close(self) -> None:
await self._client.aclose()

async def authenticate(self) -> None:
# Acquire JWT once and store in memory for subsequent requests.
res = await self._client.post(
f"{self.base_url}/auth/token",
json={"username": self.username, "password": self.password},
)
res.raise_for_status()
self._token = res.json()["access_token"]

async def _request(self, method: str, path: str, **kwargs) -> dict:
if not self._token:
await self.authenticate()

headers = kwargs.pop("headers", {})
headers["Authorization"] = f"Bearer {self._token}"

for attempt in range(4):
res = await self._client.request(
method,
f"{self.base_url}{path}",
headers=headers,
**kwargs,
)

if res.status_code == 401 and attempt == 0:
await self.authenticate()
headers["Authorization"] = f"Bearer {self._token}"
continue

if res.status_code in (429, 503) and attempt < 3:
await asyncio.sleep(2 ** attempt)
continue

res.raise_for_status()
return res.json()

raise RuntimeError("request retry budget exhausted")

async def list_alerts(self, limit: int = 50) -> dict:
return await self._request("GET", "/alerts", params={"limit": limit})

عميل TypeScript المرجعي (جلب)

export class AuroraClient {
private token: string | null = null;

constructor(
private readonly baseUrl: string,
private readonly username: string,
private readonly password: string,
) {}

private async authenticate(): Promise<void> {
// Request JWT and cache it in memory.
const res = await fetch(`${this.baseUrl}/auth/token`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: this.username, password: this.password }),
});
if (!res.ok) throw new Error(`auth failed: ${res.status}`);
const payload = await res.json();
this.token = payload.access_token;
}

private async request(path: string, init: RequestInit = {}): Promise<any> {
if (!this.token) await this.authenticate();

for (let attempt = 0; attempt < 4; attempt += 1) {
const res = await fetch(`${this.baseUrl}${path}`, {
...init,
headers: {
...(init.headers ?? {}),
Authorization: `Bearer ${this.token}`,
},
});

if (res.status === 401 && attempt === 0) {
await this.authenticate();
continue;
}

if ((res.status === 429 || res.status === 503) && attempt < 3) {
await new Promise((resolve) => setTimeout(resolve, 2 ** attempt * 1000));
continue;
}

if (!res.ok) throw new Error(`request failed: ${res.status}`);
return res.json();
}

throw new Error("retry budget exhausted");
}

async listAlerts(limit = 50): Promise<any> {
return this.request(`/alerts?limit=${limit}`);
}
}

الحالات المتطورة التي يجب تغطيتها في الاختبارات

قضيةلماذا يهم؟السلوك المتوقع
تنتهي صلاحية الرمز المميز في منتصف الجلسةشائع لدى العملاء طويلي العمرتحديث الرمز المميز مرة واحدة، طلب إعادة التشغيل
429 طلقة تحت الحمليحمي استقرار الخدمةالتراجع مع عدم الاستقرار، وإعادة المحاولة المقيدة
503 تدهور التبعيةيمنع عواصف الفشل الكاذبةأعد المحاولة باستخدام الغطاء، الانقطاع الجزئي للسطح
إرسال تنبيهات مكررةمنع الحوادث المكررةالتعامل مع دلالات dedup/الصراع بشكل نظيف

إرشادات الأداء

  • إعادة استخدام عملاء/اتصالات HTTP.
  • مكالمات الاقتراع ذات الأولوية المنخفضة حيثما أمكن ذلك.
  • اجعل مهلة الطلب واضحة لكل نوع عملية.
  • تتبع زمن الوصول p95 ومعدل إعادة المحاولة في لوحات معلومات القياس عن بعد.

الصفحات ذات الصلة