-
Notifications
You must be signed in to change notification settings - Fork 44
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
NONEVM-745 LogPoller db models #921
Open
dhaidashenko
wants to merge
8
commits into
develop
Choose a base branch
from
feature/NONEVM-745-logpoller-db-models
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
06e1ccf
logpoller db models
dhaidashenko 057ade0
Replace solana types with custom to support db read/write
dhaidashenko 3f0860d
remove redundant file
dhaidashenko 1287605
improve tests coverage & ensure subkey naming is consistent
dhaidashenko 3186314
drop redundant constraint
dhaidashenko 5688156
Merge branch 'develop' into feature/NONEVM-745-logpoller-db-models
dhaidashenko 1bd24fd
gomodtidy
dhaidashenko aae0424
linter fixes
dhaidashenko File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package logpoller | ||
|
||
import ( | ||
"time" | ||
|
||
"github.com/lib/pq" | ||
) | ||
|
||
type Filter struct { | ||
ID int64 | ||
Name string | ||
Address PublicKey | ||
EventName string | ||
EventSig []byte | ||
StartingBlock int64 | ||
EventIDL string | ||
SubKeyPaths SubKeyPaths | ||
Retention time.Duration | ||
MaxLogsKept int64 | ||
} | ||
|
||
type Log struct { | ||
ID int64 | ||
FilterId int64 | ||
ChainId string | ||
LogIndex int64 | ||
BlockHash Hash | ||
BlockNumber int64 | ||
BLockTimestamp time.Time | ||
Address PublicKey | ||
EventSig []byte | ||
SubKeyValues pq.ByteaArray | ||
TxHash Signature | ||
Data []byte | ||
CreatedAt time.Time | ||
ExpiresAt *time.Time | ||
SequenceNum int64 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,160 @@ | ||
package logpoller | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"fmt" | ||
|
||
"github.com/smartcontractkit/chainlink-common/pkg/logger" | ||
"github.com/smartcontractkit/chainlink-common/pkg/sqlutil" | ||
) | ||
|
||
type DSORM struct { | ||
chainID string | ||
ds sqlutil.DataSource | ||
lggr logger.Logger | ||
} | ||
|
||
// NewORM creates an DSORM scoped to chainID. | ||
func NewORM(chainID string, ds sqlutil.DataSource, lggr logger.Logger) *DSORM { | ||
return &DSORM{ | ||
chainID: chainID, | ||
ds: ds, | ||
lggr: lggr, | ||
} | ||
} | ||
|
||
func (o *DSORM) Transact(ctx context.Context, fn func(*DSORM) error) (err error) { | ||
return sqlutil.Transact(ctx, o.new, o.ds, nil, fn) | ||
} | ||
|
||
// new returns a NewORM like o, but backed by ds. | ||
func (o *DSORM) new(ds sqlutil.DataSource) *DSORM { return NewORM(o.chainID, ds, o.lggr) } | ||
|
||
// InsertFilter is idempotent. | ||
// | ||
// Each address/event pair must have a unique job id, so it may be removed when the job is deleted. | ||
// Returns ID for updated or newly inserted filter. | ||
func (o *DSORM) InsertFilter(ctx context.Context, filter Filter) (id int64, err error) { | ||
args, err := newQueryArgs(o.chainID). | ||
withField("name", filter.Name). | ||
withRetention(filter.Retention). | ||
withMaxLogsKept(filter.MaxLogsKept). | ||
withName(filter.Name). | ||
withAddress(filter.Address). | ||
withEventName(filter.EventName). | ||
withEventSig(filter.EventSig). | ||
withStartingBlock(filter.StartingBlock). | ||
withEventIDL(filter.EventIDL). | ||
withSubKeyPaths(filter.SubKeyPaths). | ||
toArgs() | ||
if err != nil { | ||
return 0, err | ||
} | ||
|
||
// '::' has to be escaped in the query string | ||
// https://github.com/jmoiron/sqlx/issues/91, https://github.com/jmoiron/sqlx/issues/428 | ||
query := ` | ||
INSERT INTO solana.log_poller_filters | ||
(chain_id, name, address, event_name, event_sig, starting_block, event_idl, sub_key_paths, retention, max_logs_kept) | ||
VALUES (:chain_id, :name, :address, :event_name, :event_sig, :starting_block, :event_idl, :sub_key_paths, :retention, :max_logs_kept) | ||
ON CONFLICT (solana.f_log_poller_filter_hash(name, chain_id, address, event_sig, sub_key_paths)) | ||
DO UPDATE SET retention=:retention ::::BIGINT, max_logs_kept=:max_logs_kept ::::NUMERIC, starting_block=:starting_block ::::NUMERIC | ||
RETURNING id;` | ||
|
||
query, sqlArgs, err := o.ds.BindNamed(query, args) | ||
if err != nil { | ||
return 0, err | ||
} | ||
if err = o.ds.GetContext(ctx, &id, query, sqlArgs...); err != nil { | ||
return 0, err | ||
} | ||
return id, nil | ||
} | ||
|
||
// GetFilterByID returns filter by ID | ||
func (o *DSORM) GetFilterByID(ctx context.Context, id int64) (Filter, error) { | ||
query := `SELECT id, name, address, event_name, event_sig, starting_block, event_idl, sub_key_paths, retention, max_logs_kept | ||
FROM solana.log_poller_filters WHERE id = $1` | ||
var result Filter | ||
err := o.ds.GetContext(ctx, &result, query, id) | ||
return result, err | ||
} | ||
|
||
// InsertLogs is idempotent to support replays. | ||
func (o *DSORM) InsertLogs(ctx context.Context, logs []Log) error { | ||
if err := o.validateLogs(logs); err != nil { | ||
return err | ||
} | ||
return o.Transact(ctx, func(orm *DSORM) error { | ||
return orm.insertLogsWithinTx(ctx, logs, orm.ds) | ||
}) | ||
} | ||
|
||
func (o *DSORM) insertLogsWithinTx(ctx context.Context, logs []Log, tx sqlutil.DataSource) error { | ||
batchInsertSize := 4000 | ||
for i := 0; i < len(logs); i += batchInsertSize { | ||
start, end := i, i+batchInsertSize | ||
if end > len(logs) { | ||
end = len(logs) | ||
} | ||
|
||
query := `INSERT INTO solana.logs | ||
(filter_id, chain_id, log_index, block_hash, block_number, block_timestamp, address, event_sig, subkey_values, tx_hash, data, created_at, expires_at, sequence_num) | ||
VALUES | ||
(:filter_id, :chain_id, :log_index, :block_hash, :block_number, :block_timestamp, :address, :event_sig, :subkey_values, :tx_hash, :data, NOW(), :expires_at, :sequence_num) | ||
ON CONFLICT DO NOTHING` | ||
|
||
_, err := tx.NamedExecContext(ctx, query, logs[start:end]) | ||
if err != nil { | ||
if errors.Is(err, context.DeadlineExceeded) && batchInsertSize > 500 { | ||
// In case of DB timeouts, try to insert again with a smaller batch upto a limit | ||
batchInsertSize /= 2 | ||
i -= batchInsertSize // counteract +=batchInsertSize on next loop iteration | ||
continue | ||
} | ||
return err | ||
} | ||
} | ||
return nil | ||
} | ||
|
||
func (o *DSORM) validateLogs(logs []Log) error { | ||
for _, log := range logs { | ||
if o.chainID != log.ChainId { | ||
return fmt.Errorf("invalid chainID in log got %v want %v", log.ChainId, o.chainID) | ||
} | ||
} | ||
return nil | ||
} | ||
|
||
// SelectLogs finds the logs in a given block range. | ||
func (o *DSORM) SelectLogs(ctx context.Context, start, end int64, address PublicKey, eventSig []byte) ([]Log, error) { | ||
args, err := newQueryArgsForEvent(o.chainID, address, eventSig). | ||
withStartBlock(start). | ||
withEndBlock(end). | ||
toArgs() | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
query := logsQuery(` | ||
WHERE chain_id = :chain_id | ||
AND address = :address | ||
AND event_sig = :event_sig | ||
AND block_number >= :start_block | ||
AND block_number <= :end_block | ||
ORDER BY block_number, log_index`) | ||
|
||
var logs []Log | ||
query, sqlArgs, err := o.ds.BindNamed(query, args) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
err = o.ds.SelectContext(ctx, &logs, query, sqlArgs...) | ||
if err != nil { | ||
return nil, err | ||
} | ||
return logs, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,135 @@ | ||
//go:build db_tests | ||
|
||
package logpoller | ||
|
||
import ( | ||
"os" | ||
"testing" | ||
"time" | ||
|
||
"github.com/gagliardetto/solana-go" | ||
"github.com/google/uuid" | ||
_ "github.com/jackc/pgx/v4/stdlib" | ||
"github.com/lib/pq" | ||
"github.com/smartcontractkit/chainlink-common/pkg/logger" | ||
"github.com/smartcontractkit/chainlink-common/pkg/pg" | ||
"github.com/smartcontractkit/chainlink-common/pkg/utils/tests" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
// NOTE: at the moment it's not possible to run all db tests at once. This issue will be addressed separately | ||
|
||
func TestLogPollerFilters(t *testing.T) { | ||
lggr := logger.Test(t) | ||
dbURL, ok := os.LookupEnv("CL_DATABASE_URL") | ||
require.True(t, ok, "CL_DATABASE_URL must be set") | ||
chainID := uuid.NewString() | ||
dbx := pg.NewSqlxDB(t, dbURL) | ||
orm := NewORM(chainID, dbx, lggr) | ||
|
||
privateKey, err := solana.NewRandomPrivateKey() | ||
require.NoError(t, err) | ||
pubKey := privateKey.PublicKey() | ||
filters := []Filter{ | ||
{ | ||
Name: "happy path", | ||
Address: PublicKey(pubKey), | ||
EventName: "event", | ||
EventSig: []byte{1, 2, 3}, | ||
StartingBlock: 1, | ||
EventIDL: "{}", | ||
SubKeyPaths: SubKeyPaths([][]string{{"a", "b"}, {"c"}}), | ||
Retention: 1000, | ||
MaxLogsKept: 3, | ||
}, | ||
{ | ||
Name: "empty sub key paths", | ||
Address: PublicKey(pubKey), | ||
EventName: "event", | ||
EventSig: []byte{1, 2, 3}, | ||
StartingBlock: 1, | ||
EventIDL: "{}", | ||
SubKeyPaths: SubKeyPaths([][]string{}), | ||
Retention: 1000, | ||
MaxLogsKept: 3, | ||
}, | ||
{ | ||
Name: "nil sub key paths", | ||
Address: PublicKey(pubKey), | ||
EventName: "event", | ||
EventSig: []byte{1, 2, 3}, | ||
StartingBlock: 1, | ||
EventIDL: "{}", | ||
SubKeyPaths: nil, | ||
Retention: 1000, | ||
MaxLogsKept: 3, | ||
}, | ||
} | ||
|
||
for _, filter := range filters { | ||
t.Run("Save filter: "+filter.Name, func(t *testing.T) { | ||
ctx := tests.Context(t) | ||
id, err := orm.InsertFilter(ctx, filter) | ||
require.NoError(t, err) | ||
filter.ID = id | ||
dbFilter, err := orm.GetFilterByID(ctx, id) | ||
require.NoError(t, err) | ||
require.Equal(t, filter, dbFilter) | ||
|
||
// subsequent insert of the same filter won't produce new db row | ||
secondID, err := orm.InsertFilter(ctx, filter) | ||
require.NoError(t, err) | ||
require.Equal(t, secondID, id) | ||
}) | ||
} | ||
} | ||
|
||
func TestLogPollerLogs(t *testing.T) { | ||
lggr := logger.Test(t) | ||
dbURL, ok := os.LookupEnv("CL_DATABASE_URL") | ||
require.True(t, ok, "CL_DATABASE_URL must be set") | ||
chainID := uuid.NewString() | ||
dbx := pg.NewSqlxDB(t, dbURL) | ||
orm := NewORM(chainID, dbx, lggr) | ||
|
||
privateKey, err := solana.NewRandomPrivateKey() | ||
require.NoError(t, err) | ||
pubKey := privateKey.PublicKey() | ||
|
||
ctx := tests.Context(t) | ||
// create filter as it's required for a log | ||
filterID, err := orm.InsertFilter(ctx, Filter{ | ||
Name: "awesome filter", | ||
Address: PublicKey(pubKey), | ||
EventName: "event", | ||
EventSig: []byte{1, 2, 3}, | ||
StartingBlock: 1, | ||
EventIDL: "{}", | ||
SubKeyPaths: [][]string{{"a", "b"}, {"c"}}, | ||
Retention: 1000, | ||
MaxLogsKept: 3, | ||
}) | ||
require.NoError(t, err) | ||
data := []byte("solana is fun") | ||
signature, err := privateKey.Sign(data) | ||
require.NoError(t, err) | ||
log := Log{ | ||
FilterId: filterID, | ||
ChainId: chainID, | ||
LogIndex: 1, | ||
BlockHash: Hash(pubKey), | ||
BlockNumber: 10, | ||
BLockTimestamp: time.Now(), | ||
Address: PublicKey(pubKey), | ||
EventSig: []byte{3, 2, 1}, | ||
SubKeyValues: pq.ByteaArray([][]byte{{3, 2, 1}, {1}, {1, 2}, pubKey.Bytes()}), | ||
TxHash: Signature(signature), | ||
Data: data, | ||
} | ||
err = orm.InsertLogs(ctx, []Log{log}) | ||
require.NoError(t, err) | ||
dbLogs, err := orm.SelectLogs(ctx, 0, 100, log.Address, log.EventSig) | ||
require.NoError(t, err) | ||
require.Len(t, dbLogs, 1) | ||
require.Equal(t, log, dbLogs[0]) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm really confused... I have a PR open to move
NewSqlDB
and some other things over fromchainlink
tochainlink-common
, but as far as I know it hasn't been merged yet. 🤔I wonder if someone else moved it over already.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, it's not merged. I've used your PR as a dependency to unblock myself.