Files
ipx/ios/Sources/Outbox.swift
Ray Slakinski baa6661622 iOS app asks ipx in protobuf, not JSON (#469)
The badge's and CarPlay's reads (/api/feeds, the entry lists) and the
player's writes (position, flags) now go as application/x-protobuf, the
messages generated from crates/wire/proto by ios/scripts/proto.sh into
Sources/Wire, committed so the build needs no protoc. SwiftProtobuf is
pinned to the generator's version, 1.41.0, whose code refuses another.

A read whose answer is not protobuf counts as no answer: a server from
before #465 answers JSON whatever it is asked, and JSON can decode as a
message of nothing, which would have set the badge to zero.

The outbox keeps its stored key, `json`, for the body, and marks the
new writes protobuf, so places saved offline by an older build are
still sent, as JSON.

Built for the simulator with Xcode 27.2; not run against a server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 19:00:10 -05:00

74 lines
3.3 KiB
Swift

import Foundation
import Network
import SwiftProtobuf
/// Writes the player made with no connection, sent when there is one (#425): where you got to in
/// an episode, and that you finished it. In a browser the page's service worker holds these; the
/// app's player is the one writing them, so it holds its own.
///
/// A newer write to the same address replaces an older one, since each says where you are now, and
/// the queue then stays as long as the episodes played offline, not as long as the time spent.
enum Outbox {
struct Write: Codable, Equatable {
var path: String
var body: Data
/// The body is protobuf (#469). Nil in a write queued by a build before it, whose body is
/// JSON, and is sent as JSON.
var protobuf: Bool?
// `json` was the body's name when it could only be JSON; kept, so those writes still read.
enum CodingKeys: String, CodingKey { case path, body = "json", protobuf }
}
private static let key = "ipx.outbox"
private static var flushing = false
private static let monitor = NWPathMonitor()
static var pending: [Write] {
get { UserDefaults.standard.data(forKey: key).flatMap { try? JSONDecoder().decode([Write].self, from: $0) } ?? [] }
set { UserDefaults.standard.set(try? JSONEncoder().encode(newValue), forKey: key) }
}
/// A write that never arrived. Only the player's own two kinds are kept: anything else, such
/// as adding a feed, fails offline as it always has.
static func add(path: String, _ body: any SwiftProtobuf.Message) {
guard path.hasSuffix("/position") || path.hasSuffix("/flags"),
let data = try? body.serializedData() else { return }
var all = pending.filter { $0.path != path }
all.append(Write(path: path, body: data, protobuf: true))
pending = all
}
/// In the order they were made. The first that does not reach the server stops it for the next
/// try; one the server answered at all is done, whatever it said, as the worker treats it.
static func flush() async {
guard !flushing, !pending.isEmpty else { return }
flushing = true
defer { flushing = false }
let cfg = URLSessionConfiguration.default
cfg.httpCookieStorage = .shared
cfg.timeoutIntervalForRequest = 20
let session = URLSession(configuration: cfg)
for w in pending {
guard let url = Server.resolveForPlayer(w.path) else { return }
var req = URLRequest(url: url)
req.httpMethod = "POST"
req.setValue(w.protobuf == true ? API.protobuf : "application/json", forHTTPHeaderField: "Content-Type")
Credentials.headers.forEach { req.setValue($1, forHTTPHeaderField: $0) }
req.httpBody = w.body
guard (try? await session.data(for: req)) != nil else { return }
// Removed by what it is, not where it was: a newer write may have replaced it while
// this one was on its way.
pending.removeAll { $0 == w }
}
}
/// Sends what waited whenever the phone gets a connection back.
static func watch() {
monitor.pathUpdateHandler = { path in
if path.status == .satisfied { Task { await flush() } }
}
monitor.start(queue: .global(qos: .utility))
}
}