Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion apple/TablePro/Core/Sync/MoveBetweenProviders.swift
Original file line number Diff line number Diff line change
Expand Up @@ -728,8 +728,11 @@ extension ProviderMoves {
return String(localized: "This Mac was removed from your account. Sign in again to use TablePro Sync here.")
case "sync.locked", "sync.not_allowed", "sync.device_not_approved":
return String(localized: "This Mac cannot read your account's keys. Approve it from another device, or use your recovery key.")
case "sync.network", "sync.server", "sync.rate_limited", "sync.restore_check_unavailable", "account.unreachable":
case "sync.network", "account.unreachable":
return String(localized: "TablePro Sync cannot be reached. Your data stays on this Mac; try again once you are online.")
// The server answered and named a wait (core ADR 0051, Rate limits), so this Mac is online.
case "sync.rate_limited", "sync.restore_check_unavailable":
return String(localized: "TablePro Sync asked this Mac to wait. Your data stays on this Mac; try again in a minute.")
case "sync.feature_required", "sync.license_expired", "sync.seat_required":
return String(localized: "Your account no longer includes TablePro Sync uploads. Your data stays on this Mac.")
case "sync.signed_out":
Expand Down
3 changes: 3 additions & 0 deletions apple/TablePro/Resources/Localizable.xcstrings
Original file line number Diff line number Diff line change
Expand Up @@ -209116,6 +209116,9 @@
"TablePro supports these MAC algorithms: %@." : {
"extractionState" : "manual",
"generatesSymbol" : false
},
"TablePro Sync asked this Mac to wait. Your data stays on this Mac; try again in a minute." : {

},
"TablePro Sync cannot be reached. Your data stays on this Mac; try again once you are online." : {

Expand Down
19 changes: 19 additions & 0 deletions apple/TableProTests/Core/Sync/ProviderMovesTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1149,6 +1149,25 @@ struct ProviderMovesTests {
))
}

// E2E O9: the server answered, so a Mac it asked to wait is online.
@Test("A wait the server named is never worded as being offline", arguments: [
"sync.rate_limited", "sync.restore_check_unavailable"
])
func serverWaitIsNotOffline(code: String) {
let message = ProviderMoves.message(forCode: code)

#expect(message == String(
localized: "TablePro Sync asked this Mac to wait. Your data stays on this Mac; try again in a minute."
))
#expect(message != ProviderMoves.message(forCode: "sync.network"))
}

@Test("A server error is not worded as being offline")
func serverErrorIsNotOffline() {
#expect(ProviderMoves.message(forCode: "sync.server") == ProviderMoves.message(forCode: ""))
#expect(ProviderMoves.message(forCode: "sync.server") != ProviderMoves.message(forCode: "sync.network"))
}

// E2E F33: approval can't help a removed Mac, so its words are its own.
@Test("A removed Mac is told it was removed, not to ask for approval")
func removedMacHasItsOwnWords() {
Expand Down
1 change: 1 addition & 0 deletions apple/changelog.d/4857.fixed.1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
TablePro Sync said it could not be reached while the server only asked this Mac to wait.
1 change: 1 addition & 0 deletions apple/changelog.d/4857.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A Mac waiting for its approval ran into TablePro Sync's request limit, which held its sync for a minute.
11 changes: 11 additions & 0 deletions core/crates/sync/src/api/control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,9 @@ pub enum PassReason {
Journal,
// A key flow wrote something a pass should carry (`KeyHooks::pass_soon`).
KeyFlow,
// An open approval sheet's poll (`KeyHooks::approval_poll_soon`): it reads only the personal scope, where the
// session's steps and the approval arrive, so a poll every 1 to 2 seconds stays inside the rate limit (0051).
ApprovalPoll,
// `CKAccountChanged`: the engine reads the account status and opens that account's state file.
AccountChanged,
Launch,
Expand All @@ -151,6 +154,14 @@ pub enum PassReason {
Person,
}

impl PassReason {
// A journal pass diffs only the records the journal named and an approval poll reads only the personal scope, so
// neither stands in for a pass over everything.
pub const fn covers_all(self) -> bool {
!matches!(self, Self::Journal | Self::ApprovalPoll)
}
}

// The kinds turned off on this device, and the password switch.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SyncCategories {
Expand Down
3 changes: 3 additions & 0 deletions core/crates/sync/src/api/key_flows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -592,6 +592,9 @@ pub trait KeyHooks: Send + Sync {

// A flow wrote something a pass should carry.
fn pass_soon(&self);

// An open approval session waits on the other side's step, which only a pull of the personal scope brings.
fn approval_poll_soon(&self);
}

// A draft, review or other flow step this service holds between two calls.
Expand Down
4 changes: 4 additions & 0 deletions core/crates/sync/src/engine/hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,4 +181,8 @@ impl KeyHooks for EngineHooks {
fn pass_soon(&self) {
self.wake.pass_soon(PassReason::KeyFlow);
}

fn approval_poll_soon(&self) {
self.wake.pass_soon(PassReason::ApprovalPoll);
}
}
11 changes: 6 additions & 5 deletions core/crates/sync/src/engine/scheduler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,14 +147,15 @@ impl Wake {
}
}

// One pass covers every reason asked for since the last take. It is a journal pass only when nothing else asked,
// since a journal pass diffs only the records the journal named.
// One pass covers every reason asked for since the last take. A journal pass, which pulls every scope, runs only
// when no reason that covers all asked, and an approval poll only when nothing else did.
fn take(&self) -> Option<PassReason> {
let mut reasons = self.reasons();
let why = reasons
.iter()
.copied()
.find(|why| *why != PassReason::Journal)
.find(|why| why.covers_all())
.or_else(|| reasons.iter().copied().find(|why| *why == PassReason::Journal))
.or_else(|| reasons.first().copied());
reasons.clear();
why
Expand Down Expand Up @@ -193,7 +194,7 @@ pub fn spawn(pass: Arc<dyn Pass>, wake: Wake, stop: StopSignal, backoff: Backoff
}

// The poll falls due a poll interval after the last full pass, so journal passes, which diff only what they were told
// of, never put it off.
// of, and approval polls, which read only the personal scope, never put it off.
async fn run(pass: Arc<dyn Pass>, wake: Wake, stop: StopSignal, mut backoff: Backoff) {
let mut poll_at = tokio::time::Instant::now() + pass.poll_interval();
// The code of the failure the passes are in, so a device offline for hours warns once, not on every retry.
Expand All @@ -208,7 +209,7 @@ async fn run(pass: Arc<dyn Pass>, wake: Wake, stop: StopSignal, mut backoff: Bac
}
why = wake.next() => why,
};
if why != PassReason::Journal {
if why.covers_all() {
poll_at = tokio::time::Instant::now() + pass.poll_interval();
}
if stop.is_stopped() {
Expand Down
39 changes: 37 additions & 2 deletions core/crates/sync/src/http/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use crate::api::transport::{
ClearedKeyDevice, DpopKey, Proof, PullRequest, PulledPage, PushAnswer, PushBatch, RowKeyDevice, ServiceTransport,
Transport, TransportError,
};
use crate::engine::Backoff;

// A page stops at 4 MiB of records but never inside a change set, which can itself take a 4 MiB push and its 10,000
// records' columns (0051, Limits; Pull), so a page is bounded well above both. A push's answer holds one outcome per
Expand Down Expand Up @@ -151,6 +152,9 @@ pub struct HttpTransport {
binding: Binding,
// The server's last `DPoP-Nonce`, which the next proof carries (RFC 9449 section 8).
nonce: Mutex<Option<String>>,
// Until when the last 429's `Retry-After` holds every call: the limit counts all of the sign-in's `/v2` calls, so
// one call's 429 is every call's (0051, Rate limits).
held_until: Mutex<Option<tokio::time::Instant>>,
// How long the scopes body, a pass's first call, waits for its answer to start.
answer_within: Duration,
transfers: TransferBudget,
Expand Down Expand Up @@ -184,6 +188,7 @@ impl HttpTransport {
http,
binding,
nonce: Mutex::new(None),
held_until: Mutex::new(None),
answer_within: tablepro_cloud_api::ANSWER_TIMEOUT,
transfers: TransferBudget::STANDARD,
})
Expand All @@ -209,6 +214,31 @@ impl HttpTransport {
self.nonce.lock().unwrap_or_else(PoisonError::into_inner)
}

fn held_until(&self) -> MutexGuard<'_, Option<tokio::time::Instant>> {
self.held_until.lock().unwrap_or_else(PoisonError::into_inner)
}

// A call inside the hold answers the 429 again, with the wait left, and never reaches the server.
fn waited(&self) -> Result<(), TransportError> {
let now = tokio::time::Instant::now();
match *self.held_until() {
Some(until) if until > now => Err(TransportError::RateLimited {
retry_after_ms: Some(u64::try_from((until - now).as_millis()).unwrap_or(u64::MAX).max(1)),
}),
_ => Ok(()),
}
}

// The scheduler's wait has the same cap, so a hold never outlasts the retry it gates.
fn hold(&self, retry_after_ms: u64) {
let wait = Duration::from_millis(retry_after_ms.min(Backoff::MAX_RETRY_AFTER_MS));
let until = tokio::time::Instant::now() + wait;
let mut held = self.held_until();
if held.is_none_or(|held| held < until) {
*held = Some(until);
}
}

async fn token(&self) -> Result<SecretString, TransportError> {
let now = self.sign_in.signed_in().await?;
if !self.binding.holds(&now.of) {
Expand Down Expand Up @@ -284,6 +314,7 @@ impl HttpTransport {
) -> Result<(Response, SecretString), TransportError> {
let (mut nonce_retried, mut token_retried) = (false, false);
loop {
self.waited()?;
let token = self.token().await?;
let sent = self.request(call, &token)?.send();
let sent = match within {
Expand Down Expand Up @@ -381,8 +412,12 @@ impl HttpTransport {
body: &[u8],
) -> TransportError {
let error = errors::refusal(status, headers, body);
if error == TransportError::DeviceRemoved {
self.sign_in.device_removed(token).await;
match &error {
TransportError::DeviceRemoved => self.sign_in.device_removed(token).await,
TransportError::RateLimited {
retry_after_ms: Some(wait),
} => self.hold(*wait),
_ => {}
}
error
}
Expand Down
46 changes: 46 additions & 0 deletions core/crates/sync/src/http/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -784,3 +784,49 @@ async fn a_removal_sends_the_key_device_it_expects_and_reads_the_one_the_server_
assert_eq!(unsaid, Ok(ClearedKeyDevice::NotSaid));
assert_eq!(refused, Err(TransportError::KeyDeviceChanged));
}

// The server's limit counts every `/v2` call of the sign-in, so after its 429 no call of any kind goes out until the
// `Retry-After` passes, and each answers the wait left (0051, Rate limits; E2E O9).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_429_holds_every_call_of_the_sign_in_until_its_retry_after_passes() {
let (api, log) = server(|index, _| match index {
0 => (
429,
"retry-after: 1\r\n".to_owned(),
r#"{"type":"about:blank","title":"Rate limited","status":429,"code":"rate_limited"}"#.to_owned(),
),
_ => ok(r#"{"records":[],"cursor":"c9"}"#.to_owned()),
});
let (transport, _) = transport(&api).await;
let team = ScopeName::parse(TEAM).unwrap();
let read = |scope| PullRequest {
scope,
cursor: None,
limit: None,
proof: Proof::None,
};

let limited = transport.pull(read(team)).await;
let pull_held = transport.pull(read(team)).await;
let scopes_held = transport.scopes(None, Proof::None).await;
let sent_while_held = log.lock().unwrap().len();
tokio::time::sleep(std::time::Duration::from_millis(1_100)).await;
let after = transport.pull(read(team)).await;

assert_eq!(
limited,
Err(TransportError::RateLimited {
retry_after_ms: Some(1_000)
})
);
for held in [pull_held.map(|_| ()), scopes_held.map(|_| ())] {
let wait = match held {
Err(TransportError::RateLimited { retry_after_ms }) => retry_after_ms,
other => panic!("{other:?}"),
};
assert!(wait.is_some_and(|wait| (1..=1_000).contains(&wait)), "{wait:?}");
}
assert_eq!(sent_while_held, 1);
assert!(after.expect("a page after the wait").caught_up);
assert_eq!(log.lock().unwrap().len(), 2);
}
2 changes: 1 addition & 1 deletion core/crates/sync/src/keys/approval/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ impl ApprovalFlows for KeyService {
let mut record = self.require_session(request).await?;
self.drive(&mut record).await?;
if record.live() {
self.hooks().pass_soon();
self.hooks().approval_poll_soon();
}
self.session_view(&mut record).await
}
Expand Down
7 changes: 6 additions & 1 deletion core/crates/sync/src/keys/restore/tests/fakes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ pub(crate) enum Hook {
End(ScopeName, Option<EpochId>),
Notice(KeyNotice),
PassSoon,
ApprovalPoll,
}

#[derive(Default)]
Expand All @@ -237,7 +238,7 @@ impl Hooks {
pub fn without_notices(&self) -> Vec<Hook> {
self.calls()
.into_iter()
.filter(|call| !matches!(call, Hook::Notice(_) | Hook::PassSoon))
.filter(|call| !matches!(call, Hook::Notice(_) | Hook::PassSoon | Hook::ApprovalPoll))
.collect()
}
}
Expand Down Expand Up @@ -266,6 +267,10 @@ impl KeyHooks for Hooks {
fn pass_soon(&self) {
lock(&self.0).push(Hook::PassSoon);
}

fn approval_poll_soon(&self) {
lock(&self.0).push(Hook::ApprovalPoll);
}
}

struct FixedClock;
Expand Down
Loading
Loading