diff --git a/app/android/app/src/main/AndroidManifest.xml b/app/android/app/src/main/AndroidManifest.xml
index 8609352a..2e2bdf08 100644
--- a/app/android/app/src/main/AndroidManifest.xml
+++ b/app/android/app/src/main/AndroidManifest.xml
@@ -12,6 +12,11 @@
+
+
+
@@ -69,6 +74,11 @@
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="Persistent connection to the user's self-hosted Pipelines server for instant notifications"/>
+
+
diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ConnectWakeLock.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ConnectWakeLock.kt
new file mode 100644
index 00000000..7d68e2df
--- /dev/null
+++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ConnectWakeLock.kt
@@ -0,0 +1,27 @@
+package net.awan.pipelines_app.notify
+
+import android.content.Context
+import android.os.PowerManager
+
+/**
+ * A short partial wake lock held while the service opens its socket, so the
+ * CPU stays awake through the handshake. The timeout bounds it if no answer
+ * comes; [release] runs as soon as the socket opens or fails.
+ */
+class ConnectWakeLock(context: Context) {
+ private val lock = context.getSystemService(PowerManager::class.java)
+ .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "pipelines:connect")
+ .apply { setReferenceCounted(false) }
+
+ fun hold() {
+ lock.acquire(HOLD_MILLIS)
+ }
+
+ fun release() {
+ if (lock.isHeld) lock.release()
+ }
+
+ companion object {
+ const val HOLD_MILLIS = 30_000L
+ }
+}
diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ConnectionLog.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ConnectionLog.kt
new file mode 100644
index 00000000..2d9b85d9
--- /dev/null
+++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/ConnectionLog.kt
@@ -0,0 +1,73 @@
+package net.awan.pipelines_app.notify
+
+import org.json.JSONArray
+import org.json.JSONException
+import org.json.JSONObject
+
+/** One entry of the connection log: when, what happened, and the error or HTTP code. */
+data class ConnectionEvent(
+ val timeMillis: Long,
+ val event: String,
+ val error: String?,
+ val code: Int?,
+)
+
+/**
+ * The last [CAPACITY] connection events, kept in the service's preferences so
+ * Settings can show why delivery stalled. Newest first. Error text is trimmed;
+ * the session cookie never reaches the log.
+ */
+class ConnectionLog(
+ private val store: LedgerStore,
+ private val clock: () -> Long = System::currentTimeMillis,
+) {
+ /** Read-modify-write: the main thread (task removal) and the service thread both log. */
+ @Synchronized
+ fun record(event: String, error: String? = null, code: Int? = null) {
+ val entry = ConnectionEvent(clock(), event, error?.take(MAX_ERROR_LENGTH), code)
+ store.putString(KEY, encode((listOf(entry) + entries()).take(CAPACITY)))
+ }
+
+ fun entries(): List = decode(store.getString(KEY))
+
+ companion object {
+ const val CAPACITY = 50
+ const val KEY = "connection.log"
+ private const val MAX_ERROR_LENGTH = 200
+
+ private fun encode(events: List): String {
+ val array = JSONArray()
+ for (event in events) {
+ array.put(
+ JSONObject()
+ .put("t", event.timeMillis)
+ .put("e", event.event)
+ .apply {
+ event.error?.let { put("x", it) }
+ event.code?.let { put("c", it) }
+ },
+ )
+ }
+ return array.toString()
+ }
+
+ /** A corrupt log reads as empty rather than breaking Settings. */
+ private fun decode(raw: String?): List {
+ if (raw.isNullOrEmpty()) return emptyList()
+ return try {
+ val array = JSONArray(raw)
+ (0 until array.length()).map { index ->
+ val item = array.getJSONObject(index)
+ ConnectionEvent(
+ timeMillis = item.getLong("t"),
+ event = item.getString("e"),
+ error = if (item.has("x")) item.getString("x") else null,
+ code = if (item.has("c")) item.getInt("c") else null,
+ )
+ }
+ } catch (_: JSONException) {
+ emptyList()
+ }
+ }
+ }
+}
diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt
index ae3f35e8..35a234a8 100644
--- a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt
+++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationPresenter.kt
@@ -32,21 +32,16 @@ class NotificationPresenter(private val context: Context) {
DeliveryStatus.CONNECTED -> "Pipelines is connected"
DeliveryStatus.WAITING_FOR_NETWORK -> "Pipelines is waiting for a network"
DeliveryStatus.CONNECTING -> "Pipelines is connecting…"
+ DeliveryStatus.SIGN_IN_REQUIRED -> "Pipelines needs you to sign in"
else -> "Pipelines is reconnecting…"
}
- val open = PendingIntent.getActivity(
- context,
- 0,
- Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
- PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
- )
return builder(CONNECTION_CHANNEL)
.setSmallIcon(R.drawable.ic_stat_pipelines)
.setContentTitle(text)
.setContentText("Delivering notifications from your server")
.setOngoing(true)
.setShowWhen(false)
- .setContentIntent(open)
+ .setContentIntent(openApp())
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.build()
}
@@ -55,6 +50,30 @@ class NotificationPresenter(private val context: Context) {
manager.notify(CONNECTION_ID, connectionNotification(status))
}
+ /** Posted when the server refuses the session; cleared once a connection opens. */
+ fun signInRequired() {
+ ensureChannel(ACCOUNT_CHANNEL, "Sign-in", NotificationManager.IMPORTANCE_DEFAULT, null)
+ val notification = builder(ACCOUNT_CHANNEL)
+ .setSmallIcon(R.drawable.ic_stat_pipelines)
+ .setContentTitle("Sign in to Pipelines again to keep notifications")
+ .setContentText("Notifications are paused until you sign in.")
+ .setAutoCancel(true)
+ .setContentIntent(openApp())
+ .build()
+ manager.notify(SIGN_IN_ID, notification)
+ }
+
+ fun clearSignIn() {
+ manager.cancel(SIGN_IN_ID)
+ }
+
+ private fun openApp(): PendingIntent = PendingIntent.getActivity(
+ context,
+ 0,
+ Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
+ )
+
/** A notification without a group is posted on its own; otherwise it joins its thread. */
fun show(notification: ServerNotification) {
if (notification.group.isEmpty()) return showAlone(notification)
@@ -249,6 +268,9 @@ class NotificationPresenter(private val context: Context) {
companion object {
const val CONNECTION_ID = 1
const val CONNECTION_CHANNEL = "pipelines.connection"
+ /** The "sign in again" notice; ids up to RESERVED_IDS are the service's own. */
+ const val SIGN_IN_ID = 2
+ const val ACCOUNT_CHANNEL = "pipelines.account"
/** Holds the server id(s) a tap or dismissal clears, newline-separated. */
const val EXTRA_NOTIFICATION_ID = "net.awan.pipelines.notification_id"
/** Lines of a thread shown in its conversation; the unread count still counts all. */
diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationService.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationService.kt
index 870bb358..a029db52 100644
--- a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationService.kt
+++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationService.kt
@@ -24,6 +24,10 @@ import java.util.concurrent.TimeUnit
* engine runs here. It subscribes with the replay cursor, posts each pushed
* notification, mirrors cross-device clears and sends the user's own clears.
*
+ * Reconnects are alarms (ReconnectAlarms), so they fire during Doze; a
+ * periodic NotificationWatchdog restarts the service if it is down. A refused
+ * session (HTTP 401/403) stops the retry loop until a fresh cookie arrives.
+ *
* All state is confined to [handler]'s thread; OkHttp and connectivity
* callbacks post onto it.
*/
@@ -31,6 +35,8 @@ class NotificationService : Service() {
private lateinit var settings: ServiceSettings
private lateinit var ledger: DeliveryLedger
private lateinit var presenter: NotificationPresenter
+ private lateinit var log: ConnectionLog
+ private lateinit var wakeLock: ConnectWakeLock
private lateinit var thread: HandlerThread
private lateinit var handler: Handler
private val client = OkHttpClient.Builder()
@@ -48,7 +54,8 @@ class NotificationService : Service() {
private var networkAvailable = true
private var currentNetwork: Network? = null
private var networkCallback: ConnectivityManager.NetworkCallback? = null
- private val reconnect = Runnable { connect() }
+ /** A reconnect alarm is pending for the socket that is down. */
+ private var reconnectPending = false
override fun onBind(intent: Intent?): IBinder? = null
@@ -57,6 +64,8 @@ class NotificationService : Service() {
settings = ServiceSettings(this)
ledger = DeliveryLedger(settings)
presenter = NotificationPresenter(this)
+ log = ConnectionLog(settings)
+ wakeLock = ConnectWakeLock(this)
thread = HandlerThread("pipelines-notifications").also { it.start() }
handler = Handler(thread.looper)
goForeground(DeliveryStatus.CONNECTING)
@@ -66,16 +75,36 @@ class NotificationService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val action = intent?.action
+ // Alarms and the watchdog may start the service from the background;
+ // it must be foreground promptly, so do that before queuing the work.
+ goForeground(settings.status.let { if (it == DeliveryStatus.OFF) DeliveryStatus.CONNECTING else it })
handler.post {
when {
!settings.enabled || !settings.configured -> stopEverything()
action == ACTION_FLUSH -> flushClears()
+ action == ACTION_WATCHDOG -> if (isDown()) {
+ log.record("watchdog_restart")
+ restart()
+ }
+ action == ACTION_RECONNECT -> if (socket == null && settings.status != DeliveryStatus.SIGN_IN_REQUIRED) connect()
action == ACTION_RESTART || socket == null -> restart()
}
}
return START_STICKY
}
+ /**
+ * The app was swiped away. The foreground service keeps running, so this
+ * only queues a watchdog check shortly after, in case the process is lost.
+ */
+ override fun onTaskRemoved(rootIntent: Intent?) {
+ log.record("task_removed")
+ if (settings.enabled && settings.configured) {
+ ReconnectAlarms.schedule(this, TASK_REMOVED_CHECK_MILLIS, ACTION_WATCHDOG)
+ }
+ super.onTaskRemoved(rootIntent)
+ }
+
override fun onDestroy() {
running = null
networkCallback?.let {
@@ -87,6 +116,7 @@ class NotificationService : Service() {
socket?.close(1000, "service stopped")
socket = null
}
+ wakeLock.release()
thread.quitSafely()
if (settings.status != DeliveryStatus.UNCONFIGURED) setStatus(DeliveryStatus.OFF, notify = false)
super.onDestroy()
@@ -109,22 +139,33 @@ class NotificationService : Service() {
generation++
socket?.close(1000, "disabled")
socket = null
+ cancelReconnect()
+ wakeLock.release()
+ log.record("stopped")
setStatus(if (settings.configured) DeliveryStatus.OFF else DeliveryStatus.UNCONFIGURED, notify = false)
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
+ /**
+ * Delivery is meant to be running but no socket is open or on its way.
+ * Waiting for the network and a refused session are deliberate states.
+ */
+ private fun isDown(): Boolean =
+ socket == null && !reconnectPending &&
+ settings.status != DeliveryStatus.SIGN_IN_REQUIRED &&
+ settings.status != DeliveryStatus.WAITING_FOR_NETWORK
+
/** Server changed, credentials changed, or the first start: reopen now. */
private fun restart() {
if (ledger.bindServer(settings.serverId)) presenter.cancelAll()
- handler.removeCallbacks(reconnect)
backoff.reset()
endpointIndex = 0
connect()
}
private fun connect() {
- handler.removeCallbacks(reconnect)
+ cancelReconnect()
generation++
socket?.cancel()
socket = null
@@ -139,9 +180,12 @@ class NotificationService : Service() {
}.build()
} catch (error: IllegalArgumentException) {
Log.w(TAG, "invalid endpoint $endpoint", error)
+ log.record("invalid_endpoint", endpoint)
return scheduleReconnect()
}
setStatus(if (backoff.attempt == 0) DeliveryStatus.CONNECTING else DeliveryStatus.RECONNECTING)
+ log.record("connecting", endpoint)
+ wakeLock.hold()
val current = generation
socket = client.newWebSocket(request, Listener(current))
}
@@ -151,15 +195,46 @@ class NotificationService : Service() {
socket?.cancel()
socket = null
subscribeId = null
- if (!networkAvailable) return setStatus(DeliveryStatus.WAITING_FOR_NETWORK)
+ wakeLock.release()
+ if (!networkAvailable) {
+ cancelReconnect()
+ return setStatus(DeliveryStatus.WAITING_FOR_NETWORK)
+ }
setStatus(DeliveryStatus.RECONNECTING)
// Rotate through the server's trusted aliases on each failure.
endpointIndex++
- handler.postDelayed(reconnect, backoff.next())
+ val delay = backoff.next()
+ reconnectPending = true
+ ReconnectAlarms.schedule(this, delay, ACTION_RECONNECT)
+ log.record("retry_scheduled", "in ${delay / 1000}s")
+ }
+
+ private fun cancelReconnect() {
+ reconnectPending = false
+ ReconnectAlarms.cancel(this, ACTION_RECONNECT)
+ }
+
+ /**
+ * The server refused the session cookie. Retrying cannot succeed, so the
+ * loop stops here; a fresh cookie from the app restarts it.
+ */
+ private fun signInRequired(code: Int) {
+ generation++
+ socket?.cancel()
+ socket = null
+ subscribeId = null
+ wakeLock.release()
+ cancelReconnect()
+ log.record("sign_in_required", "HTTP $code", code)
+ setStatus(DeliveryStatus.SIGN_IN_REQUIRED)
+ presenter.signInRequired()
}
private fun onOpen(webSocket: WebSocket) {
backoff.reset()
+ wakeLock.release()
+ presenter.clearSignIn()
+ log.record("connected")
val id = "notify-${++sequence}"
subscribeId = id
webSocket.send(NotificationProtocol.subscribe(id, ledger.cursor))
@@ -179,6 +254,7 @@ class NotificationService : Service() {
is NotificationFrame.Cleared -> presenter.cancel(frame.ids)
is NotificationFrame.Refused -> {
Log.w(TAG, "subscribe_notifications refused: ${frame.error}")
+ log.record("refused", "${frame.error}")
scheduleReconnect()
}
NotificationFrame.Ignored -> Unit
@@ -212,13 +288,16 @@ class NotificationService : Service() {
val previous = currentNetwork
currentNetwork = network
networkAvailable = true
+ log.record("network_available")
// A new default network invalidates the old socket's route;
// a returning network retries at once instead of waiting
- // out the backoff.
+ // out the backoff. A refused session waits for a cookie.
val moved = previous != null && previous != network
val idle = settings.status == DeliveryStatus.WAITING_FOR_NETWORK ||
settings.status == DeliveryStatus.RECONNECTING
- if (settings.configured && (moved || previous == null || idle)) {
+ if (settings.configured && settings.status != DeliveryStatus.SIGN_IN_REQUIRED &&
+ (moved || previous == null || idle)
+ ) {
backoff.reset()
connect()
}
@@ -230,6 +309,7 @@ class NotificationService : Service() {
if (network != currentNetwork) return@post
currentNetwork = null
networkAvailable = false
+ log.record("network_lost")
scheduleReconnect()
}
}
@@ -249,17 +329,27 @@ class NotificationService : Service() {
webSocket.close(1000, null)
}
- override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = current { scheduleReconnect() }
- override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = current {
- Log.i(TAG, "socket failed (${response?.code}): ${t.message}")
+ override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = current {
+ log.record("closed", "close $code ${reason}".trim())
scheduleReconnect()
}
+
+ override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = current {
+ val code = response?.code
+ Log.i(TAG, "socket failed ($code): ${t.message}")
+ log.record("failed", t.message ?: t.javaClass.simpleName, code)
+ if (ReconnectPolicy.isAuthRejection(code) && code != null) signInRequired(code)
+ else scheduleReconnect()
+ }
}
companion object {
private const val TAG = "PipelinesNotify"
const val ACTION_RESTART = "net.awan.pipelines.notify.RESTART"
const val ACTION_FLUSH = "net.awan.pipelines.notify.FLUSH"
+ const val ACTION_RECONNECT = "net.awan.pipelines.notify.RECONNECT"
+ const val ACTION_WATCHDOG = "net.awan.pipelines.notify.WATCHDOG"
+ private const val TASK_REMOVED_CHECK_MILLIS = 2_000L
@Volatile
var running: NotificationService? = null
@@ -277,6 +367,7 @@ class NotificationService : Service() {
return try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(intent)
else context.startService(intent)
+ NotificationWatchdog.schedule(context)
true
} catch (error: Exception) {
// Android 12+ refuses a foreground start from some background
@@ -287,6 +378,9 @@ class NotificationService : Service() {
}
fun stop(context: Context) {
+ ReconnectAlarms.cancel(context, ACTION_RECONNECT)
+ ReconnectAlarms.cancel(context, ACTION_WATCHDOG)
+ NotificationWatchdog.cancel(context)
context.stopService(Intent(context, NotificationService::class.java))
}
}
diff --git a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationServiceChannel.kt b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationServiceChannel.kt
index 17da5587..ee862c0f 100644
--- a/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationServiceChannel.kt
+++ b/app/android/app/src/main/kotlin/net/awan/pipelines_app/notify/NotificationServiceChannel.kt
@@ -52,10 +52,9 @@ class NotificationServiceChannel(private val activity: Activity, messenger: Bina
return
}
val changed = settings.configure(serverId, endpoints, cookie)
- val running = NotificationService.running != null
- if (changed || !running) {
- NotificationService.start(activity, if (changed) NotificationService.ACTION_RESTART else null)
- }
+ // A null action still restarts a service whose socket is down,
+ // which is how a refused session resumes with a fresh cookie.
+ NotificationService.start(activity, if (changed) NotificationService.ACTION_RESTART else null)
result.success(status())
}
"setEnabled" -> {
@@ -69,6 +68,7 @@ class NotificationServiceChannel(private val activity: Activity, messenger: Bina
}
result.success(status())
}
+ "connectionEvents" -> result.success(connectionEvents())
"requestBatteryExemption" -> {
result.success(requestBatteryExemption())
}
@@ -92,6 +92,17 @@ class NotificationServiceChannel(private val activity: Activity, messenger: Bina
)
}
+ /** The last connection events, newest first, for Settings' diagnosis. */
+ private fun connectionEvents(): List