use std::sync::LazyLock;
use std::time::Duration;
use serde_json::Value;
use crate::error::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorGroup {
Session,
SessionRefresh,
Verification,
AccessDenied,
NotFound,
RateLimit,
Validation,
Premium,
FeatureUnavailable,
ClientBlocked,
Domain,
}
pub const SESSION_ERRORS: &[&str] = &[
"error.session.expired",
"error.session.invalid",
"error.session.revoked",
];
pub const SESSION_REFRESH_ERRORS: &[&str] = &["error.session.refresh"];
pub const VERIFICATION_ERRORS: &[&str] = &[
"error.verification.required",
"error.verification.invalid",
"error.verification.expired",
"error.verification.failure",
"error.verification.blocked",
"error.login.unknown",
"error.login.blocked",
"error.too.many.resends",
"error.email.unverified",
];
pub const ACCESS_DENIED_ERRORS: &[&str] = &["error.access.denied"];
pub const NOT_FOUND_ERRORS: &[&str] = &[
"error.network.not.found",
"error.eero.no_serial_found",
"error.software_keys.not_found",
];
pub const RATE_LIMIT_ERRORS: &[&str] = &["error.rate.limit"];
pub const VALIDATION_ERRORS: &[&str] = &[
"error.form.errors",
"error.form.email.unavailable",
"error.form.phone.unavailable",
"error.form.email.malformed",
"error.form.phone.malformed",
"error.invites.format.faulty",
"error.invalid.user.role",
"error.reservation.ip.invalid",
"error.network.multistaticipv2.wan_ip_not_in_range",
];
pub const PREMIUM_ERRORS: &[&str] = &[
"error.premium.user_not_subscribed",
"error.partner.unavailable",
];
pub const FEATURE_UNAVAILABLE_ERRORS: &[&str] = &[
"error.eero.offline",
"error.network.unavailable",
"error.eero.not.capable",
"error.eero.deactivated",
"error.eero.owned_by_organization",
"error.eero.wifibackup.as.gateway",
"error.eero.already.owned",
"error.eero.needs.reset",
];
pub const CLIENT_BLOCKED_ERRORS: &[&str] = &["error.app.version.blocked"];
pub const DOMAIN_ERRORS: &[&str] = &[
"error.reservation.failed",
"error.assignment.ip.unavailable",
"error.assignment.port.unavailable",
"error.forward.failed",
"error.backup.access.point.ssid.already.exists",
"error.backup.access.point.ssid.conflict",
"error.max.number.of.backup.access.points.reached",
"error.invite.status.accepted",
"error.invite.status.rejected",
"error.invite.status.revoked",
"error.invite.status.expired",
"error.max.admins.reached",
"error.public_static_ip.reservation.error",
"error.network.transfer.recipient.unverified_phone",
"error.network.transfer.recipient.unverified_email",
"error.network.transfer.recipient.mismatched_phone",
"error.network.transfer.recipient.mismatched_email",
"error.network.transfer.recipient.ambiguous",
"error.user.amazon_login.exists",
"error.user.amazon_login.email.unavailable",
"error.software_keys.already_used",
"error.stripe.card.incorrect_number",
"error.stripe.card.expired",
"error.stripe.card.incorrect_cvc",
"error.stripe.card.incorrect_zip",
"error.stripe.card.declined",
"error.stripe.card.processing_error",
"error.stripe.coupon.inappropriate",
"error.stripe.coupon.invalid",
"error.stripe.coupon.missing",
"encryptme.error.email.exists",
"encryptme.error.email.invalid",
"encryptme.error.creation.failed",
];
fn group_members() -> [(ErrorGroup, &'static [&'static str]); 11] {
[
(ErrorGroup::Session, SESSION_ERRORS),
(ErrorGroup::SessionRefresh, SESSION_REFRESH_ERRORS),
(ErrorGroup::Verification, VERIFICATION_ERRORS),
(ErrorGroup::AccessDenied, ACCESS_DENIED_ERRORS),
(ErrorGroup::NotFound, NOT_FOUND_ERRORS),
(ErrorGroup::RateLimit, RATE_LIMIT_ERRORS),
(ErrorGroup::Validation, VALIDATION_ERRORS),
(ErrorGroup::Premium, PREMIUM_ERRORS),
(ErrorGroup::FeatureUnavailable, FEATURE_UNAVAILABLE_ERRORS),
(ErrorGroup::ClientBlocked, CLIENT_BLOCKED_ERRORS),
(ErrorGroup::Domain, DOMAIN_ERRORS),
]
}
static STRING_TO_GROUP: LazyLock<std::collections::HashMap<&'static str, ErrorGroup>> =
LazyLock::new(|| {
let mut map = std::collections::HashMap::new();
for (group, members) in group_members() {
for member in members {
map.insert(*member, group);
}
}
map
});
fn is_status_independent(group: ErrorGroup) -> bool {
matches!(
group,
ErrorGroup::Premium
| ErrorGroup::FeatureUnavailable
| ErrorGroup::ClientBlocked
| ErrorGroup::RateLimit
)
}
#[must_use]
pub fn classify_error_code(error_code: Option<&str>) -> Option<ErrorGroup> {
let code = error_code?;
if code.trim().is_empty() {
return None;
}
let normalized = code.trim().to_lowercase();
STRING_TO_GROUP.get(normalized.as_str()).copied()
}
#[must_use]
pub fn message_for_error_code(error_code: Option<&str>) -> String {
match error_code {
Some(code) if classify_error_code(Some(code)).is_some() => code.trim().to_lowercase(),
_ => "unrecognised error string".to_owned(),
}
}
#[must_use]
pub fn error_code_from_envelope(envelope: &Value) -> Option<String> {
envelope
.as_object()?
.get("meta")?
.as_object()?
.get("error")?
.as_str()
.map(str::to_owned)
}
#[must_use]
pub fn parse_envelope(text: &str) -> Option<Value> {
if text.trim().is_empty() {
return None;
}
let parsed = serde_json::from_str::<Value>(text).ok()?;
if parsed.is_object() {
Some(parsed)
} else {
None
}
}
#[must_use]
pub fn error_for_response(
status: u16,
envelope: Option<Value>,
error_code: Option<String>,
retry_after: Option<Duration>,
) -> Error {
let message = message_for_error_code(error_code.as_deref());
let group = classify_error_code(error_code.as_deref());
if status == 401 {
return Error::Authentication {
message,
envelope,
error_code,
status: Some(status),
};
}
if group.is_some_and(is_status_independent) {
return match group {
Some(ErrorGroup::Premium) => Error::PremiumRequired {
status: Some(status),
message,
envelope,
error_code,
},
Some(ErrorGroup::FeatureUnavailable) => Error::FeatureUnavailable {
status: Some(status),
message,
envelope,
error_code,
},
Some(ErrorGroup::ClientBlocked) => Error::ClientBlocked {
status,
message,
envelope,
error_code,
},
_ => Error::RateLimit {
message,
retry_after,
envelope,
error_code,
status: Some(status),
},
};
}
match status {
403 if group == Some(ErrorGroup::AccessDenied) => Error::AccessDenied {
status,
message,
envelope,
error_code,
},
404 => Error::NotFound {
status,
message,
envelope,
error_code,
},
429 => Error::RateLimit {
message,
retry_after,
envelope,
error_code,
status: Some(status),
},
400 if group == Some(ErrorGroup::Validation) => Error::Validation {
field: "request".to_owned(),
message,
envelope,
error_code,
},
_ => Error::Api {
status,
message,
envelope,
error_code,
url: None,
},
}
}
#[cfg(test)]
fn all_catalogue_strings() -> Vec<&'static str> {
group_members()
.into_iter()
.flat_map(|(_, members)| members.iter().copied())
.collect()
}
#[cfg(test)]
mod tests {
use super::{
ErrorGroup, classify_error_code, error_code_from_envelope, error_for_response,
group_members, message_for_error_code, parse_envelope,
};
use crate::error::Error;
use serde_json::json;
use std::collections::HashSet;
use std::time::Duration;
#[test]
fn no_duplicate_strings_across_groups() {
let all = super::all_catalogue_strings();
let unique: HashSet<&str> = all.iter().copied().collect();
assert_eq!(
all.len(),
unique.len(),
"a catalogue string must belong to exactly one group"
);
}
#[test]
fn every_group_is_non_empty() {
for (group, members) in group_members() {
assert!(!members.is_empty(), "{group:?} must not be empty");
}
}
#[test]
fn every_catalogue_string_is_already_lowercase_and_trimmed() {
for string in super::all_catalogue_strings() {
assert_eq!(string, string.trim());
assert_eq!(string, string.to_lowercase());
}
}
#[test]
fn classifies_a_known_string_in_every_group() {
assert_eq!(
classify_error_code(Some("error.session.expired")),
Some(ErrorGroup::Session)
);
assert_eq!(
classify_error_code(Some("error.session.refresh")),
Some(ErrorGroup::SessionRefresh)
);
assert_eq!(
classify_error_code(Some("error.verification.required")),
Some(ErrorGroup::Verification)
);
assert_eq!(
classify_error_code(Some("error.access.denied")),
Some(ErrorGroup::AccessDenied)
);
assert_eq!(
classify_error_code(Some("error.network.not.found")),
Some(ErrorGroup::NotFound)
);
assert_eq!(
classify_error_code(Some("error.rate.limit")),
Some(ErrorGroup::RateLimit)
);
assert_eq!(
classify_error_code(Some("error.form.errors")),
Some(ErrorGroup::Validation)
);
assert_eq!(
classify_error_code(Some("error.premium.user_not_subscribed")),
Some(ErrorGroup::Premium)
);
assert_eq!(
classify_error_code(Some("error.eero.offline")),
Some(ErrorGroup::FeatureUnavailable)
);
assert_eq!(
classify_error_code(Some("error.app.version.blocked")),
Some(ErrorGroup::ClientBlocked)
);
assert_eq!(
classify_error_code(Some("error.reservation.failed")),
Some(ErrorGroup::Domain)
);
}
#[test]
fn classify_is_case_insensitive_and_trims_whitespace() {
assert_eq!(
classify_error_code(Some(" Error.Session.EXPIRED ")),
Some(ErrorGroup::Session)
);
}
#[test]
fn classify_none_empty_and_unrecognised_all_return_none() {
assert_eq!(classify_error_code(None), None);
assert_eq!(classify_error_code(Some("")), None);
assert_eq!(classify_error_code(Some(" ")), None);
assert_eq!(classify_error_code(Some("not a catalogue string")), None);
}
#[test]
fn message_for_known_code_is_the_normalized_catalogue_string() {
assert_eq!(
message_for_error_code(Some(" Error.Session.Expired ")),
"error.session.expired"
);
}
#[test]
fn message_for_unknown_or_absent_code_is_the_fixed_fallback() {
assert_eq!(message_for_error_code(None), "unrecognised error string");
assert_eq!(
message_for_error_code(Some("")),
"unrecognised error string"
);
assert_eq!(
message_for_error_code(Some("some free text sentence")),
"unrecognised error string"
);
}
#[test]
fn error_code_from_envelope_extracts_meta_error() {
let envelope = json!({"meta": {"code": 401, "error": "error.session.expired"}});
assert_eq!(
error_code_from_envelope(&envelope),
Some("error.session.expired".to_owned())
);
}
#[test]
fn error_code_from_envelope_none_when_meta_absent_or_not_object() {
assert_eq!(error_code_from_envelope(&json!({"data": {}})), None);
assert_eq!(error_code_from_envelope(&json!({"meta": "oops"})), None);
assert_eq!(
error_code_from_envelope(&json!({"meta": {"code": 401}})),
None
);
}
#[test]
fn parse_envelope_empty_or_whitespace_is_none() {
assert_eq!(parse_envelope(""), None);
assert_eq!(parse_envelope(" \n "), None);
}
#[test]
fn parse_envelope_non_object_json_is_none() {
assert_eq!(parse_envelope("[1,2,3]"), None);
assert_eq!(parse_envelope("\"a string\""), None);
assert_eq!(parse_envelope("42"), None);
}
#[test]
fn parse_envelope_invalid_json_is_none() {
assert_eq!(parse_envelope("not json at all"), None);
}
#[test]
fn parse_envelope_valid_object_is_some() {
let parsed = parse_envelope(r#"{"meta":{"code":200},"data":{}}"#).unwrap();
assert_eq!(parsed["meta"]["code"], 200);
}
#[test]
fn a_401_always_wins_even_with_a_premium_error_code() {
let err = error_for_response(
401,
None,
Some("error.premium.user_not_subscribed".to_owned()),
None,
);
assert!(matches!(err, Error::Authentication { .. }));
}
#[test]
fn a_401_carries_its_status() {
match error_for_response(401, None, None, None) {
Error::Authentication {
status,
error_code,
envelope,
..
} => {
assert_eq!(status, Some(401));
assert_eq!(error_code, None);
assert_eq!(envelope, None);
}
other => panic!("expected Error::Authentication, got {other:?}"),
}
let envelope = json!({"meta": {"code": 401, "error": "error.session.expired"}});
let err = error_for_response(
401,
Some(envelope.clone()),
Some("error.session.expired".to_owned()),
None,
);
assert_eq!(err.status(), Some(401));
assert_eq!(err.envelope(), Some(&envelope));
assert_eq!(err.error_code(), Some("error.session.expired"));
assert!(err.is_auth_error());
}
#[test]
fn a_401_with_the_rate_limit_string_stays_authentication_and_carries_401() {
let err = error_for_response(
401,
Some(json!({"meta": {"code": 401, "error": "error.rate.limit"}})),
Some("error.rate.limit".to_owned()),
Some(Duration::from_secs(5)),
);
match &err {
Error::Authentication {
status,
message,
error_code,
..
} => {
assert_eq!(*status, Some(401));
assert_eq!(message, "error.rate.limit");
assert_eq!(error_code.as_deref(), Some("error.rate.limit"));
}
other => panic!("expected Error::Authentication, got {other:?}"),
}
assert!(err.is_auth_error());
}
#[test]
fn status_independent_groups_win_regardless_of_status() {
let err = error_for_response(
200,
None,
Some("error.premium.user_not_subscribed".to_owned()),
None,
);
assert!(matches!(err, Error::PremiumRequired { .. }));
let err = error_for_response(500, None, Some("error.eero.offline".to_owned()), None);
assert!(matches!(err, Error::FeatureUnavailable { .. }));
let err = error_for_response(
200,
None,
Some("error.app.version.blocked".to_owned()),
None,
);
assert!(matches!(err, Error::ClientBlocked { .. }));
let err = error_for_response(500, None, Some("error.rate.limit".to_owned()), None);
assert!(matches!(err, Error::RateLimit { .. }));
}
#[test]
fn a_403_with_access_denied_code_is_access_denied() {
let err = error_for_response(403, None, Some("error.access.denied".to_owned()), None);
assert!(matches!(err, Error::AccessDenied { status: 403, .. }));
}
#[test]
fn a_403_without_access_denied_code_is_generic_api() {
let err = error_for_response(403, None, None, None);
assert!(matches!(err, Error::Api { status: 403, .. }));
}
#[test]
fn a_404_is_always_not_found_regardless_of_error_code() {
assert!(matches!(
error_for_response(404, None, None, None),
Error::NotFound { status: 404, .. }
));
assert!(matches!(
error_for_response(404, None, Some("free text".to_owned()), None),
Error::NotFound { status: 404, .. }
));
assert!(matches!(
error_for_response(404, None, Some("error.network.not.found".to_owned()), None),
Error::NotFound { status: 404, .. }
));
}
#[test]
fn a_429_is_always_rate_limit() {
let err = error_for_response(429, None, None, Some(Duration::from_secs(5)));
match err {
Error::RateLimit {
retry_after,
status,
..
} => {
assert_eq!(retry_after, Some(Duration::from_secs(5)));
assert_eq!(status, Some(429));
}
other => panic!("expected Error::RateLimit, got {other:?}"),
}
}
#[test]
fn a_429_without_a_catalogue_string_carries_status_and_retry_after() {
let err = error_for_response(429, None, None, Some(Duration::from_secs(120)));
match &err {
Error::RateLimit {
status,
retry_after,
message,
error_code,
..
} => {
assert_eq!(*status, Some(429));
assert_eq!(*retry_after, Some(Duration::from_secs(120)));
assert_eq!(message, "unrecognised error string");
assert_eq!(*error_code, None);
}
other => panic!("expected Error::RateLimit, got {other:?}"),
}
assert_eq!(err.status(), Some(429));
assert!(!err.is_auth_error());
}
#[test]
fn the_rate_limit_string_carries_the_actual_status_on_any_status() {
for status in [400_u16, 404, 429, 500, 503] {
let envelope = json!({"meta": {"code": status, "error": "error.rate.limit"}});
let err = error_for_response(
status,
Some(envelope.clone()),
Some("error.rate.limit".to_owned()),
Some(Duration::from_secs(30)),
);
match &err {
Error::RateLimit {
status: carried,
retry_after,
envelope: attached,
error_code,
..
} => {
assert_eq!(*carried, Some(status), "status {status}");
assert_eq!(*retry_after, Some(Duration::from_secs(30)));
assert_eq!(attached.as_ref(), Some(&envelope));
assert_eq!(error_code.as_deref(), Some("error.rate.limit"));
}
other => panic!("status {status}: expected Error::RateLimit, got {other:?}"),
}
assert_eq!(err.status(), Some(status));
assert!(!err.is_auth_error(), "status {status}");
}
}
#[test]
fn retry_after_is_dropped_by_every_variant_without_the_field() {
let nine = Some(Duration::from_secs(9));
assert!(matches!(
error_for_response(403, None, None, nine),
Error::Api { status: 403, .. }
));
assert!(matches!(
error_for_response(404, None, None, nine),
Error::NotFound { status: 404, .. }
));
assert!(matches!(
error_for_response(500, None, None, nine),
Error::Api { status: 500, .. }
));
assert!(matches!(
error_for_response(401, None, None, nine),
Error::Authentication {
status: Some(401),
..
}
));
}
#[test]
fn a_400_with_validation_code_is_validation_with_request_field() {
let err = error_for_response(400, None, Some("error.form.errors".to_owned()), None);
match err {
Error::Validation { field, .. } => assert_eq!(field, "request"),
other => panic!("expected Error::Validation, got {other:?}"),
}
}
#[test]
fn a_400_without_validation_code_is_generic_api() {
let err = error_for_response(400, None, None, None);
assert!(matches!(err, Error::Api { status: 400, .. }));
}
#[test]
fn a_domain_string_stays_generic_api_and_carries_error_code() {
let err = error_for_response(422, None, Some("error.reservation.failed".to_owned()), None);
match err {
Error::Api { error_code, .. } => {
assert_eq!(error_code.as_deref(), Some("error.reservation.failed"));
}
other => panic!("expected Error::Api, got {other:?}"),
}
}
#[test]
fn envelope_is_attached_verbatim() {
let envelope = json!({"meta": {"code": 404}});
let err = error_for_response(404, Some(envelope.clone()), None, None);
match err {
Error::NotFound { envelope: e, .. } => assert_eq!(e, Some(envelope)),
other => panic!("expected Error::NotFound, got {other:?}"),
}
}
}