HTTP put 不幂等的一种情况

A situation when HTTP put is not idempotent

考虑以下场景:

  1. Alice 使用 http put 更新 item1
  2. Bob 使用带有不同数据的 http put 更新 item1
  3. 爱丽丝使用 http put again 意外更新了 item1 和相同的数据,例如,使用浏览器中的后退按钮
  4. 查理读取数据

这是幂等的吗?

是的,这是幂等的。如果这对您来说是错误的行为,我们应该了解其背后的商业逻辑。

Is this idempotent?

是的。幂等的相关定义由RFC 7231

提供

A request method is considered "idempotent" if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request.

但是,您描述的情况是数据竞争——Charlie 收到的表示取决于服务器应用从 Alice 和 Bob 收到的 PUT 请求的顺序。

避免丢失写入的通常方法是使用针对特定版本资源的请求进行更新;这类似于在您的请求中使用 compare and swap 语义——丢失数据竞争的写入被丢弃在地板上

例如

 x = 7
 x.swap(7, 8) # Request from Alice changes x == 7 to x == 8
 x.swap(8, 9) # Request from Bob changes x == 8 to x == 9
 x.swap(7, 8) # No-Op, this request is ignored, x == 9

在 HTTP 中,Conditional Requests gives you a way to take simple predicates, and lift them into the meta data so that generic components can understand the semantics of what is going on. This is done with validators like eTag 的规范。

基本思想是这样的:服务器在元数据中提供与资源的当前表示相关联的验证器的表示。当客户端想要在表示未更改的条件下发出请求时,它会在请求中包含相同的验证器。服务器应使用服务器端资源的当前状态重新计算验证器,并仅在两个验证器表示匹配时应用更改。

如果源服务器拒绝一个请求是因为预期precondition headers are missing from the request, it can use 428 Precondition Required来分类客户端错误的性质。