# 幂等性

> 在 POST 请求中发送 Idempotency-Key，使重试的请求不会让同一次检测运行或计费两次。包括行为、重放和冲突。

来源： https://fileverity.com/zh/docs/idempotency

网络故障可能让您无法确定某个 POST 请求是否已送达。如果直接再发一次，同一次检测可能会运行并计费两次。发送 `Idempotency-Key` 请求头后，重试将返回第一次的响应。

## 使用该请求头

**幂等请求: cURL**

```bash
curl https://api.fileverity.com/v1/analyses \
  -H "Authorization: Bearer $FILEVERITY_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 0e5f6a64-52c2-4b36-9d0d-6f3d2f4c9a10" \
  -d '{"model": "fvimg-2", "file": "file_8Hk2pQ4vN9sL1xR7cW3mY6zB"}'
```

**幂等请求: JavaScript**

```javascript
async function createAnalysis(body) {
  const key = crypto.randomUUID();
  let lastError;
  for (let attempt = 0; attempt < 3; attempt++) {
    try {
      return await fetch("https://api.fileverity.com/v1/analyses", {
        method: "POST",
        headers: { Authorization: "Bearer " + process.env.FILEVERITY_API_KEY, "Content-Type": "application/json", "Idempotency-Key": key },
        body: JSON.stringify(body),
      });
    } catch (error) {
      lastError = error;
    }
  }
  throw lastError;
}
```

**幂等请求: Python**

```python
import uuid

def create_analysis(body):
    key = str(uuid.uuid4())
    last_error = None
    for attempt in range(3):
        try:
            return requests.post("https://api.fileverity.com/v1/analyses", headers={**headers, "Idempotency-Key": key}, json=body, timeout=90)
        except requests.ConnectionError as error:
            last_error = error
    raise last_error
```

- 请发送 1 到 255 个字符的任意唯一字符串，随机 UUID 是不错的选择。每个不同的请求使用新的值，仅在重试同一请求时才复用同一个值。
- 所有 POST 接口都支持：`/text/detections`、`/files`、`/analyses` 和 `/analyses/{id}/cancel`。
- Idempotency-Key 的作用范围限定于您的工作区、模式（Live 或 Test）和接口，并保留 24 小时。同一个 Idempotency-Key 分别用于 Live 密钥和测试密钥时不会冲突。

## 返回结果

| 情形 | 结果 |
| --- | --- |
| 首次使用某个 Idempotency-Key 的请求 | 正常处理。成功的响应（状态码低于 400）会被保存。 |
| 24 小时内使用相同 Idempotency-Key 和相同请求体 | 返回已保存的响应，状态码相同，并附加响应头 `idempotent-replayed: true`。不会再次运行或计费。 |
| 相同 Idempotency-Key，不同请求体 | `409` `idempotency_mismatch`. |
| 首次请求仍在运行时使用相同 Idempotency-Key | `409` `idempotency_in_progress`。请稍后重试。 |
| 出现错误响应后使用相同 Idempotency-Key | 该 Idempotency-Key 会被释放。错误响应不会被保存，因此重试会再次运行该请求。 |

重放的响应沿用新请求的 `x-request-id`，而不是原始请求的。multipart 上传按表单字段和文件内容进行比较。

> **注意。** 幂等性只能避免重复处理，并不会让失败的请求变为成功：收到 `service_unavailable` 或 `internal_error` 后，如果响应带有 `retry-after` 响应头，请等待相应秒数，然后使用相同的 Idempotency-Key 重试。

另请参阅[错误](https://fileverity.com/zh/docs/errors.md)和[速率限制与 HTTP 头](https://fileverity.com/zh/docs/rate-limits.md)。

