///|
/// What a link gives to the view that opens it.
#derive(Eq, Debug)
pub(all) struct Grant {
surface : @app.Surface
/// The project that the view shows first, if the link has one.
project : @app.ProjectId?
}
///|
/// The time in which a link works: 10 minutes.
let link_life_millis : Int64 = 600_000L
///|
#derive(Eq, Debug)
priv struct Link {
token : Secret
grant : Grant
issued : @app.UnixMillis
}
///|
/// True while the link works. The distance between the two times counts, also
/// when the clock went back. Times are not negative, so it cannot overflow.
fn Link::is_live(self : Link, now : @app.UnixMillis) -> Bool {
(now.to_int64() - self.issued.to_int64()).abs() < link_life_millis
}
///|
/// The links that the server gave and that still work. A link works many times,
/// so a user can open it in a second browser.
///
/// A link works while the time is less than 10 minutes after its issue. If the
/// clock went back, it also works while the time is less than 10 minutes before
/// its issue, and not at an earlier time. A clock that goes back by a day then
/// does not make the link work for a day.
///
/// A link that stopped can work again if the clock of the machine goes back to a
/// time near its issue. This ends at the next `issue`, which removes the links
/// that do not work at that time.
#derive(Eq, Debug)
struct Links {
links : Array[Link]
}
///|
/// No links.
pub fn Links::empty() -> Links {
{ links: [], }
}
///|
/// Adds a link with a new token, and removes the links that do not work at this
/// time, so the number of links does not grow without a limit.
pub fn Links::issue(
self : Links,
token : Secret,
grant : Grant,
now : @app.UnixMillis,
) -> Links {
let live = self.links.filter(link => link.is_live(now))
{ links: [..live, { token, grant, issued: now, }], }
}
///|
/// What the link with this token gives, or `None` if no link has the token or
/// the link does not work at this time.
pub fn Links::redeem(
self : Links,
text : String,
now : @app.UnixMillis,
) -> Grant? {
let mut found = None
// The loop compares each link, so the time does not tell which one matches.
for link in self.links {
if link.token.matches(text) && link.is_live(now) {
found = Some(link.grant)
}
}
found
}
///|
pub extend Grant with Eq::{not_equal, equal}
///|
pub extend Grant with @debug.Debug::{to_repr}
///|
pub extend Links with Eq::{not_equal, equal}
///|
pub extend Links with @debug.Debug::{to_repr}