-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
orm.go
1603 lines (1418 loc) · 61.4 KB
/
orm.go
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package job
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"reflect"
"slices"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/google/uuid"
"github.com/jackc/pgconn"
"github.com/lib/pq"
"github.com/pkg/errors"
"go.uber.org/multierr"
"github.com/jmoiron/sqlx"
"github.com/smartcontractkit/chainlink-common/pkg/sqlutil"
"github.com/smartcontractkit/chainlink-common/pkg/types"
"github.com/smartcontractkit/chainlink/v2/core/bridges"
evmconfig "github.com/smartcontractkit/chainlink/v2/core/chains/evm/config"
evmtypes "github.com/smartcontractkit/chainlink/v2/core/chains/evm/types"
"github.com/smartcontractkit/chainlink/v2/core/chains/evm/utils/big"
"github.com/smartcontractkit/chainlink/v2/core/config"
"github.com/smartcontractkit/chainlink/v2/core/logger"
"github.com/smartcontractkit/chainlink/v2/core/null"
"github.com/smartcontractkit/chainlink/v2/core/services/keystore"
medianconfig "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/plugins/median/config"
"github.com/smartcontractkit/chainlink/v2/core/services/pipeline"
"github.com/smartcontractkit/chainlink/v2/core/services/relay"
"github.com/smartcontractkit/chainlink/v2/core/store/models"
)
var (
ErrNoSuchKeyBundle = errors.New("no such key bundle exists")
ErrNoSuchTransmitterKey = errors.New("no such transmitter key exists")
ErrNoSuchSendingKey = errors.New("no such sending key exists")
ErrNoSuchPublicKey = errors.New("no such public key exists")
)
//go:generate mockery --quiet --name ORM --output ./mocks/ --case=underscore
type ORM interface {
InsertWebhookSpec(ctx context.Context, webhookSpec *WebhookSpec) error
InsertJob(ctx context.Context, job *Job) error
CreateJob(ctx context.Context, jb *Job) error
FindJobs(ctx context.Context, offset, limit int) ([]Job, int, error)
FindJobTx(ctx context.Context, id int32) (Job, error)
FindJob(ctx context.Context, id int32) (Job, error)
FindJobByExternalJobID(ctx context.Context, uuid uuid.UUID) (Job, error)
FindJobIDByAddress(ctx context.Context, address evmtypes.EIP55Address, evmChainID *big.Big) (int32, error)
FindOCR2JobIDByAddress(ctx context.Context, contractID string, feedID *common.Hash) (int32, error)
FindJobIDsWithBridge(ctx context.Context, name string) ([]int32, error)
DeleteJob(ctx context.Context, id int32) error
RecordError(ctx context.Context, jobID int32, description string) error
// TryRecordError is a helper which calls RecordError and logs the returned error if present.
TryRecordError(ctx context.Context, jobID int32, description string)
DismissError(ctx context.Context, errorID int64) error
FindSpecError(ctx context.Context, id int64) (SpecError, error)
Close() error
PipelineRuns(ctx context.Context, jobID *int32, offset, size int) ([]pipeline.Run, int, error)
FindPipelineRunIDsByJobID(ctx context.Context, jobID int32, offset, limit int) (ids []int64, err error)
FindPipelineRunsByIDs(ctx context.Context, ids []int64) (runs []pipeline.Run, err error)
CountPipelineRunsByJobID(ctx context.Context, jobID int32) (count int32, err error)
FindJobsByPipelineSpecIDs(ctx context.Context, ids []int32) ([]Job, error)
FindPipelineRunByID(ctx context.Context, id int64) (pipeline.Run, error)
FindSpecErrorsByJobIDs(ctx context.Context, ids []int32) ([]SpecError, error)
FindJobWithoutSpecErrors(ctx context.Context, id int32) (jb Job, err error)
FindTaskResultByRunIDAndTaskName(ctx context.Context, runID int64, taskName string) ([]byte, error)
AssertBridgesExist(ctx context.Context, p pipeline.Pipeline) error
DataSource() sqlutil.DataSource
WithDataSource(source sqlutil.DataSource) ORM
FindJobIDByWorkflow(ctx context.Context, spec WorkflowSpec) (int32, error)
}
type ORMConfig interface {
DatabaseDefaultQueryTimeout() time.Duration
}
type orm struct {
ds sqlutil.DataSource
keyStore keystore.Master
pipelineORM pipeline.ORM
lggr logger.SugaredLogger
bridgeORM bridges.ORM
}
var _ ORM = (*orm)(nil)
func NewORM(ds sqlutil.DataSource, pipelineORM pipeline.ORM, bridgeORM bridges.ORM, keyStore keystore.Master, lggr logger.Logger) *orm {
namedLogger := logger.Sugared(lggr.Named("JobORM"))
return &orm{
ds: ds,
keyStore: keyStore,
pipelineORM: pipelineORM,
bridgeORM: bridgeORM,
lggr: namedLogger,
}
}
func (o *orm) Close() error {
return nil
}
func (o *orm) DataSource() sqlutil.DataSource {
return o.ds
}
func (o *orm) WithDataSource(ds sqlutil.DataSource) ORM { return o.withDataSource(ds) }
func (o *orm) withDataSource(ds sqlutil.DataSource) *orm {
n := &orm{
ds: ds,
lggr: o.lggr,
keyStore: o.keyStore,
}
if o.bridgeORM != nil {
n.bridgeORM = o.bridgeORM.WithDataSource(ds)
}
if o.pipelineORM != nil {
n.pipelineORM = o.pipelineORM.WithDataSource(ds)
}
return n
}
func (o *orm) transact(ctx context.Context, readOnly bool, fn func(*orm) error) error {
opts := &sqlutil.TxOptions{TxOptions: sql.TxOptions{ReadOnly: readOnly}}
return sqlutil.Transact(ctx, o.withDataSource, o.ds, opts, fn)
}
func (o *orm) AssertBridgesExist(ctx context.Context, p pipeline.Pipeline) error {
var bridgeNames = make(map[bridges.BridgeName]struct{})
var uniqueBridges []bridges.BridgeName
for _, task := range p.Tasks {
if task.Type() == pipeline.TaskTypeBridge {
// Bridge must exist
name := task.(*pipeline.BridgeTask).Name
bridge, err := bridges.ParseBridgeName(name)
if err != nil {
return err
}
if _, have := bridgeNames[bridge]; have {
continue
}
bridgeNames[bridge] = struct{}{}
uniqueBridges = append(uniqueBridges, bridge)
}
}
if len(uniqueBridges) != 0 {
_, err := o.bridgeORM.FindBridges(ctx, uniqueBridges)
if err != nil {
return err
}
}
return nil
}
// CreateJob creates the job, and it's associated spec record.
// Expects an unmarshalled job spec as the jb argument i.e. output from ValidatedXX.
// Scans all persisted records back into jb
func (o *orm) CreateJob(ctx context.Context, jb *Job) error {
p := jb.Pipeline
if err := o.AssertBridgesExist(ctx, p); err != nil {
return err
}
var jobID int32
err := o.transact(ctx, false, func(tx *orm) error {
// Autogenerate a job ID if not specified
if jb.ExternalJobID == (uuid.UUID{}) {
jb.ExternalJobID = uuid.New()
}
switch jb.Type {
case DirectRequest:
if jb.DirectRequestSpec.EVMChainID == nil {
return errors.New("evm chain id must be defined")
}
specID, err := tx.insertDirectRequestSpec(ctx, jb.DirectRequestSpec)
if err != nil {
return fmt.Errorf("failed to create DirectRequestSpec for jobSpec: %w", err)
}
jb.DirectRequestSpecID = &specID
case FluxMonitor:
if jb.FluxMonitorSpec.EVMChainID == nil {
return errors.New("evm chain id must be defined")
}
specID, err := tx.insertFluxMonitorSpec(ctx, jb.FluxMonitorSpec)
if err != nil {
return fmt.Errorf("failed to create FluxMonitorSpec for jobSpec: %w", err)
}
jb.FluxMonitorSpecID = &specID
case OffchainReporting:
if jb.OCROracleSpec.EVMChainID == nil {
return errors.New("evm chain id must be defined")
}
if jb.OCROracleSpec.EncryptedOCRKeyBundleID != nil {
_, err := tx.keyStore.OCR().Get(jb.OCROracleSpec.EncryptedOCRKeyBundleID.String())
if err != nil {
return errors.Wrapf(ErrNoSuchKeyBundle, "no key bundle with id: %x", jb.OCROracleSpec.EncryptedOCRKeyBundleID)
}
}
if jb.OCROracleSpec.TransmitterAddress != nil {
_, err := tx.keyStore.Eth().Get(ctx, jb.OCROracleSpec.TransmitterAddress.Hex())
if err != nil {
return errors.Wrapf(ErrNoSuchTransmitterKey, "no key matching transmitter address: %s", jb.OCROracleSpec.TransmitterAddress.Hex())
}
}
newChainID := jb.OCROracleSpec.EVMChainID
existingSpec := new(OCROracleSpec)
err := tx.ds.GetContext(ctx, existingSpec, `SELECT * FROM ocr_oracle_specs WHERE contract_address = $1 and (evm_chain_id = $2 or evm_chain_id IS NULL) LIMIT 1;`,
jb.OCROracleSpec.ContractAddress, newChainID,
)
if !errors.Is(err, sql.ErrNoRows) {
if err != nil {
return errors.Wrap(err, "failed to validate OffchainreportingOracleSpec on creation")
}
return errors.Errorf("a job with contract address %s already exists for chain ID %s", jb.OCROracleSpec.ContractAddress, newChainID)
}
specID, err := tx.insertOCROracleSpec(ctx, jb.OCROracleSpec)
if err != nil {
return fmt.Errorf("failed to create OCROracleSpec for jobSpec: %w", err)
}
jb.OCROracleSpecID = &specID
case OffchainReporting2:
if jb.OCR2OracleSpec.OCRKeyBundleID.Valid {
_, err := tx.keyStore.OCR2().Get(jb.OCR2OracleSpec.OCRKeyBundleID.String)
if err != nil {
return errors.Wrapf(ErrNoSuchKeyBundle, "no key bundle with id: %q", jb.OCR2OracleSpec.OCRKeyBundleID.ValueOrZero())
}
}
if jb.OCR2OracleSpec.RelayConfig["sendingKeys"] != nil && jb.OCR2OracleSpec.TransmitterID.Valid {
return errors.New("sending keys and transmitter ID can't both be defined")
}
// checks if they are present and if they are valid
sendingKeysDefined, err := areSendingKeysDefined(ctx, jb, tx.keyStore)
if err != nil {
return err
}
if !sendingKeysDefined && !jb.OCR2OracleSpec.TransmitterID.Valid {
return errors.New("neither sending keys nor transmitter ID is defined")
}
if !sendingKeysDefined {
if err = ValidateKeyStoreMatch(ctx, jb.OCR2OracleSpec, tx.keyStore, jb.OCR2OracleSpec.TransmitterID.String); err != nil {
return errors.Wrap(ErrNoSuchTransmitterKey, err.Error())
}
}
if jb.ForwardingAllowed && !slices.Contains(ForwardersSupportedPlugins, jb.OCR2OracleSpec.PluginType) {
return errors.Errorf("forwarding is not currently supported for %s jobs", jb.OCR2OracleSpec.PluginType)
}
if jb.OCR2OracleSpec.PluginType == types.Mercury {
if jb.OCR2OracleSpec.FeedID == nil {
return errors.New("feed ID is required for mercury plugin type")
}
} else {
if jb.OCR2OracleSpec.FeedID != nil {
return errors.New("feed ID is not currently supported for non-mercury jobs")
}
}
if jb.OCR2OracleSpec.PluginType == types.Median {
var cfg medianconfig.PluginConfig
validatePipeline := func(p string) error {
pipeline, pipelineErr := pipeline.Parse(p)
if pipelineErr != nil {
return pipelineErr
}
return tx.AssertBridgesExist(ctx, *pipeline)
}
errUnmarshal := json.Unmarshal(jb.OCR2OracleSpec.PluginConfig.Bytes(), &cfg)
if errUnmarshal != nil {
return errors.Wrap(errUnmarshal, "failed to parse plugin config")
}
if errFeePipeline := validatePipeline(cfg.JuelsPerFeeCoinPipeline); errFeePipeline != nil {
return errFeePipeline
}
if cfg.HasGasPriceSubunitsPipeline() {
if errGasPipeline := validatePipeline(cfg.GasPriceSubunitsPipeline); errGasPipeline != nil {
return errGasPipeline
}
}
}
specID, err := tx.insertOCR2OracleSpec(ctx, jb.OCR2OracleSpec)
if err != nil {
return fmt.Errorf("failed to create OCR2OracleSpec for jobSpec: %w", err)
}
jb.OCR2OracleSpecID = &specID
case Keeper:
if jb.KeeperSpec.EVMChainID == nil {
return errors.New("evm chain id must be defined")
}
specID, err := tx.insertKeeperSpec(ctx, jb.KeeperSpec)
if err != nil {
return fmt.Errorf("failed to create KeeperSpec for jobSpec: %w", err)
}
jb.KeeperSpecID = &specID
case Cron:
specID, err := tx.insertCronSpec(ctx, jb.CronSpec)
if err != nil {
return fmt.Errorf("failed to create CronSpec for jobSpec: %w", err)
}
jb.CronSpecID = &specID
case VRF:
if jb.VRFSpec.EVMChainID == nil {
return errors.New("evm chain id must be defined")
}
specID, err := tx.insertVRFSpec(ctx, jb.VRFSpec)
var pqErr *pgconn.PgError
ok := errors.As(err, &pqErr)
if err != nil && ok && pqErr.Code == "23503" {
if pqErr.ConstraintName == "vrf_specs_public_key_fkey" {
return errors.Wrapf(ErrNoSuchPublicKey, "%s", jb.VRFSpec.PublicKey.String())
}
}
if err != nil {
return fmt.Errorf("failed to create VRFSpec for jobSpec: %w", err)
}
jb.VRFSpecID = &specID
case Webhook:
err := tx.InsertWebhookSpec(ctx, jb.WebhookSpec)
if err != nil {
return errors.Wrap(err, "failed to create WebhookSpec")
}
jb.WebhookSpecID = &jb.WebhookSpec.ID
if len(jb.WebhookSpec.ExternalInitiatorWebhookSpecs) > 0 {
for i := range jb.WebhookSpec.ExternalInitiatorWebhookSpecs {
jb.WebhookSpec.ExternalInitiatorWebhookSpecs[i].WebhookSpecID = jb.WebhookSpec.ID
}
sql := `INSERT INTO external_initiator_webhook_specs (external_initiator_id, webhook_spec_id, spec)
VALUES (:external_initiator_id, :webhook_spec_id, :spec);`
if _, err := tx.ds.NamedExecContext(ctx, sql, jb.WebhookSpec.ExternalInitiatorWebhookSpecs); err != nil {
return errors.Wrap(err, "failed to create ExternalInitiatorWebhookSpecs")
}
}
case BlockhashStore:
if jb.BlockhashStoreSpec.EVMChainID == nil {
return errors.New("evm chain id must be defined")
}
specID, err := tx.insertBlockhashStoreSpec(ctx, jb.BlockhashStoreSpec)
if err != nil {
return fmt.Errorf("failed to create BlockhashStoreSpec for jobSpec: %w", err)
}
jb.BlockhashStoreSpecID = &specID
case BlockHeaderFeeder:
if jb.BlockHeaderFeederSpec.EVMChainID == nil {
return errors.New("evm chain id must be defined")
}
specID, err := tx.insertBlockHeaderFeederSpec(ctx, jb.BlockHeaderFeederSpec)
if err != nil {
return fmt.Errorf("failed to create BlockHeaderFeederSpec for jobSpec: %w", err)
}
jb.BlockHeaderFeederSpecID = &specID
case LegacyGasStationServer:
if jb.LegacyGasStationServerSpec.EVMChainID == nil {
return errors.New("evm chain id must be defined")
}
specID, err := tx.insertLegacyGasStationServerSpec(ctx, jb.LegacyGasStationServerSpec)
if err != nil {
return fmt.Errorf("failed to create LegacyGasStationServerSpec for jobSpec: %w", err)
}
jb.LegacyGasStationServerSpecID = &specID
case LegacyGasStationSidecar:
if jb.LegacyGasStationSidecarSpec.EVMChainID == nil {
return errors.New("evm chain id must be defined")
}
specID, err := tx.insertLegacyGasStationSidecarSpec(ctx, jb.LegacyGasStationSidecarSpec)
if err != nil {
return fmt.Errorf("failed to create LegacyGasStationSidecarSpec for jobSpec: %w", err)
}
jb.LegacyGasStationSidecarSpecID = &specID
case Bootstrap:
specID, err := tx.insertBootstrapSpec(ctx, jb.BootstrapSpec)
if err != nil {
return fmt.Errorf("failed to create BootstrapSpec for jobSpec: %w", err)
}
jb.BootstrapSpecID = &specID
case Gateway:
specID, err := tx.insertGatewaySpec(ctx, jb.GatewaySpec)
if err != nil {
return fmt.Errorf("failed to create GatewaySpec for jobSpec: %w", err)
}
jb.GatewaySpecID = &specID
case Stream:
// 'stream' type has no associated spec, nothing to do here
case Workflow:
sql := `INSERT INTO workflow_specs (workflow, workflow_id, workflow_owner, workflow_name, created_at, updated_at)
VALUES (:workflow, :workflow_id, :workflow_owner, :workflow_name, NOW(), NOW())
RETURNING id;`
specID, err := tx.prepareQuerySpecID(ctx, sql, jb.WorkflowSpec)
if err != nil {
return fmt.Errorf("failed to create WorkflowSpec for jobSpec given %v: %w", *jb.WorkflowSpec, err)
}
jb.WorkflowSpecID = &specID
case StandardCapabilities:
sql := `INSERT INTO standardcapabilities_specs (command, config, created_at, updated_at)
VALUES (:command, :config, NOW(), NOW())
RETURNING id;`
specID, err := tx.prepareQuerySpecID(ctx, sql, jb.StandardCapabilitiesSpec)
if err != nil {
return errors.Wrap(err, "failed to create StandardCapabilities for jobSpec")
}
jb.StandardCapabilitiesSpecID = &specID
default:
o.lggr.Panicf("Unsupported jb.Type: %v", jb.Type)
}
pipelineSpecID, err := tx.pipelineORM.CreateSpec(ctx, p, jb.MaxTaskDuration)
if err != nil {
return errors.Wrap(err, "failed to create pipeline spec")
}
jb.PipelineSpecID = pipelineSpecID
err = tx.InsertJob(ctx, jb)
jobID = jb.ID
return errors.Wrap(err, "failed to insert job")
})
if err != nil {
return errors.Wrap(err, "CreateJobFailed")
}
return o.findJob(ctx, jb, "id", jobID)
}
func (o *orm) prepareQuerySpecID(ctx context.Context, sql string, arg any) (specID int32, err error) {
var stmt *sqlx.NamedStmt
stmt, err = o.ds.PrepareNamedContext(ctx, sql)
if err != nil {
return
}
defer stmt.Close()
err = stmt.QueryRowxContext(ctx, arg).Scan(&specID)
return
}
func (o *orm) insertDirectRequestSpec(ctx context.Context, spec *DirectRequestSpec) (specID int32, err error) {
return o.prepareQuerySpecID(ctx, `INSERT INTO direct_request_specs (contract_address, min_incoming_confirmations, requesters, min_contract_payment, evm_chain_id, created_at, updated_at)
VALUES (:contract_address, :min_incoming_confirmations, :requesters, :min_contract_payment, :evm_chain_id, now(), now())
RETURNING id;`, spec)
}
func (o *orm) insertFluxMonitorSpec(ctx context.Context, spec *FluxMonitorSpec) (specID int32, err error) {
return o.prepareQuerySpecID(ctx, `INSERT INTO flux_monitor_specs (contract_address, threshold, absolute_threshold, poll_timer_period, poll_timer_disabled, idle_timer_period, idle_timer_disabled,
drumbeat_schedule, drumbeat_random_delay, drumbeat_enabled, min_payment, evm_chain_id, created_at, updated_at)
VALUES (:contract_address, :threshold, :absolute_threshold, :poll_timer_period, :poll_timer_disabled, :idle_timer_period, :idle_timer_disabled,
:drumbeat_schedule, :drumbeat_random_delay, :drumbeat_enabled, :min_payment, :evm_chain_id, NOW(), NOW())
RETURNING id;`, spec)
}
func (o *orm) insertOCROracleSpec(ctx context.Context, spec *OCROracleSpec) (specID int32, err error) {
return o.prepareQuerySpecID(ctx, `INSERT INTO ocr_oracle_specs (contract_address, p2pv2_bootstrappers, is_bootstrap_peer, encrypted_ocr_key_bundle_id, transmitter_address,
observation_timeout, blockchain_timeout, contract_config_tracker_subscribe_interval, contract_config_tracker_poll_interval, contract_config_confirmations, evm_chain_id,
created_at, updated_at, database_timeout, observation_grace_period, contract_transmitter_transmit_timeout)
VALUES (:contract_address, :p2pv2_bootstrappers, :is_bootstrap_peer, :encrypted_ocr_key_bundle_id, :transmitter_address,
:observation_timeout, :blockchain_timeout, :contract_config_tracker_subscribe_interval, :contract_config_tracker_poll_interval, :contract_config_confirmations, :evm_chain_id,
NOW(), NOW(), :database_timeout, :observation_grace_period, :contract_transmitter_transmit_timeout)
RETURNING id;`, spec)
}
func (o *orm) insertOCR2OracleSpec(ctx context.Context, spec *OCR2OracleSpec) (specID int32, err error) {
return o.prepareQuerySpecID(ctx, `INSERT INTO ocr2_oracle_specs (contract_id, feed_id, relay, relay_config, plugin_type, plugin_config, onchain_signing_strategy, p2pv2_bootstrappers, ocr_key_bundle_id, transmitter_id,
blockchain_timeout, contract_config_tracker_poll_interval, contract_config_confirmations,
created_at, updated_at)
VALUES (:contract_id, :feed_id, :relay, :relay_config, :plugin_type, :plugin_config, :onchain_signing_strategy, :p2pv2_bootstrappers, :ocr_key_bundle_id, :transmitter_id,
:blockchain_timeout, :contract_config_tracker_poll_interval, :contract_config_confirmations,
NOW(), NOW())
RETURNING id;`, spec)
}
func (o *orm) insertKeeperSpec(ctx context.Context, spec *KeeperSpec) (specID int32, err error) {
return o.prepareQuerySpecID(ctx, `INSERT INTO keeper_specs (contract_address, from_address, evm_chain_id, created_at, updated_at)
VALUES (:contract_address, :from_address, :evm_chain_id, NOW(), NOW())
RETURNING id;`, spec)
}
func (o *orm) insertCronSpec(ctx context.Context, spec *CronSpec) (specID int32, err error) {
return o.prepareQuerySpecID(ctx, `INSERT INTO cron_specs (cron_schedule, evm_chain_id, created_at, updated_at)
VALUES (:cron_schedule, :evm_chain_id, NOW(), NOW())
RETURNING id;`, spec)
}
func (o *orm) insertVRFSpec(ctx context.Context, spec *VRFSpec) (specID int32, err error) {
return o.prepareQuerySpecID(ctx, `INSERT INTO vrf_specs (
coordinator_address, public_key, min_incoming_confirmations,
evm_chain_id, from_addresses, poll_period, requested_confs_delay,
request_timeout, chunk_size, batch_coordinator_address, batch_fulfillment_enabled,
batch_fulfillment_gas_multiplier, backoff_initial_delay, backoff_max_delay, gas_lane_price,
vrf_owner_address, custom_reverts_pipeline_enabled,
created_at, updated_at)
VALUES (
:coordinator_address, :public_key, :min_incoming_confirmations,
:evm_chain_id, :from_addresses, :poll_period, :requested_confs_delay,
:request_timeout, :chunk_size, :batch_coordinator_address, :batch_fulfillment_enabled,
:batch_fulfillment_gas_multiplier, :backoff_initial_delay, :backoff_max_delay, :gas_lane_price,
:vrf_owner_address, :custom_reverts_pipeline_enabled,
NOW(), NOW())
RETURNING id;`, toVRFSpecRow(spec))
}
func (o *orm) insertBlockhashStoreSpec(ctx context.Context, spec *BlockhashStoreSpec) (specID int32, err error) {
return o.prepareQuerySpecID(ctx, `INSERT INTO blockhash_store_specs (coordinator_v1_address, coordinator_v2_address, coordinator_v2_plus_address, trusted_blockhash_store_address, trusted_blockhash_store_batch_size, wait_blocks, lookback_blocks, heartbeat_period, blockhash_store_address, poll_period, run_timeout, evm_chain_id, from_addresses, created_at, updated_at)
VALUES (:coordinator_v1_address, :coordinator_v2_address, :coordinator_v2_plus_address, :trusted_blockhash_store_address, :trusted_blockhash_store_batch_size, :wait_blocks, :lookback_blocks, :heartbeat_period, :blockhash_store_address, :poll_period, :run_timeout, :evm_chain_id, :from_addresses, NOW(), NOW())
RETURNING id;`, toBlockhashStoreSpecRow(spec))
}
func (o *orm) insertBlockHeaderFeederSpec(ctx context.Context, spec *BlockHeaderFeederSpec) (specID int32, err error) {
return o.prepareQuerySpecID(ctx, `INSERT INTO block_header_feeder_specs (coordinator_v1_address, coordinator_v2_address, coordinator_v2_plus_address, wait_blocks, lookback_blocks, blockhash_store_address, batch_blockhash_store_address, poll_period, run_timeout, evm_chain_id, from_addresses, get_blockhashes_batch_size, store_blockhashes_batch_size, created_at, updated_at)
VALUES (:coordinator_v1_address, :coordinator_v2_address, :coordinator_v2_plus_address, :wait_blocks, :lookback_blocks, :blockhash_store_address, :batch_blockhash_store_address, :poll_period, :run_timeout, :evm_chain_id, :from_addresses, :get_blockhashes_batch_size, :store_blockhashes_batch_size, NOW(), NOW())
RETURNING id;`, toBlockHeaderFeederSpecRow(spec))
}
func (o *orm) insertLegacyGasStationServerSpec(ctx context.Context, spec *LegacyGasStationServerSpec) (specID int32, err error) {
return o.prepareQuerySpecID(ctx, `INSERT INTO legacy_gas_station_server_specs (forwarder_address, evm_chain_id, ccip_chain_selector, from_addresses, created_at, updated_at)
VALUES (:forwarder_address, :evm_chain_id, :ccip_chain_selector, :from_addresses, NOW(), NOW())
RETURNING id;`, toLegacyGasStationServerSpecRow(spec))
}
func (o *orm) insertLegacyGasStationSidecarSpec(ctx context.Context, spec *LegacyGasStationSidecarSpec) (specID int32, err error) {
return o.prepareQuerySpecID(ctx, `INSERT INTO legacy_gas_station_sidecar_specs (forwarder_address, off_ramp_address, lookback_blocks, poll_period, run_timeout, evm_chain_id, ccip_chain_selector, created_at, updated_at)
VALUES (:forwarder_address, :off_ramp_address, :lookback_blocks, :poll_period, :run_timeout, :evm_chain_id, :ccip_chain_selector, NOW(), NOW())
RETURNING id;`, spec)
}
func (o *orm) insertBootstrapSpec(ctx context.Context, spec *BootstrapSpec) (specID int32, err error) {
return o.prepareQuerySpecID(ctx, `INSERT INTO bootstrap_specs (contract_id, feed_id, relay, relay_config, monitoring_endpoint,
blockchain_timeout, contract_config_tracker_poll_interval,
contract_config_confirmations, created_at, updated_at)
VALUES (:contract_id, :feed_id, :relay, :relay_config, :monitoring_endpoint,
:blockchain_timeout, :contract_config_tracker_poll_interval,
:contract_config_confirmations, NOW(), NOW())
RETURNING id;`, spec)
}
func (o *orm) insertGatewaySpec(ctx context.Context, spec *GatewaySpec) (specID int32, err error) {
return o.prepareQuerySpecID(ctx, `INSERT INTO gateway_specs (gateway_config, created_at, updated_at)
VALUES (:gateway_config, NOW(), NOW())
RETURNING id;`, spec)
}
// ValidateKeyStoreMatch confirms that the key has a valid match in the keystore
func ValidateKeyStoreMatch(ctx context.Context, spec *OCR2OracleSpec, keyStore keystore.Master, key string) (err error) {
switch spec.PluginType {
case types.Mercury, types.LLO:
_, err = keyStore.CSA().Get(key)
if err != nil {
err = errors.Errorf("no CSA key matching: %q", key)
}
default:
err = validateKeyStoreMatchForRelay(ctx, spec.Relay, keyStore, key)
}
return
}
func validateKeyStoreMatchForRelay(ctx context.Context, network string, keyStore keystore.Master, key string) error {
switch network {
case relay.NetworkEVM:
_, err := keyStore.Eth().Get(ctx, key)
if err != nil {
return errors.Errorf("no EVM key matching: %q", key)
}
case relay.NetworkCosmos:
_, err := keyStore.Cosmos().Get(key)
if err != nil {
return errors.Errorf("no Cosmos key matching: %q", key)
}
case relay.NetworkSolana:
_, err := keyStore.Solana().Get(key)
if err != nil {
return errors.Errorf("no Solana key matching: %q", key)
}
case relay.NetworkStarkNet:
_, err := keyStore.StarkNet().Get(key)
if err != nil {
return errors.Errorf("no Starknet key matching: %q", key)
}
case relay.NetworkAptos:
_, err := keyStore.Aptos().Get(key)
if err != nil {
return errors.Errorf("no Aptos key matching: %q", key)
}
}
return nil
}
func areSendingKeysDefined(ctx context.Context, jb *Job, keystore keystore.Master) (bool, error) {
if jb.OCR2OracleSpec.RelayConfig["sendingKeys"] != nil {
sendingKeys, err := SendingKeysForJob(jb)
if err != nil {
return false, err
}
for _, sendingKey := range sendingKeys {
if err = ValidateKeyStoreMatch(ctx, jb.OCR2OracleSpec, keystore, sendingKey); err != nil {
return false, errors.Wrap(ErrNoSuchSendingKey, err.Error())
}
}
return true, nil
}
return false, nil
}
func (o *orm) InsertWebhookSpec(ctx context.Context, webhookSpec *WebhookSpec) error {
query, args, err := o.ds.BindNamed(`INSERT INTO webhook_specs (created_at, updated_at)
VALUES (NOW(), NOW())
RETURNING *;`, webhookSpec)
if err != nil {
return fmt.Errorf("error binding arg: %w", err)
}
return o.ds.GetContext(ctx, webhookSpec, query, args...)
}
func (o *orm) InsertJob(ctx context.Context, job *Job) error {
return o.transact(ctx, false, func(tx *orm) error {
var query string
// if job has id, emplace otherwise insert with a new id.
if job.ID == 0 {
query = `INSERT INTO jobs (name, stream_id, schema_version, type, max_task_duration, ocr_oracle_spec_id, ocr2_oracle_spec_id, direct_request_spec_id, flux_monitor_spec_id,
keeper_spec_id, cron_spec_id, vrf_spec_id, webhook_spec_id, blockhash_store_spec_id, bootstrap_spec_id, block_header_feeder_spec_id, gateway_spec_id,
legacy_gas_station_server_spec_id, legacy_gas_station_sidecar_spec_id, workflow_spec_id, standard_capabilities_spec_id, external_job_id, gas_limit, forwarding_allowed, created_at)
VALUES (:name, :stream_id, :schema_version, :type, :max_task_duration, :ocr_oracle_spec_id, :ocr2_oracle_spec_id, :direct_request_spec_id, :flux_monitor_spec_id,
:keeper_spec_id, :cron_spec_id, :vrf_spec_id, :webhook_spec_id, :blockhash_store_spec_id, :bootstrap_spec_id, :block_header_feeder_spec_id, :gateway_spec_id,
:legacy_gas_station_server_spec_id, :legacy_gas_station_sidecar_spec_id, :workflow_spec_id, :standard_capabilities_spec_id, :external_job_id, :gas_limit, :forwarding_allowed, NOW())
RETURNING *;`
} else {
query = `INSERT INTO jobs (id, name, stream_id, schema_version, type, max_task_duration, ocr_oracle_spec_id, ocr2_oracle_spec_id, direct_request_spec_id, flux_monitor_spec_id,
keeper_spec_id, cron_spec_id, vrf_spec_id, webhook_spec_id, blockhash_store_spec_id, bootstrap_spec_id, block_header_feeder_spec_id, gateway_spec_id,
legacy_gas_station_server_spec_id, legacy_gas_station_sidecar_spec_id, workflow_spec_id, standard_capabilities_spec_id, external_job_id, gas_limit, forwarding_allowed, created_at)
VALUES (:id, :name, :stream_id, :schema_version, :type, :max_task_duration, :ocr_oracle_spec_id, :ocr2_oracle_spec_id, :direct_request_spec_id, :flux_monitor_spec_id,
:keeper_spec_id, :cron_spec_id, :vrf_spec_id, :webhook_spec_id, :blockhash_store_spec_id, :bootstrap_spec_id, :block_header_feeder_spec_id, :gateway_spec_id,
:legacy_gas_station_server_spec_id, :legacy_gas_station_sidecar_spec_id, :workflow_spec_id, :standard_capabilities_spec_id, :external_job_id, :gas_limit, :forwarding_allowed, NOW())
RETURNING *;`
}
query, args, err := tx.ds.BindNamed(query, job)
if err != nil {
return fmt.Errorf("error binding arg: %w", err)
}
err = tx.ds.GetContext(ctx, job, query, args...)
if err != nil {
return err
}
// Always inserts the `job_pipeline_specs` record as primary, since this is the first one for the job.
sqlStmt := `INSERT INTO job_pipeline_specs (job_id, pipeline_spec_id, is_primary) VALUES ($1, $2, true)`
_, err = tx.ds.ExecContext(ctx, sqlStmt, job.ID, job.PipelineSpecID)
return errors.Wrap(err, "failed to insert job_pipeline_specs relationship")
})
}
// DeleteJob removes a job
func (o *orm) DeleteJob(ctx context.Context, id int32) error {
o.lggr.Debugw("Deleting job", "jobID", id)
// Added a 1-minute timeout to this query since this can take a long time as data increases.
// This was added specifically due to an issue with a database that had a million of pipeline_runs and pipeline_task_runs
// and this query was taking ~40secs.
ctx, cancel := context.WithTimeout(sqlutil.WithoutDefaultTimeout(ctx), time.Minute)
defer cancel()
query := `
WITH deleted_jobs AS (
DELETE FROM jobs WHERE id = $1 RETURNING
id,
ocr_oracle_spec_id,
ocr2_oracle_spec_id,
keeper_spec_id,
cron_spec_id,
flux_monitor_spec_id,
vrf_spec_id,
webhook_spec_id,
direct_request_spec_id,
blockhash_store_spec_id,
bootstrap_spec_id,
block_header_feeder_spec_id,
gateway_spec_id,
workflow_spec_id,
standard_capabilities_spec_id
),
deleted_oracle_specs AS (
DELETE FROM ocr_oracle_specs WHERE id IN (SELECT ocr_oracle_spec_id FROM deleted_jobs)
),
deleted_oracle2_specs AS (
DELETE FROM ocr2_oracle_specs WHERE id IN (SELECT ocr2_oracle_spec_id FROM deleted_jobs)
),
deleted_keeper_specs AS (
DELETE FROM keeper_specs WHERE id IN (SELECT keeper_spec_id FROM deleted_jobs)
),
deleted_cron_specs AS (
DELETE FROM cron_specs WHERE id IN (SELECT cron_spec_id FROM deleted_jobs)
),
deleted_fm_specs AS (
DELETE FROM flux_monitor_specs WHERE id IN (SELECT flux_monitor_spec_id FROM deleted_jobs)
),
deleted_vrf_specs AS (
DELETE FROM vrf_specs WHERE id IN (SELECT vrf_spec_id FROM deleted_jobs)
),
deleted_webhook_specs AS (
DELETE FROM webhook_specs WHERE id IN (SELECT webhook_spec_id FROM deleted_jobs)
),
deleted_dr_specs AS (
DELETE FROM direct_request_specs WHERE id IN (SELECT direct_request_spec_id FROM deleted_jobs)
),
deleted_blockhash_store_specs AS (
DELETE FROM blockhash_store_specs WHERE id IN (SELECT blockhash_store_spec_id FROM deleted_jobs)
),
deleted_bootstrap_specs AS (
DELETE FROM bootstrap_specs WHERE id IN (SELECT bootstrap_spec_id FROM deleted_jobs)
),
deleted_block_header_feeder_specs AS (
DELETE FROM block_header_feeder_specs WHERE id IN (SELECT block_header_feeder_spec_id FROM deleted_jobs)
),
deleted_gateway_specs AS (
DELETE FROM gateway_specs WHERE id IN (SELECT gateway_spec_id FROM deleted_jobs)
),
deleted_workflow_specs AS (
DELETE FROM workflow_specs WHERE id in (SELECT workflow_spec_id FROM deleted_jobs)
),
deleted_standardcapabilities_specs AS (
DELETE FROM standardcapabilities_specs WHERE id in (SELECT standard_capabilities_spec_id FROM deleted_jobs)
),
deleted_job_pipeline_specs AS (
DELETE FROM job_pipeline_specs WHERE job_id IN (SELECT id FROM deleted_jobs) RETURNING pipeline_spec_id
)
DELETE FROM pipeline_specs WHERE id IN (SELECT pipeline_spec_id FROM deleted_job_pipeline_specs)`
res, err := o.ds.ExecContext(ctx, query, id)
if err != nil {
return errors.Wrap(err, "DeleteJob failed to delete job")
}
rowsAffected, err := res.RowsAffected()
if err != nil {
return errors.Wrap(err, "DeleteJob failed getting RowsAffected")
}
if rowsAffected == 0 {
return sql.ErrNoRows
}
o.lggr.Debugw("Deleted job", "jobID", id)
return nil
}
func (o *orm) RecordError(ctx context.Context, jobID int32, description string) error {
sql := `INSERT INTO job_spec_errors (job_id, description, occurrences, created_at, updated_at)
VALUES ($1, $2, 1, $3, $3)
ON CONFLICT (job_id, description) DO UPDATE SET
occurrences = job_spec_errors.occurrences + 1,
updated_at = excluded.updated_at`
_, err := o.ds.ExecContext(ctx, sql, jobID, description, time.Now())
// Noop if the job has been deleted.
var pqErr *pgconn.PgError
ok := errors.As(err, &pqErr)
if err != nil && ok && pqErr.Code == "23503" {
if pqErr.ConstraintName == "job_spec_errors_v2_job_id_fkey" {
return nil
}
}
return err
}
func (o *orm) TryRecordError(ctx context.Context, jobID int32, description string) {
err := o.RecordError(ctx, jobID, description)
o.lggr.ErrorIf(err, fmt.Sprintf("Error creating SpecError %v", description))
}
func (o *orm) DismissError(ctx context.Context, ID int64) error {
res, err := o.ds.ExecContext(ctx, "DELETE FROM job_spec_errors WHERE id = $1", ID)
if err != nil {
return errors.Wrap(err, "failed to dismiss error")
}
n, err := res.RowsAffected()
if err != nil {
return errors.Wrap(err, "failed to dismiss error")
}
if n == 0 {
return sql.ErrNoRows
}
return nil
}
func (o *orm) FindSpecError(ctx context.Context, id int64) (SpecError, error) {
stmt := `SELECT * FROM job_spec_errors WHERE id = $1;`
specErr := new(SpecError)
err := o.ds.GetContext(ctx, specErr, stmt, id)
return *specErr, errors.Wrap(err, "FindSpecError failed")
}
func (o *orm) FindJobs(ctx context.Context, offset, limit int) (jobs []Job, count int, err error) {
err = o.transact(ctx, false, func(tx *orm) error {
sql := `SELECT count(*) FROM jobs;`
err = tx.ds.QueryRowxContext(ctx, sql).Scan(&count)
if err != nil {
return fmt.Errorf("failed to query jobs count: %w", err)
}
sql = `SELECT jobs.*, job_pipeline_specs.pipeline_spec_id as pipeline_spec_id
FROM jobs
JOIN job_pipeline_specs ON (jobs.id = job_pipeline_specs.job_id)
ORDER BY jobs.created_at DESC, jobs.id DESC OFFSET $1 LIMIT $2;`
err = tx.ds.SelectContext(ctx, &jobs, sql, offset, limit)
if err != nil {
return fmt.Errorf("failed to select jobs: %w", err)
}
err = tx.loadAllJobsTypes(ctx, jobs)
if err != nil {
return fmt.Errorf("failed to load job types: %w", err)
}
return nil
})
return jobs, count, err
}
func LoadDefaultVRFPollPeriod(vrfs VRFSpec) *VRFSpec {
if vrfs.PollPeriod == 0 {
vrfs.PollPeriod = 5 * time.Second
}
return &vrfs
}
// SetDRMinIncomingConfirmations takes the largest of the global vs specific.
func SetDRMinIncomingConfirmations(defaultMinIncomingConfirmations uint32, drs DirectRequestSpec) *DirectRequestSpec {
if !drs.MinIncomingConfirmations.Valid || drs.MinIncomingConfirmations.Uint32 < defaultMinIncomingConfirmations {
drs.MinIncomingConfirmations = null.Uint32From(defaultMinIncomingConfirmations)
}
return &drs
}
type OCRConfig interface {
BlockchainTimeout() time.Duration
CaptureEATelemetry() bool
ContractPollInterval() time.Duration
ContractSubscribeInterval() time.Duration
KeyBundleID() (string, error)
ObservationTimeout() time.Duration
TransmitterAddress() (evmtypes.EIP55Address, error)
}
// LoadConfigVarsLocalOCR loads local OCR vars into the OCROracleSpec.
func LoadConfigVarsLocalOCR(evmOcrCfg evmconfig.OCR, os OCROracleSpec, ocrCfg OCRConfig) *OCROracleSpec {
if os.ObservationTimeout == 0 {
os.ObservationTimeout = models.Interval(ocrCfg.ObservationTimeout())
}
if os.BlockchainTimeout == 0 {
os.BlockchainTimeout = models.Interval(ocrCfg.BlockchainTimeout())
}
if os.ContractConfigTrackerSubscribeInterval == 0 {
os.ContractConfigTrackerSubscribeInterval = models.Interval(ocrCfg.ContractSubscribeInterval())
}
if os.ContractConfigTrackerPollInterval == 0 {
os.ContractConfigTrackerPollInterval = models.Interval(ocrCfg.ContractPollInterval())
}
if os.ContractConfigConfirmations == 0 {
os.ContractConfigConfirmations = evmOcrCfg.ContractConfirmations()
}
if os.DatabaseTimeout == nil {
os.DatabaseTimeout = models.NewInterval(evmOcrCfg.DatabaseTimeout())
}
if os.ObservationGracePeriod == nil {
os.ObservationGracePeriod = models.NewInterval(evmOcrCfg.ObservationGracePeriod())
}
if os.ContractTransmitterTransmitTimeout == nil {
os.ContractTransmitterTransmitTimeout = models.NewInterval(evmOcrCfg.ContractTransmitterTransmitTimeout())
}
os.CaptureEATelemetry = ocrCfg.CaptureEATelemetry()
return &os
}
// LoadConfigVarsOCR loads OCR config vars into the OCROracleSpec.
func LoadConfigVarsOCR(evmOcrCfg evmconfig.OCR, ocrCfg OCRConfig, os OCROracleSpec) (*OCROracleSpec, error) {
if os.TransmitterAddress == nil {
ta, err := ocrCfg.TransmitterAddress()
if !errors.Is(errors.Cause(err), config.ErrEnvUnset) {
if err != nil {
return nil, err
}
os.TransmitterAddress = &ta
}
}
if os.EncryptedOCRKeyBundleID == nil {
kb, err := ocrCfg.KeyBundleID()
if err != nil {
return nil, err
}
encryptedOCRKeyBundleID, err := models.Sha256HashFromHex(kb)
if err != nil {
return nil, err
}
os.EncryptedOCRKeyBundleID = &encryptedOCRKeyBundleID
}
return LoadConfigVarsLocalOCR(evmOcrCfg, os, ocrCfg), nil
}
func (o *orm) FindJobTx(ctx context.Context, id int32) (Job, error) {
return o.FindJob(ctx, id)
}
// FindJob returns job by ID, with all relations preloaded
func (o *orm) FindJob(ctx context.Context, id int32) (jb Job, err error) {
err = o.findJob(ctx, &jb, "id", id)
return
}
// FindJobWithoutSpecErrors returns a job by ID, without loading Spec Errors preloaded
func (o *orm) FindJobWithoutSpecErrors(ctx context.Context, id int32) (jb Job, err error) {
err = o.transact(ctx, true, func(tx *orm) error {
stmt := "SELECT jobs.*, job_pipeline_specs.pipeline_spec_id as pipeline_spec_id FROM jobs JOIN job_pipeline_specs ON (jobs.id = job_pipeline_specs.job_id) WHERE jobs.id = $1 LIMIT 1"
err = tx.ds.GetContext(ctx, &jb, stmt, id)
if err != nil {
return errors.Wrap(err, "failed to load job")
}
if err = tx.loadAllJobTypes(ctx, &jb); err != nil {
return errors.Wrap(err, "failed to load job types")
}
return nil
})
if err != nil {
return jb, errors.Wrap(err, "FindJobWithoutSpecErrors failed")
}
return jb, nil
}
// FindSpecErrorsByJobIDs returns all jobs spec errors by jobs IDs
func (o *orm) FindSpecErrorsByJobIDs(ctx context.Context, ids []int32) ([]SpecError, error) {
stmt := `SELECT * FROM job_spec_errors WHERE job_id = ANY($1);`
var specErrs []SpecError
err := o.ds.SelectContext(ctx, &specErrs, stmt, ids)
return specErrs, errors.Wrap(err, "FindSpecErrorsByJobIDs failed")
}
func (o *orm) FindJobByExternalJobID(ctx context.Context, externalJobID uuid.UUID) (jb Job, err error) {
err = o.findJob(ctx, &jb, "external_job_id", externalJobID)
return
}
// FindJobIDByAddress - finds a job id by contract address. Currently only OCR and FM jobs are supported
func (o *orm) FindJobIDByAddress(ctx context.Context, address evmtypes.EIP55Address, evmChainID *big.Big) (jobID int32, err error) {
stmt := `
SELECT jobs.id
FROM jobs
LEFT JOIN ocr_oracle_specs ocrspec on ocrspec.contract_address = $1 AND (ocrspec.evm_chain_id = $2 OR ocrspec.evm_chain_id IS NULL) AND ocrspec.id = jobs.ocr_oracle_spec_id
LEFT JOIN flux_monitor_specs fmspec on fmspec.contract_address = $1 AND (fmspec.evm_chain_id = $2 OR fmspec.evm_chain_id IS NULL) AND fmspec.id = jobs.flux_monitor_spec_id
WHERE ocrspec.id IS NOT NULL OR fmspec.id IS NOT NULL
`
err = o.ds.GetContext(ctx, &jobID, stmt, address, evmChainID)
if err != nil {
if !errors.Is(err, sql.ErrNoRows) {
err = errors.Wrap(err, "error searching for job by contract address")
}
err = errors.Wrap(err, "FindJobIDByAddress failed")
return
}
return
}
func (o *orm) FindOCR2JobIDByAddress(ctx context.Context, contractID string, feedID *common.Hash) (jobID int32, err error) {
// NOTE: We want to explicitly match on NULL feed_id hence usage of `IS
// NOT DISTINCT FROM` instead of `=`
stmt := `
SELECT jobs.id
FROM jobs
LEFT JOIN ocr2_oracle_specs ocr2spec on ocr2spec.contract_id = $1 AND ocr2spec.feed_id IS NOT DISTINCT FROM $2 AND ocr2spec.id = jobs.ocr2_oracle_spec_id
LEFT JOIN bootstrap_specs bs on bs.contract_id = $1 AND bs.feed_id IS NOT DISTINCT FROM $2 AND bs.id = jobs.bootstrap_spec_id
WHERE ocr2spec.id IS NOT NULL OR bs.id IS NOT NULL