https://kotlinlang.org logo
Title
r

Razvan

01/20/2021, 8:13 PM
Hi, I'm playing with Caching HTTP Traffic example, I put breakpoints in DiskTree Sink but never stops. I changed a bit the response to show the current time to see if the second time it's the same but it does search the cache but the cache is always empty (as it does not enter the Sink function).
fun main() {
    val storage = ReadWriteCache.Disk()

    val withCachedContent = TrafficFilters.ServeCachedFrom(storage).then { Response(OK).body("hello world: ${LocalDateTime.now()}") }
    val aRequest = Request(Method.GET, "<http://localhost:8000/>")
    println("--- FIRST ----")
    println(withCachedContent(aRequest))

    Thread.sleep(1000)
    println("--- SECOND ----")
    println(withCachedContent(aRequest))
}
I expected both output to show the same time and not different ones....
Same behavior with the Memory cache
Looking at the Unit Test seems a bit strange as you manually set the response in the cache:
val cache = ReadWriteCache.Memory()
cache[request] = response
does that mean that
ServeCachedFrom
does not automatically cache requests that does not yet cached ?
d

dave

01/20/2021, 8:35 PM
ah
sorry - this is a misunderstanding
in order to get both read and write behaviour you need to compose 2 filters - one to record and the other to replay:
fun `disk cache!`(dir: String): Http4kServer {
    val cache = ReadWriteCache.Disk(dir)
    return ProxyHost(Https)
        .then(RecordTo(cache))
        .then(ServeCachedFrom(cache))
        .then(ReportHttpTransaction { println(it.request.uri) })
        .then(JavaHttpClient())
        .asServer(KtorCIO())
        .start()
}
👍 1
r

Razvan

01/21/2021, 8:06 AM
Ok thanks, the Caching Http Traffic example is confusing as it does not show the record part.
d

dave

01/21/2021, 8:10 AM
Maybe switching the order of the examples in that page might work? Feel free to PR it to make it better!
r

Razvan

01/21/2021, 8:23 AM
Guess it just the title as "Replay form cache HTTP Traffic" would make it clearer. And adding at the end the example you gave which does both at the end would make it perfect. Nice system by the way.