YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix(calendar): stop per-minute 500 spam when calendar providers are not connected (#4084)
Louis Beaumontf5b1f3d29246
diff --git a/apps/screenpipe-app-tauri/lib/utils/calendar.test.ts b/apps/screenpipe-app-tauri/lib/utils/calendar.test.tsindex 95ea9ae8a..e7ee87100 100644--- a/apps/screenpipe-app-tauri/lib/utils/calendar.test.ts+++ b/apps/screenpipe-app-tauri/lib/utils/calendar.test.ts@@ -125,6 +125,68 @@ describe("fetchUpcomingCalendarSnapshot", () => {).toBe(false);});+ it("skips the native HTTP probe when the platform has no native calendar", async () => {+ // Linux shape: tauri status reports unavailable. Probing the HTTP route+ // would be a guaranteed failure every 60s poll — it must not happen.+ mocks.commands.calendarStatus.mockResolvedValue({+ status: "ok",+ data: {+ available: false,+ authorized: false,+ calendarCount: 0,+ },+ });+ mocks.commands.oauthStatus.mockResolvedValue({+ status: "ok",+ data: { connected: false },+ });+ mocks.localFetch.mockImplementation((url: string) =>+ Promise.reject(new Error(`unexpected url: ${url}`)),+ );++ const snapshot = await fetchUpcomingCalendarSnapshot({ hoursAhead: 8 });++ expect(snapshot.connectedSources).toEqual([]);+ expect(snapshot.failedSources).toEqual([]);+ expect(+ mocks.localFetch.mock.calls.some(([url]) =>+ String(url).startsWith("/connections/calendar/events"),+ ),+ ).toBe(false);+ });++ it("treats a 200 connected:false native body as not connected", async () => {+ // Status command unavailable → the HTTP probe still runs, and the engine+ // answers 200 { data: [], connected: false, reason } on platforms with no+ // native calendar (instead of the old 500). That must read as "provider+ // unavailable", not "connected with zero events".+ mocks.commands.calendarStatus.mockRejectedValue(+ new Error("tauri unavailable"),+ );+ mocks.commands.oauthStatus.mockResolvedValue({+ status: "ok",+ data: { connected: false },+ });+ mocks.localFetch.mockImplementation((url: string) => {+ if (url.startsWith("/connections/calendar/events")) {+ return Promise.resolve(+ jsonResponse(true, {+ data: [],+ connected: false,+ reason: "unsupported_platform",+ }),+ );+ }++ return Promise.reject(new Error(`unexpected url: ${url}`));+ });++ const snapshot = await fetchUpcomingCalendarSnapshot({ hoursAhead: 8 });++ expect(snapshot.connectedSources).toEqual([]);+ expect(snapshot.failedSources).toEqual([]);+ });+it("includes ICS events when hoursAhead is 72", async () => {mocks.commands.oauthStatus.mockResolvedValue({status: "ok",diff --git a/apps/screenpipe-app-tauri/lib/utils/calendar.ts b/apps/screenpipe-app-tauri/lib/utils/calendar.tsindex b2afeb014..4017af5e6 100644--- a/apps/screenpipe-app-tauri/lib/utils/calendar.ts+++ b/apps/screenpipe-app-tauri/lib/utils/calendar.ts@@ -205,7 +205,14 @@ async function fetchNativeCalendar(`/connections/calendar/events?hours_back=${hoursBack}&hours_ahead=${hoursAhead}`,);if (!res.ok) return null;- const body = (await res.json()) as { data?: RawNativeEvent[] };+ const body = (await res.json()) as {+ data?: RawNativeEvent[];+ connected?: boolean;+ };+ // The engine reports "no native calendar here" (unsupported platform /+ // no OS appointment store) as 200 + connected:false instead of a 500.+ // That is "provider unavailable", not "connected with zero events".+ if (body.connected === false) return null;const arr = body.data ?? [];return arr.map(normalizeNative)@@ -240,10 +247,14 @@ async function fetchNativeProvider(hoursBack: number,hoursAhead: number,): Promise<ProviderCalendarResult> {+ let statusKnown = false;+ let statusAvailable = false;let statusConnected = false;try {const status = await commands.calendarStatus();if (status.status === "ok") {+ statusKnown = true;+ statusAvailable = status.data.available;statusConnected =status.data.available &&status.data.authorized &&@@ -253,6 +264,16 @@ async function fetchNativeProvider(// Fall through to the HTTP route below.}+ // No native calendar on this platform (Linux) or no OS appointment store+ // (some Windows setups): the HTTP probe can only fail. This poller runs+ // every 60s — skip the guaranteed-failing request instead of generating a+ // log entry per minute forever. Unauthorized-but-available (macOS pending+ // permission) still probes: reads can succeed right after an in-process+ // grant even while the cached OS status lags.+ if (statusKnown && !statusAvailable) {+ return { source: "native", connected: false, ok: true, events: [] };+ }+const events = await fetchNativeCalendar(hoursBack, hoursAhead);return {source: "native",diff --git a/apps/screenpipe-app-tauri/src-tauri/src/google_calendar.rs b/apps/screenpipe-app-tauri/src-tauri/src/google_calendar.rsindex dce204ffc..cc2a65507 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/google_calendar.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/google_calendar.rs@@ -15,17 +15,40 @@//! (endpoint returns 401) so this loop is a safe no-op for users who//! haven't connected gcal.+use std::sync::OnceLock;use std::time::Duration;use serde::Deserialize;use tauri::{AppHandle, Manager};+use tokio::sync::Notify;use tracing::{debug, info};use crate::calendar::CalendarEventItem;const POLL_INTERVAL: Duration = Duration::from_secs(60);+/// Backed-off cadence while Google Calendar is not connected. Polling a+/// disconnected integration every 60s buys nothing (the state only changes+/// when the user reconnects) and used to fill the engine log with a WARN ++/// failed-request pair every minute, forever. `poke()` short-circuits the+/// wait the moment an OAuth connect completes, so the 15 min worst case only+/// applies to reconnects that happen outside this app process.+const NOT_CONNECTED_POLL_INTERVAL: Duration = Duration::from_secs(15 * 60);const BOOT_DELAY: Duration = Duration::from_secs(10);+static RECHECK: OnceLock<Notify> = OnceLock::new();++fn recheck() -> &'static Notify {+ RECHECK.get_or_init(Notify::new)+}++/// Wake the publisher immediately (e.g. right after a Google Calendar OAuth+/// connect) instead of waiting out the not-connected backoff. `notify_one`+/// stores a permit when the publisher is mid-fetch rather than waiting, so a+/// poke is never lost (it would be with `notify_waiters`).+pub fn poke() {+ recheck().notify_one();+}+#[derive(Debug, Deserialize)]#[serde(rename_all = "camelCase")]struct GoogleCalendarEventDto {@@ -53,11 +76,13 @@ pub async fn start_google_calendar_publisher(app: AppHandle) {tokio::time::sleep(BOOT_DELAY).await;info!("google calendar publisher: started");let client = reqwest::Client::new();+ let mut interval = POLL_INTERVAL;loop {if let Some((port, api_key)) = local_api_config(&app).await {match fetch_events(&client, port, api_key.as_deref()).await {Ok(events) if !events.is_empty() => {+ interval = POLL_INTERVAL;let count = events.len();let items: Vec<CalendarEventItem> =events.into_iter().map(into_calendar_event_item).collect();@@ -67,16 +92,35 @@ pub async fn start_google_calendar_publisher(app: AppHandle) {debug!("google calendar publisher: published {count} events");}}- Ok(_) => debug!("google calendar publisher: no events in window"),+ Ok(_) => {+ interval = POLL_INTERVAL;+ debug!("google calendar publisher: no events in window");+ }Err(PublisherError::NotConnected) => {- debug!("google calendar publisher: not connected, skipping");+ // Not connected is a stable state — back off hard instead+ // of re-asking every minute. poke() (fired on OAuth+ // connect) wakes us immediately.+ if interval != NOT_CONNECTED_POLL_INTERVAL {+ debug!(+ "google calendar publisher: not connected — backing off to {}s",+ NOT_CONNECTED_POLL_INTERVAL.as_secs()+ );+ }+ interval = NOT_CONNECTED_POLL_INTERVAL;}Err(PublisherError::Other(msg)) => {+ interval = POLL_INTERVAL;debug!("google calendar publisher: fetch failed: {msg}");}}}- tokio::time::sleep(POLL_INTERVAL).await;+ tokio::select! {+ _ = tokio::time::sleep(interval) => {}+ _ = recheck().notified() => {+ debug!("google calendar publisher: poked — rechecking now");+ interval = POLL_INTERVAL;+ }+ }}}diff --git a/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs b/apps/screenpipe-app-tauri/src-tauri/src/oauth.rsindex 805fce8c4..852f467a7 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/oauth.rs@@ -410,6 +410,13 @@ pub async fn oauth_connect(integration_id, store_instance, display_name);+ // The background calendar publisher backs off to a long interval while+ // Google Calendar is disconnected — wake it so prewarm/meeting-detection+ // get events immediately after a connect instead of after the backoff.+ if integration_id == "google-calendar" {+ crate::google_calendar::poke();+ }+Ok(OAuthStatus {connected: true,display_name,diff --git a/crates/screenpipe-connect/src/calendar.rs b/crates/screenpipe-connect/src/calendar.rsindex 5da9dad8b..5f1750db2 100644--- a/crates/screenpipe-connect/src/calendar.rs+++ b/crates/screenpipe-connect/src/calendar.rs@@ -15,6 +15,10 @@ use chrono::{DateTime, Duration, Local, Utc};use eventkit::{AuthorizationStatus, CalendarInfo, EventKitError, EventsManager, Result as EKResult,};+// Re-export so downstream crates (screenpipe-engine's calendar routes) can+// classify failures (AuthorizationDenied vs real errors) without depending+// on the eventkit crate directly.+pub use eventkit::EventKitError as CalendarError;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::OnceLock;use tracing::{info, warn};diff --git a/crates/screenpipe-connect/src/oauth.rs b/crates/screenpipe-connect/src/oauth.rsindex a91fcb0d8..390228708 100644--- a/crates/screenpipe-connect/src/oauth.rs+++ b/crates/screenpipe-connect/src/oauth.rs@@ -1061,6 +1061,25 @@ pub async fn get_valid_token_instance(if let Some(token) = read_oauth_token_instance(store, integration_id, instance).await {return Some(token);}+ // No token stored at all (never connected, or an interrupted OAuth flow+ // that never reached the token write): a refresh cannot possibly succeed,+ // so don't attempt one and don't WARN. Callers poll this path on a timer+ // (the app's 60s calendar publisher, status checks), and the old+ // unconditional WARN ("oauth refresh failed ...: no stored token") filled+ // user log bundles twice a minute forever. This is an expected state, not+ // a failure — keep it at debug. Real refresh failures (a token exists but+ // the provider rejected it) still WARN below.+ if load_oauth_json_with_instance(store, integration_id, instance)+ .await+ .is_none()+ {+ tracing::debug!(+ "oauth: no stored token for {}(instance={:?}) — skipping refresh",+ integration_id,+ instance,+ );+ return None;+ }match refresh_token_instance(store, client, integration_id, instance).await {Ok(token) => Some(token),Err(e) => {@@ -1150,6 +1169,22 @@ mod tests {// this, tests would pass/fail based on whether the tester happens to have// gmail connected locally.+ #[tokio::test]+ async fn get_valid_token_with_no_stored_token_returns_none_without_refresh() {+ // Never-connected integration: there is nothing to refresh. The old+ // path attempted a refresh anyway, hit "no stored token", and WARNed —+ // and because the app polls calendar endpoints every 60s, that WARN+ // (plus the resulting 5xx) repeated twice a minute in user logs+ // forever. The short-circuit returns None before any network attempt+ // (this test performs no real HTTP: with the pre-check the exchange+ // proxy is never contacted).+ let store = mem_store().await;+ let client = reqwest::Client::new();+ let token =+ get_valid_token_instance(Some(&store), &client, "_t_never_connected", None).await;+ assert!(token.is_none());+ }+#[tokio::test]async fn load_with_explicit_instance_hits_exact_key() {let store = mem_store().await;diff --git a/crates/screenpipe-engine/src/connections_api.rs b/crates/screenpipe-engine/src/connections_api.rsindex 4db7de3b9..1ae500110 100644--- a/crates/screenpipe-engine/src/connections_api.rs+++ b/crates/screenpipe-engine/src/connections_api.rs@@ -592,6 +592,68 @@ pub struct CalendarEventsQuery {pub hours_ahead: Option<i64>,}+/// Why the native calendar produced no events. Only `Internal` is a server+/// error; the other variants are expected machine states. They used to all+/// collapse to HTTP 500, which made the app's 60-second calendar poll fire+/// two `tower_http` ERROR lines per minute forever on hosts where the native+/// calendar simply does not exist (Linux) or is not authorized (macOS).+enum NativeCalendarError {+ /// Platform has no native calendar integration at all (Linux).+ #[allow(dead_code)] // constructed only on the non-macOS/non-Windows arm+ Unsupported,+ /// The OS appointment store could not be opened (Windows without a+ /// calendar store). Permanent machine state, not a server error.+ #[allow(dead_code)] // constructed only on the Windows arm+ StoreUnavailable(String),+ /// Calendar exists but screenpipe lacks permission (macOS TCC).+ #[allow(dead_code)] // constructed only on the macOS arm+ AuthRequired(String),+ /// Real failure while reading events.+ Internal(String),+}++/// Map a native-calendar failure to an HTTP response. Split out of the+/// handler so the status mapping is unit-testable.+fn native_calendar_error_response(e: NativeCalendarError) -> (StatusCode, Json<Value>) {+ match e {+ // Nothing to fix and nothing failed — same convention as the ICS+ // events route returning 200 [] when no feed is configured. The+ // explicit `connected: false` + `reason` let clients distinguish+ // this from "connected, empty window".+ NativeCalendarError::Unsupported => (+ StatusCode::OK,+ Json(json!({+ "data": [],+ "connected": false,+ "reason": "unsupported_platform",+ })),+ ),+ NativeCalendarError::StoreUnavailable(msg) => (+ StatusCode::OK,+ Json(json!({+ "data": [],+ "connected": false,+ "reason": "store_unavailable",+ "detail": msg,+ })),+ ),+ // User-fixable: same 401 convention as the Google Calendar events+ // route when OAuth is missing.+ NativeCalendarError::AuthRequired(msg) => (+ StatusCode::UNAUTHORIZED,+ Json(json!({+ "error": msg,+ "reason": "auth_required",+ "connected": false,+ })),+ ),+ NativeCalendarError::Internal(msg) => (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(json!({ "error": msg })),+ ),+ }+}+/// GET /connections/calendar/events — fetch native OS calendar events.async fn calendar_events(Query(params): Query<CalendarEventsQuery>) -> (StatusCode, Json<Value>) {let hours_back = params.hours_back.unwrap_or(1);@@ -601,10 +663,7 @@ async fn calendar_events(Query(params): Query<CalendarEventsQuery>) -> (StatusCo.await{Ok(Ok(events)) => (StatusCode::OK, Json(json!({ "data": events }))),- Ok(Err(e)) => (- StatusCode::INTERNAL_SERVER_ERROR,- Json(json!({ "error": e })),- ),+ Ok(Err(e)) => native_calendar_error_response(e),Err(e) => (StatusCode::INTERNAL_SERVER_ERROR,Json(json!({ "error": format!("task join error: {}", e) })),@@ -621,12 +680,22 @@ async fn calendar_status() -> Json<Value> {}#[cfg(target_os = "macos")]-fn get_native_calendar_events(hours_back: i64, hours_ahead: i64) -> Result<Vec<Value>, String> {- use screenpipe_connect::calendar::ScreenpipeCalendar;+fn get_native_calendar_events(+ hours_back: i64,+ hours_ahead: i64,+) -> Result<Vec<Value>, NativeCalendarError> {+ use screenpipe_connect::calendar::{CalendarError, ScreenpipeCalendar};let cal = ScreenpipeCalendar::new();let events = cal.get_events(hours_back, hours_ahead)- .map_err(|e| format!("{:?}", e))?;+ .map_err(|e| match e {+ CalendarError::AuthorizationDenied => NativeCalendarError::AuthRequired(+ "calendar access not granted — allow screenpipe under System Settings > \+ Privacy & Security > Calendars"+ .to_string(),+ ),+ other => NativeCalendarError::Internal(format!("{:?}", other)),+ })?;Ok(events.into_iter().map(|e| {@@ -648,10 +717,18 @@ fn get_native_calendar_events(hours_back: i64, hours_ahead: i64) -> Result<Vec<V}#[cfg(target_os = "windows")]-fn get_native_calendar_events(hours_back: i64, hours_ahead: i64) -> Result<Vec<Value>, String> {+fn get_native_calendar_events(+ hours_back: i64,+ hours_ahead: i64,+) -> Result<Vec<Value>, NativeCalendarError> {use screenpipe_connect::calendar_windows::ScreenpipeCalendar;- let cal = ScreenpipeCalendar::new()?;- let events = cal.get_events(hours_back, hours_ahead)?;+ // Store open failure = no usable appointment store on this machine+ // (expected on hosts without the WinRT calendar infrastructure);+ // a query failure on an open store is a real error.+ let cal = ScreenpipeCalendar::new().map_err(NativeCalendarError::StoreUnavailable)?;+ let events = cal+ .get_events(hours_back, hours_ahead)+ .map_err(NativeCalendarError::Internal)?;Ok(events.into_iter().map(|e| {@@ -673,8 +750,14 @@ fn get_native_calendar_events(hours_back: i64, hours_ahead: i64) -> Result<Vec<V}#[cfg(not(any(target_os = "macos", target_os = "windows")))]-fn get_native_calendar_events(_hours_back: i64, _hours_ahead: i64) -> Result<Vec<Value>, String> {- Err("native calendar not supported on this platform".into())+fn get_native_calendar_events(+ _hours_back: i64,+ _hours_ahead: i64,+) -> Result<Vec<Value>, NativeCalendarError> {+ // Linux: there is no native OS calendar to read. This is an expected+ // state of the world, not a 500 — the app polls this route every 60s+ // and used to log two ERROR lines per minute forever.+ Err(NativeCalendarError::Unsupported)}#[cfg(target_os = "macos")]@@ -1105,6 +1188,46 @@ pub struct GoogleCalendarInstanceQuery {pub instance: Option<String>,}+/// Typed "Google Calendar OAuth is missing/broken/ambiguous" failure, so the+/// route handlers can map it to a structured 401 by downcast instead of+/// string-matching the human-readable message (which silently broke whenever+/// `describe_oauth_error` wording changed, collapsing an expected+/// "not connected" state into a 500).+#[derive(Debug)]+struct GcalAuthError {+ message: String,+}++impl std::fmt::Display for GcalAuthError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(&self.message)+ }+}++impl std::error::Error for GcalAuthError {}++/// Map a Google Calendar events failure to an HTTP response. Auth failures+/// (no token stored, broken token, ambiguous multi-account) become a 401 with+/// a machine-readable body — `reason: "auth_required"` mirrors the native+/// calendar route — so pollers can back off instead of retrying a state that+/// can only change when the user reconnects. Everything else stays 500.+fn gcal_events_error_response(e: &anyhow::Error) -> (StatusCode, Json<Value>) {+ if let Some(auth) = e.downcast_ref::<GcalAuthError>() {+ return (+ StatusCode::UNAUTHORIZED,+ Json(json!({+ "error": auth.message,+ "reason": "auth_required",+ "connected": false,+ })),+ );+ }+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(json!({ "error": e.to_string() })),+ )+}+/// Retrieve a valid Google Calendar OAuth token or return an error. See/// [`gmail_token`] for why "not connected" is split into distinct cases.async fn gcal_token(@@ -1118,10 +1241,15 @@ async fn gcal_token({return Ok(token);}- Err(anyhow::anyhow!(- oauth_store::describe_oauth_error(store, "google-calendar", "Google Calendar", instance)- .await- ))+ Err(anyhow::Error::new(GcalAuthError {+ message: oauth_store::describe_oauth_error(+ store,+ "google-calendar",+ "Google Calendar",+ instance,+ )+ .await,+ }))}/// GET /connections/google-calendar/status — check connection + email.@@ -1190,22 +1318,7 @@ async fn gcal_events(let client = reqwest::Client::new();match gcal_events_inner(&client, params, &state.secret_store).await {Ok(events) => (StatusCode::OK, Json(json!(events))),- Err(e) => {- let message = e.to_string();- // Recognize every variant of the OAuth-failure message from- // `describe_oauth_error` (not-connected, single-instance broken,- // multi-instance ambiguous, explicit-instance broken) and surface- // them as 401 so callers can distinguish auth from upstream 5xx.- let is_oauth_failure = message.contains("Google Calendar not connected")- || message.contains("Google Calendar account")- || message.contains("multiple Google Calendar accounts connected");- let status = if is_oauth_failure {- StatusCode::UNAUTHORIZED- } else {- StatusCode::INTERNAL_SERVER_ERROR- };- (status, Json(json!({ "error": message })))- }+ Err(e) => gcal_events_error_response(&e),}}@@ -2864,6 +2977,74 @@ mod gcal_merge_tests {}}+/// The "calendar configured but not usable" states must never be 500s: the+/// app polls both calendar event routes every 60 seconds, so a 500 here is+/// two tower_http ERROR log lines per minute forever (observed in user log+/// bundles on Linux with no Google Calendar token stored).+#[cfg(test)]+mod calendar_error_response_tests {+ use super::*;++ #[test]+ fn gcal_auth_failure_maps_to_structured_401() {+ let err = anyhow::Error::new(GcalAuthError {+ message: "Google Calendar not connected — use 'Connect Google Calendar' in Settings > Connections".to_string(),+ });+ let (status, Json(body)) = gcal_events_error_response(&err);+ assert_eq!(status, StatusCode::UNAUTHORIZED);+ assert_eq!(body["reason"], "auth_required");+ assert_eq!(body["connected"], false);+ assert!(body["error"].as_str().unwrap().contains("not connected"));+ }++ #[test]+ fn gcal_non_auth_failure_stays_500() {+ let err = anyhow::anyhow!("google api returned 503: backend unavailable");+ let (status, Json(body)) = gcal_events_error_response(&err);+ assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);+ assert!(body["error"].as_str().unwrap().contains("503"));+ assert!(body.get("reason").is_none());+ }++ #[test]+ fn native_unsupported_platform_is_200_not_connected() {+ let (status, Json(body)) = native_calendar_error_response(NativeCalendarError::Unsupported);+ assert_eq!(status, StatusCode::OK);+ assert_eq!(body["connected"], false);+ assert_eq!(body["reason"], "unsupported_platform");+ assert!(body["data"].as_array().unwrap().is_empty());+ }++ #[test]+ fn native_store_unavailable_is_200_not_connected() {+ let (status, Json(body)) = native_calendar_error_response(+ NativeCalendarError::StoreUnavailable("RequestStoreAsync failed".to_string()),+ );+ assert_eq!(status, StatusCode::OK);+ assert_eq!(body["connected"], false);+ assert_eq!(body["reason"], "store_unavailable");+ }++ #[test]+ fn native_auth_required_is_401_with_reason() {+ let (status, Json(body)) = native_calendar_error_response(+ NativeCalendarError::AuthRequired("calendar access not granted".to_string()),+ );+ assert_eq!(status, StatusCode::UNAUTHORIZED);+ assert_eq!(body["reason"], "auth_required");+ assert_eq!(body["connected"], false);+ }++ #[test]+ fn native_internal_error_stays_500() {+ let (status, Json(body)) = native_calendar_error_response(NativeCalendarError::Internal(+ "EventKit query failed".to_string(),+ ));+ assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);+ assert!(body["error"].as_str().unwrap().contains("EventKit"));+ }+}+#[cfg(test)]mod tests {use super::*;