-
Notifications
You must be signed in to change notification settings - Fork 199
/
ContractsFetch.scala
414 lines (381 loc) · 14.8 KB
/
ContractsFetch.scala
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
// Copyright (c) 2021 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package com.daml.http
import akka.stream.scaladsl.{Flow, GraphDSL, Keep, RunnableGraph, Sink, Source}
import akka.stream.{ClosedShape, FanOutShape2, Materializer}
import com.daml.http.dbbackend.{ContractDao, SupportedJdbcDriver}
import com.daml.http.dbbackend.Queries.{DBContract, SurrogateTpId}
import com.daml.http.domain.TemplateId
import com.daml.http.LedgerClientJwt.Terminates
import com.daml.http.util.ApiValueToLfValueConverter.apiValueToLfValue
import com.daml.http.json.JsonProtocol.LfValueDatabaseCodec.{
apiValueToJsValue => lfValueToDbJsValue
}
import com.daml.http.util.Logging.{InstanceUUID}
import com.daml.fetchcontracts.util.{
AbsoluteBookmark,
BeginBookmark,
ContractStreamStep,
InsertDeleteStep,
LedgerBegin,
}
import com.daml.scalautil.ExceptionOps._
import com.daml.scalautil.nonempty.NonEmpty
import com.daml.jwt.domain.Jwt
import com.daml.ledger.api.{v1 => lav1}
import com.daml.logging.{ContextualizedLogger, LoggingContextOf}
import doobie.free.{connection => fconn}
import fconn.ConnectionIO
import scalaz.std.vector._
import scalaz.std.list._
import scalaz.std.option.none
import scalaz.syntax.show._
import scalaz.syntax.tag._
import scalaz.syntax.functor._
import scalaz.syntax.foldable._
import scalaz.syntax.order._
import scalaz.syntax.std.option._
import scalaz.\/
import spray.json.{JsNull, JsValue}
import scala.concurrent.ExecutionContext
import com.daml.ledger.api.{domain => LedgerApiDomain}
private class ContractsFetch(
getActiveContracts: LedgerClientJwt.GetActiveContracts,
getCreatesAndArchivesSince: LedgerClientJwt.GetCreatesAndArchivesSince,
getTermination: LedgerClientJwt.GetTermination,
)(implicit dblog: doobie.LogHandler, sjd: SupportedJdbcDriver.TC) {
import ContractsFetch._
import com.daml.fetchcontracts.AcsTxStreams._
import com.daml.fetchcontracts.util.AkkaStreamsDoobie.{connectionIOFuture, sinkCioSequence_}
import sjd.retrySqlStates
private[this] val logger = ContextualizedLogger.get(getClass)
/** run `within` repeatedly after fetchAndPersist until the latter is
* consistent before and after `within`
*/
def fetchAndPersistBracket[A](
jwt: Jwt,
ledgerId: LedgerApiDomain.LedgerId,
parties: domain.PartySet,
templateIds: List[domain.TemplateId.RequiredPkg],
)(within: BeginBookmark[Terminates.AtAbsolute] => ConnectionIO[A])(implicit
ec: ExecutionContext,
mat: Materializer,
lc: LoggingContextOf[InstanceUUID],
): ConnectionIO[A] = {
import ContractDao.laggingOffsets
val initTries = 10
val fetchContext = FetchContext(jwt, ledgerId, parties)
def go(
maxAttempts: Int,
fetchTemplateIds: List[domain.TemplateId.RequiredPkg],
absEnd: Terminates.AtAbsolute,
): ConnectionIO[A] = for {
bb <- fetchToAbsEnd(fetchContext, fetchTemplateIds, absEnd)
a <- within(bb)
// fetchTemplateIds can be a subset of templateIds (or even empty),
// but we only get away with that by checking _all_ of templateIds,
// which can then indicate that a larger set than fetchTemplateIds
// has desynchronized
lagging <- (templateIds.toSet, bb.map(_.toDomain)) match {
case (NonEmpty(tids), AbsoluteBookmark(expectedOff)) =>
laggingOffsets(parties, expectedOff, tids)
case _ => fconn.pure(none[(domain.Offset, Set[domain.TemplateId.RequiredPkg])])
}
retriedA <- lagging.cata(
{ case (newOff, laggingTids) =>
if (maxAttempts > 1)
go(
maxAttempts - 1,
laggingTids.toList,
Terminates fromDomain newOff,
)
else
fconn.raiseError(
new IllegalStateException(
s"failed after $initTries attempts to synchronize database for $fetchContext, $templateIds"
)
)
},
fconn.pure(a),
)
} yield retriedA
// we assume that if the ledger termination is LedgerBegin, then
// `within` will not yield concurrency-relevant results
connectionIOFuture(getTermination(jwt, ledgerId)) flatMap {
_.cata(go(initTries, templateIds, _), within(LedgerBegin))
}
}
def fetchAndPersist(
jwt: Jwt,
ledgerId: LedgerApiDomain.LedgerId,
parties: domain.PartySet,
templateIds: List[domain.TemplateId.RequiredPkg],
)(implicit
ec: ExecutionContext,
mat: Materializer,
lc: LoggingContextOf[InstanceUUID],
): ConnectionIO[BeginBookmark[Terminates.AtAbsolute]] =
connectionIOFuture(getTermination(jwt, ledgerId)) flatMap {
_.cata(
fetchToAbsEnd(FetchContext(jwt, ledgerId, parties), templateIds, _),
fconn.pure(LedgerBegin),
)
}
private[this] def fetchToAbsEnd(
fetchContext: FetchContext,
templateIds: List[domain.TemplateId.RequiredPkg],
absEnd: Terminates.AtAbsolute,
)(implicit
ec: ExecutionContext,
mat: Materializer,
lc: LoggingContextOf[InstanceUUID],
): ConnectionIO[BeginBookmark[Terminates.AtAbsolute]] = {
import cats.instances.list._, cats.syntax.foldable.{toFoldableOps => ToFoldableOps},
cats.syntax.traverse.{toTraverseOps => ToTraverseOps}, cats.syntax.functor._, doobie.implicits._
// we can fetch for all templateIds on a single acsFollowingAndBoundary
// by comparing begin offsets; however this is trickier so we don't do it
// right now -- Stephen / Leo
//
// traverse once, use the max _returned_ bookmark,
// re-traverse any that != the max returned bookmark (overriding lastOffset)
// fetch cannot go "too far" the second time
templateIds
.traverse(fetchAndPersist(fetchContext, false, absEnd, _))
.flatMap { actualAbsEnds =>
val newAbsEndTarget = {
import scalaz.std.list._, scalaz.syntax.foldable._, domain.Offset.`Offset ordering`
// it's fine if all yielded LedgerBegin, so we don't want to conflate the "fallback"
// with genuine results
actualAbsEnds.maximum getOrElse AbsoluteBookmark(absEnd.toDomain)
}
newAbsEndTarget match {
case LedgerBegin =>
fconn.pure(AbsoluteBookmark(absEnd))
case AbsoluteBookmark(feedback) =>
val feedbackTerminator = Terminates fromDomain feedback
// contractsFromOffsetIo can go _past_ absEnd, because the ACS ignores
// this argument; see https://github.com/digital-asset/daml/pull/8226#issuecomment-756446537
// for an example of this happening. We deal with this race condition
// by detecting that it has happened and rerunning any other template IDs
// to "catch them up" to the one that "raced" ahead
(actualAbsEnds zip templateIds)
.collect { case (`newAbsEndTarget`, templateId) => templateId }
.traverse_ {
// passing a priorBookmark prevents contractsIo_ from using the ACS,
// and it cannot go "too far" reading only the tx stream
fetchAndPersist(
fetchContext,
true,
feedbackTerminator,
_,
)
}
.as(AbsoluteBookmark(feedbackTerminator))
}
}
}
private[this] def fetchAndPersist(
fetchContext: FetchContext,
disableAcs: Boolean,
absEnd: Terminates.AtAbsolute,
templateId: domain.TemplateId.RequiredPkg,
)(implicit
ec: ExecutionContext,
mat: Materializer,
lc: LoggingContextOf[InstanceUUID],
): ConnectionIO[BeginBookmark[domain.Offset]] = {
import doobie.implicits._, cats.syntax.apply._
def loop(maxAttempts: Int): ConnectionIO[BeginBookmark[domain.Offset]] = {
logger.debug(s"contractsIo, maxAttempts: $maxAttempts")
(contractsIo_(fetchContext, disableAcs, absEnd, templateId) <* fconn.commit)
.exceptSql {
case e if maxAttempts > 0 && retrySqlStates(e.getSQLState) =>
logger.debug(s"contractsIo, exception: ${e.description}, state: ${e.getSQLState}")
fconn.rollback flatMap (_ => loop(maxAttempts - 1))
case e @ _ =>
logger.error(s"contractsIo3 exception: ${e.description}, state: ${e.getSQLState}")
fconn.raiseError(e)
}
}
loop(5)
}
private def contractsIo_(
fetchContext: FetchContext,
disableAcs: Boolean,
absEnd: Terminates.AtAbsolute,
templateId: domain.TemplateId.RequiredPkg,
)(implicit
ec: ExecutionContext,
mat: Materializer,
lc: LoggingContextOf[InstanceUUID],
): ConnectionIO[BeginBookmark[domain.Offset]] = {
import fetchContext.parties
for {
offsets <- ContractDao.lastOffset(parties, templateId)
offset1 <- contractsFromOffsetIo(
fetchContext,
templateId,
offsets,
disableAcs,
absEnd,
)
_ = logger.debug(
s"contractsFromOffsetIo($fetchContext, $templateId, $offsets, $disableAcs, $absEnd): $offset1"
)
} yield offset1
}
private def prepareCreatedEventStorage(
ce: lav1.event.CreatedEvent
): Exception \/ PreInsertContract = {
import scalaz.syntax.traverse._
import scalaz.std.option._
import com.daml.lf.crypto.Hash
for {
ac <- domain.ActiveContract fromLedgerApi ce leftMap (de =>
new IllegalArgumentException(s"contract ${ce.contractId}: ${de.shows}"): Exception
)
lfKey <- ac.key.traverse(apiValueToLfValue).leftMap(_.cause: Exception)
lfArg <- apiValueToLfValue(ac.payload) leftMap (_.cause: Exception)
} yield DBContract(
contractId = ac.contractId.unwrap,
templateId = ac.templateId,
key = lfKey.cata(lfValueToDbJsValue, JsNull),
keyHash = lfKey.map(
Hash
.assertHashContractKey(TemplateId.toLedgerApiValue(ac.templateId), _)
.toHexString
),
payload = lfValueToDbJsValue(lfArg),
signatories = ac.signatories,
observers = ac.observers,
agreementText = ac.agreementText,
)
}
private def jsonifyInsertDeleteStep(
a: InsertDeleteStep[Any, lav1.event.CreatedEvent]
): InsertDeleteStep[Unit, PreInsertContract] =
a.leftMap(_ => ())
.mapPreservingIds(prepareCreatedEventStorage(_) valueOr (e => throw e))
private def contractsFromOffsetIo(
fetchContext: FetchContext,
templateId: domain.TemplateId.RequiredPkg,
offsets: Map[domain.Party, domain.Offset],
disableAcs: Boolean,
absEnd: Terminates.AtAbsolute,
)(implicit
ec: ExecutionContext,
mat: Materializer,
lc: LoggingContextOf[InstanceUUID],
): ConnectionIO[BeginBookmark[domain.Offset]] = {
import domain.Offset._, fetchContext.{jwt, ledgerId, parties}
val startOffset = offsets.values.toList.minimum.cata(AbsoluteBookmark(_), LedgerBegin)
val graph = RunnableGraph.fromGraph(
GraphDSL.create(
Sink.queue[ConnectionIO[Unit]](),
Sink.last[BeginBookmark[String]],
)(Keep.both) { implicit builder => (acsSink, offsetSink) =>
import GraphDSL.Implicits._
val txnK = getCreatesAndArchivesSince(
jwt,
ledgerId,
transactionFilter(parties, List(templateId)),
_: lav1.ledger_offset.LedgerOffset,
absEnd,
)
// include ACS iff starting at LedgerBegin
val (idses, lastOff) = (startOffset, disableAcs) match {
case (LedgerBegin, false) =>
val stepsAndOffset = builder add acsFollowingAndBoundary(txnK)
stepsAndOffset.in <~ getActiveContracts(
jwt,
ledgerId,
transactionFilter(parties, List(templateId)),
true,
)
(stepsAndOffset.out0, stepsAndOffset.out1)
case (AbsoluteBookmark(_), _) | (LedgerBegin, true) =>
val stepsAndOffset = builder add transactionsFollowingBoundary(txnK)
stepsAndOffset.in <~ Source.single(domain.Offset.tag.unsubst(startOffset))
(
(stepsAndOffset: FanOutShape2[_, ContractStreamStep.LAV1, _]).out0,
stepsAndOffset.out1,
)
}
val transactInsertsDeletes = Flow
.fromFunction(jsonifyInsertDeleteStep)
.conflate(_ append _)
.map(insertAndDelete)
idses.map(_.toInsertDelete) ~> transactInsertsDeletes ~> acsSink
lastOff ~> offsetSink
ClosedShape
}
)
val (acsQueue, lastOffsetFuture) = graph.run()
for {
_ <- sinkCioSequence_(acsQueue)
offset0 <- connectionIOFuture(lastOffsetFuture)
offsetOrError <- (domain.Offset.tag.subst(offset0) max AbsoluteBookmark(
absEnd.toDomain
)) match {
case ab @ AbsoluteBookmark(newOffset) =>
ContractDao
.updateOffset(parties, templateId, newOffset, offsets)
.map(_ => ab)
case LedgerBegin =>
fconn.pure(LedgerBegin)
}
} yield offsetOrError
}
}
private[http] object ContractsFetch {
type PreInsertContract = DBContract[TemplateId.RequiredPkg, JsValue, JsValue, Seq[domain.Party]]
private def surrogateTemplateIds[K <: TemplateId.RequiredPkg](
ids: Set[K]
)(implicit
log: doobie.LogHandler,
sjd: SupportedJdbcDriver.TC,
lc: LoggingContextOf[InstanceUUID],
): ConnectionIO[Map[K, SurrogateTpId]] = {
import doobie.implicits._, cats.instances.vector._, cats.syntax.functor._,
cats.syntax.traverse._
import sjd.q.queries.surrogateTemplateId
ids.toVector
.traverse(k => surrogateTemplateId(k.packageId, k.moduleName, k.entityName) tupleLeft k)
.map(_.toMap)
}
@SuppressWarnings(Array("org.wartremover.warts.Any"))
private def insertAndDelete(
step: InsertDeleteStep[Any, PreInsertContract]
)(implicit
log: doobie.LogHandler,
sjd: SupportedJdbcDriver.TC,
lc: LoggingContextOf[InstanceUUID],
): ConnectionIO[Unit] = {
import doobie.implicits._, cats.syntax.functor._
surrogateTemplateIds(step.inserts.iterator.map(_.templateId).toSet).flatMap { stidMap =>
import cats.syntax.apply._, cats.instances.vector._
import json.JsonProtocol._
import sjd.q.queries
(queries.deleteContracts(step.deletes.keySet) *>
queries.insertContracts(
step.inserts map (dbc =>
dbc.copy(
templateId = stidMap.getOrElse(
dbc.templateId,
throw new IllegalStateException(
"template ID missing from prior retrieval; impossible"
),
),
signatories = domain.Party.unsubst(dbc.signatories),
observers = domain.Party.unsubst(dbc.observers),
)
)
))
}.void
}
private final case class FetchContext(
jwt: Jwt,
ledgerId: LedgerApiDomain.LedgerId,
parties: domain.PartySet,
)
}