-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add idempotency module and table
- Loading branch information
1 parent
be13f41
commit df40619
Showing
9 changed files
with
190 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
-- Add migration script here | ||
CREATE TYPE header_pair AS ( | ||
name TEXT, | ||
value BYTEA | ||
); | ||
|
||
CREATE TABLE idempotency ( | ||
user_id uuid NOT NULL REFERENCES users(user_id), | ||
idempotency_key TEXT NOT NULL, | ||
response_status_code SMALLINT NOT NULL, | ||
response_headers header_pair[] NOT NULL, | ||
response_body BYTEA NOT NULL, | ||
created_at timestamptz NOT NULL, | ||
PRIMARY KEY(user_id, idempotency_key) | ||
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
#[derive(Debug)] | ||
pub struct IdempotencyKey(String); | ||
|
||
impl TryFrom<String> for IdempotencyKey { | ||
type Error = anyhow::Error; | ||
|
||
fn try_from(s: String) -> Result<Self, Self::Error> { | ||
if s.is_empty() { | ||
anyhow::bail!("The idempotency key cannot be empty"); | ||
} | ||
let max_length = 50; | ||
if s.len() >= max_length { | ||
anyhow::bail!( | ||
"The idempotency key must be shorter | ||
than {max_length} characters" | ||
); | ||
} | ||
Ok(Self(s)) | ||
} | ||
} | ||
|
||
impl From<IdempotencyKey> for String { | ||
fn from(k: IdempotencyKey) -> Self { | ||
k.0 | ||
} | ||
} | ||
|
||
impl AsRef<str> for IdempotencyKey { | ||
fn as_ref(&self) -> &str { | ||
&self.0 | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
mod key; | ||
mod persistence; | ||
|
||
pub use key::IdempotencyKey; | ||
pub use persistence::{get_saved_response, save_response}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
use super::IdempotencyKey; | ||
use actix_web::body::to_bytes; | ||
use actix_web::http::StatusCode; | ||
use actix_web::HttpResponse; | ||
use sqlx::postgres::PgHasArrayType; | ||
use sqlx::PgPool; | ||
use uuid::Uuid; | ||
|
||
#[derive(Debug, sqlx::Type)] | ||
#[sqlx(type_name = "header_pair")] | ||
struct HeaderPairRecord { | ||
name: String, | ||
value: Vec<u8>, | ||
} | ||
|
||
pub async fn get_saved_response( | ||
pool: &PgPool, | ||
idempotency_key: &IdempotencyKey, | ||
user_id: Uuid, | ||
) -> Result<Option<HttpResponse>, anyhow::Error> { | ||
let saved_response = sqlx::query!( | ||
r#" | ||
SELECT | ||
response_status_code, | ||
response_headers as "response_headers: Vec<HeaderPairRecord>", | ||
response_body | ||
FROM idempotency | ||
WHERE | ||
user_id = $1 AND | ||
idempotency_key = $2 | ||
"#, | ||
user_id, | ||
idempotency_key.as_ref() | ||
) | ||
.fetch_optional(pool) | ||
.await?; | ||
|
||
if let Some(r) = saved_response { | ||
let status_code = StatusCode::from_u16(r.response_status_code.try_into()?)?; | ||
let mut response = HttpResponse::build(status_code); | ||
for HeaderPairRecord { name, value } in r.response_headers { | ||
response.append_header((name, value)); | ||
} | ||
Ok(Some(response.body(r.response_body))) | ||
} else { | ||
Ok(None) | ||
} | ||
} | ||
|
||
impl PgHasArrayType for HeaderPairRecord { | ||
fn array_type_info() -> sqlx::postgres::PgTypeInfo { | ||
sqlx::postgres::PgTypeInfo::with_name("_header_pair") | ||
} | ||
} | ||
|
||
pub async fn save_response( | ||
pool: &PgPool, | ||
idempotency_key: &IdempotencyKey, | ||
user_id: Uuid, | ||
http_response: HttpResponse, | ||
) -> Result<HttpResponse, anyhow::Error> { | ||
let (response_head, body) = http_response.into_parts(); | ||
let body = to_bytes(body).await.map_err(|e| anyhow::anyhow!("{}", e))?; | ||
let status_code = response_head.status().as_u16() as i16; | ||
let headers = { | ||
let mut h = Vec::with_capacity(response_head.headers().len()); | ||
for (name, value) in response_head.headers().iter() { | ||
let name = name.as_str().to_owned(); | ||
let value = value.as_bytes().to_owned(); | ||
h.push(HeaderPairRecord { name, value }); | ||
} | ||
h | ||
}; | ||
|
||
sqlx::query_unchecked!( | ||
r#" | ||
INSERT INTO idempotency ( | ||
user_id, | ||
idempotency_key, | ||
response_status_code, | ||
response_headers, | ||
response_body, | ||
created_at) | ||
VALUES ($1, $2, $3, $4, $5, now()) | ||
"#, | ||
user_id, | ||
idempotency_key.as_ref(), | ||
status_code, | ||
headers, | ||
body.as_ref() | ||
) | ||
.execute(pool) | ||
.await?; | ||
|
||
let http_response = response_head.set_body(body).map_into_boxed_body(); | ||
Ok(http_response) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters