-
Notifications
You must be signed in to change notification settings - Fork 556
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
Reduce CPU & network consumption of Facia JSON download #26338
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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 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
This file contains 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
This file was deleted.
Oops, something went wrong.
This file contains 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
This file contains 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
This file contains 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 |
---|---|---|
@@ -1,70 +1,67 @@ | ||
package services.fronts | ||
|
||
import common.{FaciaPressMetrics, GuLogging} | ||
import concurrent.{BlockingOperations, FutureSemaphore} | ||
import com.gu.etagcaching.ETagCache | ||
import com.gu.etagcaching.FreshnessPolicy.AlwaysWaitForRefreshedValue | ||
import com.gu.etagcaching.aws.s3.ObjectId | ||
import com.gu.etagcaching.aws.sdkv2.s3.S3ObjectFetching | ||
import com.gu.etagcaching.aws.sdkv2.s3.response.Transformer.Bytes | ||
import common.FaciaPressMetrics.{FrontDecodingLatency, FrontDownloadLatency, FrontNotModifiedDownloadLatency} | ||
import common.GuLogging | ||
import conf.Configuration | ||
import metrics.DurationMetric | ||
import metrics.DurationMetric.withMetrics | ||
import model.{PressedPage, PressedPageType} | ||
import play.api.libs.json.Json | ||
import services.S3 | ||
import services.S3.logS3ExceptionWithDevHint | ||
import services._ | ||
import software.amazon.awssdk.services.s3.model.S3Exception | ||
import utils.AWSv2.S3Async | ||
|
||
import java.util.zip.GZIPInputStream | ||
import scala.concurrent.duration.DurationInt | ||
import scala.concurrent.{ExecutionContext, Future} | ||
import scala.util.Using | ||
|
||
trait FrontJsonFapi extends GuLogging { | ||
implicit val executionContext: ExecutionContext | ||
lazy val stage: String = Configuration.facia.stage.toUpperCase | ||
val bucketLocation: String | ||
val parallelJsonPresses = 32 | ||
val futureSemaphore = new FutureSemaphore(parallelJsonPresses) | ||
|
||
def blockingOperations: BlockingOperations | ||
private def s3ObjectIdFor(path: String, prefix: String): ObjectId = | ||
ObjectId( | ||
S3.bucket, | ||
s"$bucketLocation/${path.replaceAll("""\+""", "%2B")}/fapi/pressed.v2$prefix.json", | ||
) | ||
|
||
private def getAddressForPath(path: String, prefix: String): String = | ||
s"$bucketLocation/${path.replaceAll("""\+""", "%2B")}/fapi/pressed.v2$prefix.json" | ||
|
||
def get(path: String, pageType: PressedPageType)(implicit | ||
executionContext: ExecutionContext, | ||
): Future[Option[PressedPage]] = | ||
errorLoggingF(s"FrontJsonFapi.get $path") { | ||
pressedPageFromS3(getAddressForPath(path, pageType.suffix)) | ||
} | ||
|
||
private def parsePressedPage( | ||
jsonStringOpt: Option[String], | ||
)(implicit executionContext: ExecutionContext): Future[Option[PressedPage]] = | ||
futureSemaphore.execute { | ||
blockingOperations.executeBlocking { | ||
jsonStringOpt.map { jsonString => | ||
DurationMetric.withMetrics(FaciaPressMetrics.FrontDecodingLatency) { | ||
// This operation is run in the thread pool since it is very CPU intensive | ||
Json.parse(jsonString).as[PressedPage] | ||
} | ||
private val pressedPageCache: ETagCache[ObjectId, PressedPage] = new ETagCache( | ||
S3ObjectFetching(S3Async, Bytes) | ||
.timing( | ||
successWith = FrontDownloadLatency.recordDuration, | ||
notModifiedWith = FrontNotModifiedDownloadLatency.recordDuration, | ||
) | ||
.thenParsing { bytes => | ||
withMetrics(FrontDecodingLatency) { | ||
Using(new GZIPInputStream(bytes.asInputStream()))(Json.parse(_).as[PressedPage]).get | ||
} | ||
} | ||
} | ||
}, | ||
AlwaysWaitForRefreshedValue, | ||
_.maximumSize(180).expireAfterAccess(1.hour), | ||
) | ||
|
||
private def loadPressedPageFromS3(path: String) = | ||
blockingOperations.executeBlocking { | ||
DurationMetric.withMetrics(FaciaPressMetrics.FrontDownloadLatency) { | ||
S3.getGzipped(path) | ||
def get(path: String, pageType: PressedPageType): Future[Option[PressedPage]] = | ||
errorLoggingF(s"FrontJsonFapi.get $path") { | ||
val objectId = s3ObjectIdFor(path, pageType.suffix) | ||
pressedPageCache.get(objectId).map(Some(_)).recover { | ||
case s3Exception: S3Exception => | ||
logS3ExceptionWithDevHint(objectId, s3Exception) | ||
None | ||
} | ||
} | ||
|
||
private def pressedPageFromS3( | ||
path: String, | ||
)(implicit executionContext: ExecutionContext): Future[Option[PressedPage]] = | ||
errorLoggingF(s"FrontJsonFapi.pressedPageFromS3 $path") { | ||
for { | ||
s3FrontData <- loadPressedPageFromS3(path) | ||
pressedPage <- parsePressedPage(s3FrontData) | ||
} yield pressedPage | ||
} | ||
|
||
} | ||
|
||
class FrontJsonFapiLive(val blockingOperations: BlockingOperations) extends FrontJsonFapi { | ||
class FrontJsonFapiLive(implicit val executionContext: ExecutionContext) extends FrontJsonFapi { | ||
override val bucketLocation: String = s"$stage/frontsapi/pressed/live" | ||
} | ||
|
||
class FrontJsonFapiDraft(val blockingOperations: BlockingOperations) extends FrontJsonFapi { | ||
class FrontJsonFapiDraft(implicit val executionContext: ExecutionContext) extends FrontJsonFapi { | ||
override val bucketLocation: String = s"$stage/frontsapi/pressed/draft" | ||
} |
This file contains 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,25 @@ | ||
package utils | ||
|
||
import software.amazon.awssdk.auth.credentials._ | ||
import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder | ||
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient | ||
import software.amazon.awssdk.regions.Region | ||
import software.amazon.awssdk.regions.Region.EU_WEST_1 | ||
import software.amazon.awssdk.services.s3.{S3AsyncClient, S3AsyncClientBuilder} | ||
|
||
object AWSv2 { | ||
val region: Region = EU_WEST_1 | ||
|
||
def credentialsForDevAndProd(devProfile: String, prodCreds: AwsCredentialsProvider): AwsCredentialsProviderChain = | ||
AwsCredentialsProviderChain.of(prodCreds, ProfileCredentialsProvider.builder().profileName(devProfile).build()) | ||
|
||
lazy val credentials: AwsCredentialsProvider = | ||
credentialsForDevAndProd("frontend", InstanceProfileCredentialsProvider.create()) | ||
|
||
def build[T, B <: AwsClientBuilder[B, T]](builder: B): T = | ||
builder.credentialsProvider(credentials).region(region).build() | ||
|
||
val S3Async: S3AsyncClient = build[S3AsyncClient, S3AsyncClientBuilder]( | ||
S3AsyncClient.builder().httpClientBuilder(NettyNioAsyncHttpClient.builder().maxConcurrency(250)), | ||
) | ||
} |
This file contains 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
This file contains 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
This file contains 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
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.
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.
Since we're deleting
BlockingOperations
this config can also be removed.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, that bit of config is still used by the
BlockingOperations
class, and that hasn't been deleted (unfortunately?!) - we're no longer using it for the Fronts-JSON download code, but it's still used elsewhere, egdfp.OrderAgent
.