File size: 1,321 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package processinglock

import (
	"context"
	"database/sql"
	"encoding/json"

	"github.com/target/goalert/gadb"
	"github.com/target/goalert/util/jsonutil"
)

// State manages the state value for a processing lock.
type State struct {
	data json.RawMessage
	tx   *sql.Tx
	l    *Lock
}

// BeginTxWithState will start a transaction, returning a State object.
func (l *Lock) BeginTxWithState(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, *State, error) {
	tx, err := l.BeginTx(ctx, opts)
	if err != nil {
		return nil, nil, err
	}

	return tx, &State{tx: tx, l: l}, nil
}

// Load will load the JSON state from the database.
func (s *State) Load(ctx context.Context, v interface{}) (err error) {
	s.data, err = gadb.New(s.tx).ProcLoadState(ctx, gadb.EngineProcessingType(s.l.cfg.Type))
	if err != nil {
		return err
	}

	return json.Unmarshal(s.data, v)
}

// Save will save the JSON state to the database, taking care to ensure that
// existing unknown fields are preserved.
func (s *State) Save(ctx context.Context, v interface{}) error {
	data, err := jsonutil.Apply(s.data, v)
	if err != nil {
		return err
	}
	s.data = data

	err = gadb.New(s.tx).ProcSaveState(ctx, gadb.ProcSaveStateParams{
		TypeID: gadb.EngineProcessingType(s.l.cfg.Type),
		State:  s.data,
	})
	if err != nil {
		return err
	}

	return nil
}