-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathCacheResponseAttribute.cs
More file actions
219 lines (183 loc) · 7.54 KB
/
Copy pathCacheResponseAttribute.cs
File metadata and controls
219 lines (183 loc) · 7.54 KB
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
using System;
using System.Threading;
using System.Threading.Tasks;
using ServiceStack.Caching;
using ServiceStack.Html;
using ServiceStack.Text;
using ServiceStack.Web;
namespace ServiceStack
{
/// <summary>
/// Cache the Response of a Service
/// </summary>
public class CacheResponseAttribute : RequestFilterAsyncAttribute
{
/// <summary>
/// Cache expiry in seconds
/// </summary>
public int Duration { get; set; }
/// <summary>
/// MaxAge in seconds
/// </summary>
public int MaxAge { get; set; }
/// <summary>
/// Cache-Control HTTP Headers
/// </summary>
public CacheControl CacheControl { get; set; }
/// <summary>
/// Vary cache per user
/// </summary>
public bool VaryByUser { get; set; }
/// <summary>
/// Vary cache for users in these roles
/// </summary>
public string[] VaryByRoles { get; set; }
/// <summary>
/// Vary cache for different HTTP Headers
/// </summary>
public string[] VaryByHeaders { get; set; }
/// <summary>
/// Use HostContext.LocalCache or HostContext.Cache
/// </summary>
public bool LocalCache { get; set; }
/// <summary>
/// Skip compression for this Cache Result
/// </summary>
public bool NoCompression { get; set; }
public CacheResponseAttribute()
{
MaxAge = -1;
}
public override async Task ExecuteAsync(IRequest req, IResponse res, object requestDto)
{
if (req.Verb != HttpMethods.Get && req.Verb != HttpMethods.Head)
return;
if (req.IsInProcessRequest())
return;
var feature = HostContext.GetPlugin<HttpCacheFeature>();
if (feature == null)
throw new NotSupportedException(ErrorMessages.CacheFeatureMustBeEnabled.LocalizeFmt(req, "[CacheResponse]"));
if (feature.DisableCaching)
return;
var keyBase = "res:" + req.RawUrl;
var keySuffix = MimeTypes.GetExtension(req.ResponseContentType);
var modifiers = "";
if (req.ResponseContentType == MimeTypes.Json)
{
string jsonp = req.GetJsonpCallback();
if (jsonp != null)
modifiers = "jsonp:" + jsonp.SafeVarName();
}
if (VaryByUser)
modifiers += (modifiers.Length > 0 ? "+" : "") + "user:" + req.GetSessionId();
if (VaryByRoles is { Length: > 0 })
{
var userSession = await req.GetSessionAsync().ConfigAwait();
if (userSession != null)
{
var authRepo = HostContext.AppHost.GetAuthRepositoryAsync(req);
await using (authRepo as IAsyncDisposable)
{
var allRoles = await userSession.GetRolesAsync(authRepo).ConfigAwait();
foreach (var role in VaryByRoles)
{
if (allRoles.Contains(role))
modifiers += (modifiers.Length > 0 ? "+" : "") + "role:" + role;
}
}
}
}
if (VaryByHeaders is { Length: > 0 })
{
foreach (var header in VaryByHeaders)
{
var value = req.GetHeader(header);
if (!string.IsNullOrEmpty(value))
{
modifiers += (modifiers.Length > 0 ? "+" : "") + $"{header}:{value}";
}
}
}
if (modifiers.Length > 0)
keySuffix += "+" + modifiers;
var cacheInfo = new CacheInfo
{
KeyBase = keyBase,
KeyModifiers = keySuffix,
ExpiresIn = Duration > 0 ? TimeSpan.FromSeconds(Duration) : (TimeSpan?)null,
MaxAge = MaxAge >= 0 ? TimeSpan.FromSeconds(MaxAge) : (TimeSpan?)null,
CacheControl = CacheControl,
VaryByUser = VaryByUser,
LocalCache = LocalCache,
NoCompression = NoCompression,
};
if (await req.HandleValidCache(cacheInfo).ConfigAwait())
return;
req.Items[Keywords.CacheInfo] = cacheInfo;
}
}
public static class CacheResponseExtensions
{
public static string LastModifiedKey(this CacheInfo cacheInfo)
{
return "date:" + cacheInfo.CacheKey;
}
public static async Task<bool> HandleValidCache(this IRequest req, CacheInfo cacheInfo, CancellationToken token=default)
{
if (cacheInfo == null)
return false;
ICacheClient cache;
ICacheClientAsync cacheAsync = null; // only non-null if native ICacheClientAsync exists
if (cacheInfo.LocalCache)
cache = HostContext.AppHost.GetMemoryCacheClient(req);
else
HostContext.AppHost.TryGetNativeCacheClient(req, out cache, out cacheAsync);
var cacheControl = HostContext.GetPlugin<HttpCacheFeature>().BuildCacheControlHeader(cacheInfo);
var res = req.Response;
DateTime? lastModified = null;
var doHttpCaching = cacheInfo.MaxAge != null || cacheInfo.CacheControl != CacheControl.None;
if (doHttpCaching)
{
lastModified = cacheAsync != null
? await cacheAsync.GetAsync<DateTime?>(cacheInfo.LastModifiedKey(), token).ConfigAwait()
: cache.Get<DateTime?>(cacheInfo.LastModifiedKey());
if (req.HasValidCache(lastModified))
{
if (cacheControl != null)
res.AddHeader(HttpHeaders.CacheControl, cacheControl);
res.EndNotModified();
return true;
}
}
var encoding = !cacheInfo.NoCompression
? req.GetCompressionType()
: null;
var useCacheKey = encoding != null
? cacheInfo.CacheKey + "." + encoding
: cacheInfo.CacheKey;
var responseBytes = cacheAsync != null
? await cacheAsync.GetAsync<byte[]>(useCacheKey, token).ConfigAwait()
: cache.Get<byte[]>(useCacheKey);
if (responseBytes != null)
{
if (encoding != null)
res.AddHeader(HttpHeaders.ContentEncoding, encoding);
if (cacheInfo.VaryByUser)
res.AddHeader(HttpHeaders.Vary, "Cookie");
if (cacheControl != null)
res.AddHeader(HttpHeaders.CacheControl, cacheControl);
if (!doHttpCaching)
{
lastModified = cacheAsync != null ?
await cacheAsync.GetAsync<DateTime?>(cacheInfo.LastModifiedKey(), token).ConfigAwait() :
cache.Get<DateTime?>(cacheInfo.LastModifiedKey());
}
if (lastModified != null)
res.AddHeader(HttpHeaders.LastModified, lastModified.Value.ToUniversalTime().ToString("r"));
await res.WriteBytesToResponse(responseBytes, req.ResponseContentType, token).ConfigAwait();
return true;
}
return false;
}
}
}