summaryrefslogtreecommitdiff
path: root/nexus/src/main/kotlin/tech/libeufin/nexus/Scheduling.kt
blob: 51f5285c40373278889857ef726dc4d70d6968b2 (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
/*
 * This file is part of LibEuFin.
 * Copyright (C) 2020 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

import com.cronutils.model.definition.CronDefinitionBuilder
import com.cronutils.model.time.ExecutionTime
import com.cronutils.parser.CronParser
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import io.ktor.client.HttpClient
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.time.delay
import org.jetbrains.exposed.sql.transactions.transaction
import tech.libeufin.nexus.bankaccount.fetchBankAccountTransactions
import tech.libeufin.nexus.bankaccount.submitAllPaymentInitiations
import tech.libeufin.nexus.server.FetchSpecJson
import tech.libeufin.util.getNow
import java.lang.IllegalArgumentException
import java.time.Duration
import java.time.Instant
import java.time.ZonedDateTime

// tick duration in milliseconds.
private var tick: Long = 1000

fun setTick(millis: Long) {
    tick = millis
}

fun getTick(): Long {
    return tick
}

private data class TaskSchedule(
    val taskId: Long,
    val name: String,
    val type: String,
    val resourceType: String,
    val resourceId: String,
    val params: String
)

private suspend fun runTask(client: HttpClient, sched: TaskSchedule) {
    logger.info("running task $sched")
    try {
        when (sched.resourceType) {
            "bank-account" -> {
                when (sched.type) {
                    "fetch" -> {
                        @Suppress("BlockingMethodInNonBlockingContext")
                        val fetchSpec = jacksonObjectMapper().readValue(sched.params, FetchSpecJson::class.java)
                        fetchBankAccountTransactions(client, fetchSpec, sched.resourceId)
                    }
                    "submit" -> {
                        submitAllPaymentInitiations(client, sched.resourceId)
                    }
                    else -> {
                        logger.error("task type ${sched.type} not understood")
                    }
                }
            }
            else -> logger.error("task on resource ${sched.resourceType} not understood")
        }
    } catch (e: Exception) {
        logger.error("Exception during task $sched", e)
    }
}

object NexusCron {
    val parser = run {
        val cronDefinition =
            CronDefinitionBuilder.defineCron()
                .withSeconds().and()
                .withMinutes().and()
                .withHours().and()
                .withDayOfMonth().optional().and()
                .withMonth().optional().and()
                .withDayOfWeek().optional()
                .and().instance()
        CronParser(cronDefinition)
    }
}

fun startOperationScheduler(httpClient: HttpClient) {
    GlobalScope.launch {
        while (true) {
            logger.trace("running schedule loop")

            // First, assign next execution time stamps to all tasks that need them
            transaction {
                NexusScheduledTaskEntity.find {
                    NexusScheduledTasksTable.nextScheduledExecutionSec.isNull()
                }.forEach {
                    val cron = try {
                        NexusCron.parser.parse(it.taskCronspec)
                    } catch (e: IllegalArgumentException) {
                        logger.error("invalid cronspec in schedule ${it.resourceType}/${it.resourceId}/${it.taskName}")
                        return@forEach
                    }
                    val zonedNow = getNow()
                    val et = ExecutionTime.forCron(cron)
                    val next = et.nextExecution(zonedNow)
                    logger.info("scheduling task ${it.taskName} at $next (now is $zonedNow)")
                    it.nextScheduledExecutionSec = next.get().toEpochSecond()
                }
            }

            val nowSec = getNow().toEpochSecond()
            // Second, find tasks that are due
            val dueTasks = transaction {
                NexusScheduledTaskEntity.find {
                    NexusScheduledTasksTable.nextScheduledExecutionSec lessEq nowSec
                }.map {
                    TaskSchedule(it.id.value, it.taskName, it.taskType, it.resourceType, it.resourceId, it.taskParams)
                }
            }

            // Execute those due tasks
            dueTasks.forEach {
                runTask(httpClient, it)
                transaction {
                    val t = NexusScheduledTaskEntity.findById(it.taskId)
                    if (t != null) {
                        // Reset next scheduled execution
                        t.nextScheduledExecutionSec = null
                        t.prevScheduledExecutionSec = nowSec
                        t.iterations++
                    }
                }
            }

            // Wait a bit
            delay(Duration.ofMillis(tick))
        }
    }
}