Repository navigation
Expand file tree
/
Copy pathcomponents.go
More file actions
437 lines (404 loc) · 12.6 KB
/
Copy pathcomponents.go
File metadata and controls
437 lines (404 loc) · 12.6 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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
// components.go — tr-cluster component A/B/Z bandit delivery (v2).
//
// Serves component variants from the CDN (the immutable content backbone) so the
// tr cluster (ch1-3) can deliver component experiments when x-1 (the source of
// truth) is down. Mirrors content.go's contentResolveHandler.
//
// The route: GET /tr/{apiVersion}/components/resolve?site=&page=&vid=
// - Resolves the host -> site config (from the ~5-min CH cache).
// - Fetches the component registry from the CDN:
// {cdn}/{org}/components/{site}/{page-key}.json
// (published by x-1 whenever a component/variant changes).
// - Thompson-samples an arm per component (sticky per vid via the
// _sfpl_cmp_<cid> cookie, same pattern as the CMS arm stickiness).
// - Returns the component contract:
// {components: {cid: {arm_id, payload, slots, xid, decision_id, mode}}, vid}
//
// Fail-open: any error -> 200 with canonical-only (bots/no-experiment mode),
// so the site always renders. Never 500.
package main
import (
"encoding/json"
"fmt"
"math"
"math/rand"
"net/http"
"net/url"
"strings"
"sync"
"time"
)
// cdnComponentArm is one variant arm in the CDN component registry.
type cdnComponentArm struct {
ArmID string `json:"arm_id"`
Name string `json:"name"`
Payload map[string]interface{} `json:"payload"`
Status string `json:"status"`
}
// cdnComponent is one component in the CDN registry.
type cdnComponent struct {
ComponentID string `json:"component_id"`
XID string `json:"xid"`
RewardMetric string `json:"reward_metric"`
CanonicalArmID string `json:"canonical_arm_id"`
AllowLayoutChanges bool `json:"allow_layout_changes"`
Slots []map[string]interface{} `json:"slots"`
Canonical map[string]interface{} `json:"canonical"`
Arms []cdnComponentArm `json:"arms"`
// Posteriors (updated by x-1; used for Thompson sampling on the tr edge).
Posteriors map[string]cdnPosterior `json:"posteriors"`
}
// cdnPosterior is one arm's cached Beta posterior + win probability.
type cdnPosterior struct {
Alpha float64 `json:"alpha"`
Beta float64 `json:"beta"`
Exposures float64 `json:"exposures"`
}
// componentsResolveHandler serves the component bandit resolution from the CDN.
func componentsResolveHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
q := r.URL.Query()
site := strings.ToLower(strings.TrimSpace(q.Get("site")))
page := q.Get("page")
if page == "" {
page = "/"
}
vid := strings.TrimSpace(q.Get("vid"))
if vid == "" {
vid = "vid_" + randomHex8()
}
resp := map[string]interface{}{
"success": true,
"site": site,
"page": strings.Trim(page, "/"),
"vid": vid,
"is_bot": false,
"served_by": "tr_cluster",
"components": map[string]interface{}{},
}
// 1) Resolve host -> site config.
host := r.Host
if h := r.Header.Get("X-Forwarded-Host"); h != "" {
host = h
}
if gTlsCertMgr == nil {
writeComponentsCanonical(w, resp)
return
}
siteCfg, ok := gTlsCertMgr.ResolveHost(host)
if !ok || siteCfg.CdnCname == "" {
writeComponentsCanonical(w, resp)
return
}
cdnBase := strings.TrimSuffix(siteCfg.CdnCname, "/")
org := siteCfg.Org
// 2) Fetch the component registry from the CDN.
pageKey := strings.Trim(page, "/")
if pageKey == "" {
pageKey = "home"
}
registryURL := fmt.Sprintf("%s/%s/components/%s/%s.json", cdnBase, org, site, pageKey)
regBytes, err := contentFetch(registryURL)
if err != nil || len(regBytes) == 0 {
// No registry published -> canonical only (fail-open).
writeComponentsCanonical(w, resp)
return
}
var components []cdnComponent
if err := json.Unmarshal(regBytes, &components); err != nil {
writeComponentsCanonical(w, resp)
return
}
// 3) Thompson-sample each active component (sticky per vid).
var comps map[string]interface{}
comps = make(map[string]interface{})
for i := range components {
c := components[i]
cid := c.ComponentID
if cid == "" {
continue
}
arms := map[string]map[string]interface{}{}
for j := range c.Arms {
if c.Arms[j].Status != "" && c.Arms[j].Status != "active" && c.Arms[j].Status != "canonical" {
continue
}
arms[c.Arms[j].ArmID] = c.Arms[j].Payload
}
chosenArm := c.CanonicalArmID
if chosenArm == "" {
chosenArm = "v0_control"
}
mode := "canonical"
decisionID := "canonical"
// Only sample if we have >=2 arms and a xid.
if c.XID != "" && len(arms) >= 2 {
// 1) Sticky: honor an existing _sfpl_cmp_<cid> cookie if present + valid.
stickyArm := readStickyCookie(r, cid)
if stickyArm != "" {
if _, exists := arms[stickyArm]; exists {
chosenArm = stickyArm
mode = "sticky"
decisionID = stableDecisionID(vid, cid, stickyArm)
setStickyCookie(w, r, cid, stickyArm)
if vid != "" {
vidDecisionSet(vid, cid, stickyArm, decisionID)
}
} else {
// Sticky arm no longer exists — fall through to re-sample
sampleArm := thompsonSample(c, arms)
if sampleArm != "" {
chosenArm = sampleArm
mode = "thompson_sampling"
decisionID = randomHex16()
setStickyCookie(w, r, cid, chosenArm)
if vid != "" {
vidDecisionSet(vid, cid, chosenArm, decisionID)
}
}
}
} else if vid != "" {
// 2) Server-side vid sticky cache (for SSR calls without browser cookies).
if cachedArm, cachedDec, ok := vidDecisionGet(vid, cid); ok {
if _, exists := arms[cachedArm]; exists {
chosenArm = cachedArm
mode = "vid_sticky"
decisionID = cachedDec
setStickyCookie(w, r, cid, cachedArm)
} else {
// Cached arm no longer exists — re-sample
sampleArm := thompsonSample(c, arms)
if sampleArm != "" {
chosenArm = sampleArm
mode = "thompson_sampling"
decisionID = randomHex16()
setStickyCookie(w, r, cid, chosenArm)
vidDecisionSet(vid, cid, chosenArm, decisionID)
}
}
} else {
// 3) Thompson sample from posteriors (fallback: uniform weights).
sampleArm := thompsonSample(c, arms)
if sampleArm != "" {
chosenArm = sampleArm
mode = "thompson_sampling"
decisionID = randomHex16()
setStickyCookie(w, r, cid, chosenArm)
vidDecisionSet(vid, cid, chosenArm, decisionID)
}
}
}
}
payload := arms[chosenArm]
if payload == nil {
payload = c.Canonical
}
comps[cid] = map[string]interface{}{
"arm_id": chosenArm,
"payload": payload,
"slots": c.Slots,
"xid": c.XID,
"decision_id": decisionID,
"mode": mode,
"vid": vid,
"reward_metric": c.RewardMetric,
}
}
resp["components"] = comps
resp["count"] = len(comps)
json.NewEncoder(w).Encode(resp)
}
// writeComponentsCanonical returns a 200 with empty components (site renders canonical).
func writeComponentsCanonical(w http.ResponseWriter, resp map[string]interface{}) {
json.NewEncoder(w).Encode(resp)
}
// thompsonSample draws a Beta(alpha, beta) sample per arm and returns the argmax.
func thompsonSample(c cdnComponent, arms map[string]map[string]interface{}) string {
if len(c.Posteriors) == 0 {
// No posteriors yet -> pick the first arm (uniform exploration over time via
// the decision_id randomness is NOT used here; x-1 will publish posteriors).
for k := range arms {
return k
}
}
bestArm := ""
bestVal := -1.0
for armID := range arms {
p, ok := c.Posteriors[armID]
if !ok {
continue
}
a := math.Max(0.01, p.Alpha)
b := math.Max(0.01, p.Beta)
v := betaSample(a, b)
if v > bestVal {
bestVal = v
bestArm = armID
}
}
return bestArm
}
// betaSample returns a single draw from Beta(a, b) using the Gamma-ratio method.
// (Avoids a full distribution dependency.)
func betaSample(a, b float64) float64 {
// Box-Muller-free: use the fact that if X~Gamma(a,1), Y~Gamma(b,1) then X/(X+Y)~Beta(a,b).
// Implement Gamma via Marsaglia-Tsang for a>=1, with the standard split for a<1.
x := gammaSample(a)
y := gammaSample(b)
if x+y == 0 {
return 0.5
}
return x / (x + y)
}
// gammaSample — Marsaglia & Tsang (1984) for shape >= 1; handles shape < 1.
func gammaSample(shape float64) float64 {
if shape < 1.0 {
u := rand.Float64()
if u == 0 {
u = 1e-12
}
return gammaSample(shape + 1.0) * math.Pow(u, 1.0/shape)
}
d := shape - 1.0/3.0
c := 1.0 / math.Sqrt(9.0*d)
for {
var x, v float64
for {
x = rand.NormFloat64()
v = 1.0 + c*x
if v > 0 {
break
}
}
v = v * v * v
u := rand.Float64()
if u < 1.0-1.3e-5*x*x*x*x {
return d * v
}
if math.Log(u+1e-300) < 0.5*x*x+d*(1.0-v+math.Log(v)) {
return d * v
}
}
}
// ---- sticky cookie helpers (mirror the CMS arm stickiness pattern) ---------
const componentsCookieName = "_sfpl_cmp"
func readStickyCookie(r *http.Request, cid string) string {
c, err := r.Cookie(componentsCookieName)
if err != nil || c.Value == "" {
return ""
}
rawVal := c.Value
if decoded, decErr := url.QueryUnescape(rawVal); decErr == nil {
rawVal = decoded
}
// Cookie format: cid:arm;cid2:arm2;... (URL-encoded by cmp.js / setStickyCookie)
for _, pair := range strings.Split(rawVal, ";") {
parts := strings.SplitN(pair, ":", 2)
if len(parts) == 2 && parts[0] == cid {
return parts[1]
}
}
return ""
}
func setStickyCookie(w http.ResponseWriter, r *http.Request, cid, arm string) {
// Merge into existing `_sfpl_cmp` cookie (`cid:arm;cid2:arm2`) so multiple
// components across pages preserve sticky assignment simultaneously.
// URL-encode `;` and `:` (matching `encodeURIComponent` in `cmp.js`) so Go's
// `net/http.SetCookie` never strips `;` as an invalid RFC 6265 cookie byte.
pairs := make([]string, 0, 8)
if r != nil {
if c, err := r.Cookie(componentsCookieName); err == nil && c.Value != "" {
rawVal := c.Value
if decoded, decErr := url.QueryUnescape(rawVal); decErr == nil {
rawVal = decoded
}
for _, pair := range strings.Split(rawVal, ";") {
parts := strings.SplitN(pair, ":", 2)
if len(parts) == 2 && parts[0] != "" && parts[0] != cid {
pairs = append(pairs, parts[0]+":"+parts[1])
}
}
}
}
if len(pairs) >= 7 {
pairs = pairs[len(pairs)-7:]
}
pairs = append(pairs, fmt.Sprintf("%s:%s", cid, arm))
encoded := strings.ReplaceAll(url.QueryEscape(strings.Join(pairs, ";")), "+", "%20")
http.SetCookie(w, &http.Cookie{
Name: componentsCookieName,
Value: encoded,
Path: "/",
MaxAge: 30 * 24 * 3600,
HttpOnly: false,
SameSite: http.SameSiteLaxMode,
})
}
// stableDecisionID is a deterministic decision id for sticky (no random re-roll).
func stableDecisionID(vid, cid, arm string) string {
h := uint32(2166136261)
for _, b := range []byte(vid + "|" + cid + "|" + arm) {
h ^= uint32(b)
h *= 16777619
}
return fmt.Sprintf("%08x", h)
}
// ---- vid-based sticky decision cache (server-side) --------------------------
// When the caller provides a `vid` (e.g. from a first-party cookie), we cache
// the Thompson-sampled arm in memory so that repeated SSR requests for the same
// visitor always resolve to the same arm — even if the browser-side `_sfpl_cmp`
// cookie is absent (e.g. server-to-server calls from the CMS/SSR layer).
type vidDecision struct {
armID string
decisionID string
expiresAt time.Time
}
var (
vidDecisionMu sync.RWMutex
vidDecisions = make(map[string]vidDecision) // key: vid|cid
)
const vidDecisionTTL = 30 * 24 * time.Hour // 30 days
func vidDecisionKey(vid, cid string) string {
return vid + "|" + cid
}
func vidDecisionGet(vid, cid string) (string, string, bool) {
vidDecisionMu.RLock()
defer vidDecisionMu.RUnlock()
d, ok := vidDecisions[vidDecisionKey(vid, cid)]
if !ok || time.Now().After(d.expiresAt) {
return "", "", false
}
return d.armID, d.decisionID, true
}
func vidDecisionSet(vid, cid, armID, decisionID string) {
vidDecisionMu.Lock()
defer vidDecisionMu.Unlock()
// Evict expired entries (amortized: only when map grows large)
if len(vidDecisions) > 100000 {
now := time.Now()
for k, v := range vidDecisions {
if now.After(v.expiresAt) {
delete(vidDecisions, k)
}
}
}
vidDecisions[vidDecisionKey(vid, cid)] = vidDecision{
armID: armID,
decisionID: decisionID,
expiresAt: time.Now().Add(vidDecisionTTL),
}
}
func randomHex8() string { return randomHexN(8) }
func randomHex16() string { return randomHexN(16) }
func randomHexN(n int) string {
b := make([]byte, n/2+1)
for i := range b {
b[i] = byte(rand.Intn(256))
}
return fmt.Sprintf("%x", b)[:n]
}