-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathsqliteCompute.ts
More file actions
377 lines (359 loc) · 11.5 KB
/
sqliteCompute.ts
File metadata and controls
377 lines (359 loc) · 11.5 KB
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
import { typesenseSchemas, TypesenseSchema } from './TypesenseSchemas.js'
import {
C2DStatusNumber,
C2DStatusText,
ComputeEnvironment,
type DBComputeJob
} from '../../@types/C2D/C2D.js'
import sqlite3, { RunResult } from 'sqlite3'
import { DATABASE_LOGGER } from '../../utils/logging/common.js'
import { createHash } from 'crypto'
interface ComputeDatabaseProvider {
newJob(job: DBComputeJob): Promise<string>
getJob(jobId?: string, agreementId?: string, owner?: string): Promise<DBComputeJob[]>
updateJob(job: DBComputeJob): Promise<number>
getRunningJobs(engine?: string, environment?: string): Promise<DBComputeJob[]>
deleteJob(jobId: string): Promise<boolean>
getFinishedJobs(): Promise<DBComputeJob[]>
}
export function generateUniqueID(jobStructure: any): string {
const timestamp =
BigInt(Date.now()) * 1_000_000n + (process.hrtime.bigint() % 1_000_000n)
const random = Math.random()
const jobId = createHash('sha256')
.update(JSON.stringify(jobStructure) + timestamp.toString() + random.toString())
.digest('hex')
return jobId
}
function getInternalStructure(job: DBComputeJob): any {
const internalBlob = {
clusterHash: job.clusterHash,
configlogURL: job.configlogURL,
publishlogURL: job.publishlogURL,
algologURL: job.algologURL,
outputsURL: job.outputsURL,
stopRequested: job.stopRequested,
algorithm: job.algorithm,
assets: job.assets,
isRunning: job.isRunning,
isStarted: job.isStarted,
containerImage: job.containerImage,
resources: job.resources,
isFree: job.isFree,
algoStartTimestamp: job.algoStartTimestamp,
algoStopTimestamp: job.algoStopTimestamp
}
return internalBlob
}
export function generateBlobFromJSON(job: DBComputeJob): Buffer {
return Buffer.from(JSON.stringify(getInternalStructure(job)))
}
export function generateJSONFromBlob(blob: any): Promise<any> {
return JSON.parse(blob.toString())
}
// we cannot store array of strings, so we use string separators instead
export const STRING_SEPARATOR = '__,__'
export function convertArrayToString(array: string[]) {
let str: string = ''
for (let i = 0; i < array.length; i++) {
str = str + array[i]
// Do not append comma at the end of last element
if (i < array.length - 1) {
str = str + STRING_SEPARATOR
}
}
return str
}
export function convertStringToArray(str: string) {
const arr: string[] = str.split(STRING_SEPARATOR)
return arr
}
export class SQLiteCompute implements ComputeDatabaseProvider {
private db: sqlite3.Database
private schema: TypesenseSchema
constructor(dbFilePath: string) {
this.db = new sqlite3.Database(dbFilePath)
this.schema = typesenseSchemas.c2dSchemas
}
deleteJob(jobId: string): Promise<boolean> {
const deleteSQL = `
DELETE FROM ${this.schema.name} WHERE jobId = ?
`
return new Promise<boolean>((resolve, reject) => {
this.db.run(deleteSQL, [jobId], function (this: RunResult, err) {
if (err) reject(err)
else resolve(this.changes === 1)
})
})
}
createTable() {
/* although we have field called expiteTimestamp, we are actually storing maxJobDuration in it */
const createTableSQL = `
CREATE TABLE IF NOT EXISTS ${this.schema.name} (
owner TEXT,
did TEXT DEFAULT NULL,
jobId TEXT PRIMARY KEY,
dateCreated TEXT,
dateFinished TEXT DEFAULT NULL,
status INTEGER,
statusText TEXT,
results BLOB,
inputDID TEXT DEFAULT NULL,
algoDID TEXT DEFAULT NULL,
agreementId TEXT DEFAULT NULL,
expireTimestamp INTEGER,
environment TEXT DEFAULT NULL,
body BLOB
);
`
return new Promise<void>((resolve, reject) => {
this.db.run(createTableSQL, (err) => {
if (err) reject(err)
else resolve()
})
})
}
newJob(job: DBComputeJob): Promise<string> {
// TO DO C2D
const insertSQL = `
INSERT INTO ${this.schema.name}
(
owner,
did,
jobId,
dateCreated,
status,
statusText,
inputDID,
algoDID,
agreementId,
expireTimestamp,
environment,
body
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
`
let jobId: string
if (!job.jobId) {
const jobStructure = {
assets: job.assets,
algorithm: job.algorithm,
output: {},
environment: job.environment,
owner: job.owner,
maxJobDuration: job.maxJobDuration,
chainId: job.payment?.chainId || null,
agreementId: job.agreementId,
resources: job.resources
}
jobId = generateUniqueID(jobStructure)
job.jobId = jobId
} else {
jobId = job.jobId
}
return new Promise<string>((resolve, reject) => {
this.db.run(
insertSQL,
[
job.owner,
job.did,
jobId,
job.dateCreated || String(Date.now() / 1000), // seconds from epoch,
job.status || C2DStatusNumber.JobStarted,
job.statusText || C2DStatusText.JobStarted,
job.inputDID ? convertArrayToString(job.inputDID) : job.inputDID,
job.algoDID,
job.agreementId,
job.maxJobDuration,
job.environment,
generateBlobFromJSON(job)
],
(err) => {
if (err) {
DATABASE_LOGGER.error('Could not insert C2D job on DB: ' + err.message)
reject(err)
} else {
DATABASE_LOGGER.info('Successfully inserted job with id:' + jobId)
resolve(jobId)
}
}
)
})
}
/**
* on a get status for instance, all params are optional
* but at least one is required... In case we don't have a jobId,
* we have multiple results (by owner for instance)
* So, it refines the query or we can have more than 1 result (same as current implementation)
* @param jobId the job identifier
* @param agreementId the agreement identifier (did ?)
* @param owner the consumer address / job owner
* @returns job(s)
*/
getJob(jobId?: string, agreementId?: string, owner?: string): Promise<DBComputeJob[]> {
const params: any = []
let selectSQL = `SELECT * FROM ${this.schema.name} WHERE 1=1`
if (jobId) {
selectSQL += ` AND jobId = ?`
params.push(jobId)
}
if (agreementId) {
if (!agreementId.startsWith('0x')) {
agreementId = '0x' + agreementId
}
selectSQL += ` AND agreementId = ?`
params.push(agreementId)
}
if (owner) {
selectSQL += ` AND owner = ?`
params.push(owner)
}
return new Promise<DBComputeJob[]>((resolve, reject) => {
this.db.all(selectSQL, params, (err, rows: any[] | undefined) => {
if (err) {
DATABASE_LOGGER.error(err.message)
reject(err)
} else {
// also decode the internal data into job data
if (rows && rows.length > 0) {
const all: DBComputeJob[] = rows.map((row) => {
const body = generateJSONFromBlob(row.body)
delete row.body
const maxJobDuration = row.expireTimestamp
delete row.expireTimestamp
const job: DBComputeJob = { ...row, ...body, maxJobDuration }
return job
})
resolve(all)
} else {
DATABASE_LOGGER.error(
`Could not find any job with jobId: ${jobId}, agreementId: ${agreementId}, or owner: ${owner} in database!`
)
resolve([])
}
}
})
})
}
updateJob(job: DBComputeJob): Promise<number> {
// if (job.dateFinished && job.isRunning) {
// job.isRunning = false
// }
// TO DO C2D
const data: any[] = [
job.owner,
job.status,
job.statusText,
job.maxJobDuration,
generateBlobFromJSON(job),
job.dateFinished,
job.jobId
]
const updateSQL = `
UPDATE ${this.schema.name}
SET
owner = ?,
status = ?,
statusText = ?,
expireTimestamp = ?,
body = ?,
dateFinished = ?
WHERE jobId = ?;
`
return new Promise((resolve, reject) => {
this.db.run(updateSQL, data, function (this: RunResult, err: Error | null) {
if (err) {
DATABASE_LOGGER.error(`Error while updating job: ${err.message}`)
reject(err)
} else {
// number of rows updated successfully
resolve(this.changes)
}
})
})
}
getRunningJobs(engine?: string, environment?: string): Promise<DBComputeJob[]> {
const selectSQL = `
SELECT * FROM ${this.schema.name} WHERE dateFinished IS NULL
`
return new Promise<DBComputeJob[]>((resolve, reject) => {
this.db.all(selectSQL, (err, rows: any[] | undefined) => {
if (err) {
DATABASE_LOGGER.error(err.message)
reject(err)
} else {
// also decode the internal data into job data
// get them all running
if (rows && rows.length > 0) {
const all: DBComputeJob[] = rows.map((row) => {
const body = generateJSONFromBlob(row.body)
delete row.body
const maxJobDuration = row.expireTimestamp
delete row.expireTimestamp
const job: DBComputeJob = { ...row, ...body, maxJobDuration }
return job
})
// filter them out
const filtered = all.filter((job) => {
let include = true
if (engine && engine !== job.clusterHash) {
include = false
}
if (environment && environment !== job.environment) {
include = false
}
if (job.dateFinished) {
include = false
}
return include
})
resolve(filtered)
} else {
DATABASE_LOGGER.info('Could not find any running C2D jobs!')
resolve([])
}
}
})
})
}
getFinishedJobs(environment?: ComputeEnvironment): Promise<DBComputeJob[]> {
// get jobs that already finished (have results), for this environment, and clear storage + job if expired
const selectSQL = `
SELECT * FROM ${this.schema.name} WHERE environment = ? AND dateFinished IS NOT NULL OR results IS NOT NULL
`
return new Promise<DBComputeJob[]>((resolve, reject) => {
this.db.all(selectSQL, [environment.id], (err, rows: any[] | undefined) => {
if (err) {
DATABASE_LOGGER.error(err.message)
reject(err)
} else {
// also decode the internal data into job data
// get them all running
if (rows && rows.length > 0) {
const all: DBComputeJob[] = rows.map((row) => {
const body = generateJSONFromBlob(row.body)
delete row.body
const maxJobDuration = row.expireTimestamp
delete row.expireTimestamp
const job: DBComputeJob = { ...row, ...body, maxJobDuration }
return job
})
if (!environment) {
resolve(all)
}
// filter them out
const filtered = all.filter((job) => {
return environment && environment.id === job.environment
})
resolve(filtered)
} else {
DATABASE_LOGGER.info(
'Could not find any jobs for the specified enviroment: ' + environment.id
)
resolve([])
}
}
})
})
}
}