diff --git a/app/javascript/controllers/connection_controller.js b/app/javascript/controllers/connection_controller.js
index d63e11e..f298c8b 100644
--- a/app/javascript/controllers/connection_controller.js
+++ b/app/javascript/controllers/connection_controller.js
@@ -12,6 +12,8 @@ import { t } from "i18n"
// sam:progress { source, done, total } (done >= total when finished)
// sam:waiting { count }
// sam:unreachable / sam:reachable
+// and it says when the server answers again with sam:back-online (what was
+// logged offline is sent then).
// The header is replaced on every page, so the state and the listeners live
// in this module and the header on the page just shows them.
const RETRY_EVERY = 15 * 1000
@@ -38,6 +40,7 @@ function setOnline(online) {
state.online = online
header?.announce(online ? t("connection.back_online") : t("connection.offline"))
update()
+ if (online) document.dispatchEvent(new CustomEvent("sam:back-online"))
}
// Several reports often arrive together (done sending, then none waiting):
@@ -56,6 +59,9 @@ document.addEventListener("sam:reachable", () => setOnline(true))
document.addEventListener("sam:progress", ({ detail }) => { state.progress[detail.source] = detail; update() })
document.addEventListener("sam:waiting", ({ detail }) => { state.waiting = detail.count; update() })
+// Whether the server answered last time (false while the top bar is red).
+export const serverReachable = () => state.online
+
export default class extends Controller {
static targets = [ "ring", "label", "announce" ]
diff --git a/app/javascript/controllers/offline_form_controller.js b/app/javascript/controllers/offline_form_controller.js
index ba714f6..c309201 100644
--- a/app/javascript/controllers/offline_form_controller.js
+++ b/app/javascript/controllers/offline_form_controller.js
@@ -1,10 +1,18 @@
import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
import { queue, formFields, newKey, currentUser } from "controllers/offline_queue"
+import { serverReachable } from "controllers/connection_controller"
+
+// How long to wait for the server before keeping it here instead. Photos
+// on a squawk take longer to send.
+const WAIT = 10 * 1000
+const WAIT_WITH_FILES = 60 * 1000
// Log Flight and Report Squawk: with no connection, the form is kept on this
// device and sent later (see offline_sync_controller). For flights, the next
-// leg starts where the last saved one ended.
+// leg starts where the last saved one ended. A signal so weak the server
+// doesn't answer counts as none: it's kept here too, and if it got through
+// after all, the server drops the copy sent later (same client_key).
export default class extends Controller {
static targets = [ "key", "notice" ]
static values = { kind: { type: String, default: "flight" }, tail: String }
@@ -23,14 +31,21 @@ export default class extends Controller {
get flight() { return this.kindValue === "flight" }
- // No connection: keep it here instead of submitting.
+ // No connection (or the top bar is red): keep it here instead of submitting.
async submit(event) {
- if (navigator.onLine) return
+ if (navigator.onLine && serverReachable()) return
event.preventDefault()
event.stopImmediatePropagation()
await this.save(formFields(this.element))
}
+ // Give up waiting after a while; the request then fails (networkFailed).
+ limit(event) {
+ const options = event.detail.fetchOptions
+ const files = [ ...this.element.querySelectorAll("input[type=file]") ].some((input) => input.files?.length)
+ options.signal = AbortSignal.any([ options.signal, AbortSignal.timeout(files ? WAIT_WITH_FILES : WAIT) ].filter(Boolean))
+ }
+
// Kept in case the request fails on the way (no signal but the browser thinks it's online).
remember() { this.pending = formFields(this.element) }
diff --git a/app/javascript/controllers/offline_sync_controller.js b/app/javascript/controllers/offline_sync_controller.js
index fff8b53..dcae68d 100644
--- a/app/javascript/controllers/offline_sync_controller.js
+++ b/app/javascript/controllers/offline_sync_controller.js
@@ -1,12 +1,20 @@
import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
import { queue } from "controllers/offline_queue"
+import { serverReachable } from "controllers/connection_controller"
+
+// How long to wait for the server to take one before trying again later
+// (a weak signal can leave a request hanging for minutes). Photos take longer.
+const WAIT = 15 * 1000
+const WAIT_WITH_FILES = 60 * 1000
const report = (name, detail) => document.dispatchEvent(new CustomEvent(name, { detail }))
// On every page: sends the flights and squawks this user saved offline once
// there's a connection, says what happened, and shows the count on the app
-// icon. A rejected item stays until it's discarded.
+// icon. A rejected item stays until it's discarded. Nothing is tried while
+// the top bar is red; it goes again as soon as it turns back
+// (connection_controller.js), signal or not.
export default class extends Controller {
static targets = [ "banner" ]
@@ -14,19 +22,21 @@ export default class extends Controller {
this.sync = this.sync.bind(this)
window.addEventListener("online", this.sync)
document.addEventListener("offline-queue:changed", this.sync)
+ document.addEventListener("sam:back-online", this.sync)
this.sync()
}
disconnect() {
window.removeEventListener("online", this.sync)
document.removeEventListener("offline-queue:changed", this.sync)
+ document.removeEventListener("sam:back-online", this.sync)
}
async sync() {
let items
try { items = await queue.mine() } catch (_) { return }
if (!items.length) { this.badge(0); report("sam:waiting", { count: 0 }); return this.show("") }
- if (!navigator.onLine || this.running) return this.status(items)
+ if (!navigator.onLine || !serverReachable() || this.running) return this.status(items)
this.running = true
const sent = []
const sending = items.filter((i) => !i.error)
@@ -53,7 +63,9 @@ export default class extends Controller {
if (token) body.append("authenticity_token", token)
let response
try {
- response = await fetch(item.url, { method: "POST", body, credentials: "same-origin", headers: { Accept: "text/html" } })
+ const files = item.fields.some(([ , value ]) => value instanceof Blob)
+ response = await fetch(item.url, { method: "POST", body, credentials: "same-origin", headers: { Accept: "text/html" },
+ signal: AbortSignal.timeout(files ? WAIT_WITH_FILES : WAIT) })
} catch (_) { return "offline" }
if ([ 502, 503, 504 ].includes(response.status)) return "offline"
if (response.url.includes("/session/new")) return "signin"
diff --git a/app/views/flight_logs/new.html.erb b/app/views/flight_logs/new.html.erb
index 2af939d..54bcd79 100644
--- a/app/views/flight_logs/new.html.erb
+++ b/app/views/flight_logs/new.html.erb
@@ -2,7 +2,7 @@
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<%= form_with model: [@aircraft, @flight_log], class: "card card-body space-y-5 max-w-3xl",
data: { controller: "offline-form", offline_form_kind_value: "flight", offline_form_tail_value: @aircraft.tail_number,
- action: "submit->offline-form#submit turbo:submit-start->offline-form#remember turbo:fetch-request-error->offline-form#networkFailed turbo:before-fetch-response->offline-form#gatewayFailed" } do |f| %>
+ action: "submit->offline-form#submit turbo:before-fetch-request->offline-form#limit turbo:submit-start->offline-form#remember turbo:fetch-request-error->offline-form#networkFailed turbo:before-fetch-response->offline-form#gatewayFailed" } do |f| %>
<%= f.hidden_field :client_key, data: { offline_form_target: "key" } %>
<%= f.errors_summary %>
@@ -40,8 +40,8 @@
<%= t(".saving_adds_the_tach_time") %>
- <%= f.submit t(".log_flight") %>
- <%= f.submit t(".log_and_next_leg"), name: "next_leg", class: "btn-secondary", title: t(".log_and_next_leg_title") %>
+ <%= f.submit t(".log_flight"), data: { turbo_submits_with: t(".sending") } %>
+ <%= f.submit t(".log_and_next_leg"), name: "next_leg", class: "btn-secondary", title: t(".log_and_next_leg_title"), data: { turbo_submits_with: t(".sending") } %>
<%= link_to t(".cancel"), aircraft_flight_logs_path(@aircraft), class: "btn-secondary" %>
<% end %>
diff --git a/app/views/pwa/service-worker.js.erb b/app/views/pwa/service-worker.js.erb
index 7c937cb..6d169fb 100644
--- a/app/views/pwa/service-worker.js.erb
+++ b/app/views/pwa/service-worker.js.erb
@@ -9,6 +9,8 @@
// - each aircraft's photo (put in sam-images ahead of time), shown when offline.
// The forms and pages are saved ahead of time for all your aircraft
// (offline_prep_controller.js), not only the ones you've opened.
+// Any other page, when the server can't be reached (no signal, or one so
+// weak nothing comes back within NETWORK_TIMEOUT), gets the offline page.
// Nothing else is cached; signing out clears the forms and pages.
// The version changes with every build, so a release refreshes the cached shell.
const VERSION = "<%= j "#{SystemInfo.new.revision}-#{I18n.locale}" %>"
@@ -24,6 +26,19 @@ const SHORTCUTS = { "/go/log-flight": "flight_logs", "/go/report-squawk": "squaw
// A proxy in front of the app (Traefik, Authentik) answers these when the app
// itself can't be reached: treat them like no connection.
const UNREACHABLE = [ 502, 503, 504 ]
+// A weak signal can leave a request hanging for minutes: give up after this.
+const NETWORK_TIMEOUT = 10 * 1000
+// Downloads made while you wait (the .sam.zip, the records package, PDFs)
+// can take longer than that to start, so they get no time limit.
+const DOWNLOADS = /\.\w+$|^\/aircraft\/\d+\/(export|records)$/
+// After a request fails, pages go straight to the kept copy or the offline
+// page for a moment instead of trying again (Turbo follows a failed visit
+// with a full page load, which would otherwise wait all over again), then
+// for a while longer wait only briefly, so moving around offline is quick.
+const RECENTLY = 5 * 1000
+const STILL_OFFLINE = 60 * 1000
+const OFFLINE_TIMEOUT = 3 * 1000
+let failedAt = 0
const SHELL = [ "/offline", "/offline.js", "/icon.svg", "/icon-192.png", "/favicon.svg" ]
self.addEventListener("install", (event) => {
@@ -53,11 +68,9 @@ self.addEventListener("fetch", (event) => {
event.respondWith(keptPage(request, PAGE_CACHE))
} else if (request.mode === "navigate" && SHORTCUTS[url.pathname]) {
event.respondWith(shortcut(request, SHORTCUTS[url.pathname]))
- } else if (request.mode === "navigate") {
- // Always go to the network for pages; show the offline page if it's unreachable.
- event.respondWith(fetch(request)
- .then((response) => UNREACHABLE.includes(response.status) ? offlinePage() : response)
- .catch(() => offlinePage()))
+ } else if (wantsHtml) {
+ // Any other page comes from the network; the offline page when it's unreachable.
+ event.respondWith(page(request))
} else if (SHELL.includes(url.pathname)) {
// The offline page's own script and icon: fresh when online, kept copy when not.
event.respondWith(fetch(request).then((r) => r.ok ? r : caches.match(url.pathname).then((hit) => hit || r))
@@ -74,6 +87,39 @@ self.addEventListener("fetch", (event) => {
})
const offlinePage = () => caches.match("/offline")
+
+// The network, within NETWORK_TIMEOUT. A proxy's "can't reach the app" counts
+// as no connection. Rejects when there isn't one (and remembers that).
+async function network(request) {
+ const since = Date.now() - failedAt
+ if (since < RECENTLY) throw new Error("offline")
+ const wait = since < STILL_OFFLINE ? OFFLINE_TIMEOUT : NETWORK_TIMEOUT
+ let timer
+ try {
+ const limit = DOWNLOADS.test(new URL(request.url).pathname) ? [] :
+ [ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("timed out")), wait) }) ]
+ const response = await Promise.race([ fetch(request), ...limit ])
+ if (UNREACHABLE.includes(response.status)) throw new Error("unreachable")
+ failedAt = 0
+ return response
+ } catch (error) {
+ failedAt = Date.now()
+ throw error
+ } finally {
+ clearTimeout(timer)
+ }
+}
+
+// A page with no kept copy. A Turbo fetch gets the error instead, so Turbo
+// falls back to a full page load, which then gets the offline page.
+async function page(request) {
+ try {
+ return await network(request)
+ } catch (error) {
+ if (request.mode !== "navigate") throw error
+ return offlinePage()
+ }
+}
const savedImage = async (request, response) => {
const key = imageKey(request.url)
return (key && await caches.open(IMAGE_CACHE).then((c) => c.match(key))) || response || Response.error()
@@ -114,12 +160,7 @@ async function keptPage(request, cacheName) {
const cache = await caches.open(cacheName)
const key = request.url.split("?")[0]
try {
- const response = await fetch(request)
- if (UNREACHABLE.includes(response.status)) {
- const kept = await cache.match(key)
- if (kept) return kept
- return request.mode === "navigate" ? offlinePage() : response
- }
+ const response = await network(request)
const html = (response.headers.get("Content-Type") || "").includes("text/html")
if (response.ok && !response.redirected && html) await cache.put(key, response.clone())
return response
@@ -136,8 +177,7 @@ async function keptPage(request, cacheName) {
// of that kind (one aircraft), otherwise the offline page, which lists them.
async function shortcut(request, kind) {
try {
- const response = await fetch(request)
- if (!UNREACHABLE.includes(response.status)) return response
+ return await network(request)
} catch (_) { /* offline */ }
const cache = await caches.open(FORM_CACHE)
const forms = (await cache.keys()).filter((r) => new URL(r.url).pathname.includes(`/${kind}/new`))
diff --git a/app/views/squawks/_form.html.erb b/app/views/squawks/_form.html.erb
index 335002a..83a6526 100644
--- a/app/views/squawks/_form.html.erb
+++ b/app/views/squawks/_form.html.erb
@@ -1,6 +1,6 @@
<%= form_with model: [aircraft, squawk], multipart: true, class: "card card-body space-y-4 max-w-2xl",
data: (squawk.new_record? ? { controller: "offline-form show-when", offline_form_kind_value: "squawk", offline_form_tail_value: aircraft.tail_number,
- action: "submit->offline-form#submit turbo:submit-start->offline-form#remember turbo:fetch-request-error->offline-form#networkFailed turbo:before-fetch-response->offline-form#gatewayFailed" } : { controller: "show-when" }) do |f| %>
+ action: "submit->offline-form#submit turbo:before-fetch-request->offline-form#limit turbo:submit-start->offline-form#remember turbo:fetch-request-error->offline-form#networkFailed turbo:before-fetch-response->offline-form#gatewayFailed" } : { controller: "show-when" }) do |f| %>
<% if squawk.new_record? %>
<%= f.hidden_field :client_key, data: { offline_form_target: "key" } %>
@@ -25,7 +25,7 @@
<% end %>
<% if squawk.persisted? %><%= f.field :notes, as: :textarea, rows: 3 %><% end %>
- <%= f.submit squawk.new_record? ? t(".report_squawk") : t(".save") %>
+ <%= f.submit squawk.new_record? ? t(".report_squawk") : t(".save"), data: { turbo_submits_with: t(".sending") } %>
<%= link_to t(".cancel"), aircraft_squawks_path(aircraft), class: "btn-secondary" %>
<% end %>
diff --git a/config/locales/en.yml b/config/locales/en.yml
index cdc79cb..c8b2c81 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -2401,6 +2401,7 @@ en:
oil_qt: Oil (qt)
no_flights_logged_yet: No flights logged yet.
new:
+ sending: Sending…
log_flight: Log Flight
from: From
koqu: KOQU
@@ -3382,6 +3383,7 @@ en:
edit:
edit_squawk: Edit Squawk
form:
+ sending: Sending…
ground_aircraft_makes_the_aircraft: "“Ground Aircraft” makes the aircraft not airworthy until resolved."
issue: Issue
component_optional: Component (optional)
diff --git a/test/integration/weak_signal_test.rb b/test/integration/weak_signal_test.rb
new file mode 100644
index 0000000..8d2852c
--- /dev/null
+++ b/test/integration/weak_signal_test.rb
@@ -0,0 +1,35 @@
+require "test_helper"
+
+# A signal so weak requests hang counts as none: pages fall back to the
+# offline page within a time limit, and the Log Flight / Report Squawk forms
+# are kept on the device instead of waiting.
+class WeakSignalTest < ActionDispatch::IntegrationTest
+ setup do
+ @owner = create_user("owner@example.com")
+ @a = create_aircraft(owner: @owner)
+ end
+
+ test "the service worker gives up on pages after a time limit and sends every page to the offline page" do
+ get pwa_service_worker_path(format: :js)
+ js = response.body
+ assert_match(/const NETWORK_TIMEOUT = 10 \* 1000/, js)
+ assert_match(/const wait = since < STILL_OFFLINE \? OFFLINE_TIMEOUT : NETWORK_TIMEOUT/, js) # quick while offline
+ assert_match(/\} else if \(wantsHtml\) \{\s*\/\/[^\n]*\n\s*event\.respondWith\(page\(request\)\)/, js)
+ assert_match "if (request.mode !== \"navigate\") throw error\n return offlinePage()", js
+ # downloads built while you wait get no time limit
+ downloads = Regexp.new(js[%r{const DOWNLOADS = /(.+)/$}, 1])
+ %w[/aircraft/1/export /aircraft/1/records /aircraft/1/logbook/print.pdf].each { |path| assert_match downloads, path }
+ %w[/aircraft/1 /aircraft/1/flight_logs/new /aircraft/1/documents/2].each { |path| assert_no_match downloads, path }
+ end
+
+ test "the flight and squawk forms limit the wait and say they're sending" do
+ sign_in @owner
+ get new_aircraft_flight_log_path(@a)
+ assert_select "form[data-controller~=offline-form][data-action*='turbo:before-fetch-request->offline-form#limit']"
+ assert_select "input[type=submit][data-turbo-submits-with='Sending…']", 2
+
+ get new_aircraft_squawk_path(@a)
+ assert_select "form[data-controller~=offline-form][data-action*='turbo:before-fetch-request->offline-form#limit']"
+ assert_select "input[type=submit][data-turbo-submits-with='Sending…']", 1
+ end
+end