1 parent
e37d583179
commit
5260c2828b
65 files changed
+8469
-380
No files matched your search
+180
-20
@@ -13,10 +13,17 @@ use tokio::{
|
||||
pub struct State {
|
||||
pub objects: BTreeMap<String, Value>,
|
||||
pub writes: usize,
|
||||
pub rotation_creates: usize,
|
||||
pub rotation_patches: usize,
|
||||
pub fail_after_rotation_patch: bool,
|
||||
pub fail_after_schedule_patch: bool,
|
||||
pub fail_once: Option<String>,
|
||||
pub external_override: bool,
|
||||
pub users: Vec<Value>,
|
||||
pub lookups: usize,
|
||||
pub fail_after_override_create: bool,
|
||||
pub fail_after_resource_create: bool,
|
||||
pub override_not_before: Option<chrono::DateTime<chrono::Utc>>,
|
||||
}
|
||||
pub struct Server {
|
||||
pub base: String,
|
||||
@@ -72,13 +79,14 @@ impl Server {
|
||||
assert!(head.to_lowercase().contains("authorization: basic "));
|
||||
let mut first = head.lines().next().unwrap().split_whitespace();
|
||||
let method = first.next().unwrap();
|
||||
let path = first.next().unwrap().split('?').next().unwrap();
|
||||
let uri = first.next().unwrap();
|
||||
let body = if length > 0 {
|
||||
serde_json::from_slice(&buffer[head_end..head_end + length]).unwrap()
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
let (code, result) = handle(&mut shared.lock().unwrap(), method, path, body);
|
||||
let (code, result) =
|
||||
handle_page(&mut shared.lock().unwrap(), method, uri, body);
|
||||
let body = result.to_string();
|
||||
let response = format!(
|
||||
"HTTP/1.1 {code} Result\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
@@ -91,6 +99,42 @@ impl Server {
|
||||
Self { base, state, task }
|
||||
}
|
||||
}
|
||||
fn handle_page(s: &mut State, method: &str, uri: &str, body: Value) -> (u16, Value) {
|
||||
let url = reqwest::Url::parse(&format!("http://localhost{uri}")).unwrap();
|
||||
let query: BTreeMap<_, _> = url.query_pairs().into_owned().collect();
|
||||
let size = query.get("size").and_then(|s| s.parse::<usize>().ok());
|
||||
if size.is_some_and(|size| size > 50) {
|
||||
return (
|
||||
422,
|
||||
json!({"errors":[{"title":"Field: size, error: must be less than or equal to 50"}]}),
|
||||
);
|
||||
}
|
||||
let (code, mut result) = handle(s, method, url.path(), body);
|
||||
if method == "GET"
|
||||
&& let Some(size) = size
|
||||
&& let Some(values) = result.get_mut("values").and_then(Value::as_array_mut)
|
||||
{
|
||||
let offset = query
|
||||
.get("offset")
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
let more = offset + size < values.len();
|
||||
*values = values.iter().skip(offset).take(size).cloned().collect();
|
||||
if more {
|
||||
result["links"] =
|
||||
json!({"next":format!("{}?offset={}&size={size}",url.path(),offset+size)});
|
||||
}
|
||||
}
|
||||
(code, result)
|
||||
}
|
||||
fn read_response(path: &str, value: &Value) -> Value {
|
||||
let mut response = value.clone();
|
||||
if path.contains("/escalations/") && response["repeat"]["waitInterval"] == 0 {
|
||||
response.as_object_mut().unwrap().remove("repeat");
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
fn handle(s: &mut State, method: &str, path: &str, mut body: Value) -> (u16, Value) {
|
||||
if method == "POST" && s.fail_once.as_ref().is_some_and(|p| path.ends_with(p)) {
|
||||
s.fail_once = None;
|
||||
@@ -102,19 +146,36 @@ fn handle(s: &mut State, method: &str, path: &str, mut body: Value) -> (u16, Val
|
||||
return (200, json!(s.users));
|
||||
}
|
||||
if path.ends_with("/overrides") {
|
||||
return (
|
||||
200,
|
||||
json!({"values":if s.external_override{vec![json!({"alias":"external"})]}else{vec![]}}),
|
||||
);
|
||||
if !s
|
||||
.objects
|
||||
.contains_key(path.strip_suffix("/overrides").unwrap())
|
||||
{
|
||||
return (404, json!({}));
|
||||
}
|
||||
let mut values: Vec<_> = s
|
||||
.objects
|
||||
.iter()
|
||||
.filter(|(key, _)| {
|
||||
key.rsplit_once('/')
|
||||
.is_some_and(|(parent, _)| parent == path)
|
||||
})
|
||||
.map(|(_, value)| value.clone())
|
||||
.collect();
|
||||
if s.external_override {
|
||||
values.push(json!({"alias":"external"}));
|
||||
}
|
||||
return (200, json!({"values":values}));
|
||||
}
|
||||
if let Some(parent) = path.strip_suffix("/rotations") {
|
||||
return (
|
||||
200,
|
||||
json!({"values":s.objects.get(parent).unwrap()["rotations"]}),
|
||||
);
|
||||
let Some(object) = s.objects.get(parent) else {
|
||||
return (404, json!({}));
|
||||
};
|
||||
let mut rotations = object["rotations"].as_array().unwrap().clone();
|
||||
rotations.reverse();
|
||||
return (200, json!({"values":rotations}));
|
||||
}
|
||||
if let Some(value) = s.objects.get(path) {
|
||||
return (200, value.clone());
|
||||
return (200, read_response(path, value));
|
||||
}
|
||||
if path.ends_with("/schedules")
|
||||
|| path.ends_with("/escalations")
|
||||
@@ -122,7 +183,7 @@ fn handle(s: &mut State, method: &str, path: &str, mut body: Value) -> (u16, Val
|
||||
{
|
||||
return (
|
||||
200,
|
||||
json!({"values":s.objects.iter().filter(|(k,_)|k.rsplit_once('/').is_some_and(|(p,_)|p==path)).map(|(_,v)|v.clone()).collect::<Vec<_>>()}),
|
||||
json!({"values":s.objects.iter().filter(|(k,_)|k.rsplit_once('/').is_some_and(|(p,_)|p==path)).map(|(k,v)|read_response(k,v)).collect::<Vec<_>>()}),
|
||||
);
|
||||
}
|
||||
return (404, json!({}));
|
||||
@@ -133,6 +194,8 @@ fn handle(s: &mut State, method: &str, path: &str, mut body: Value) -> (u16, Val
|
||||
s.external_override = false;
|
||||
} else {
|
||||
s.objects.remove(path);
|
||||
s.objects
|
||||
.retain(|key, _| !key.starts_with(&format!("{path}/")));
|
||||
}
|
||||
return (200, json!({"result":"deleted"}));
|
||||
}
|
||||
@@ -144,26 +207,123 @@ fn handle(s: &mut State, method: &str, path: &str, mut body: Value) -> (u16, Val
|
||||
assert!((1..=20).contains(&body["repeat"]["count"].as_u64().unwrap()));
|
||||
assert!(body["rules"].is_array());
|
||||
}
|
||||
if path.contains("schedules") {
|
||||
for rotation in body["rotations"].as_array().unwrap() {
|
||||
assert_eq!(rotation["participants"].as_array().unwrap().len(), 1);
|
||||
assert!(
|
||||
rotation["endDate"].as_str().unwrap() > rotation["startDate"].as_str().unwrap()
|
||||
if path.contains("/overrides") {
|
||||
assert!(body["responder"]["type"] == "user" || body["responder"]["type"] == "noone");
|
||||
for field in ["startDate", "endDate"] {
|
||||
let time = body[field]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.parse::<chrono::DateTime<chrono::Utc>>()
|
||||
.unwrap();
|
||||
body[field] =
|
||||
json!(chrono::DateTime::from_timestamp_millis(time.timestamp_millis()).unwrap());
|
||||
}
|
||||
if method == "POST"
|
||||
&& s.override_not_before.is_some_and(|now| {
|
||||
body["startDate"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.parse::<chrono::DateTime<chrono::Utc>>()
|
||||
.unwrap()
|
||||
< now
|
||||
})
|
||||
{
|
||||
return (
|
||||
400,
|
||||
json!({"error":"Start time cannot be earlier than the current time"}),
|
||||
);
|
||||
}
|
||||
s.writes += 1;
|
||||
if method == "POST" {
|
||||
let alias = uuid::Uuid::new_v4().to_string();
|
||||
body["alias"] = json!(alias);
|
||||
s.objects.insert(format!("{path}/{alias}"), body.clone());
|
||||
if s.fail_after_override_create {
|
||||
s.fail_after_override_create = false;
|
||||
return (500, json!({"error":"Lost response after create"}));
|
||||
}
|
||||
} else {
|
||||
assert_eq!(method, "PUT");
|
||||
body["alias"] = json!(path.rsplit('/').next().unwrap());
|
||||
s.objects.insert(path.into(), body.clone());
|
||||
}
|
||||
return (201, body);
|
||||
}
|
||||
if let Some((parent, id)) = path.split_once("/rotations/") {
|
||||
assert_eq!(method, "PATCH");
|
||||
let Some(rotation) = s
|
||||
.objects
|
||||
.get_mut(parent)
|
||||
.and_then(|v| v["rotations"].as_array_mut())
|
||||
.and_then(|r| r.iter_mut().find(|r| r["id"] == id))
|
||||
else {
|
||||
return (404, json!({}));
|
||||
};
|
||||
body["id"] = json!(id);
|
||||
*rotation = body.clone();
|
||||
s.writes += 1;
|
||||
s.rotation_patches += 1;
|
||||
if s.fail_after_rotation_patch {
|
||||
s.fail_after_rotation_patch = false;
|
||||
return (500, json!({"error":"Lost rotation update response"}));
|
||||
}
|
||||
return (200, body);
|
||||
}
|
||||
if path.contains("schedules") && body.get("rotations").is_some() {
|
||||
let zone = body["timezone"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.parse::<chrono_tz::Tz>()
|
||||
.unwrap();
|
||||
for rotation in body["rotations"].as_array_mut().unwrap() {
|
||||
rotation["id"] = json!(uuid::Uuid::new_v4().to_string());
|
||||
s.rotation_creates += 1;
|
||||
assert!(!rotation["participants"].as_array().unwrap().is_empty());
|
||||
if let Some(end) = rotation["endDate"].as_str() {
|
||||
assert!(end > rotation["startDate"].as_str().unwrap());
|
||||
} else {
|
||||
assert_eq!(rotation["participants"][0]["type"], "noone");
|
||||
}
|
||||
// Anonymized live behavior: native rotation minutes snap to a half-hour;
|
||||
// override endpoints above retain arbitrary minutes and milliseconds.
|
||||
for field in ["startDate", "endDate"] {
|
||||
if let Some(raw) = rotation[field].as_str() {
|
||||
use chrono::Timelike;
|
||||
let time = raw.parse::<chrono::DateTime<chrono::Utc>>().unwrap();
|
||||
let minute = i64::from(time.with_timezone(&zone).minute());
|
||||
let rounded =
|
||||
time + chrono::Duration::minutes(((minute + 15) / 30) * 30 - minute);
|
||||
rotation[field] = json!(
|
||||
chrono::DateTime::from_timestamp_millis(rounded.timestamp_millis())
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
s.writes += 1;
|
||||
if method == "POST" {
|
||||
let id = uuid::Uuid::new_v4().to_string();
|
||||
body["id"] = json!(id);
|
||||
s.objects.insert(format!("{path}/{id}"), body.clone());
|
||||
if s.fail_after_resource_create {
|
||||
s.fail_after_resource_create = false;
|
||||
return (500, json!({"error":"Lost resource create response"}));
|
||||
}
|
||||
return (201, body);
|
||||
}
|
||||
assert_eq!(method, "PATCH");
|
||||
if let Some(previous) = s.objects.get(path) {
|
||||
body["id"] = previous["id"].clone();
|
||||
s.objects.insert(path.into(), body.clone());
|
||||
(200, body)
|
||||
let mut merged = previous.clone();
|
||||
for (key, value) in body.as_object().unwrap() {
|
||||
merged[key] = value.clone();
|
||||
}
|
||||
s.objects.insert(path.into(), merged.clone());
|
||||
if path.starts_with("/schedules/") && s.fail_after_schedule_patch {
|
||||
s.fail_after_schedule_patch = false;
|
||||
return (500, json!({"error":"Lost schedule metadata response"}));
|
||||
}
|
||||
(200, merged)
|
||||
} else {
|
||||
(404, json!({}))
|
||||
}
|
||||
|
||||
+36
-6
@@ -1,8 +1,8 @@
|
||||
use chrono::{Duration, Utc};
|
||||
use cot::db::Model;
|
||||
use cot::db::{Model, query};
|
||||
use meguri::{
|
||||
domain::*,
|
||||
models::UserRow,
|
||||
models::{HistoryRow, UserRow},
|
||||
service,
|
||||
store::{Store, WorkspaceRecord},
|
||||
};
|
||||
@@ -24,19 +24,26 @@ impl Fixture {
|
||||
for name in ["Alice", "Bob", "Carol"] {
|
||||
let user = User {
|
||||
language: None,
|
||||
id: Uuid::new_v4(),
|
||||
person: Person {
|
||||
id: Uuid::new_v4(),
|
||||
user_id: None,
|
||||
display_name: name.into(),
|
||||
email: Some(format!("{}@example.com", Uuid::new_v4())),
|
||||
country: Some("CY".into()),
|
||||
},
|
||||
username: format!("test-{}", Uuid::new_v4().simple()),
|
||||
display_name: name.into(),
|
||||
country: "CY".into(),
|
||||
timezone: None,
|
||||
};
|
||||
let mut user = user;
|
||||
user.person.user_id = Some(user.id);
|
||||
UserRow {
|
||||
language: None,
|
||||
demo_deleted_at: None,
|
||||
id: user.id.to_string(),
|
||||
username: user.username.clone(),
|
||||
display_name: user.display_name.clone(),
|
||||
country: user.country.clone(),
|
||||
country: user.country.clone().unwrap(),
|
||||
email: user.email.clone().unwrap(),
|
||||
timezone: None,
|
||||
password_hash: "test-only-unusable-password".into(),
|
||||
created_at: Utc::now(),
|
||||
@@ -121,6 +128,29 @@ impl Fixture {
|
||||
}
|
||||
}
|
||||
pub async fn prioritize_publication(&self) {
|
||||
let revision = self.db.workspace(self.team.id).await.unwrap().revision;
|
||||
self.db
|
||||
.retry(self.team.id, self.people[0].id, revision)
|
||||
.await
|
||||
.unwrap();
|
||||
// PostgreSQL and the worker can run on different host clocks. Publish only
|
||||
// once this test's latest committed revision has actually become effective.
|
||||
let workspace = self.team.id.to_string();
|
||||
let effective = query!(HistoryRow, $workspace_id == workspace)
|
||||
.all(&self.db.db)
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|row| row.effective_at)
|
||||
.max()
|
||||
.unwrap();
|
||||
if let Ok(delay) = (effective - Utc::now()).to_std() {
|
||||
assert!(
|
||||
delay < std::time::Duration::from_secs(2),
|
||||
"Database clock is too far ahead of the test worker"
|
||||
);
|
||||
tokio::time::sleep(delay + std::time::Duration::from_millis(1)).await;
|
||||
}
|
||||
// The worker takes a bounded batch. Repeated runs leave other test tenants
|
||||
// in this disposable database, so explicitly put this test's job first.
|
||||
self.db
|
||||
|
||||
Reference in new issue
Block a user