1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
//! Shared online user queries based on recent authenticated heartbeats.
//!
//! Enable `presence-postgres` for `PostgresPresence` or `presence-sqlite` for
//! `SqlitePresence`. Both may be enabled together. Each backend keeps one row
//! per opaque `(scope, user_id)`: multiple tabs, devices, and application instances
//! using the same database share that row. A user is online when
//! `last_seen > database_time - timeout`.
//! This measures recently received heartbeats, not human attention, current
//! page visibility, or whether a login session is still valid.
//!
//! # Integration
//!
//! 1. Copy `POSTGRES_SCHEMA` or `SQLITE_SCHEMA` into a host-owned, versioned
//! migration file. They create `public.footing_presence` (PostgreSQL) or
//! `main.footing_presence` (SQLite), without a foreign key to business tables.
//! These are **frozen version 1** schemas; future changes will be separate
//! incremental migrations. Preserve the copied SQL and host-assigned version:
//! do not regenerate an applied migration from a newer dependency. One migration
//! sequence owns this table even when multiple services use it. Footing does
//! not run migrations automatically or maintain a second migration history.
//! 2. Construct a store with the application's existing pool, a trusted scope,
//! and an online timeout. All instances sharing a scope must use the same
//! timeout, including cleanup jobs. Use separate scopes for applications,
//! environments, or tenants whose users must not be combined; avoid ambiguous
//! concatenation when constructing a scope from multiple identifiers.
//! 3. In an authenticated heartbeat handler, pass the **verified user's ID** to
//! the store's `heartbeat` method. Do not take identity or scope from an
//! untrusted request body. Apply normal credential validation, CSRF protection
//! where applicable, and rate limits. Configure authentication so heartbeats
//! do not extend sliding login sessions.
//! 4. Authorize count/list queries in the host. Join returned IDs to names or
//! departments there. No HTTP routes, tasks, or migrations are installed by
//! enabling the feature or constructing a store.
//!
//! PostgreSQL:
//!
//! ```no_run
//! # #[cfg(feature = "presence-postgres")]
//! # async fn example(pool: sqlx::PgPool, verified_user_id: &str)
//! # -> Result<(), footing::presence::PresenceError> {
//! use footing::presence::{DEFAULT_ONLINE_TIMEOUT, PostgresPresence};
//!
//! // The host has already applied POSTGRES_SCHEMA through its migration system.
//! let presence = PostgresPresence::new(pool, "admin:production", DEFAULT_ONLINE_TIMEOUT)?;
//! presence.heartbeat(verified_user_id).await?;
//! let count = presence.count_online().await?;
//! let first = presence.list_online(None, 50).await?;
//! if let Some(after) = first.next_user_id.as_deref() {
//! let next = presence.list_online(Some(after), 50).await?;
//! # let _ = next;
//! }
//! // Optional, bounded maintenance; expiration does not depend on this call.
//! presence.prune_expired(500).await?;
//! # let _ = count;
//! # Ok(())
//! # }
//! ```
//!
//! SQLite exposes the same operations:
//!
//! ```no_run
//! # #[cfg(feature = "presence-sqlite")]
//! # async fn example(pool: sqlx::SqlitePool, verified_user_id: &str)
//! # -> Result<(), footing::presence::PresenceError> {
//! use footing::presence::{DEFAULT_ONLINE_TIMEOUT, SqlitePresence};
//!
//! // The host has applied SQLITE_SCHEMA through its migration system.
//! let presence = SqlitePresence::new(pool, "admin:production", DEFAULT_ONLINE_TIMEOUT)?;
//! presence.heartbeat(verified_user_id).await?;
//! let page = presence.list_online(None, 50).await?;
//! # let _ = page;
//! # Ok(())
//! # }
//! ```
//!
//! # Browser behavior and guarantees
//!
//! A reasonable starting point is a heartbeat every 30 seconds while the page
//! is visible and authenticated, with a 90-second online timeout. Send a fresh
//! heartbeat on becoming visible. Allow at most one request in flight, bound its
//! duration, and wait for the next interval after a failure: do not buffer or
//! replay heartbeats. Stop on logout, authentication failure, or account changes.
//! The host must also coordinate cross-tab account changes; an old page using a
//! newly switched cookie would otherwise report the newly authenticated user.
//! This API does not bind browser instances to login sessions.
//!
//! There are no event IDs, client timestamps, or exactly-once delivery guarantees.
//! A delayed request can extend presence on arrival.
//! Unknown commit outcomes are reported as errors; the next regular heartbeat
//! can recover without a retry queue.
//! Hiding, closing, or logging out of a page does not immediately remove the
//! user: other tabs or devices may still be active, and absence takes effect
//! through the timeout. Presence must not authorize access or serve as an audit
//! log. Identifiers must not be used as Prometheus labels.
//!
//! Both backends accept positive, whole-millisecond timeouts up to
//! [`MAX_ONLINE_TIMEOUT`]. PostgreSQL timestamps retain microsecond precision;
//! SQLite timestamps use integer Unix milliseconds. PostgreSQL samples statement
//! arrival time; SQLite samples its host's wall clock during execution, which
//! may be delayed by its write lock. See each backend's heartbeat documentation.
//! Heartbeats never reduce a stored `last_seen`, but wall-clock adjustments can
//! still affect expiration. SQLite sharing is intended for processes on one
//! host using the same local file; use PostgreSQL for deployment-wide shared state.
//!
//! Use the same database for writes and queries; replica lag can otherwise give
//! stale results. Independent queries and successive pages observe a changing
//! set, not a shared historical snapshot. Explicit `prune_expired` calls reclaim
//! storage in bounded batches. The host chooses the schedule, connection/query
//! deadlines, and backend-specific lock-wait policy.
use Duration;
use OffsetDateTime;
pub use PresenceError;
pub use ;
pub use ;
/// Suggested online window when clients send a heartbeat every 30 seconds.
pub const DEFAULT_ONLINE_TIMEOUT: Duration = from_secs;
/// Maximum timeout, bounded to keep timestamp arithmetic within a practical range.
pub const MAX_ONLINE_TIMEOUT: Duration = from_secs;
/// Maximum UTF-8 byte length of each scope and user ID.
pub const MAX_ID_LENGTH: usize = 256;
/// Maximum number of users returned or expired records deleted in one call.
pub const MAX_BATCH_SIZE: u32 = 1000;
/// One online user in a scope. Times come from the database engine, never the browser.
/// A bounded page ordered by user ID with a case-sensitive binary collation.