-
Notifications
You must be signed in to change notification settings - Fork 4
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
nonce: support reading a new Claimed state. #136
Open
mfycheng
wants to merge
2
commits into
code-payments:main
Choose a base branch
from
mfycheng:nonce-claim-state
base: main
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 all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
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 |
---|---|---|
|
@@ -3,6 +3,7 @@ package postgres | |
import ( | ||
"context" | ||
"database/sql" | ||
"time" | ||
|
||
"github.com/jmoiron/sqlx" | ||
|
||
|
@@ -17,13 +18,15 @@ const ( | |
) | ||
|
||
type nonceModel struct { | ||
Id sql.NullInt64 `db:"id"` | ||
Address string `db:"address"` | ||
Authority string `db:"authority"` | ||
Blockhash string `db:"blockhash"` | ||
Purpose uint `db:"purpose"` | ||
State uint `db:"state"` | ||
Signature string `db:"signature"` | ||
Id sql.NullInt64 `db:"id"` | ||
Address string `db:"address"` | ||
Authority string `db:"authority"` | ||
Blockhash string `db:"blockhash"` | ||
Purpose uint `db:"purpose"` | ||
State uint `db:"state"` | ||
Signature string `db:"signature"` | ||
ClaimNodeId string `db:"claim_node_id"` | ||
ClaimExpiresAtMs int64 `db:"claim_expires_at"` | ||
} | ||
|
||
func toNonceModel(obj *nonce.Record) (*nonceModel, error) { | ||
|
@@ -32,33 +35,37 @@ func toNonceModel(obj *nonce.Record) (*nonceModel, error) { | |
} | ||
|
||
return &nonceModel{ | ||
Id: sql.NullInt64{Int64: int64(obj.Id), Valid: true}, | ||
Address: obj.Address, | ||
Authority: obj.Authority, | ||
Blockhash: obj.Blockhash, | ||
Purpose: uint(obj.Purpose), | ||
State: uint(obj.State), | ||
Signature: obj.Signature, | ||
Id: sql.NullInt64{Int64: int64(obj.Id), Valid: true}, | ||
Address: obj.Address, | ||
Authority: obj.Authority, | ||
Blockhash: obj.Blockhash, | ||
Purpose: uint(obj.Purpose), | ||
State: uint(obj.State), | ||
Signature: obj.Signature, | ||
ClaimNodeId: obj.ClaimNodeId, | ||
ClaimExpiresAtMs: obj.ClaimExpiresAt.UnixMilli(), | ||
}, nil | ||
} | ||
|
||
func fromNonceModel(obj *nonceModel) *nonce.Record { | ||
return &nonce.Record{ | ||
Id: uint64(obj.Id.Int64), | ||
Address: obj.Address, | ||
Authority: obj.Authority, | ||
Blockhash: obj.Blockhash, | ||
Purpose: nonce.Purpose(obj.Purpose), | ||
State: nonce.State(obj.State), | ||
Signature: obj.Signature, | ||
Id: uint64(obj.Id.Int64), | ||
Address: obj.Address, | ||
Authority: obj.Authority, | ||
Blockhash: obj.Blockhash, | ||
Purpose: nonce.Purpose(obj.Purpose), | ||
State: nonce.State(obj.State), | ||
Signature: obj.Signature, | ||
ClaimNodeId: obj.ClaimNodeId, | ||
ClaimExpiresAt: time.UnixMilli(obj.ClaimExpiresAtMs), | ||
} | ||
} | ||
|
||
func (m *nonceModel) dbSave(ctx context.Context, db *sqlx.DB) error { | ||
return pgutil.ExecuteInTx(ctx, db, sql.LevelDefault, func(tx *sqlx.Tx) error { | ||
query := `INSERT INTO ` + nonceTableName + ` | ||
(address, authority, blockhash, purpose, state, signature) | ||
VALUES ($1,$2,$3,$4,$5,$6) | ||
(address, authority, blockhash, purpose, state, signature, claim_node_id, claim_expires_at) | ||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8) | ||
ON CONFLICT (address) | ||
DO UPDATE | ||
SET blockhash = $3, state = $5, signature = $6 | ||
|
@@ -75,6 +82,8 @@ func (m *nonceModel) dbSave(ctx context.Context, db *sqlx.DB) error { | |
m.Purpose, | ||
m.State, | ||
m.Signature, | ||
m.ClaimNodeId, | ||
m.ClaimExpiresAtMs, | ||
).StructScan(m) | ||
|
||
return pgutil.CheckNoRows(err, nonce.ErrInvalidNonce) | ||
|
@@ -162,48 +171,77 @@ func dbGetAllByState(ctx context.Context, db *sqlx.DB, state nonce.State, cursor | |
return res, nil | ||
} | ||
|
||
// todo: Implementation still isn't perfect, but better than no randomness. It's | ||
// sufficiently efficient, as long as our nonce pool is larger than the max offset. | ||
// todo: We may need to tune the offset based on pool size and environment, but it | ||
// should be sufficiently good enough for now. | ||
// We query a random nonce by first selecting any available candidate from the | ||
// total set, applying an upper limit of 100, and _then_ randomly shuffling the | ||
// results and selecting the first. By bounding the size before ORDER BY random(), | ||
// we avoid having to shuffle large sets of results. | ||
// | ||
// Previously, we would use OFFSET FLOOR(RANDOM() * 100). However, if the pool | ||
// (post filter) size was less than 100, any selection > pool size would result | ||
// in the OFFSET being set to zero. This meant random() disappeared for a subset | ||
// of values. In practice, this would result in a bias, and increased contention. | ||
// | ||
// For example, 50 Available nonce's, 25 Claimed (expired), 25 Reserved. With Offset: | ||
// | ||
// 1. 50% of the time would be a random Available. | ||
// 2. 25% of the time would be a random expired Claimed. | ||
// 3. 25% of the time would be _the first_ Available. | ||
// | ||
// This meant that 25% of the time would not be random. As we pull from the pool, | ||
// this % only increases, further causing contention. | ||
// | ||
// Performance wise, this approach is slightly worse, but the vast majority of the | ||
// time is spent on the scan and filter. Below are two example query plans (from a | ||
// small dataset in an online editor). | ||
// | ||
// QUERY PLAN (OFFSET): | ||
// | ||
// Limit (cost=17.80..35.60 rows=1 width=140) (actual time=0.019..0.019 rows=0 loops=1) | ||
// -> Seq Scan on codewallet__core_nonce (cost=0.00..17.80 rows=1 width=140) (actual time=0.016..0.017 rows=0 loops=1) | ||
// Filter: ((signature IS NOT NULL) AND (purpose = 1) AND ((state = 0) OR ((state = 2) AND (claim_expires_at < 200)))) | ||
// Rows Removed by Filter: 100 | ||
// | ||
// Planning Time: 0.046 ms | ||
// Execution Time: 0.031 ms | ||
// | ||
// QUERY PLAN (ORDER BY): | ||
// | ||
// Limit (cost=17.82..17.83 rows=1 width=148) (actual time=0.018..0.019 rows=0 loops=1) | ||
// -> Sort (cost=17.82..17.83 rows=1 width=148) (actual time=0.018..0.018 rows=0 loops=1) | ||
// Sort Key: (random()) | ||
// Sort Method: quicksort Memory: 25kB | ||
// -> Subquery Scan on sub (cost=0.00..17.81 rows=1 width=148) (actual time=0.015..0.016 rows=0 loops=1) | ||
// -> Limit (cost=0.00..17.80 rows=1 width=140) (actual time=0.015..0.015 rows=0 loops=1) | ||
// -> Seq Scan on codewallet__core_nonce (cost=0.00..17.80 rows=1 width=140) (actual time=0.015..0.015 rows=0 loops=1) | ||
// Filter: ((signature IS NOT NULL) AND (purpose = 1) AND ((state = 0) OR ((state = 2) AND (claim_expires_at < 200)))) | ||
// Rows Removed by Filter: 100 | ||
// | ||
// Planning Time: 0.068 ms | ||
// Execution Time: 0.037 ms | ||
// | ||
// Overall, the Seq Scan and Filter is the bulk of the work, with the ORDER BY RANDOM() | ||
// adding a small (fixed) amount of overhead. The trade-off is negligible time complexity | ||
// for more reliable semantics. | ||
Comment on lines
+174
to
+224
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is probably a thing to really double check.
|
||
func dbGetRandomAvailableByPurpose(ctx context.Context, db *sqlx.DB, purpose nonce.Purpose) (*nonceModel, error) { | ||
res := &nonceModel{} | ||
nowMs := time.Now().UnixMilli() | ||
|
||
// Signature null check is required because some legacy records didn't have this | ||
// set and causes this call to fail. This is a result of the field not being | ||
// defined at the time of record creation. | ||
// | ||
// todo: Fix said nonce records | ||
query := `SELECT | ||
id, address, authority, blockhash, purpose, state, signature | ||
FROM ` + nonceTableName + ` | ||
WHERE state = $1 AND purpose = $2 AND signature IS NOT NULL | ||
OFFSET FLOOR(RANDOM() * 100) | ||
LIMIT 1 | ||
` | ||
fallbackQuery := `SELECT | ||
id, address, authority, blockhash, purpose, state, signature | ||
FROM ` + nonceTableName + ` | ||
WHERE state = $1 AND purpose = $2 AND signature IS NOT NULL | ||
query := ` | ||
SELECT id, address, authority, blockhash, purpose, state, signature FROM ( | ||
SELECT id, address, authority, blockhash, purpose, state, signature | ||
FROM ` + nonceTableName + ` | ||
WHERE ((state = $1) OR (state = $2 AND claim_expires_at < $3)) AND purpose = $4 AND signature IS NOT NULL | ||
LIMIT 100 | ||
) sub | ||
ORDER BY random() | ||
LIMIT 1 | ||
` | ||
|
||
err := db.GetContext(ctx, res, query, nonce.StateAvailable, purpose) | ||
if err != nil { | ||
err = pgutil.CheckNoRows(err, nonce.ErrNonceNotFound) | ||
|
||
// No nonces found. Because our query isn't perfect, fall back to a | ||
// strategy that will guarantee to select something if an available | ||
// nonce exists. | ||
if err == nonce.ErrNonceNotFound { | ||
err := db.GetContext(ctx, res, fallbackQuery, nonce.StateAvailable, purpose) | ||
if err != nil { | ||
return nil, pgutil.CheckNoRows(err, nonce.ErrNonceNotFound) | ||
} | ||
return res, nil | ||
} | ||
|
||
return nil, err | ||
} | ||
return res, nil | ||
err := db.GetContext(ctx, res, query, nonce.StateAvailable, nonce.StateClaimed, nowMs, purpose) | ||
return res, pgutil.CheckNoRows(err, nonce.ErrNonceNotFound) | ||
} |
Oops, something went wrong.
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.
From the docs[1], as long as we allow these two fields to be
NULL
(and have it as the default), then there won't need to be any rewrite of the underlying tables. This means theALTER TABLE
command will place an exclusive access on the table, but the duration of the command should be quick.[1] https://www.postgresql.org/docs/current/sql-altertable.html