summaryrefslogtreecommitdiff
path: root/nexus/src/main/kotlin/tech/libeufin/nexus/db/InitiatedDAO.kt
blob: 4df7f0c9934073d45da36f8549e2a213284dcbcb (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
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
/*
 * This file is part of LibEuFin.
 * Copyright (C) 2024 Taler Systems S.A.

 * LibEuFin is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation; either version 3, or
 * (at your option) any later version.

 * LibEuFin is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General
 * Public License for more details.

 * You should have received a copy of the GNU Affero General Public
 * License along with LibEuFin; see the file COPYING.  If not, see
 * <http://www.gnu.org/licenses/>
 */

package tech.libeufin.nexus.db

import tech.libeufin.nexus.*
import tech.libeufin.common.*
import java.time.Instant
import java.sql.ResultSet

/** Data access logic for initiated outgoing payments */
class InitiatedDAO(private val db: Database) {

    /** Outgoing payments initiation result */
    enum class PaymentInitiationResult {
        REQUEST_UID_REUSE,
        SUCCESS
    }

    /** Register a new pending payment in the database */
    suspend fun create(paymentData: InitiatedPayment): PaymentInitiationResult = db.conn { conn ->
        val stmt = conn.prepareStatement("""
           INSERT INTO initiated_outgoing_transactions (
             amount
             ,wire_transfer_subject
             ,credit_payto_uri
             ,initiation_time
             ,request_uid
           ) VALUES ((?,?)::taler_amount,?,?,?,?)
        """)
        stmt.setLong(1, paymentData.amount.value)
        stmt.setInt(2, paymentData.amount.frac)
        stmt.setString(3, paymentData.wireTransferSubject)
        stmt.setString(4, paymentData.creditPaytoUri.toString())
        val initiationTime = paymentData.initiationTime.toDbMicros() ?: run {
            throw Exception("Initiation time could not be converted to microseconds for the database.")
        }
        stmt.setLong(5, initiationTime)
        stmt.setString(6, paymentData.requestUid)
        if (stmt.executeUpdateViolation())
            return@conn PaymentInitiationResult.SUCCESS
        return@conn PaymentInitiationResult.REQUEST_UID_REUSE
    }

    /** Register EBICS submission success */
    suspend fun submissionSuccess(
        id: Long,
        now: Instant,
        orderId: String
    ) = db.conn { conn ->
        val stmt = conn.prepareStatement("""
            UPDATE initiated_outgoing_transactions SET 
                 submitted = 'success'::submission_state
                ,last_submission_time = ?
                ,failure_message = NULL
                ,order_id = ?
                ,submission_counter = submission_counter + 1
            WHERE initiated_outgoing_transaction_id = ?
        """)
        stmt.setLong(1, now.toDbMicros()!!)
        stmt.setString(2, orderId)
        stmt.setLong(3, id)
        stmt.execute()
    }

    /** Register EBICS submission failure */
    suspend fun submissionFailure(
        id: Long,
        now: Instant,
        msg: String?
    ) = db.conn { conn ->
        val stmt = conn.prepareStatement("""
            UPDATE initiated_outgoing_transactions SET 
                 submitted = 'transient_failure'::submission_state
                ,last_submission_time = ?
                ,failure_message = ?
                ,submission_counter = submission_counter + 1
            WHERE initiated_outgoing_transaction_id = ?
        """)
        stmt.setLong(1, now.toDbMicros()!!)
        stmt.setString(2, msg)
        stmt.setLong(3, id)
        stmt.execute()
    }

    /** Register EBICS log status message */
    suspend fun logMessage(orderId: String, msg: String) = db.conn { conn ->
        val stmt = conn.prepareStatement("""
            UPDATE initiated_outgoing_transactions SET failure_message = ?
            WHERE order_id = ?
        """)
        stmt.setString(1, msg)
        stmt.setString(2, orderId)
        stmt.execute()
    }

    /** Register EBICS log success and return request_uid if found */
    suspend fun logSuccess(orderId: String): String? = db.conn { conn ->
        val stmt = conn.prepareStatement("""
            SELECT request_uid FROM initiated_outgoing_transactions
            WHERE order_id = ?
        """)
        stmt.setString(1, orderId)
        stmt.oneOrNull { it.getString(1) }
    }

    /** Register EBICS log failure and return request_uid and previous message if found */
    suspend fun logFailure(orderId: String): Pair<String, String?>? = db.conn { conn ->
        val stmt = conn.prepareStatement("""
            UPDATE initiated_outgoing_transactions 
                SET submitted = 'permanent_failure'::submission_state
            WHERE order_id = ?
            RETURNING request_uid, failure_message
        """)
        stmt.setString(1, orderId)
        stmt.oneOrNull { Pair(it.getString(1), it.getString(2)) }
    }

    /** Register bank status message */
    suspend fun bankMessage(requestUID: String, msg: String) = db.conn { conn ->
        val stmt = conn.prepareStatement("""
            UPDATE initiated_outgoing_transactions 
                SET failure_message = ?
            WHERE request_uid = ?
        """)
        stmt.setString(1, msg)
        stmt.setString(2, requestUID)
        stmt.execute()
    }

    /** Register bank failure */
    suspend fun bankFailure(requestUID: String, msg: String) = db.conn { conn ->
        val stmt = conn.prepareStatement("""
            UPDATE initiated_outgoing_transactions SET 
                 submitted = 'permanent_failure'::submission_state
                ,failure_message = ?
            WHERE request_uid = ?
        """)
        stmt.setString(1, msg)
        stmt.setString(2, requestUID)
        stmt.execute()
    }

    /** Register reversal */
    suspend fun reversal(requestUID: String, msg: String) = db.conn { conn ->
        val stmt = conn.prepareStatement("""
            UPDATE initiated_outgoing_transactions SET
                 submitted = 'permanent_failure'::submission_state
                ,failure_message = ?
            WHERE request_uid = ?
        """)
        stmt.setString(1, msg)
        stmt.setString(2, requestUID)
        stmt.execute()
    }

    /** List every initiated payment pending submission in ther order they should be submitted */
    suspend fun submittable(currency: String): List<InitiatedPayment> = db.conn { conn ->
        fun extract(it: ResultSet): InitiatedPayment {
            val rowId = it.getLong("initiated_outgoing_transaction_id")
            val initiationTime = it.getLong("initiation_time").microsToJavaInstant()
            if (initiationTime == null) { // nexus fault
                throw Exception("Found invalid timestamp at initiated payment with ID: $rowId")
            }
            return InitiatedPayment(
                id = it.getLong("initiated_outgoing_transaction_id"),
                amount = it.getAmount("amount", currency),
                creditPaytoUri = it.getString("credit_payto_uri"),
                wireTransferSubject = it.getString("wire_transfer_subject"),
                initiationTime = initiationTime,
                requestUid = it.getString("request_uid")
            )
        }
        val selectPart = """
            SELECT
                initiated_outgoing_transaction_id
                ,(amount).val as amount_val
                ,(amount).frac as amount_frac
                ,wire_transfer_subject
                ,credit_payto_uri
                ,initiation_time
                ,request_uid
            FROM initiated_outgoing_transactions
        """
        // We want to maximize the number of successfully submitted transactions in the event 
        // of a malformed transaction or a persistent error classified as transient. We send 
        // the unsubmitted transactions first, starting with the oldest by creation time.
        // This is the happy  path, giving every transaction a chance while being fair on the
        // basis of creation date. 
        // Then we retry the failed transaction, starting with the oldest by submission time.
        // This the bad path retrying each failed transaction applying a rotation based on 
        // resubmission time.
        val unsubmitted = conn.prepareStatement(
            "$selectPart WHERE submitted='unsubmitted' ORDER BY initiation_time"
        ).all(::extract)
        val failed = conn.prepareStatement(
            "$selectPart WHERE submitted='transient_failure' ORDER BY last_submission_time"
        ).all(::extract)
        unsubmitted + failed
    }
}