batch: update to allow for read-only calls

In this commit, we update the batch schedular so that it has the ability
to do read-only calls. It will do a best effort attempt at keeping a
transaction in read-only mode and then if any requests get added to a
batch that require a read-write tx, then the entire batch's tx will be
upgraded to use a read-write tx.
This commit is contained in:
Elle Mouton
2025-05-22 09:46:57 +02:00
parent e743878bd5
commit df1e6da94e
6 changed files with 332 additions and 25 deletions

View File

@@ -14,6 +14,19 @@ var errSolo = errors.New(
"batch function returned an error and should be re-run solo",
)
// txOpts implements the sqldb.TxOptions interface. It is used to indicate that
// the transaction can be read-only or not transaction.
type txOpts struct {
readOnly bool
}
// ReadOnly returns true if the transaction should be read only.
//
// NOTE: This is part of the sqldb.TxOptions interface.
func (t *txOpts) ReadOnly() bool {
return t.readOnly
}
type request[Q any] struct {
*Request[Q]
errChan chan error
@@ -25,6 +38,7 @@ type batch[Q any] struct {
reqs []*request[Q]
clear func(b *batch[Q])
locker sync.Locker
txOpts txOpts
}
// trigger is the entry point for the batch and ensures that run is started at
@@ -52,12 +66,11 @@ func (b *batch[Q]) run(ctx context.Context) {
// Apply the batch until a subset succeeds or all of them fail. Requests
// that fail will be retried individually.
var writeTx writeOpts
for len(b.reqs) > 0 {
var failIdx = -1
err := b.db.ExecTx(ctx, &writeTx, func(tx Q) error {
err := b.db.ExecTx(ctx, &b.txOpts, func(tx Q) error {
for i, req := range b.reqs {
err := req.Update(tx)
err := req.Do(tx)
if err != nil {
// If we get a serialization error, we
// want the underlying SQL retry