diff --git a/db.go b/db.go index e5f837e..9e41802 100644 --- a/db.go +++ b/db.go @@ -96,7 +96,7 @@ type Db struct { fwdHistoryLimit int } -func NewDb(dbPath string, fwdHistoryLimit int) (*Db, error) { +func NewDb(ctx context.Context, dbPath string, fwdHistoryLimit int) (*Db, error) { const busyTimeoutMs = 5000 dsn := dbPath + fmt.Sprintf("?_pragma=busy_timeout=%d", busyTimeoutMs) @@ -119,6 +119,12 @@ func NewDb(dbPath string, fwdHistoryLimit int) (*Db, error) { fwdHistoryLimit: fwdHistoryLimit, } + // Perform a once-off cleanup of the records in the db to update to a potential + // change in limit value. + if err := database.limitHTLCRecords(ctx); err != nil { + return nil, err + } + return database, nil } diff --git a/db_test.go b/db_test.go index 94f0435..ac12e0b 100644 --- a/db_test.go +++ b/db_test.go @@ -14,7 +14,7 @@ func setupTestDb(t *testing.T, fwdingHistoryLimit int) (*Db, func()) { file, err := os.CreateTemp("", "test_db_") require.NoError(t, err) - db, err := NewDb(file.Name(), fwdingHistoryLimit) + db, err := NewDb(context.Background(), file.Name(), fwdingHistoryLimit) require.NoError(t, err) return db, func() { @@ -129,3 +129,28 @@ func TestDbNoForwardingHistory(t *testing.T) { require.NoError(t, err) require.Len(t, fwds, 0) } + +func TestForwadingHistoryDelete(t *testing.T) { + // Create a db that will store HTLCs. + ctx := context.Background() + db, cleanup := setupTestDb(t, 5) + defer cleanup() + + // Write a test HTLC and assert that it's stored. + htlc := testHtlc(1) + require.NoError(t, db.RecordHtlcResolution(ctx, htlc)) + + fwds, err := db.ListForwardingHistory(ctx, time.Time{}, time.Unix(1000000, 0)) + require.NoError(t, err) + require.Len(t, fwds, 1) + + // Modify the db to have a zero limit on forwarding history. We don't recreate + // the test db because it would re-create the file. Run limitHTLCRecords once + // (as we would on NewDb) to assert that we clean up our records. + db.fwdHistoryLimit = 0 + require.NoError(t, db.limitHTLCRecords(ctx)) + + fwds, err = db.ListForwardingHistory(ctx, time.Time{}, time.Unix(1000000, 0)) + require.NoError(t, err) + require.Len(t, fwds, 0) +} diff --git a/run.go b/run.go index 0dccd87..ab700ea 100644 --- a/run.go +++ b/run.go @@ -43,7 +43,7 @@ func run(c *cli.Context) error { log.Infow("Opening database", "path", dbPath) // Open database. - db, err := NewDb(dbPath, c.Int("fwdhistorylimit")) + db, err := NewDb(ctx, dbPath, c.Int("fwdhistorylimit")) if err != nil { return err }