Pass the state-file flush to a subscription in its options
A subscription flushed its state file through a package variable, which the ntfy tests replaced with a no-op in their TestMain. Tests in other packages could not reach it, so the daemon's own tests still flushed for real. Options.Sync now takes the flush; nil means (*os.File).Sync, as before. The ntfy tests pass a no-op through their options and to saveState. Behaviour is unchanged. docs/plans/ntfy.md names the option, and its line references follow the code. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c548833656
commit
62e5ec9c66
9 files changed
+49
-49
No files matched your search
+12
-12
@@ -31,7 +31,7 @@ For stage 1:
|
|||||||
- An unknown ID, one that has expired or is not yet stored on the node asked, replays the topic's whole history. The only exception is an ID that node delivered in the last two minutes (server_tail.go:70-85). The subscriber keeps seen IDs only back to two minutes before its cursor, and checks no message against its floor, so such a replay would print again what printed within `max_backlog`.
|
- An unknown ID, one that has expired or is not yet stored on the node asked, replays the topic's whole history. The only exception is an ID that node delivered in the last two minutes (server_tail.go:70-85). The subscriber keeps seen IDs only back to two minutes before its cursor, and checks no message against its floor, so such a replay would print again what printed within `max_backlog`.
|
||||||
- A time never replays from before the floor.
|
- A time never replays from before the floor.
|
||||||
- Trade-off: in an ntfy cluster, a message that a node cut off from its database stores more than two minutes late is missed. The owner's ntfy is one node.
|
- Trade-off: in an ntfy cluster, a message that a node cut off from its database stores more than two minutes late is missed. The owner's ntfy is one node.
|
||||||
2. **The cursor while a replay is under way.** Today each message dealt with moves the cursor to its own time (subscriber.go:560-580). But messages do not always come in time order. ntfy subscribes a connection before it sends `open` and the replay, so a message published meanwhile can come between two replayed ones. ntfy's tail and slow attachment uploads also deliver older messages late (Findings, NTFY'S STREAMS). If such a message moves the cursor and the connection then drops, or the daemon restarts, the next request starts after it. The rest of the replay is never asked for again, and is lost. On the JSON stream this needs a drop or a restart in mid-replay. On a WebSocket a full print queue is enough: the subscription stops reading, answers no ping, and ntfy closes the connection about a minute later (decision 11). So, on a connection that asked for a replay (`since`), no message moves the cursor until the first `keepalive`, which moves it to its own time, as today. ntfy sends keepalives only after the replay (server.go:1786-1811), so the first one marks its end. A replay cut short is then asked for again from the old cursor, and the seen IDs drop what printed. A connection without `since` replays nothing and moves the cursor as today. Stage 1 makes this fix on its own.
|
2. **The cursor while a replay is under way.** Today each message dealt with moves the cursor to its own time (subscriber.go:568-588). But messages do not always come in time order. ntfy subscribes a connection before it sends `open` and the replay, so a message published meanwhile can come between two replayed ones. ntfy's tail and slow attachment uploads also deliver older messages late (Findings, NTFY'S STREAMS). If such a message moves the cursor and the connection then drops, or the daemon restarts, the next request starts after it. The rest of the replay is never asked for again, and is lost. On the JSON stream this needs a drop or a restart in mid-replay. On a WebSocket a full print queue is enough: the subscription stops reading, answers no ping, and ntfy closes the connection about a minute later (decision 11). So, on a connection that asked for a replay (`since`), no message moves the cursor until the first `keepalive`, which moves it to its own time, as today. ntfy sends keepalives only after the replay (server.go:1786-1811), so the first one marks its end. A replay cut short is then asked for again from the old cursor, and the seen IDs drop what printed. A connection without `since` replays nothing and moves the cursor as today. Stage 1 makes this fix on its own.
|
||||||
- On a WebSocket, which has no keepalives, the cursor then stays put for the whole connection. The next connection replays it again, within `max_backlog` (decision 12), and the seen IDs drop the repeats.
|
- On a WebSocket, which has no keepalives, the cursor then stays put for the whole connection. The next connection replays it again, within `max_backlog` (decision 12), and the seen IDs drop the repeats.
|
||||||
- A cap at the time of `open` is not enough: a replay that reaches back more than two minutes before `open` would still lose its rest. Nor can WebSocket pings stand in for keepalives: ntfy starts pinging before the replay (server.go:1878, 1949), a ping can come between replayed messages, and it carries no time.
|
- A cap at the time of `open` is not enough: a replay that reaches back more than two minutes before `open` would still lose its rest. Nor can WebSocket pings stand in for keepalives: ntfy starts pinging before the replay (server.go:1878, 1949), a ping can come between replayed messages, and it carries no time.
|
||||||
- Trade-off: longer replays after a reconnect, and on a WebSocket larger state writes (decision 12). Nothing more prints.
|
- Trade-off: longer replays after a reconnect, and on a WebSocket larger state writes (decision 12). Nothing more prints.
|
||||||
@@ -53,8 +53,8 @@ For stage 2:
|
|||||||
- Trade-off: the library takes `http` and SOCKS5 proxies but not an `https` one, which the stream takes (Findings, THE WEBSOCKET LIBRARY). Decision 15 counts that as a refusal, so `auto` uses the stream.
|
- Trade-off: the library takes `http` and SOCKS5 proxies but not an `https` one, which the stream takes (Findings, THE WEBSOCKET LIBRARY). Decision 15 counts that as a refusal, so `auto` uses the stream.
|
||||||
9. **Pings, the clock and stalls.** ntfy pings a WebSocket every keepalive interval, 45 s by default, and closes it when no pong comes within that interval plus 15 s (server.go:1856-1904).
|
9. **Pings, the clock and stalls.** ntfy pings a WebSocket every keepalive interval, 45 s by default, and closes it when no pong comes within that interval plus 15 s (server.go:1856-1904).
|
||||||
- The reader answers each ping at once with a pong, with a 1-s write deadline as the library's own handler has, and sends no pings of its own.
|
- The reader answers each ping at once with a pong, with a 1-s write deadline as the library's own handler has, and sends no pings of its own.
|
||||||
- Each ping then gives the loop a `ping` event, sent as every event is, so a stop frees the reader (subscriber.go:970-978). It resets the stall timer as a keepalive does: a connection with no message and no ping for twice `keepalive` plus 15 s is opened again. A ping never moves the cursor.
|
- Each ping then gives the loop a `ping` event, sent as every event is, so a stop frees the reader (subscriber.go:978-986). It resets the stall timer as a keepalive does: a connection with no message and no ping for twice `keepalive` plus 15 s is opened again. A ping never moves the cursor.
|
||||||
- No read deadline is set on the socket; the loop's stall timer closes it, as it closes a stream (subscriber.go:376-379).
|
- No read deadline is set on the socket; the loop's stall timer closes it, as it closes a stream (subscriber.go:384-387).
|
||||||
- A WebSocket learns the server's clock from `open` alone. ntfy's `101` answer has no `Date`, and one a proxy adds is the proxy's clock (design.md:337-339). An `open` without a time ends the connection as a protocol error (decision 15).
|
- A WebSocket learns the server's clock from `open` alone. ntfy's `101` answer has no `Date`, and one a proxy adds is the proxy's clock (design.md:337-339). An `open` without a time ends the connection as a protocol error (decision 15).
|
||||||
- `keepalive` keeps its meaning, the server's keepalive interval, which ntfy also pings at.
|
- `keepalive` keeps its meaning, the server's keepalive interval, which ntfy also pings at.
|
||||||
- Trade-off: a dead connection is found only after twice `keepalive` plus 15 s, 105 s by default, as on the stream.
|
- Trade-off: a dead connection is found only after twice `keepalive` plus 15 s, 105 s by default, as on the stream.
|
||||||
@@ -62,7 +62,7 @@ For stage 2:
|
|||||||
- Trade-off: a hostile server can still keep the subscriber reading, as on the stream.
|
- Trade-off: a hostile server can still keep the subscriber reading, as on the stream.
|
||||||
11. **A full print queue on a WebSocket.** While the handler cannot take a message, the loop stops reading (design.md:312-317), so the reader answers no ping. Nothing special is done. ntfy closes the connection about a minute later. The reader's last events wait until the queue has room; then the subscription reconnects after the usual backoff, and decision 2 keeps the cursor behind what it has not dealt with. The JSON stream stays open through such a pause, held by TCP backpressure, since ntfy's HTTP server has no write timeout (server.go:509).
|
11. **A full print queue on a WebSocket.** While the handler cannot take a message, the loop stops reading (design.md:312-317), so the reader answers no ping. Nothing special is done. ntfy closes the connection about a minute later. The reader's last events wait until the queue has room; then the subscription reconnects after the usual backoff, and decision 2 keeps the cursor behind what it has not dealt with. The JSON stream stays open through such a pause, held by TCP backpressure, since ntfy's HTTP server has no write timeout (server.go:509).
|
||||||
- Trade-off: one reconnect, with its replay, after each pause longer than about a minute. docs/ntfy.md says so.
|
- Trade-off: one reconnect, with its replay, after each pause longer than about a minute. docs/ntfy.md says so.
|
||||||
12. **`max_backlog` while connected.** With decision 2, a WebSocket's cursor stays put, and the seen IDs are kept from two minutes before the cursor (state.go:184-197). On a long connection they would grow to the 20,000 cap. So, at each save, while the connection knows the server's clock, the floor rises to the server's time now less `max_backlog`, computed as `checkBacklog` computes it (subscriber.go:596-608). The raised floor bounds the next replay and the seen IDs, and nothing else: a message on the current connection is not checked against it, so one held in a JSON stream through a long printer outage still prints, as today. It applies to both transports; on the stream, whose keepalives move the cursor, it rarely changes anything.
|
12. **`max_backlog` while connected.** With decision 2, a WebSocket's cursor stays put, and the seen IDs are kept from two minutes before the cursor (state.go:179-192). On a long connection they would grow to the 20,000 cap. So, at each save, while the connection knows the server's clock, the floor rises to the server's time now less `max_backlog`, computed as `checkBacklog` computes it (subscriber.go:596-608). The raised floor bounds the next replay and the seen IDs, and nothing else: a message on the current connection is not checked against it, so one held in a JSON stream through a long printer outage still prints, as today. It applies to both transports; on the stream, whose keepalives move the cursor, it rarely changes anything.
|
||||||
- Trade-off: on a WebSocket every save writes the IDs within `max_backlog`, about 60 an hour at a message a minute. A busy topic with a 12-hour `max_backlog` can reach the 20,000 cap, some 700 KB written and synced within a second of each message. The stream writes about two minutes' worth.
|
- Trade-off: on a WebSocket every save writes the IDs within `max_backlog`, about 60 an hour at a message a minute. A busy topic with a 12-hour `max_backlog` can reach the 20,000 cap, some 700 KB written and synced within a second of each message. The stream writes about two minutes' worth.
|
||||||
13. **The config key and the Go field.** `transport` per subscription, `"websocket"` or `"json"`, written exactly so. Its default is `"json"` in stage 2, so a build between stages 2 and 3 behaves as today unless a subscription asks; stage 3 adds `"auto"` and makes it the default (decisions 14 and 15). In Go, `ntfy.Options.Transport` takes this meaning, and today's field of that name, the stream's `http.RoundTripper`, becomes `RoundTripper` in stage 2's first commit.
|
13. **The config key and the Go field.** `transport` per subscription, `"websocket"` or `"json"`, written exactly so. Its default is `"json"` in stage 2, so a build between stages 2 and 3 behaves as today unless a subscription asks; stage 3 adds `"auto"` and makes it the default (decisions 14 and 15). In Go, `ntfy.Options.Transport` takes this meaning, and today's field of that name, the stream's `http.RoundTripper`, becomes `RoundTripper` in stage 2's first commit.
|
||||||
- Trade-off: the default changes again in stage 3, so a build between the two stages differs from the release.
|
- Trade-off: the default changes again in stage 3, so a build between the two stages differs from the release.
|
||||||
@@ -147,12 +147,12 @@ THE WEBSOCKET LIBRARY
|
|||||||
- Latest versions on proxy.golang.org on 2026-12-01: fasthttp/websocket v1.5.12 (2025-01-01), coder/websocket v1.8.15 (2026-06-15), gorilla/websocket v1.5.3 (2024-06-14), gofiber/contrib/v3/websocket v1.3.1 (2026-11-25).
|
- Latest versions on proxy.golang.org on 2026-12-01: fasthttp/websocket v1.5.12 (2025-01-01), coder/websocket v1.8.15 (2026-06-15), gorilla/websocket v1.5.3 (2024-06-14), gofiber/contrib/v3/websocket v1.3.1 (2026-11-25).
|
||||||
|
|
||||||
THE SUBSCRIBER TODAY
|
THE SUBSCRIBER TODAY
|
||||||
- One goroutine reads each connection and hands the loop events (subscriber.go:862-885, 924-968, 970-978). The loop owns all state and stops reading while a message waits (334-356).
|
- One goroutine reads each connection and hands the loop events (subscriber.go:870-893, 932-976, 978-986). The loop owns all state and stops reading while a message waits (342-364).
|
||||||
- The clock: `open`'s time first, then the answer's `Date`, measured on the monotonic clock, afresh for each connection (453-470, 585-608, 916-920). A keepalive moves the cursor and never sets the clock (471-473).
|
- The clock: `open`'s time first, then the answer's `Date`, measured on the monotonic clock, afresh for each connection (461-478, 593-616, 924-928). A keepalive moves the cursor and never sets the clock (479-481).
|
||||||
- `since` is the cursor less two minutes, never before the floor and never clamped by the host's clock (611-613, 655-666). `max_backlog` is applied by the server's clock as messages arrive (476-479, 596-608).
|
- `since` is the cursor less two minutes, never before the floor and never clamped by the host's clock (619-621, 663-674). `max_backlog` is applied by the server's clock as messages arrive (484-487, 604-616).
|
||||||
- The seen IDs: those a replay could send, at least the last 512, at most 20,000; the floor rises past the ones the cap forgets (state.go:14-20, 159-197; subscriber.go:557-568).
|
- The seen IDs: those a replay could send, at least the last 512, at most 20,000; the floor rises past the ones the cap forgets (state.go:14-20, 154-192; subscriber.go:565-576).
|
||||||
- Redirects are never followed (220-226, 773-775). Errors leave out the URL (835-844).
|
- Redirects are never followed (228-234, 781-783). Errors leave out the URL (843-852).
|
||||||
- Saves: within `saveEvery` (1 s) for a change a restart must see, within `cursorSaveEvery` (10 min) for a cursor that alone moved, and at once for the first move from 0 (50-57, 385-394, 573-580). Tests skip the sync through `syncFile` (state.go:78-82).
|
- Saves: within `saveEvery` (1 s) for a change a restart must see, within `cursorSaveEvery` (10 min) for a cursor that alone moved, and at once for the first move from 0 (51-58, 393-402, 581-588). Tests skip the sync through `Options.Sync` (137-139).
|
||||||
- Tests: the synctest fake answers through `RoundTrip` (fake_test.go:21-139); replays (replay_test.go), redirects over real sockets (redirect_test.go), goroutines over real sockets (leak_test.go) and a 24-hour soak (soak_test.go).
|
- Tests: the synctest fake answers through `RoundTrip` (fake_test.go:21-139); replays (replay_test.go), redirects over real sockets (redirect_test.go), goroutines over real sockets (leak_test.go) and a 24-hour soak (soak_test.go).
|
||||||
|
|
||||||
WHERE THIS IS UNSURE
|
WHERE THIS IS UNSURE
|
||||||
@@ -189,7 +189,7 @@ INVARIANTS
|
|||||||
4. The cursor moves past a message only once it is queued, held or deliberately left out. On a connection that asked for a replay, no message moves it before the first keepalive. A ping never moves it.
|
4. The cursor moves past a message only once it is queued, held or deliberately left out. On a connection that asked for a replay, no message moves it before the first keepalive. A ping never moves it.
|
||||||
5. The seen IDs hold at least the last 512 and at most 20,000, and the floor rises past the ones the cap forgets.
|
5. The seen IDs hold at least the last 512 and at most 20,000, and the floor rises past the ones the cap forgets.
|
||||||
6. Redirects are never followed, on either transport.
|
6. Redirects are never followed, on either transport.
|
||||||
7. A change a restart must see is saved within a second; a cursor that alone moved, within ten minutes; the first move from 0, at once. Tests skip the sync through `syncFile`.
|
7. A change a restart must see is saved within a second; a cursor that alone moved, within ten minutes; the first move from 0, at once. Tests skip the sync through `Options.Sync`.
|
||||||
8. Credentials go only in the `Authorization` header. No URL, topic, token or message text reaches a log, `last_error` or Sentry.
|
8. Credentials go only in the `Authorization` header. No URL, topic, token or message text reaches a log, `last_error` or Sentry.
|
||||||
9. ntfy never imports modules.
|
9. ntfy never imports modules.
|
||||||
|
|
||||||
@@ -201,7 +201,7 @@ OTHER PLANS
|
|||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
TRANSPORTS (stages 1-3)
|
TRANSPORTS (stages 1-3)
|
||||||
- Today's reader, `conn.read` (subscriber.go:924-968), becomes one of two readers, chosen per connection: the stream's, unchanged, and the WebSocket's. Both send the loop the same events: `opened` with the answer's `Date`, `msg`, `skipped`, and `end` with the status, `Retry-After` and ntfy's code. The WebSocket's adds `ping`, and its `end` says whether the WebSocket was refused, for `auto`.
|
- Today's reader, `conn.read` (subscriber.go:932-976), becomes one of two readers, chosen per connection: the stream's, unchanged, and the WebSocket's. Both send the loop the same events: `opened` with the answer's `Date`, `msg`, `skipped`, and `end` with the status, `Retry-After` and ntfy's code. The WebSocket's adds `ping`, and its `end` says whether the WebSocket was refused, for `auto`.
|
||||||
- One function builds the query, `since` and `priority`, for both. The WebSocket URL swaps the scheme (`https` to `wss`, `http` to `ws`) and the last path part (`/json` to `/ws`).
|
- One function builds the query, `since` and `priority`, for both. The WebSocket URL swaps the scheme (`https` to `wss`, `http` to `ws`) and the last path part (`/json` to `/ws`).
|
||||||
- `Options.Transport` names the transport (decision 13), and `Options.DialContext` (name assumed) the WebSocket's dial function, which tests replace.
|
- `Options.Transport` names the transport (decision 13), and `Options.DialContext` (name assumed) the WebSocket's dial function, which tests replace.
|
||||||
|
|
||||||
|
|||||||
@@ -421,6 +421,7 @@ func testOptions(f *fakeServer, dir string) Options {
|
|||||||
BypassPriority: 5,
|
BypassPriority: 5,
|
||||||
Keepalive: 45 * time.Second,
|
Keepalive: 45 * time.Second,
|
||||||
StateFile: filepath.Join(dir, "ntfy-home.json"),
|
StateFile: filepath.Join(dir, "ntfy-home.json"),
|
||||||
|
Sync: skipSync,
|
||||||
Transport: f,
|
Transport: f,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ func TestNoGoroutineLeakOverRealConnections(t *testing.T) {
|
|||||||
o := Options{
|
o := Options{
|
||||||
Name: "home", Server: srv.URL, Topics: []string{"alerts"}, MinPriority: 1,
|
Name: "home", Server: srv.URL, Topics: []string{"alerts"}, MinPriority: 1,
|
||||||
MaxBacklog: time.Hour, RateLimit: 1000, RateWindow: time.Minute, BypassPriority: 5,
|
MaxBacklog: time.Hour, RateLimit: 1000, RateWindow: time.Minute, BypassPriority: 5,
|
||||||
Keepalive: 45 * time.Second, StateFile: t.TempDir() + "/ntfy-home.json",
|
Keepalive: 45 * time.Second, StateFile: t.TempDir() + "/ntfy-home.json", Sync: skipSync,
|
||||||
}
|
}
|
||||||
s, err := New(o)
|
s, err := New(o)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ func TestRedirectsAreNotFollowed(t *testing.T) {
|
|||||||
o := Options{
|
o := Options{
|
||||||
Name: "home", Server: srv.URL, Topics: []string{"alerts"}, Token: "tk_secret",
|
Name: "home", Server: srv.URL, Topics: []string{"alerts"}, Token: "tk_secret",
|
||||||
MinPriority: 1, MaxBacklog: time.Hour, RateLimit: 5, RateWindow: time.Minute, BypassPriority: 5,
|
MinPriority: 1, MaxBacklog: time.Hour, RateLimit: 5, RateWindow: time.Minute, BypassPriority: 5,
|
||||||
Keepalive: 45 * time.Second, StateFile: t.TempDir() + "/ntfy-home.json",
|
Keepalive: 45 * time.Second, StateFile: t.TempDir() + "/ntfy-home.json", Sync: skipSync,
|
||||||
Transport: srv.Client().Transport,
|
Transport: srv.Client().Transport,
|
||||||
}
|
}
|
||||||
s, err := New(o)
|
s, err := New(o)
|
||||||
|
|||||||
@@ -127,7 +127,7 @@ func TestBacklogUsesTheServerClock(t *testing.T) {
|
|||||||
serverNow := func() int64 { return time.Now().Add(f.skew).Unix() }
|
serverNow := func() int64 { return time.Now().Add(f.skew).Unix() }
|
||||||
|
|
||||||
// The subscription last ran ten hours ago by the server's clock.
|
// The subscription last ran ten hours ago by the server's clock.
|
||||||
if err := saveState(o.StateFile, state{Cursor: serverNow() - 10*3600}); err != nil {
|
if err := saveState(o.StateFile, state{Cursor: serverNow() - 10*3600}, skipSync); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
old := f.publish(Message{Title: "five hours ago", Time: serverNow() - 5*3600})
|
old := f.publish(Message{Title: "five hours ago", Time: serverNow() - 5*3600})
|
||||||
@@ -164,7 +164,7 @@ func TestBacklogFollowsTheStreamClock(t *testing.T) {
|
|||||||
f.skew, f.authFails, f.noDate = tt.skew, true, tt.noDate
|
f.skew, f.authFails, f.noDate = tt.skew, true, tt.noDate
|
||||||
o := testOptions(f, t.TempDir())
|
o := testOptions(f, t.TempDir())
|
||||||
serverNow := func() int64 { return time.Now().Add(f.skew).Unix() }
|
serverNow := func() int64 { return time.Now().Add(f.skew).Unix() }
|
||||||
if err := saveState(o.StateFile, state{Cursor: serverNow() - 2*3600}); err != nil {
|
if err := saveState(o.StateFile, state{Cursor: serverNow() - 2*3600}, skipSync); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
old := f.publish(Message{Title: "ninety minutes ago", Time: serverNow() - 5400})
|
old := f.publish(Message{Title: "ninety minutes ago", Time: serverNow() - 5400})
|
||||||
@@ -235,7 +235,7 @@ func TestBacklogIgnoresAnEarlierClock(t *testing.T) {
|
|||||||
f := newFakeServer()
|
f := newFakeServer()
|
||||||
f.authSkew = tt.authSkew
|
f.authSkew = tt.authSkew
|
||||||
o := testOptions(f, t.TempDir())
|
o := testOptions(f, t.TempDir())
|
||||||
if err := saveState(o.StateFile, state{Cursor: time.Now().Unix() - 2*3600}); err != nil {
|
if err := saveState(o.StateFile, state{Cursor: time.Now().Unix() - 2*3600}, skipSync); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
old := f.publish(Message{Title: "ninety minutes ago", Time: time.Now().Unix() - 5400})
|
old := f.publish(Message{Title: "ninety minutes ago", Time: time.Now().Unix() - 5400})
|
||||||
@@ -286,7 +286,7 @@ func TestBacklogPrefersTheOpenEvent(t *testing.T) {
|
|||||||
f := newFakeServer()
|
f := newFakeServer()
|
||||||
f.dateSkew = tt.dateSkew
|
f.dateSkew = tt.dateSkew
|
||||||
o := testOptions(f, t.TempDir())
|
o := testOptions(f, t.TempDir())
|
||||||
if err := saveState(o.StateFile, state{Cursor: time.Now().Unix() - 2*3600}); err != nil {
|
if err := saveState(o.StateFile, state{Cursor: time.Now().Unix() - 2*3600}, skipSync); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
old := f.publish(Message{Title: "ninety minutes ago", Time: time.Now().Unix() - 5400})
|
old := f.publish(Message{Title: "ninety minutes ago", Time: time.Now().Unix() - 5400})
|
||||||
@@ -327,7 +327,7 @@ func TestBacklogFromTheDate(t *testing.T) {
|
|||||||
f.skew, f.openNoTime = 10*time.Hour, true
|
f.skew, f.openNoTime = 10*time.Hour, true
|
||||||
o := testOptions(f, t.TempDir())
|
o := testOptions(f, t.TempDir())
|
||||||
serverNow := func() int64 { return time.Now().Add(f.skew).Unix() }
|
serverNow := func() int64 { return time.Now().Add(f.skew).Unix() }
|
||||||
if err := saveState(o.StateFile, state{Cursor: serverNow() - 10*3600}); err != nil {
|
if err := saveState(o.StateFile, state{Cursor: serverNow() - 10*3600}, skipSync); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
old := f.publish(Message{Title: "five hours ago", Time: serverNow() - 5*3600})
|
old := f.publish(Message{Title: "five hours ago", Time: serverNow() - 5*3600})
|
||||||
|
|||||||
+10
-15
@@ -75,16 +75,11 @@ func loadState(path string) (state, error) {
|
|||||||
return st, nil
|
return st, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// syncFile flushes a file, or a directory, to disk. It is a variable so
|
|
||||||
// that tests, which write state files hundreds of times, can skip the
|
|
||||||
// flush; on a disk that is slow to sync, each one costs tens of
|
|
||||||
// milliseconds.
|
|
||||||
var syncFile = (*os.File).Sync
|
|
||||||
|
|
||||||
// saveState writes st to path atomically: to a temporary file in the same
|
// saveState writes st to path atomically: to a temporary file in the same
|
||||||
// directory, synced to disk, then renamed over path. A crash leaves the
|
// directory, flushed to disk with sync, then renamed over path, and the
|
||||||
// old file or the new one, never part of either.
|
// directory flushed after the rename. A crash leaves the old file or the
|
||||||
func saveState(path string, st state) error {
|
// new one, never part of either.
|
||||||
|
func saveState(path string, st state, sync func(*os.File) error) error {
|
||||||
st.Version = stateVersion
|
st.Version = stateVersion
|
||||||
data, err := json.Marshal(st)
|
data, err := json.Marshal(st)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -100,7 +95,7 @@ func saveState(path string, st state) error {
|
|||||||
tmp := f.Name()
|
tmp := f.Name()
|
||||||
_, err = f.Write(data)
|
_, err = f.Write(data)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
err = syncFile(f)
|
err = sync(f)
|
||||||
}
|
}
|
||||||
if closeErr := f.Close(); err == nil {
|
if closeErr := f.Close(); err == nil {
|
||||||
err = closeErr
|
err = closeErr
|
||||||
@@ -112,13 +107,13 @@ func saveState(path string, st state) error {
|
|||||||
_ = os.Remove(tmp)
|
_ = os.Remove(tmp)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
syncDir(dir)
|
syncDir(dir, sync)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// syncDir makes a rename in dir durable. Windows cannot open a directory
|
// syncDir makes a rename in dir durable by flushing dir with sync. Windows
|
||||||
// to sync it, and its renames need no such step.
|
// cannot open a directory to sync it, and its renames need no such step.
|
||||||
func syncDir(dir string) {
|
func syncDir(dir string, sync func(*os.File) error) {
|
||||||
if runtime.GOOS == "windows" {
|
if runtime.GOOS == "windows" {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -126,7 +121,7 @@ func syncDir(dir string) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
_ = syncFile(d)
|
_ = sync(d)
|
||||||
_ = d.Close()
|
_ = d.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,13 +9,10 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestMain skips flushing state files to disk. The tests write them
|
// skipSync stands in for the flush to disk in the tests. They write state
|
||||||
// hundreds of times, and on a disk that is slow to sync each flush costs
|
// files hundreds of times, and on a disk that is slow to sync each flush
|
||||||
// tens of milliseconds. TestSaveStateSyncs checks the flush itself.
|
// costs tens of milliseconds. TestSaveStateSyncs checks the flush itself.
|
||||||
func TestMain(m *testing.M) {
|
func skipSync(*os.File) error { return nil }
|
||||||
syncFile = func(*os.File) error { return nil }
|
|
||||||
m.Run()
|
|
||||||
}
|
|
||||||
|
|
||||||
// saveState flushes the new file before renaming it over the old one, and,
|
// saveState flushes the new file before renaming it over the old one, and,
|
||||||
// where the system allows, the directory after the rename. A failed flush
|
// where the system allows, the directory after the rename. A failed flush
|
||||||
@@ -24,10 +21,9 @@ func TestSaveStateSyncs(t *testing.T) {
|
|||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
path := filepath.Join(dir, "ntfy-home.json")
|
path := filepath.Join(dir, "ntfy-home.json")
|
||||||
|
|
||||||
defer func(f func(*os.File) error) { syncFile = f }(syncFile)
|
|
||||||
var synced []string
|
var synced []string
|
||||||
renamed := false
|
renamed := false
|
||||||
syncFile = func(f *os.File) error {
|
sync := func(f *os.File) error {
|
||||||
name := filepath.Base(f.Name())
|
name := filepath.Base(f.Name())
|
||||||
if name == filepath.Base(dir) {
|
if name == filepath.Base(dir) {
|
||||||
st, err := loadState(path)
|
st, err := loadState(path)
|
||||||
@@ -37,7 +33,7 @@ func TestSaveStateSyncs(t *testing.T) {
|
|||||||
return f.Sync()
|
return f.Sync()
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := saveState(path, state{Cursor: 42}); err != nil {
|
if err := saveState(path, state{Cursor: 42}, sync); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if st, err := loadState(path); err != nil || st.Cursor != 42 {
|
if st, err := loadState(path); err != nil || st.Cursor != 42 {
|
||||||
@@ -58,8 +54,8 @@ func TestSaveStateSyncs(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
syncFile = func(*os.File) error { return errors.New("disk full") }
|
diskFull := func(*os.File) error { return errors.New("disk full") }
|
||||||
if err := saveState(path, state{Cursor: 43}); err == nil {
|
if err := saveState(path, state{Cursor: 43}, diskFull); err == nil {
|
||||||
t.Fatal("saveState succeeded although the flush failed")
|
t.Fatal("saveState succeeded although the flush failed")
|
||||||
}
|
}
|
||||||
if st, err := loadState(path); err != nil || st.Cursor != 42 {
|
if st, err := loadState(path); err != nil || st.Cursor != 42 {
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -133,6 +134,10 @@ type Options struct {
|
|||||||
// StateFile is where the subscription keeps its state.
|
// StateFile is where the subscription keeps its state.
|
||||||
StateFile string
|
StateFile string
|
||||||
|
|
||||||
|
// Sync flushes a written state file to disk, and then its directory
|
||||||
|
// where the system allows. Nil means (*os.File).Sync.
|
||||||
|
Sync func(*os.File) error
|
||||||
|
|
||||||
// Transport sends the requests. Nil means a transport with dial, TLS
|
// Transport sends the requests. Nil means a transport with dial, TLS
|
||||||
// handshake and response header timeouts and no overall timeout,
|
// handshake and response header timeouts and no overall timeout,
|
||||||
// since the response is a stream.
|
// since the response is a stream.
|
||||||
@@ -197,6 +202,9 @@ func New(o Options) (*Subscriber, error) {
|
|||||||
if o.Report == nil {
|
if o.Report == nil {
|
||||||
o.Report = func(error) {}
|
o.Report = func(error) {}
|
||||||
}
|
}
|
||||||
|
if o.Sync == nil {
|
||||||
|
o.Sync = (*os.File).Sync
|
||||||
|
}
|
||||||
base := strings.TrimRight(u.String(), "/") + "/" + strings.Join(o.Topics, ",")
|
base := strings.TrimRight(u.String(), "/") + "/" + strings.Join(o.Topics, ",")
|
||||||
s := &Subscriber{
|
s := &Subscriber{
|
||||||
o: o,
|
o: o,
|
||||||
@@ -816,7 +824,7 @@ func (r *run) save(now time.Time) {
|
|||||||
st.Held = &h
|
st.Held = &h
|
||||||
}
|
}
|
||||||
r.savedAt = now
|
r.savedAt = now
|
||||||
if err := saveState(r.o.StateFile, st); err != nil {
|
if err := saveState(r.o.StateFile, st, r.o.Sync); err != nil {
|
||||||
if !r.saveFailed {
|
if !r.saveFailed {
|
||||||
r.log.Error("ntfy state not saved", "err", err)
|
r.log.Error("ntfy state not saved", "err", err)
|
||||||
r.o.Report(fmt.Errorf("saving state: %w", err))
|
r.o.Report(fmt.Errorf("saving state: %w", err))
|
||||||
|
|||||||
@@ -179,7 +179,7 @@ func TestStaleCursorReplaysUnclamped(t *testing.T) {
|
|||||||
f := newFakeServer()
|
f := newFakeServer()
|
||||||
o := testOptions(f, dir)
|
o := testOptions(f, dir)
|
||||||
old := f.publish(Message{Title: "three hours ago"})
|
old := f.publish(Message{Title: "three hours ago"})
|
||||||
if err := saveState(o.StateFile, state{Cursor: old.Time}); err != nil {
|
if err := saveState(o.StateFile, state{Cursor: old.Time}, skipSync); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
time.Sleep(3 * time.Hour)
|
time.Sleep(3 * time.Hour)
|
||||||
@@ -213,7 +213,7 @@ func TestBacklogFloorIsSaved(t *testing.T) {
|
|||||||
f := newFakeServer()
|
f := newFakeServer()
|
||||||
o := testOptions(f, t.TempDir())
|
o := testOptions(f, t.TempDir())
|
||||||
o.MaxBacklog = 2 * time.Minute
|
o.MaxBacklog = 2 * time.Minute
|
||||||
if err := saveState(o.StateFile, state{Cursor: time.Now().Unix()}); err != nil {
|
if err := saveState(o.StateFile, state{Cursor: time.Now().Unix()}, skipSync); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
time.Sleep(time.Second)
|
time.Sleep(time.Second)
|
||||||
|
|||||||
Reference in new issue
Block a user