Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
216 lines (204 loc) · 9.13 KB
/
Copy pathindex.html
File metadata and controls
216 lines (204 loc) · 9.13 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="alternate icon" type="image/x-icon" href="/favicon.ico" />
<title>Serverless App</title>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
background: #f5f5f5;
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}
.card {
background: #fff;
border-radius: 12px;
box-shadow: 0 4px 24px rgba(0,0,0,0.08);
padding: 48px 56px;
text-align: center;
max-width: 480px;
width: 100%;
}
h1 { font-size: 1.5rem; color: #111; margin-bottom: 8px; }
p.subtitle { color: #666; font-size: 0.95rem; margin-bottom: 32px; }
button {
background: #232f3e;
color: #fff;
border: none;
border-radius: 8px;
padding: 12px 28px;
font-size: 1rem;
cursor: pointer;
transition: background 0.15s;
}
button:hover { background: #374151; }
button:disabled { background: #9ca3af; cursor: not-allowed; }
.response {
margin-top: 28px;
padding: 16px 20px;
border-radius: 8px;
font-size: 1.1rem;
font-weight: 500;
display: none;
}
.response.success { background: #f0fdf4; color: #166534; border: 1px solid #bbf7d0; }
.response.error { background: #fef2f2; color: #991b1b; border: 1px solid #fecaca; }
.spinner {
display: none;
width: 20px; height: 20px;
border: 2px solid #e5e7eb;
border-top-color: #6b7280;
border-radius: 50%;
animation: spin 0.6s linear infinite;
margin: 20px auto 0;
}
@keyframes spin { to { transform: rotate(360deg); } }
</style>
<script>
// CloudWatch RUM client — fetches config.json synchronously in <head> so
// the RUM snippet can initialize before the app code runs. enableXRay=true
// makes the client attach an X-Amzn-Trace-Id header to outbound fetch()
// calls so browser spans join the backend API Gateway + Lambda trace.
(function () {
// Check status AND content type before parsing. r.ok alone is not enough:
// CloudFront maps 403/404 → /index.html with a *200* for SPA routing, so a
// missing/forbidden config.json (partial deploy, OAC misgrant, invalidation
// race) arrives as a 200 HTML page and r.json() would throw a confusing
// "Unexpected token '<'" SyntaxError. The content-type guard catches that
// mapped case; the r.ok guard catches everything CloudFront doesn't map.
const configPromise = fetch("/config.json").then(function (r) {
const ct = r.headers.get("content-type") || "";
if (!r.ok || ct.indexOf("application/json") === -1) {
throw new Error("config.json unavailable: " + r.status + " (" + ct + ")");
}
return r.json();
});
window.__appConfigPromise = configPromise;
configPromise.then(function (cfg) {
if (!cfg || !cfg.rum || !cfg.rum.appMonitorId) return;
(function (n, i, v, r, s, c, x, z) {
x = window.AwsRumClient = { q: [], n: n, i: i, v: v, r: r, c: c };
window[n] = function (c, p) { x.q.push({ c: c, p: p }); };
z = document.createElement("script");
z.async = true;
z.src = s;
document.head.insertBefore(z, document.head.getElementsByTagName("script")[0]);
})(
"cwr",
cfg.rum.appMonitorId,
"1.0.0",
cfg.rum.region,
// The cwr.js loader host is intentionally pinned to us-east-1 regardless
// of deploy region (the loader is region-agnostic; the data plane below
// follows cfg.rum.region). The CSP script-src in the CDK
// ResponseHeadersPolicy (_build_response_headers_policy) is pinned to
// this same us-east-1 host — do not "regionalize" this URL without
// updating the CSP to match, or the script will be blocked.
"https://client.rum.us-east-1.amazonaws.com/1.x/cwr.js",
{
sessionSampleRate: 1,
identityPoolId: cfg.rum.identityPoolId,
endpoint: "https://dataplane.rum." + cfg.rum.region + ".amazonaws.com",
// The http telemetry is written as a [name, config] tuple so
// addXRayTraceIdHeader is set explicitly. enableXRay: true defaults
// it to true today, but stating it explicitly guards against future
// client-version regressions of that default and matches the AWS
// reference snippet pattern.
telemetries: ["performance", "errors", ["http", { addXRayTraceIdHeader: true }], "interaction"],
allowCookies: true,
enableXRay: true,
// Session attributes are deploy-time injected via config.json so
// multiple deploys can feed the same monitor while remaining
// filterable in the dashboard.
sessionAttributes: cfg.rum.sessionAttributes || {},
}
);
}).catch(function () { /* config missing — skip RUM init */ });
})();
</script>
</head>
<body>
<div class="card">
<h1>Serverless App</h1>
<p class="subtitle">Serverless reference architecture — Lambda + API Gateway + CloudFront</p>
<button id="btn" type="button">Call API</button>
<div class="spinner" id="spinner" role="progressbar" aria-label="Loading"></div>
<div class="response" id="response" role="status" aria-live="polite"></div>
</div>
<script>
const btn = document.getElementById("btn");
const spinner = document.getElementById("spinner");
const response = document.getElementById("response");
async function getApiUrl() {
// Reuse the promise the head IIFE created; the `??` fallback only fires if
// that <head> script never ran (stripped / CSP-blocked / failed), in which
// case we fetch config.json ourselves with the same status + content-type
// guard (the SPA 403/404 → index.html mapping returns HTML with a 200).
const cfg = await (window.__appConfigPromise ?? fetch("/config.json").then((r) => {
const ct = r.headers.get("content-type") || "";
if (!r.ok || ct.indexOf("application/json") === -1) {
throw new Error("config.json unavailable: " + r.status + " (" + ct + ")");
}
return r.json();
}));
if (!cfg || typeof cfg.apiUrl !== "string" || !cfg.apiUrl) {
throw new Error("config.json is missing apiUrl");
}
return cfg.apiUrl;
}
btn.addEventListener("click", async () => {
btn.disabled = true;
spinner.style.display = "block";
response.style.display = "none";
try {
const apiUrl = await getApiUrl();
// Idempotency-Key is required by the Lambda — Powertools' @idempotent
// layer keys on this header to deduplicate retries. A fresh key per click
// makes each user-initiated call a distinct logical operation; a real
// client should reuse the same key across automatic retries of the same
// logical request instead. crypto.randomUUID() is feature-detected so a
// pre-2022 browser (no Web Crypto randomUUID) still works — the key only
// needs to be reasonably unique, not cryptographically random.
const key = (typeof crypto !== "undefined" && crypto.randomUUID)
? crypto.randomUUID()
: Date.now().toString(36) + Math.random().toString(36).slice(2);
// apiUrl from API Gateway ends in "/", so strip it before joining.
const base = apiUrl.replace(/\/$/, "");
const res = await fetch(`${base}/greeting`, {
headers: { "Idempotency-Key": key },
});
const data = await res.json();
// Surface non-2xx responses as errors. The backend legitimately returns
// 400 (missing Idempotency-Key) and can return 429 under stage throttling;
// without this check those bodies would render in the green "success"
// style and never reach the RUM recordError hook below.
if (!res.ok) {
response.textContent = `Error ${res.status}: ${data.message ?? JSON.stringify(data)}`;
response.className = "response error";
if (window.cwr) window.cwr("recordError", new Error(`API ${res.status}`));
return;
}
response.textContent = data.message ?? JSON.stringify(data);
response.className = "response success";
} catch (err) {
response.textContent = `Error: ${err.message}`;
response.className = "response error";
// Caught errors aren't picked up by the RUM "errors" telemetry
// (which hooks window.onerror / unhandledrejection), so record
// them explicitly so they still surface in the RUM dashboard.
if (window.cwr) window.cwr("recordError", err);
} finally {
btn.disabled = false;
spinner.style.display = "none";
response.style.display = "block";
}
});
</script>
</body>
</html>