-
Notifications
You must be signed in to change notification settings - Fork 0
Upgrade dynamo to use sdk v2 #133
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
2088b8f
Construct the test set up for v2
lindseydew a4567ca
Use enhanced client to get the doc
lindseydew 29c0733
Add in a scan simple method
lindseydew ceab641
Add an update method
lindseydew 5f6c88a
Add the ability to create an atom with a composite key
lindseydew 05cd03a
Remove unneeded methods
lindseydew f153912
Refactor the table query
lindseydew a6877db
Delete unused methods
lindseydew b1325e2
Merge branch 'main' into ld/upgrade-dynamo
lindseydew 5868a9e
Use awsverion variable
lindseydew 1311195
Merge branch 'ld/upgrade-dynamo' of github.com:guardian/atom-maker in…
lindseydew 517918e
Update failure case for scan
lindseydew 8df7842
Import rejig
lindseydew 7dc2429
Merge branch 'main' into ld/upgrade-dynamo
lindseydew File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
11 changes: 11 additions & 0 deletions
11
atom-publisher-lib/src/main/scala/com/gu/atom/data/AtomSerializer.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| package com.gu.atom.data | ||
|
|
||
| import com.gu.contentatom.thrift.Atom | ||
| import io.circe.Json | ||
| import io.circe.syntax._ | ||
| import com.gu.fezziwig.CirceScroogeMacros.{encodeThriftStruct, encodeThriftUnion} | ||
| import com.gu.atom.util.JsonSupport.{backwardsCompatibleAtomDecoder, thriftEnumEncoder} | ||
| object AtomSerializer { | ||
|
|
||
| def toJson(newAtom: Atom): Json = newAtom.asJson | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
240 changes: 240 additions & 0 deletions
240
atom-publisher-lib/src/main/scala/com/gu/atom/data/DynamoDataStoreV2.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,240 @@ | ||
| package com.gu.atom.data | ||
|
|
||
| import software.amazon.awssdk.services.dynamodb.DynamoDbClient | ||
| import software.amazon.awssdk.services.dynamodb.model.{ | ||
| AttributeValue, | ||
| ConditionalCheckFailedException, | ||
| DescribeTableRequest, | ||
| KeyType | ||
| } | ||
| import software.amazon.awssdk.awscore.exception.AwsServiceException | ||
| import com.gu.contentatom.thrift.Atom | ||
| import cats.implicits._ | ||
| import io.circe._ | ||
| import com.gu.atom.util.JsonSupport.backwardsCompatibleAtomDecoder | ||
| import software.amazon.awssdk.core.exception.SdkException | ||
| import software.amazon.awssdk.enhanced.dynamodb.document.EnhancedDocument | ||
| import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest | ||
| import software.amazon.awssdk.enhanced.dynamodb.{ | ||
| AttributeConverterProvider, | ||
| AttributeValueType, | ||
| DynamoDbEnhancedClient, | ||
| Expression, | ||
| Key, | ||
| TableMetadata, | ||
| TableSchema | ||
| } | ||
|
|
||
| import scala.jdk.CollectionConverters.{ | ||
| CollectionHasAsScala, | ||
| IteratorHasAsScala, | ||
| MapHasAsJava | ||
| } | ||
| import scala.util.{Failure, Success, Try} | ||
|
|
||
| abstract class DynamoDataStoreV2(dynamo: DynamoDbClient, tableName: String) | ||
| extends AtomDataStore { | ||
|
|
||
| private val SimpleKeyName = "id" | ||
| private object CompositeKey { | ||
| val partitionKey = "atomType" | ||
| val sortKey = "id" | ||
| } | ||
| val desc = dynamo | ||
| .describeTable( | ||
| DescribeTableRequest.builder().tableName(tableName).build() | ||
| ) | ||
| .table() | ||
|
|
||
| val hasSortKey = | ||
| desc.keySchema().asScala.exists(_.keyType() == KeyType.RANGE) | ||
|
|
||
| lazy val tableSchema: TableSchema[EnhancedDocument] = { | ||
| val builder = TableSchema | ||
| .documentSchemaBuilder() | ||
| .attributeConverterProviders(AttributeConverterProvider.defaultProvider()) | ||
|
|
||
| if (hasSortKey) { | ||
| builder.addIndexPartitionKey( | ||
| TableMetadata.primaryIndexName(), | ||
| CompositeKey.partitionKey, | ||
| AttributeValueType.S | ||
| ) | ||
| builder.addIndexSortKey( | ||
| TableMetadata.primaryIndexName(), | ||
| CompositeKey.sortKey, | ||
| AttributeValueType.S | ||
| ) | ||
| } else | ||
| builder.addIndexPartitionKey( | ||
| TableMetadata.primaryIndexName(), | ||
| SimpleKeyName, | ||
| AttributeValueType.S | ||
| ) | ||
|
|
||
| builder.build() | ||
| } | ||
| lazy val ddb: DynamoDbEnhancedClient = | ||
| DynamoDbEnhancedClient.builder().dynamoDbClient(dynamo).build() | ||
|
|
||
| val table = ddb.table(tableName, tableSchema) | ||
|
|
||
| import AtomSerializer._ | ||
|
|
||
| protected def get(key: DynamoCompositeKey): DataStoreResult[Json] = { | ||
| Try { | ||
| Option(table.getItem(uniqueKey(key))) | ||
| } match { | ||
| case Success(Some(item)) => parseJson(item.toJson) | ||
| case Success(None) => Left(IDNotFound) | ||
| case Failure(e) => Left(handleException(e)) | ||
| } | ||
| } | ||
|
|
||
| protected def put(json: Json): DataStoreResult[Json] = { | ||
| Try( | ||
| table.putItem( | ||
| EnhancedDocument.builder().json(json.spaces2).build() | ||
| ) | ||
| ) match { | ||
| case Success(_) => Right(json) | ||
| case Failure(e) => Left(handleException(e)) | ||
| } | ||
| } | ||
|
|
||
| /** Conditional put, ensuring passed revision is higher than the value in | ||
| * dynamo | ||
| */ | ||
| protected def put(json: Json, revision: Long): DataStoreResult[Json] = { | ||
| val expressionAttrValues = Map[String, AttributeValue]( | ||
| ":revision" -> AttributeValue.builder().n(revision.toString).build() | ||
| ) | ||
| val expression = Expression | ||
| .builder() | ||
| .expression("contentChangeDetails.revision < :revision") | ||
| .expressionValues(expressionAttrValues.asJava) | ||
| .build() | ||
| val doc = EnhancedDocument.fromJson(json.spaces2) | ||
| val putItemRequest = PutItemEnhancedRequest | ||
| .builder(classOf[EnhancedDocument]) | ||
| .item(doc) | ||
| .conditionExpression(expression) | ||
| .build() | ||
| Try { | ||
| table.putItem(putItemRequest) | ||
| } match { | ||
| case Success(item) => Right(json) | ||
| case Failure(conditionError: ConditionalCheckFailedException) => | ||
| Left(VersionConflictError(revision)) | ||
| case Failure(e) => Left(handleException(e)) | ||
| } | ||
| } | ||
|
|
||
| protected def delete(key: DynamoCompositeKey): DataStoreResult[Unit] = { | ||
| Try { | ||
| table.deleteItem(uniqueKey(key)) | ||
| } match { | ||
| case Success(_) => Right(()) | ||
| case Failure(e) => Left(handleException(e)) | ||
| } | ||
| } | ||
|
|
||
| protected def scan: DataStoreResult[List[Json]] = { | ||
| Try { | ||
| table.scan().iterator().asScala.toList | ||
| } match { | ||
| case Success(page) => | ||
| page | ||
| .flatMap(p => p.items().asScala.map(i => parseJson(i.toJson))) | ||
| .sequence | ||
| case Failure(e) => Left(DynamoError(e.getMessage)) | ||
| } | ||
| } | ||
|
|
||
| private def uniqueKey(dynamoCompositeKey: DynamoCompositeKey): Key = | ||
| dynamoCompositeKey match { | ||
| case DynamoCompositeKey(partitionKey, None) => | ||
| Key.builder().partitionValue(partitionKey).build() | ||
|
|
||
| case DynamoCompositeKey(partitionKey, Some(sortKey)) => | ||
| Key.builder().partitionValue(partitionKey).addSortValue(sortKey).build() | ||
| } | ||
|
|
||
| def parseJson(s: String): DataStoreResult[Json] = | ||
| parser | ||
| .parse(s) | ||
| .leftMap(parsingFailure => DynamoError(parsingFailure.getMessage)) | ||
|
|
||
| def jsonToAtom(json: Json): DataStoreResult[Atom] = | ||
| json | ||
| .as[Atom](backwardsCompatibleAtomDecoder) | ||
| .leftMap(error => DecoderError(error.message)) | ||
|
|
||
| private def handleException(e: Throwable) = e match { | ||
| case serviceError: AwsServiceException => | ||
| DynamoError(serviceError.awsErrorDetails().errorMessage) | ||
| case clientError: SdkException => { | ||
| ClientError(clientError.getMessage) | ||
| } | ||
| case _ => ReadError | ||
| } | ||
|
|
||
| def getAtom(id: String): DataStoreResult[Atom] = getAtom( | ||
| DynamoCompositeKey(id) | ||
| ) | ||
|
|
||
| def getAtom(dynamoCompositeKey: DynamoCompositeKey): DataStoreResult[Atom] = { | ||
| get(dynamoCompositeKey) flatMap jsonToAtom | ||
| } | ||
|
|
||
| def createAtom(atom: Atom): DataStoreResult[Atom] = | ||
| createAtom(DynamoCompositeKey(atom.id), atom) | ||
|
|
||
| def createAtom( | ||
| dynamoCompositeKey: DynamoCompositeKey, | ||
| atom: Atom | ||
| ): DataStoreResult[Atom] = { | ||
| getAtom(dynamoCompositeKey) match { | ||
| case Right(_) => | ||
| Left(IDConflictError) | ||
| case Left(_) => | ||
| put(toJson(atom)).map(_ => atom) | ||
| } | ||
| } | ||
|
|
||
| def deleteAtom(id: String): DataStoreResult[Atom] = deleteAtom( | ||
| DynamoCompositeKey(id) | ||
| ) | ||
|
|
||
| def deleteAtom( | ||
| dynamoCompositeKey: DynamoCompositeKey | ||
| ): DataStoreResult[Atom] = | ||
| getAtom(dynamoCompositeKey).flatMap { atom => | ||
| delete(dynamoCompositeKey).map(_ => atom) | ||
| } | ||
|
|
||
|
|
||
| def listAtoms: DataStoreResult[List[Atom]] = scan.flatMap(_.traverse(jsonToAtom)) | ||
|
|
||
| } | ||
|
|
||
| class PreviewDynamoDataStoreV2(dynamo: DynamoDbClient, tableName: String) | ||
| extends DynamoDataStoreV2(dynamo, tableName) | ||
| with PreviewDataStore { | ||
|
|
||
| import AtomSerializer._ | ||
|
|
||
| def updateAtom(newAtom: Atom) = | ||
| put(toJson(newAtom), newAtom.contentChangeDetails.revision).map(_ => | ||
| newAtom | ||
| ) | ||
| } | ||
|
|
||
| class PublishedDynamoDataStoreV2(dynamo: DynamoDbClient, tableName: String) | ||
| extends DynamoDataStoreV2(dynamo, tableName) | ||
| with PublishedDataStore { | ||
|
|
||
| import AtomSerializer._ | ||
|
|
||
| def updateAtom(newAtom: Atom) = put(toJson(newAtom)).map(_ => newAtom) | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It looks like there's a
table.scan().items()method available, which would give you a list of documents, rather than a list of pages of documents.I wondered if there was a performance difference between the two but I can't see anything obvious about this in the docs. So just suggesting it as slight simplification of the code, but I'm happy either way :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah cool thanks, that's a good point. I think we will do some refactoring of this after the upgrade, so I'll have a look into doing that then 👍