| 1 |
""" |
| 2 |
A simple caching system for nevow pages. |
| 3 |
|
| 4 |
The basic idea is to monkeypatch the request object in order to |
| 5 |
snarf content and headers. |
| 6 |
""" |
| 7 |
|
| 8 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 9 |
#c |
| 10 |
#c This program is free software, covered by the GNU GPL. See the |
| 11 |
#c COPYING file in the source distribution. |
| 12 |
|
| 13 |
|
| 14 |
import time |
| 15 |
|
| 16 |
from twisted.web import http |
| 17 |
from twisted.web import resource |
| 18 |
|
| 19 |
from gavo import base |
| 20 |
from gavo import utils |
| 21 |
|
| 22 |
|
| 23 |
# The size up to which each RD cache accepts new entries |
| 24 |
DEFAULT_CACHE_LIMIT = 10000000 |
| 25 |
|
| 26 |
|
| 27 |
# A cache for RD-specific page caches. Each of these maps segments |
| 28 |
# (tuples) to a finished caching.CachedPage. The argument is the id of the |
| 29 |
# RD responsible for generating that data. This ensures that pre-computed |
| 30 |
# data is cleared when the RD is reloaded. |
| 31 |
base.caches.makeCache("getPageCache", lambda rdId: PageCache()) |
| 32 |
|
| 33 |
|
| 34 |
class PageCache: |
| 35 |
"""a cache for resources already served out. |
| 36 |
|
| 37 |
This is kept per-RD, and it is removed when an RD is removed. |
| 38 |
It is allowed to grow to a certain size determined at construction time; |
| 39 |
it will stop adding new items when it's full (this is under the assumption |
| 40 |
that something has gone wrong and something tries to cache things |
| 41 |
we shouldn't cache). |
| 42 |
|
| 43 |
When you add things here, make sure the key actually gives everything |
| 44 |
that might influence a response. Below, we make sure we don't cache |
| 45 |
anything that has parameters, depends on the user. Compression, |
| 46 |
content negotiation, would have to be dealt with separately. |
| 47 |
|
| 48 |
The key actually used is determined in getFromRDCache -- and |
| 49 |
we should try hard to keep the key making logic local to that function. |
| 50 |
""" |
| 51 |
def __init__(self, maxSize=DEFAULT_CACHE_LIMIT): |
| 52 |
self.maxSize, self.curSize = maxSize, 0 |
| 53 |
self.cacheDict = {} |
| 54 |
self.get = self.cacheDict.get |
| 55 |
|
| 56 |
def add(self, key, cachedPage): |
| 57 |
"""enters content into the cache if it still fits. |
| 58 |
|
| 59 |
cachedPage is assomed to have a content attribute that will be |
| 60 |
taken as a proxy for the size. |
| 61 |
""" |
| 62 |
if self.curSize+len(cachedPage.content)>self.maxSize: |
| 63 |
return |
| 64 |
self.cacheDict[key] = cachedPage |
| 65 |
self.curSize += len(cachedPage.content) |
| 66 |
|
| 67 |
def __contains__(self, key): |
| 68 |
return key in self.cacheDict |
| 69 |
|
| 70 |
def __getitem__(self, key): |
| 71 |
return self.cacheDict[key] |
| 72 |
|
| 73 |
|
| 74 |
def instrumentRequestForCaching(request, finishAction): |
| 75 |
"""changes request such that finishAction is called with the request and |
| 76 |
the content written for a successful page render. |
| 77 |
""" |
| 78 |
builder = CacheItemBuilder(finishAction) |
| 79 |
origWrite, origFinish = request.write, request.finish |
| 80 |
|
| 81 |
def write(content): |
| 82 |
builder.addContent(content) |
| 83 |
return origWrite(content) |
| 84 |
|
| 85 |
def finish(): |
| 86 |
builder.finish(request) |
| 87 |
return origFinish() |
| 88 |
|
| 89 |
request.write = write |
| 90 |
request.finish = finish |
| 91 |
|
| 92 |
|
| 93 |
class CacheItemBuilder(object): |
| 94 |
"""an aggregator for web pages as they are written. |
| 95 |
|
| 96 |
On successful page generation an function is called with |
| 97 |
the request and the content written as arguments. |
| 98 |
""" |
| 99 |
def __init__(self, finishAction): |
| 100 |
self.finishAction = finishAction |
| 101 |
self.contentBuffer = [] |
| 102 |
|
| 103 |
def addContent(self, data): |
| 104 |
self.contentBuffer.append(data) |
| 105 |
|
| 106 |
def finish(self, request): |
| 107 |
try: |
| 108 |
if request.code==200: |
| 109 |
self.finishAction(request, b"".join(self.contentBuffer)) |
| 110 |
except Exception: |
| 111 |
base.ui.notifyError("Exception while building cache item.") |
| 112 |
|
| 113 |
|
| 114 |
class CachedPage(resource.Resource): |
| 115 |
"""A piece of cached content. |
| 116 |
|
| 117 |
This is built with the content to return, the headers, and a |
| 118 |
unix timestamp for the last modification time (as applicable). |
| 119 |
This is enough for it to work as a nevow resource (i.e., run |
| 120 |
a renderHTTP method. |
| 121 |
|
| 122 |
For cache management, this has a lastUsed unix timestamp that is bumped |
| 123 |
for each renderHTTP call, and a size attribute that gives the length |
| 124 |
of the content. |
| 125 |
""" |
| 126 |
def __init__(self, content, headers, lastModified): |
| 127 |
self.content = content |
| 128 |
self.size = len(content) |
| 129 |
self.creationStamp = time.time() |
| 130 |
headers.setRawHeaders("x-cache-creation", [str(self.creationStamp)]) |
| 131 |
self.changeStamp = self.lastModified = lastModified |
| 132 |
|
| 133 |
if headers.hasHeader("last-modified"): |
| 134 |
headers.removeHeader("last-modified") |
| 135 |
# at some point twisted stopped clearing transfer-encoding headers |
| 136 |
# when one had a content-length. |
| 137 |
# we need to do this because claiming chunked transfers when we |
| 138 |
# dump the whole thing in one go won't work. |
| 139 |
if headers.hasHeader("transfer-encoding"): |
| 140 |
headers.removeHeader("transfer-encoding") |
| 141 |
|
| 142 |
self.headers = headers |
| 143 |
self.lastUsed = None |
| 144 |
|
| 145 |
def render(self, request): |
| 146 |
self.lastUsed = time.time() |
| 147 |
if self.lastModified: |
| 148 |
if request.setLastModified(self.lastModified)==http.CACHED: |
| 149 |
return b"" |
| 150 |
for key, values in self.headers.getAllRawHeaders(): |
| 151 |
request.responseHeaders.setRawHeaders(key, values) |
| 152 |
request.responseHeaders.setRawHeaders('date', [utils.formatRFC2616Date()]) |
| 153 |
return self.content |
| 154 |
|
| 155 |
|
| 156 |
def enterIntoCacheAs(destKey, destDict): |
| 157 |
"""returns a finishAction that enters a page into destDict under key. |
| 158 |
""" |
| 159 |
def finishAction(request, content): |
| 160 |
destDict.add(destKey, |
| 161 |
CachedPage( |
| 162 |
content, |
| 163 |
request.responseHeaders.copy(), |
| 164 |
request.lastModified)) |
| 165 |
return finishAction |
| 166 |
|
| 167 |
|
| 168 |
def getFromRDCache(request, rd, segments): |
| 169 |
"""returns a cached resource for segments on rd. |
| 170 |
|
| 171 |
This will also instrument the request to enter the result into the |
| 172 |
cache. Hence, do not use this unless you are certain that the request |
| 173 |
is cacheable. Otherwise, use getFromServiceCache, which contains |
| 174 |
some sanity checks. |
| 175 |
""" |
| 176 |
if request.method!=b"GET" or request.strargs or request.getUser(): |
| 177 |
return None |
| 178 |
|
| 179 |
cache = base.caches.getPageCache(rd.sourceId) |
| 180 |
segments = tuple(segments) |
| 181 |
if segments in cache: |
| 182 |
return cache[segments] |
| 183 |
|
| 184 |
instrumentRequestForCaching(request, |
| 185 |
enterIntoCacheAs(segments, cache)) |
| 186 |
return None |
| 187 |
|
| 188 |
|
| 189 |
def getFromServiceCache(request, service, rendC, segments): |
| 190 |
"""returns a cached resource for service request if applicable, |
| 191 |
None otherwise. |
| 192 |
|
| 193 |
Requests with arguments or a user info are never cacheable; we |
| 194 |
don't look at content negotiation, though, so make sure whatever |
| 195 |
is content-negotiated isn't marked cacheable by the renderer class |
| 196 |
rendC. |
| 197 |
|
| 198 |
For cacheable requests for resources not in the cache, the function |
| 199 |
also instruments the request such that the rendered page is cached. |
| 200 |
|
| 201 |
Cacheable pages also cause request's lastModified to be set. |
| 202 |
""" |
| 203 |
if not rendC.isCacheable(segments, request): |
| 204 |
return None |
| 205 |
|
| 206 |
return getFromRDCache(request, service.rd, segments) |