Skip to content

Commit 5e08d52

Browse files
committed
session: add migration code from kvdb to SQL
This commit introduces the migration logic for transitioning the sessions store from kvdb to SQL. Note that as of this commit, the migration is not yet triggered by any production code, i.e. only tests execute the migration logic.
1 parent 6b7d00d commit 5e08d52

File tree

2 files changed

+716
-0
lines changed

2 files changed

+716
-0
lines changed

session/sql_migration.go

Lines changed: 348 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,348 @@
1+
package session
2+
3+
import (
4+
"context"
5+
"database/sql"
6+
"errors"
7+
"fmt"
8+
"reflect"
9+
"time"
10+
11+
"github.com/davecgh/go-spew/spew"
12+
"github.com/lightninglabs/lightning-terminal/accounts"
13+
"github.com/lightninglabs/lightning-terminal/db/sqlc"
14+
"github.com/pmezard/go-difflib/difflib"
15+
)
16+
17+
var (
18+
// ErrMigrationMismatch is returned when the migrated session does not
19+
// match the original session.
20+
ErrMigrationMismatch = fmt.Errorf("migrated session does not match " +
21+
"original session")
22+
)
23+
24+
// MigrateSessionStoreToSQL runs the migration of all sessions from the KV
25+
// database to the SQL database. The migration is done in a single transaction
26+
// to ensure that all sessions are migrated or none at all.
27+
//
28+
// NOTE: As sessions may contain linked accounts, the accounts sql migration
29+
// MUST be run prior to this migration.
30+
func MigrateSessionStoreToSQL(ctx context.Context, kvStore *BoltStore,
31+
tx SQLQueries) error {
32+
33+
log.Infof("Starting migration of the KV sessions store to SQL")
34+
35+
kvSessions, err := kvStore.ListAllSessions(ctx)
36+
if err != nil {
37+
return err
38+
}
39+
40+
// If sessions are linked to a group, we must insert the initial session
41+
// of each group before the other sessions in that group. This ensures
42+
// we can retrieve the SQL group ID when inserting the remaining
43+
// sessions. Therefore, we first insert all initial group sessions,
44+
// allowing us to fetch the group IDs and insert the rest of the
45+
// sessions afterward.
46+
// We therefore filter out the initial sessions first, and then migrate
47+
// them prior to the rest of the sessions.
48+
var (
49+
initialGroupSessions []*Session
50+
linkedSessions []*Session
51+
)
52+
53+
for _, kvSession := range kvSessions {
54+
if kvSession.GroupID == kvSession.ID {
55+
initialGroupSessions = append(
56+
initialGroupSessions, kvSession,
57+
)
58+
} else {
59+
linkedSessions = append(linkedSessions, kvSession)
60+
}
61+
}
62+
63+
err = migrateSessionsToSQLAndValidate(ctx, tx, initialGroupSessions)
64+
if err != nil {
65+
return fmt.Errorf("migration of non-linked session failed: %w",
66+
err)
67+
}
68+
69+
err = migrateSessionsToSQLAndValidate(ctx, tx, linkedSessions)
70+
if err != nil {
71+
return fmt.Errorf("migration of linked session failed: %w", err)
72+
}
73+
74+
total := len(initialGroupSessions) + len(linkedSessions)
75+
log.Infof("All sessions migrated from KV to SQL. Total number of "+
76+
"sessions migrated: %d", total)
77+
78+
return nil
79+
}
80+
81+
// migrateSessionsToSQLAndValidate runs the migration for the passed sessions
82+
// from the KV database to the SQL database, and validates that the migrated
83+
// sessions match the original sessions.
84+
func migrateSessionsToSQLAndValidate(ctx context.Context,
85+
tx SQLQueries, kvSessions []*Session) error {
86+
87+
for _, kvSession := range kvSessions {
88+
err := migrateSingleSessionToSQL(ctx, tx, kvSession)
89+
if err != nil {
90+
return fmt.Errorf("unable to migrate session(%v): %w",
91+
kvSession.ID, err)
92+
}
93+
94+
// Validate that the session was correctly migrated and matches
95+
// the original session in the kv store.
96+
sqlSess, err := tx.GetSessionByAlias(ctx, kvSession.ID[:])
97+
if err != nil {
98+
if errors.Is(err, sql.ErrNoRows) {
99+
err = ErrSessionNotFound
100+
}
101+
return fmt.Errorf("unable to get migrated session "+
102+
"from sql store: %w", err)
103+
}
104+
105+
migratedSession, err := unmarshalSession(ctx, tx, sqlSess)
106+
if err != nil {
107+
return fmt.Errorf("unable to unmarshal migrated "+
108+
"session: %w", err)
109+
}
110+
111+
overrideSessionTimeZone(kvSession)
112+
overrideSessionTimeZone(migratedSession)
113+
114+
if !reflect.DeepEqual(kvSession, migratedSession) {
115+
diff := difflib.UnifiedDiff{
116+
A: difflib.SplitLines(
117+
spew.Sdump(kvSession),
118+
),
119+
B: difflib.SplitLines(
120+
spew.Sdump(migratedSession),
121+
),
122+
FromFile: "Expected",
123+
FromDate: "",
124+
ToFile: "Actual",
125+
ToDate: "",
126+
Context: 3,
127+
}
128+
diffText, _ := difflib.GetUnifiedDiffString(diff)
129+
130+
return fmt.Errorf("%w: %v.\n%v", ErrMigrationMismatch,
131+
kvSession.ID, diffText)
132+
}
133+
}
134+
135+
return nil
136+
}
137+
138+
// migrateSingleSessionToSQL runs the migration for a single session from the
139+
// KV database to the SQL database. Note that if the session links to an
140+
// account, the linked accounts store MUST have been migrated before that
141+
// session is migrated.
142+
func migrateSingleSessionToSQL(ctx context.Context,
143+
tx SQLQueries, session *Session) error {
144+
145+
var (
146+
acctID sql.NullInt64
147+
err error
148+
remotePubKey []byte
149+
)
150+
151+
session.AccountID.WhenSome(func(alias accounts.AccountID) {
152+
// Check that the account exists in the SQL store, before
153+
// linking it.
154+
var acctAlias int64
155+
acctAlias, err = alias.ToInt64()
156+
if err != nil {
157+
return
158+
}
159+
160+
var acctDBID int64
161+
acctDBID, err = tx.GetAccountIDByAlias(ctx, acctAlias)
162+
if errors.Is(err, sql.ErrNoRows) {
163+
err = accounts.ErrAccNotFound
164+
return
165+
} else if err != nil {
166+
return
167+
}
168+
169+
acctID = sql.NullInt64{
170+
Int64: acctDBID,
171+
Valid: true,
172+
}
173+
})
174+
if err != nil {
175+
return err
176+
}
177+
178+
// The remote public key is currently only set for autopilot sessions,
179+
// else it's a nil byte array.
180+
if session.RemotePublicKey != nil {
181+
remotePubKey = session.RemotePublicKey.SerializeCompressed()
182+
}
183+
184+
// Proceed to insert the session into the sql db.
185+
insertSessionParams := sqlc.InsertSessionParams{
186+
Alias: session.ID[:],
187+
Label: session.Label,
188+
State: int16(session.State),
189+
Type: int16(session.Type),
190+
Expiry: session.Expiry.UTC(),
191+
CreatedAt: session.CreatedAt.UTC(),
192+
ServerAddress: session.ServerAddr,
193+
DevServer: session.DevServer,
194+
MacaroonRootKey: int64(session.MacaroonRootKey),
195+
PairingSecret: session.PairingSecret[:],
196+
LocalPrivateKey: session.LocalPrivateKey.Serialize(),
197+
LocalPublicKey: session.LocalPublicKey.SerializeCompressed(),
198+
RemotePublicKey: remotePubKey,
199+
Privacy: session.WithPrivacyMapper,
200+
AccountID: acctID,
201+
}
202+
203+
sqlId, err := tx.InsertSession(ctx, insertSessionParams)
204+
if err != nil {
205+
return err
206+
}
207+
208+
// Since the InsertSession query doesn't support that we set the revoked
209+
// field during the insert, we need to set the field after the session
210+
// has been created.
211+
if !session.RevokedAt.IsZero() {
212+
setSessionRevokedParams := sqlc.SetSessionRevokedAtParams{
213+
ID: sqlId,
214+
RevokedAt: sql.NullTime{
215+
Time: session.RevokedAt.UTC(),
216+
Valid: true,
217+
},
218+
}
219+
220+
err = tx.SetSessionRevokedAt(ctx, setSessionRevokedParams)
221+
if err != nil {
222+
return err
223+
}
224+
}
225+
226+
// After the session has been inserted, we need to update the session
227+
// with the group ID if it is linked to a group. We need to do this
228+
// after the session has been inserted, because the group ID can be the
229+
// session itself, and therefore the SQL id for the session won't exist
230+
// prior to inserting the session.
231+
groupID, err := tx.GetSessionIDByAlias(ctx, session.GroupID[:])
232+
if errors.Is(err, sql.ErrNoRows) {
233+
return ErrUnknownGroup
234+
} else if err != nil {
235+
return fmt.Errorf("unable to fetch group(%x): %w",
236+
session.GroupID[:], err)
237+
}
238+
239+
// Now lets set the group ID for the session.
240+
err = tx.SetSessionGroupID(ctx, sqlc.SetSessionGroupIDParams{
241+
ID: sqlId,
242+
GroupID: sql.NullInt64{
243+
Int64: groupID,
244+
Valid: true,
245+
},
246+
})
247+
if err != nil {
248+
return fmt.Errorf("unable to set group Alias: %w", err)
249+
}
250+
251+
// Once we have the sqlID for the session, we can proceed to insert rows
252+
// into the linked child tables.
253+
if session.MacaroonRecipe != nil {
254+
// We start by inserting the macaroon permissions.
255+
for _, sessionPerm := range session.MacaroonRecipe.Permissions {
256+
permParam := sqlc.InsertSessionMacaroonPermissionParams{
257+
SessionID: sqlId,
258+
Entity: sessionPerm.Entity,
259+
Action: sessionPerm.Action,
260+
}
261+
262+
err = tx.InsertSessionMacaroonPermission(
263+
ctx, permParam,
264+
)
265+
if err != nil {
266+
return err
267+
}
268+
}
269+
270+
// Next we insert the macaroon caveats.
271+
for _, sessCaveat := range session.MacaroonRecipe.Caveats {
272+
caveatParams := sqlc.InsertSessionMacaroonCaveatParams{
273+
SessionID: sqlId,
274+
CaveatID: sessCaveat.Id,
275+
VerificationID: sessCaveat.VerificationId,
276+
Location: sql.NullString{
277+
String: sessCaveat.Location,
278+
Valid: sessCaveat.Location != "",
279+
},
280+
}
281+
282+
err = tx.InsertSessionMacaroonCaveat(
283+
ctx, caveatParams,
284+
)
285+
if err != nil {
286+
return err
287+
}
288+
}
289+
}
290+
291+
// That's followed by the feature config.
292+
if session.FeatureConfig != nil {
293+
for featureName, config := range *session.FeatureConfig {
294+
fConfParams := sqlc.InsertSessionFeatureConfigParams{
295+
SessionID: sqlId,
296+
FeatureName: featureName,
297+
Config: config,
298+
}
299+
300+
err = tx.InsertSessionFeatureConfig(ctx, fConfParams)
301+
if err != nil {
302+
return err
303+
}
304+
}
305+
}
306+
307+
// Finally we insert the privacy flags.
308+
for _, privacyFlag := range session.PrivacyFlags {
309+
privacyFlagParams := sqlc.InsertSessionPrivacyFlagParams{
310+
SessionID: sqlId,
311+
Flag: int32(privacyFlag),
312+
}
313+
314+
err = tx.InsertSessionPrivacyFlag(
315+
ctx, privacyFlagParams,
316+
)
317+
if err != nil {
318+
return err
319+
}
320+
}
321+
322+
return nil
323+
}
324+
325+
// overrideSessionTimeZone overrides the time zone of the session to the local
326+
// time zone and chops off the nanosecond part for comparison. This is needed
327+
// because KV database stores times as-is which as an unwanted side effect would
328+
// fail migration due to time comparison expecting both the original and
329+
// migrated sessions to be in the same local time zone and in microsecond
330+
// precision. Note that PostgresSQL stores times in microsecond precision while
331+
// SQLite can store times in nanosecond precision if using TEXT storage class.
332+
func overrideSessionTimeZone(session *Session) {
333+
fixTime := func(t time.Time) time.Time {
334+
return t.In(time.Local).Truncate(time.Microsecond)
335+
}
336+
337+
if !session.Expiry.IsZero() {
338+
session.Expiry = fixTime(session.Expiry)
339+
}
340+
341+
if !session.CreatedAt.IsZero() {
342+
session.CreatedAt = fixTime(session.CreatedAt)
343+
}
344+
345+
if !session.RevokedAt.IsZero() {
346+
session.RevokedAt = fixTime(session.RevokedAt)
347+
}
348+
}

0 commit comments

Comments
 (0)