oficina / base Public

Clone
git clone https://amadan.net/oficina/base

Plain git — no account needed to clone.

Download

Download this file

1import Combine
2import Foundation
3import Observation
4import RastrilloApple
5
6/// Base's session on this device: Oficina ID through the kit, and once
7/// signed in, the client, the member, Home and Ask.
8///
9/// - Oficina ID is the kit's `OficinaIDModel` (app "base"): straight in
10/// when another Oficina app holds the ID, the kit's onboarding otherwise.
11/// `OficinaApp.base` arrives with the kit's next pin; until then the
12/// onboarding draws in the kit's default appearance.
13/// - The client keeps one transport for the whole session and swaps the
14/// kit's session under it when the kit mints a new one (a 401's
15/// `sessionRejected()`, a stale one renewed on foreground), so Ask's
16/// stream and writes never hold an ended cookie.
17/// - Coming forward: `renewIfNeeded()`, then Home and Ask read afresh and
18/// Ask listens again (Task 12 adds renewing Ask's own key first).
19@MainActor @Observable public final class BaseSession {
20 public static let configuration = OficinaIDConfiguration(app: "base", appName: "Base")
21 public static var appGroup: String {
22 #if os(iOS)
23 "group.works.oficina"
24 #else
25 "9U4A84C4WK.works.oficina"
26 #endif
27 }
28
29 public let oficina: OficinaIDModel
30 public private(set) var signedIn: OficinaSignedIn?
31 public private(set) var client: BaseClient?
32 public private(set) var ask: AskModel?
33 public private(set) var me: Me?
34 public private(set) var home: HomeData?
35 @ObservationIgnored public private(set) var askSetup: AskSetup?
36
37 @ObservationIgnored private var transport: SwappableTransport?
38 @ObservationIgnored private var watching: AnyCancellable?
39
40 /// Where the person's Disconnect is kept, per account.
41 let defaults: UserDefaults
42
43 public init(oficina: OficinaIDModel, defaults: UserDefaults = .standard) {
44 self.oficina = oficina
45 self.defaults = defaults
46 watching = oficina.$step.sink { [weak self] step in
47 Task { @MainActor in self?.stepChanged(step) }
48 }
49 }
50
51 public static func live() -> BaseSession {
52 BaseSession(oficina: .live(configuration: configuration, appGroup: appGroup))
53 }
54
55 /// The kit moved: signed in (perhaps with a fresh session), or out.
56 func stepChanged(_ step: OficinaIDModel.Step) {
57 // Loading is the kit reading its store, not a sign-out.
58 if step == .loading { return }
59 guard case .signedIn(let state) = step else {
60 if let left = account {
61 end()
62 forgetDisconnectIfGone(left.identity)
63 }
64 return
65 }
66 if let previous = account, previous.identity != state.identity.id { forgetDisconnectIfGone(previous.identity) }
67 begin(identity: state.identity.id, origin: state.origin, transport: CapabilityTransport(state.client()), state: state)
68 }
69
70 /// Who the session is for: an identity at a Base. Anything that
71 /// started for one account publishes nothing once the account changes.
72 struct Account: Equatable { let identity: String; let origin: URL }
73 @ObservationIgnored private(set) var account: Account?
74 /// Bumped whenever the account changes or ends: work started under an
75 /// older generation publishes nothing.
76 @ObservationIgnored private(set) var generation = 0
77 @ObservationIgnored private(set) var refreshing: Task<Void, Never>?
78 /// Ask's set-up running on its own (a state or a write said reconnect):
79 /// the session owns it, and cancels it on sign-out and in the background.
80 @ObservationIgnored private(set) var settingUp: Task<Void, Never>?
81
82 func startSetup() {
83 guard let askSetup, settingUp == nil else { return }
84 settingUp = Task { [weak self] in
85 _ = await askSetup.runIfNeeded()
86 self?.settingUp = nil
87 }
88 }
89 /// An Oficina ID assertion addressed to `audience` (Equipo): the kit's.
90 @ObservationIgnored lazy var assertion: @MainActor (URL) async throws -> (assertion: String, verifier: String) = { [oficina] audience in
91 try await oficina.assertion(for: audience)
92 }
93 /// Base refused the session: the kit mints a new one silently.
94 @ObservationIgnored lazy var rejected: @MainActor () async -> Void = { [oficina] in await oficina.sessionRejected() }
95
96 /// Signed in as `identity` at `origin`. The same account again (the kit
97 /// renewed its session) swaps the session under the client; another
98 /// account starts afresh, and nothing of the old one lands.
99 func begin(identity: String, origin: URL, transport http: NativeTransport, state: OficinaSignedIn? = nil) {
100 let next = Account(identity: identity, origin: origin)
101 if let transport, account == next {
102 transport.swap(http)
103 signedIn = state
104 return
105 }
106 end()
107 let epoch = generation
108 let swappable = SwappableTransport(http)
109 // A 401 is only this account's to act on while it is still the one.
110 let client = BaseClient(transport: swappable) { [weak self] in
111 guard let self, await self.generation == epoch else { return }
112 await self.rejected()
113 }
114 account = next
115 transport = swappable
116 self.client = client
117 signedIn = state
118 let ask = AskModel(client: client)
119 let setup = AskSetup(client: client, ask: ask, assertion: { [weak self] equipo in
120 guard let self, self.generation == epoch else { throw CancellationError() }
121 return try await self.assertion(equipo)
122 }, fallbackEquipo: { [weak self] in self?.me?.equipoOrigin })
123 setup.isCurrent = { [weak self] in self?.generation == epoch }
124 // Both read and write the flag of the account this set-up belongs
125 // to, and only while it is still the one signed in: a gone
126 // account's set-up is held off and writes nothing.
127 setup.heldOff = { [weak self, weak ask] in
128 guard let self, self.generation == epoch else { return true }
129 // Base's word wins, and the device's cache follows it.
130 if let said = ask?.disconnected {
131 if self.disconnected(next) != said { self.setDisconnected(said, for: next) }
132 return said
133 }
134 return self.disconnected(next)
135 }
136 setup.onDisconnected = { [weak self] in
137 guard let self, self.generation == epoch else { return }
138 self.setDisconnected(true, for: next)
139 }
140 ask.onNeedsSetup = { [weak self] in
141 guard let self, self.generation == epoch else { return }
142 self.startSetup()
143 }
144 self.ask = ask
145 askSetup = setup
146 refreshing = Task { await self.refresh() }
147 }
148
149 /// Signed out, or about to be someone else: the old account's work is
150 /// cancelled and anything still in flight lands on nothing.
151 func end() {
152 generation += 1
153 refreshing?.cancel()
154 refreshing = nil
155 settingUp?.cancel()
156 settingUp = nil
157 ask?.dispose()
158 ask = nil; askSetup = nil; client = nil; transport = nil; account = nil
159 signedIn = nil; me = nil; home = nil
160 }
161
162 /// Reads the member, Home and Ask afresh, for the account it started
163 /// under only.
164 public func refresh() async {
165 guard let client else { return }
166 let epoch = generation
167 async let me = try? client.me()
168 async let home = try? client.home()
169 await ask?.resume()
170 let (newMe, newHome) = await (me, home)
171 guard generation == epoch, !Task.isCancelled else { return }
172 if let newMe { self.me = newMe }
173 if let newHome { self.home = newHome }
174 // Ask set up (or renewed) with Oficina ID, if it wants it.
175 await askSetup?.runIfNeeded()
176 }
177
178 /// Set it up (the person pressed the button): now, whatever the minute.
179 public func setUpAsk() async {
180 // The person's own: whatever set-up is in flight gives way to it.
181 settingUp?.cancel()
182 settingUp = nil
183 askSetup?.invalidate()
184 askDisconnected = false
185 await askSetup?.runIfNeeded(force: true)
186 }
187
188 /// The app came forward.
189 public func foreground() async {
190 await oficina.renewIfNeeded()
191 await refresh()
192 }
193
194 /// The app went away: Ask stops listening.
195 public func background() {
196 settingUp?.cancel()
197 settingUp = nil
198 ask?.pause()
199 }
200
201 /// The session's transport, for what loads from Base's origin (icons).
202 public var iconTransport: NativeTransport? { transport }
203
204 /// The member's Appearance: shown at once, kept on the web too. A
205 /// failure puts the old one back.
206 public func setAppearance(_ appearance: BaseAppearance) async {
207 guard let client, var me else { return }
208 let epoch = generation
209 let before = me.appearance
210 me.appearance = appearance
211 self.me = me
212 do { try await client.setAppearance(appearance) } catch {
213 if generation == epoch { self.me?.appearance = before }
214 }
215 }
216
217 /// The person disconnected Ask on this account (Settings' Disconnect).
218 /// It sticks, across launches: no set-up runs by itself until they set
219 /// Ask up again or sign in afresh.
220 var askDisconnected: Bool {
221 get { account.map(disconnected) ?? false }
222 set { if let account { setDisconnected(newValue, for: account) } }
223 }
224 func disconnected(_ account: Account) -> Bool { defaults.bool(forKey: Self.disconnectedKey(account)) }
225 func setDisconnected(_ value: Bool, for account: Account) { defaults.set(value, forKey: Self.disconnectedKey(account)) }
226 static func disconnectedKey(_ account: Account) -> String { "askDisconnected:\(account.identity)@\(account.origin.absoluteString)" }
227
228 /// The identity has left this device (a sign-out here, in another
229 /// Oficina app, or Home ending its grant): its Disconnect goes for every
230 /// team, so the next sign-in is a fresh one. A team switch or a
231 /// relaunch keeps it: the identity is still here.
232 func forgetDisconnectIfGone(_ identity: String) {
233 guard (try? oficina.store.hasIdentity(identity)) != true else { return }
234 let prefix = "askDisconnected:\(identity)@"
235 for key in defaults.dictionaryRepresentation().keys where key.hasPrefix(prefix) { defaults.removeObject(forKey: key) }
236 }
237
238 /// Settings' Disconnect for Ask, then Ask as it is now. It stops any
239 /// set-up running, and keeps one from running again by itself.
240 public func disconnectAsk() async {
241 guard let client else { return }
242 let before = askDisconnected
243 askDisconnected = true
244 settingUp?.cancel()
245 settingUp = nil
246 askSetup?.invalidate()
247 let epoch = generation
248 do {
249 try await client.disconnectAsk()
250 } catch {
251 // Nothing was disconnected (offline, a 502): as Base says, the
252 // flag stays as it was, and renewal goes on.
253 guard generation == epoch else { return }
254 askDisconnected = before
255 return
256 }
257 guard generation == epoch else { return }
258 await ask?.load()
259 }
260
261 /// The teams this Oficina ID is in, for Switch team.
262 ///
263 /// The kit refreshes its cache when it's older than a minute; nil means
264 /// it didn't (fresh already, a refresh already running, or a failure),
265 /// never "no teams", so the cache for this identity is the answer then.
266 /// Signed out or someone else meanwhile: none.
267 public func teams() async -> [OficinaTeam] {
268 guard let asked = account else { return [] }
269 let fresh = await oficina.refreshTeams(maxAge: 60)
270 guard account == asked else { return [] }
271 return fresh ?? oficina.store.teams(asked.identity)?.teams ?? []
272 }
273
274 /// Switch team: the kit opens the other team's Base.
275 public func switchTo(_ team: OficinaTeam) async { await oficina.choose(team) }
276
277 /// Sign out (confirmed by the caller): the kit's sign-out of this
278 /// Oficina ID, everywhere on this device.
279 public func signOut() {
280 // The kit's step change clears Disconnect for every team of the
281 // identity (forgetDisconnectIfGone), whoever signed it out.
282 oficina.signOut()
283 }
284}
285
286/// A transport whose session can be replaced under the requests that use
287/// it: each request goes to whichever `NativeHTTP` is current when it starts.
288final class SwappableTransport: NativeTransport, @unchecked Sendable {
289 private let lock = NSLock()
290 private var inner: NativeTransport
291 init(_ inner: NativeTransport) { self.inner = inner }
292 func swap(_ next: NativeTransport) { lock.withLock { inner = next } }
293 private var current: NativeTransport { lock.withLock { inner } }
294
295 var origin: URL { current.origin }
296 func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse {
297 try await current.responseDetails(path, method: method, body: body, contentType: contentType, maxBytes: maxBytes)
298 }
299 func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws {
300 try await current.stream(path, onOpen: onOpen, onLine: onLine)
301 }
302 func download(_ path: String, to destination: URL) async throws {
303 try await current.download(path, to: destination)
304 }
305}
306
307/// Says what this app draws on its Ask reads, `/ask/state` and
308/// `/ask/events` (docs/api/base-native-v1.md, "What the app can draw"):
309/// `client_caps=lookup_answers`, a query parameter, since the kit's
310/// NativeHTTP sets no header of its own. Base counts it as
311/// `Base-Client-Capabilities`. Every other request goes as it is.
312final class CapabilityTransport: NativeTransport, @unchecked Sendable {
313 /// What this build draws, comma-separated.
314 static let capabilities = "lookup_answers"
315 private let inner: NativeTransport
316 init(_ inner: NativeTransport) { self.inner = inner }
317
318 /// path with the capabilities added, if it is one of Ask's reads.
319 static func path(_ path: String) -> String {
320 let bare = path.split(separator: "?", maxSplits: 1).first.map(String.init) ?? path
321 guard bare == "/ask/state" || bare == "/ask/events" else { return path }
322 return path + (path.contains("?") ? "&" : "?") + "client_caps=" + capabilities
323 }
324
325 var origin: URL { inner.origin }
326 func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse {
327 try await inner.responseDetails(method == "GET" ? Self.path(path) : path, method: method, body: body, contentType: contentType, maxBytes: maxBytes)
328 }
329 func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws {
330 try await inner.stream(Self.path(path), onOpen: onOpen, onLine: onLine)
331 }
332 func download(_ path: String, to destination: URL) async throws {
333 try await inner.download(path, to: destination)
334 }
335}
336