graph/db: cache source node info

Save future round trips by caching source node info since this info will
never change.
This commit is contained in:
Elle Mouton
2025-05-28 11:37:38 +02:00
parent a27bd69b9c
commit 3ed53cdcba

View File

@@ -119,6 +119,9 @@ type SQLStore struct {
chanScheduler batch.Scheduler[SQLQueries]
nodeScheduler batch.Scheduler[SQLQueries]
srcNodes map[ProtocolVersion]*srcNodeInfo
srcNodeMu sync.Mutex
// Temporary fall-back to the KVStore so that we can implement the
// interface incrementally.
*KVStore
@@ -156,6 +159,7 @@ func NewSQLStore(cfg *SQLStoreConfig, db BatchedSQLQueries, kvStore *KVStore,
KVStore: kvStore,
rejectCache: newRejectCache(opts.RejectCacheSize),
chanCache: newChannelCache(opts.ChannelCacheSize),
srcNodes: make(map[ProtocolVersion]*srcNodeInfo),
}
s.chanScheduler = batch.NewTimeScheduler(
@@ -382,7 +386,7 @@ func (s *SQLStore) SourceNode() (*models.LightningNode, error) {
var node *models.LightningNode
err := s.db.ExecTx(ctx, sqldb.ReadTxOpt(), func(db SQLQueries) error {
_, nodePub, err := getSourceNode(ctx, db, ProtocolV1)
_, nodePub, err := s.getSourceNode(ctx, db, ProtocolV1)
if err != nil {
return fmt.Errorf("unable to fetch V1 source node: %w",
err)
@@ -416,7 +420,7 @@ func (s *SQLStore) SetSourceNode(node *models.LightningNode) error {
// Make sure that if a source node for this version is already
// set, then the ID is the same as the one we are about to set.
dbSourceNodeID, _, err := getSourceNode(ctx, db, ProtocolV1)
dbSourceNodeID, _, err := s.getSourceNode(ctx, db, ProtocolV1)
if err != nil && !errors.Is(err, ErrSourceNodeNotSet) {
return fmt.Errorf("unable to fetch source node: %w",
err)
@@ -1254,11 +1258,29 @@ func upsertNodeExtraSignedFields(ctx context.Context, db SQLQueries,
return nil
}
// srcNodeInfo holds the information about the source node of the graph.
type srcNodeInfo struct {
// id is the DB level ID of the source node entry in the "nodes" table.
id int64
// pub is the public key of the source node.
pub route.Vertex
}
// getSourceNode returns the DB node ID and pub key of the source node for the
// specified protocol version.
func getSourceNode(ctx context.Context, db SQLQueries,
func (s *SQLStore) getSourceNode(ctx context.Context, db SQLQueries,
version ProtocolVersion) (int64, route.Vertex, error) {
s.srcNodeMu.Lock()
defer s.srcNodeMu.Unlock()
// If we already have the source node ID and pub key cached, then
// return them.
if info, ok := s.srcNodes[version]; ok {
return info.id, info.pub, nil
}
var pubKey route.Vertex
nodes, err := db.GetSourceNodesByVersion(ctx, int16(version))
@@ -1276,6 +1298,11 @@ func getSourceNode(ctx context.Context, db SQLQueries,
copy(pubKey[:], nodes[0].PubKey)
s.srcNodes[version] = &srcNodeInfo{
id: nodes[0].NodeID,
pub: pubKey,
}
return nodes[0].NodeID, pubKey, nil
}