Skip to content

Commit 9e26f74

Browse files
Merge pull request #717 from freeCodeCamp/main
Create a new pull request by comparing changes across two branches
2 parents fcc88c8 + a073b39 commit 9e26f74

File tree

26 files changed

+973
-719
lines changed

26 files changed

+973
-719
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,3 +210,6 @@ curriculum/build
210210
### Playwright ###
211211

212212
/playwright
213+
214+
### Shadow Testing Log Files Folder ###
215+
api/logs/

api/src/app.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ import bouncer from './plugins/bouncer';
2727
import errorHandling from './plugins/error-handling';
2828
import csrf from './plugins/csrf';
2929
import notFound from './plugins/not-found';
30+
import shadowCapture from './plugins/shadow-capture';
31+
3032
import * as publicRoutes from './routes/public';
3133
import * as protectedRoutes from './routes/protected';
3234

@@ -35,6 +37,7 @@ import {
3537
EMAIL_PROVIDER,
3638
FCC_ENABLE_DEV_LOGIN_MODE,
3739
FCC_ENABLE_SWAGGER_UI,
40+
FCC_ENABLE_SHADOW_CAPTURE,
3841
FREECODECAMP_NODE_ENV
3942
} from './utils/env';
4043
import { isObjectID } from './utils/validation';
@@ -127,6 +130,10 @@ export const build = async (
127130
fastify.log.info(`Swagger UI available at ${API_LOCATION}/documentation`);
128131
}
129132

133+
if (FCC_ENABLE_SHADOW_CAPTURE) {
134+
void fastify.register(shadowCapture);
135+
}
136+
130137
void fastify.register(auth);
131138
void fastify.register(notFound);
132139
void fastify.register(prismaPlugin);

api/src/plugins/shadow-capture.ts

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
import { randomUUID } from 'crypto';
2+
import { appendFileSync, mkdirSync } from 'fs';
3+
import { join } from 'path';
4+
import type { FastifyPluginCallback } from 'fastify';
5+
6+
import fp from 'fastify-plugin';
7+
import { FastifyReply } from 'fastify/types/reply';
8+
import { FastifyRequest } from 'fastify/types/request';
9+
10+
const LOGS_DIRECTORY = 'logs';
11+
const REQUEST_CAPTURE_FILE = 'request-capture.jsonl';
12+
const RESPONSE_CAPTURE_FILE = 'response-capture.jsonl';
13+
14+
let REQUEST_BUFFER: unknown[] = [];
15+
let RESPONSE_BUFFER: unknown[] = [];
16+
17+
/**
18+
* Plugin for capturing requests and responses to allow shadow testing.
19+
*
20+
* @param fastify The Fastify instance.
21+
* @param _options Options passed to the plugin via `fastify.register(plugin, options)`.
22+
* @param done Callback to signal that the logic has completed.
23+
*/
24+
const shadowCapture: FastifyPluginCallback = (fastify, _options, done) => {
25+
mkdirSync(LOGS_DIRECTORY, { recursive: true });
26+
fastify.addHook('onRequest', (req, rep, done) => {
27+
// Attach timestamp at beginning of lifecycle
28+
// @ts-expect-error Exists
29+
req.__timestamp = Date.now();
30+
31+
// Give request and response same id to match.
32+
const id = randomUUID();
33+
// @ts-expect-error Exists
34+
req.__id = id;
35+
// @ts-expect-error Exists
36+
rep.__id = id;
37+
done();
38+
});
39+
40+
// Body is only included after `Parsing` lifecycle
41+
fastify.addHook('preValidation', (req, rep, done) => {
42+
captureRequest(req);
43+
done();
44+
});
45+
46+
fastify.addHook('onSend', async (_req, rep, payload) => {
47+
// @ts-expect-error Exists
48+
rep.__payload = payload;
49+
return payload;
50+
});
51+
52+
fastify.addHook('onResponse', (_req, rep, done) => {
53+
captureReply(rep);
54+
done();
55+
});
56+
57+
done();
58+
};
59+
60+
/* eslint-disable @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-return */
61+
function captureRequest(req: FastifyRequest) {
62+
const savedRequest = {
63+
// @ts-expect-error Exists
64+
id: req.__id,
65+
// @ts-expect-error Exists
66+
timestamp: req.__timestamp,
67+
url: req.url,
68+
headers: omit(req.headers, 'cookie'),
69+
cookies: include(req.cookies, '_csrf', 'csrf_token', 'jwt_access_token'),
70+
user: req.user,
71+
body: req.body
72+
};
73+
74+
if (REQUEST_BUFFER.length > 10) {
75+
appendFileSync(
76+
join(LOGS_DIRECTORY, REQUEST_CAPTURE_FILE),
77+
REQUEST_BUFFER.map(rb => JSON.stringify(rb)).join('\n') + '\n'
78+
);
79+
REQUEST_BUFFER = [savedRequest];
80+
} else {
81+
REQUEST_BUFFER.push(savedRequest);
82+
}
83+
}
84+
85+
function captureReply(rep: FastifyReply) {
86+
const savedReply = {
87+
// @ts-expect-error Exists
88+
id: rep.__id,
89+
headers: rep.getHeaders(),
90+
timestamp: Date.now(),
91+
// @ts-expect-error Exists
92+
payload: rep.__payload,
93+
statusCode: rep.statusCode
94+
};
95+
96+
if (RESPONSE_BUFFER.length > 10) {
97+
appendFileSync(
98+
join(LOGS_DIRECTORY, RESPONSE_CAPTURE_FILE),
99+
RESPONSE_BUFFER.map(rb => JSON.stringify(rb)).join('\n') + '\n'
100+
);
101+
RESPONSE_BUFFER = [savedReply];
102+
} else {
103+
RESPONSE_BUFFER.push(savedReply);
104+
}
105+
}
106+
107+
/**
108+
* Returns a subset of the given object with the values or properties given removed.
109+
* @param obj - An array or an object literal.
110+
* @param vals - Items or properties to exclude from `obj`.
111+
* @returns Subset of `obj`.
112+
*/
113+
function omit(obj: Record<string, unknown> | unknown[], ...vals: unknown[]) {
114+
if (Array.isArray(obj)) {
115+
return obj.filter(o => !vals.includes(o));
116+
} else {
117+
return Object.keys(obj)
118+
.filter(k => {
119+
return !vals.includes(k);
120+
})
121+
.reduce((acc, curr) => ({ ...acc, [curr]: obj[curr] }), {});
122+
}
123+
}
124+
125+
function include(obj: Record<string, unknown> | unknown[], ...vals: unknown[]) {
126+
if (Array.isArray(obj)) {
127+
return obj.filter(o => vals.includes(o));
128+
} else {
129+
return Object.keys(obj)
130+
.filter(k => {
131+
return vals.includes(k);
132+
})
133+
.reduce((acc, curr) => ({ ...acc, [curr]: obj[curr] }), {});
134+
}
135+
}
136+
137+
export default fp(shadowCapture);

api/src/utils/env.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,8 @@ export const FCC_ENABLE_SWAGGER_UI =
125125
process.env.FCC_ENABLE_SWAGGER_UI === 'true';
126126
export const FCC_ENABLE_DEV_LOGIN_MODE =
127127
process.env.FCC_ENABLE_DEV_LOGIN_MODE === 'true';
128+
export const FCC_ENABLE_SHADOW_CAPTURE =
129+
process.env.FCC_ENABLE_SHADOW_CAPTURE === 'true';
128130
export const SENTRY_DSN =
129131
process.env.SENTRY_DSN === 'dsn_from_sentry_dashboard'
130132
? ''

curriculum/challenges/english/01-responsive-web-design/applied-visual-design/create-a-horizontal-line-using-the-hr-element.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ You can use the `hr` tag to add a horizontal line across the width of its contai
1515

1616
Add an `hr` tag underneath the `h4` which contains the card title.
1717

18-
**Note:** In HTML, `hr` is a self-closing tag, and therefore doesn't need a separate closing tag.
18+
**Note:** In HTML, `hr` is a void element, and therefore doesn't need a separate closing tag.
1919

2020
# --hints--
2121

curriculum/challenges/english/01-responsive-web-design/basic-html-and-html5/add-images-to-your-website.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ An example of this would be:
1616
<img src="https://www.freecatphotoapp.com/your-image.jpg">
1717
```
1818

19-
Note that `img` elements are self-closing.
19+
Note that `img` is a void element.
2020

2121
All `img` elements **must** have an `alt` attribute. The text inside an `alt` attribute is used for screen readers to improve accessibility and is displayed if the image fails to load.
2222

curriculum/challenges/english/01-responsive-web-design/basic-html-and-html5/add-placeholder-text-to-a-text-field.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ You can create placeholder text like so:
1717
<input type="text" placeholder="this is placeholder text">
1818
```
1919

20-
**Note:** Remember that `input` elements are self-closing.
20+
**Note:** Remember that `input` is a void element.
2121

2222
# --instructions--
2323

curriculum/challenges/english/01-responsive-web-design/basic-html-and-html5/create-a-text-field.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ You can create a text input like this:
1919
<input type="text">
2020
```
2121

22-
Note that `input` elements are self-closing.
22+
Note that `input` is a void element.
2323

2424
# --instructions--
2525

curriculum/challenges/english/03-front-end-development-libraries/react/learn-about-self-closing-jsx-tags.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ So far, you’ve seen how JSX differs from HTML in a key way with the use of `cl
1212

1313
Another important way in which JSX differs from HTML is in the idea of the self-closing tag.
1414

15-
In HTML, almost all tags have both an opening and closing tag: `<div></div>`; the closing tag always has a forward slash before the tag name that you are closing. However, there are special instances in HTML called “self-closing tags”, or tags that don’t require both an opening and closing tag before another tag can start.
15+
In HTML, almost all tags have both an opening and closing tag: `<div></div>`; the closing tag always has a forward slash before the tag name that you are closing. However, there are special instances in HTML called <dfn>void elements</dfn>, or elements that don’t require both an opening and closing tag before another element can start.
1616

1717
For example the line-break tag can be written as `<br>` or as `<br />`, but should never be written as `<br></br>`, since it doesn't contain any content.
1818

curriculum/challenges/english/07-scientific-computing-with-python/learn-encapsulation-by-building-a-projectile-trajectory-calculator/663353465bfb14259717da93.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ The method should return the correct output.
4747
```js
4848
({
4949
test: () => assert(runPython(
50-
`str = """
50+
`a = """
5151
x y
5252
0 3.00
5353
1 3.90
@@ -65,7 +65,7 @@ The method should return the correct output.
6565
"""
6666
ball = Projectile(10, 3, 45)
6767
g = Graph(ball.calculate_all_coordinates())
68-
g.create_coordinates_table() == str`
68+
g.create_coordinates_table() == a`
6969
))
7070
})
7171
```

0 commit comments

Comments
 (0)