aboutsummaryrefslogtreecommitdiff
path: root/relayapi/storage/shared/storage.go
blob: 456158caa0cfbd3c63a1618ab93dc227cae0bdab (plain)
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
// Copyright 2024 New Vector Ltd.
// Copyright 2022 The Matrix.org Foundation C.I.C.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
// Please see LICENSE files in the repository root for full details.

package shared

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

	"github.com/element-hq/dendrite/federationapi/storage/shared/receipt"
	"github.com/element-hq/dendrite/internal/caching"
	"github.com/element-hq/dendrite/internal/sqlutil"
	"github.com/element-hq/dendrite/relayapi/storage/tables"
	"github.com/matrix-org/gomatrixserverlib"
	"github.com/matrix-org/gomatrixserverlib/spec"
)

type Database struct {
	DB                *sql.DB
	IsLocalServerName func(spec.ServerName) bool
	Cache             caching.FederationCache
	Writer            sqlutil.Writer
	RelayQueue        tables.RelayQueue
	RelayQueueJSON    tables.RelayQueueJSON
}

func (d *Database) StoreTransaction(
	ctx context.Context,
	transaction gomatrixserverlib.Transaction,
) (*receipt.Receipt, error) {
	var err error
	jsonTransaction, err := json.Marshal(transaction)
	if err != nil {
		return nil, fmt.Errorf("failed to marshal: %w", err)
	}

	var nid int64
	_ = d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error {
		nid, err = d.RelayQueueJSON.InsertQueueJSON(ctx, txn, string(jsonTransaction))
		return err
	})
	if err != nil {
		return nil, fmt.Errorf("d.insertQueueJSON: %w", err)
	}

	newReceipt := receipt.NewReceipt(nid)
	return &newReceipt, nil
}

func (d *Database) AssociateTransactionWithDestinations(
	ctx context.Context,
	destinations map[spec.UserID]struct{},
	transactionID gomatrixserverlib.TransactionID,
	dbReceipt *receipt.Receipt,
) error {
	err := d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error {
		var lastErr error
		for destination := range destinations {
			destination := destination
			err := d.RelayQueue.InsertQueueEntry(
				ctx,
				txn,
				transactionID,
				destination.Domain(),
				dbReceipt.GetNID(),
			)
			if err != nil {
				lastErr = fmt.Errorf("d.insertQueueEntry: %w", err)
			}
		}
		return lastErr
	})

	return err
}

func (d *Database) CleanTransactions(
	ctx context.Context,
	userID spec.UserID,
	receipts []*receipt.Receipt,
) error {
	nids := make([]int64, len(receipts))
	for i, dbReceipt := range receipts {
		nids[i] = dbReceipt.GetNID()
	}

	err := d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error {
		deleteEntryErr := d.RelayQueue.DeleteQueueEntries(ctx, txn, userID.Domain(), nids)
		// TODO : If there are still queue entries for any of these nids for other destinations
		// then we shouldn't delete the json entries.
		// But this can't happen with the current api design.
		// There will only ever be one server entry for each nid since each call to send_relay
		// only accepts a single server name and inside there we create a new json entry.
		// So for multiple destinations we would call send_relay multiple times and have multiple
		// json entries of the same transaction.
		//
		// TLDR; this works as expected right now but can easily be optimised in the future.
		deleteJSONErr := d.RelayQueueJSON.DeleteQueueJSON(ctx, txn, nids)

		if deleteEntryErr != nil {
			return fmt.Errorf("d.deleteQueueEntries: %w", deleteEntryErr)
		}
		if deleteJSONErr != nil {
			return fmt.Errorf("d.deleteQueueJSON: %w", deleteJSONErr)
		}
		return nil
	})

	return err
}

func (d *Database) GetTransaction(
	ctx context.Context,
	userID spec.UserID,
) (*gomatrixserverlib.Transaction, *receipt.Receipt, error) {
	entriesRequested := 1
	nids, err := d.RelayQueue.SelectQueueEntries(ctx, nil, userID.Domain(), entriesRequested)
	if err != nil {
		return nil, nil, fmt.Errorf("d.SelectQueueEntries: %w", err)
	}
	if len(nids) == 0 {
		return nil, nil, nil
	}
	firstNID := nids[0]

	txns := map[int64][]byte{}
	err = d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error {
		txns, err = d.RelayQueueJSON.SelectQueueJSON(ctx, txn, nids)
		return err
	})
	if err != nil {
		return nil, nil, fmt.Errorf("d.SelectQueueJSON: %w", err)
	}

	transaction := &gomatrixserverlib.Transaction{}
	if _, ok := txns[firstNID]; !ok {
		return nil, nil, fmt.Errorf("Failed retrieving json blob for transaction: %d", firstNID)
	}

	err = json.Unmarshal(txns[firstNID], transaction)
	if err != nil {
		return nil, nil, fmt.Errorf("Unmarshal transaction: %w", err)
	}

	newReceipt := receipt.NewReceipt(firstNID)
	return transaction, &newReceipt, nil
}

func (d *Database) GetTransactionCount(
	ctx context.Context,
	userID spec.UserID,
) (int64, error) {
	count, err := d.RelayQueue.SelectQueueEntryCount(ctx, nil, userID.Domain())
	if err != nil {
		return 0, fmt.Errorf("d.SelectQueueEntryCount: %w", err)
	}
	return count, nil
}