| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package rethinkdb |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "errors" |
| 8 | "time" |
| 9 | |
| 10 | "gopkg.in/rethinkdb/rethinkdb-go.v6" |
| 11 | ) |
| 12 | |
| 13 | type rdbConn interface { |
| 14 | stats() ([][]byte, error) |
| 15 | jobs(ctx context.Context) ([]map[string]any, error) |
| 16 | close() error |
| 17 | } |
| 18 | |
| 19 | func newRethinkdbConn(cfg Config) (rdbConn, error) { |
| 20 | sess, err := rethinkdb.Connect(rethinkdb.ConnectOpts{ |
| 21 | Address: cfg.Address, |
| 22 | Username: cfg.Username, |
| 23 | Password: cfg.Password, |
| 24 | }) |
| 25 | if err != nil { |
| 26 | return nil, err |
| 27 | } |
| 28 | |
| 29 | client := &rethinkdbClient{ |
| 30 | timeout: cfg.Timeout.Duration(), |
| 31 | sess: sess, |
| 32 | } |
| 33 | |
| 34 | return client, nil |
| 35 | } |
| 36 | |
| 37 | type rethinkdbClient struct { |
| 38 | timeout time.Duration |
| 39 | |
| 40 | sess *rethinkdb.Session |
| 41 | } |
| 42 | |
| 43 | func (c *rethinkdbClient) stats() ([][]byte, error) { |
| 44 | ctx, cancel := context.WithTimeout(context.Background(), c.timeout) |
| 45 | defer cancel() |
| 46 | |
| 47 | opts := rethinkdb.RunOpts{Context: ctx} |
| 48 | |
| 49 | cur, err := rethinkdb.DB("rethinkdb").Table("stats").Run(c.sess, opts) |
| 50 | if err != nil { |
| 51 | return nil, err |
| 52 | } |
| 53 | |
| 54 | if cur.IsNil() { |
| 55 | return nil, errors.New("no stats found (cursor is nil)") |
| 56 | } |
| 57 | defer func() { _ = cur.Close() }() |
| 58 | |
| 59 | var stats [][]byte |
| 60 | for { |
| 61 | bs, ok := cur.NextResponse() |
| 62 | if !ok { |
| 63 | break |
| 64 | } |
| 65 | stats = append(stats, bs) |
| 66 | } |
| 67 | |
| 68 | return stats, nil |
| 69 | } |
| 70 | |
| 71 | func (c *rethinkdbClient) jobs(ctx context.Context) ([]map[string]any, error) { |
| 72 | ctx, cancel := context.WithTimeout(ctx, c.timeout) |
| 73 | defer cancel() |
| 74 | |
| 75 | opts := rethinkdb.RunOpts{Context: ctx} |
| 76 | |
| 77 | cur, err := rethinkdb.DB("rethinkdb").Table("jobs").Run(c.sess, opts) |
| 78 | if err != nil { |
| 79 | return nil, err |
| 80 | } |
| 81 | |
| 82 | if cur.IsNil() { |
| 83 | return nil, errors.New("no jobs found (cursor is nil)") |
| 84 | } |
| 85 | defer func() { _ = cur.Close() }() |
| 86 | |
| 87 | var rows []map[string]any |
| 88 | if err := cur.All(&rows); err != nil { |
| 89 | return nil, err |
| 90 | } |
| 91 | |
| 92 | return rows, nil |
| 93 | } |
| 94 | |
| 95 | func (c *rethinkdbClient) close() (err error) { |
| 96 | return c.sess.Close() |
| 97 | } |