-
Notifications
You must be signed in to change notification settings - Fork 5
feat: add mock-upstream mode for fetch/http/nextjs e2e suites #125
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
116 changes: 116 additions & 0 deletions
116
src/instrumentation/libraries/e2e-common/external-http.cjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| const http = require("http"); | ||
| const https = require("https"); | ||
|
|
||
| const EXTERNAL_HTTP_TIMEOUT_MS = Number(process.env.EXTERNAL_HTTP_TIMEOUT_MS || "3000"); | ||
| const USE_MOCK_EXTERNALS = ["1", "true", "yes"].includes((process.env.USE_MOCK_EXTERNALS || "").toLowerCase()); | ||
| const MOCK_SERVER_BASE_URL = process.env.MOCK_SERVER_BASE_URL || "http://mock-upstream:8081"; | ||
|
|
||
| function upstreamUrl(rawUrl) { | ||
| if (!USE_MOCK_EXTERNALS) { | ||
| return rawUrl; | ||
| } | ||
| const src = new URL(rawUrl); | ||
| const base = new URL(MOCK_SERVER_BASE_URL); | ||
| return `${base.origin}${src.pathname}${src.search}`; | ||
| } | ||
|
|
||
| function withExternalTimeout(init = {}) { | ||
| if (init.signal) { | ||
| return init; | ||
| } | ||
|
|
||
| const timeoutSignal = createTimeoutSignal(EXTERNAL_HTTP_TIMEOUT_MS); | ||
| return { | ||
| ...init, | ||
| ...(timeoutSignal ? { signal: timeoutSignal } : {}), | ||
| }; | ||
| } | ||
|
|
||
| function createTimeoutSignal(timeoutMs) { | ||
| if (typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function") { | ||
| return AbortSignal.timeout(timeoutMs); | ||
| } | ||
|
|
||
| if (typeof AbortController === "undefined") { | ||
| return undefined; | ||
| } | ||
|
|
||
| const controller = new AbortController(); | ||
| const timer = setTimeout(() => controller.abort(), timeoutMs); | ||
| if (typeof timer.unref === "function") { | ||
| timer.unref(); | ||
| } | ||
| controller.signal.addEventListener("abort", () => clearTimeout(timer), { once: true }); | ||
| return controller.signal; | ||
| } | ||
|
|
||
| function resolveClient(target) { | ||
| return target.protocol === "https:" ? https : http; | ||
| } | ||
|
|
||
| function getExternalHttpTimeoutMs() { | ||
| return EXTERNAL_HTTP_TIMEOUT_MS; | ||
| } | ||
|
|
||
| function getTextViaNode(rawUrl) { | ||
| const target = new URL(upstreamUrl(rawUrl.toString())); | ||
| const client = resolveClient(target); | ||
| return new Promise((resolve, reject) => { | ||
| client | ||
| .get( | ||
| target, | ||
| { | ||
| timeout: EXTERNAL_HTTP_TIMEOUT_MS, | ||
| }, | ||
| (response) => { | ||
| let data = ""; | ||
| response.on("data", (chunk) => { | ||
| data += chunk; | ||
| }); | ||
| response.on("end", () => resolve(data)); | ||
| }, | ||
| ) | ||
| .on("error", reject); | ||
| }); | ||
| } | ||
|
|
||
| function requestTextViaNode(rawUrl, method, body) { | ||
| const target = new URL(upstreamUrl(rawUrl.toString())); | ||
| const client = resolveClient(target); | ||
| return new Promise((resolve, reject) => { | ||
| const request = client.request( | ||
| { | ||
| protocol: target.protocol, | ||
| hostname: target.hostname, | ||
| port: target.port ? Number(target.port) : target.protocol === "https:" ? 443 : 80, | ||
| path: `${target.pathname}${target.search}`, | ||
| method, | ||
| headers: { | ||
| "Content-Type": "application/json", | ||
| }, | ||
| timeout: EXTERNAL_HTTP_TIMEOUT_MS, | ||
| }, | ||
| (response) => { | ||
| let data = ""; | ||
| response.on("data", (chunk) => { | ||
| data += chunk; | ||
| }); | ||
| response.on("end", () => resolve(data)); | ||
| }, | ||
| ); | ||
|
|
||
| request.on("error", reject); | ||
| if (body) { | ||
| request.write(body); | ||
| } | ||
| request.end(); | ||
| }); | ||
| } | ||
|
|
||
| module.exports = { | ||
| upstreamUrl, | ||
| withExternalTimeout, | ||
| getExternalHttpTimeoutMs, | ||
| getTextViaNode, | ||
| requestTextViaNode, | ||
| }; |
115 changes: 115 additions & 0 deletions
115
src/instrumentation/libraries/e2e-common/mock-upstream/mock-server.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| #!/usr/bin/env node | ||
|
|
||
| const http = require("http"); | ||
| const { URL } = require("url"); | ||
|
|
||
| const port = Number(process.env.MOCK_UPSTREAM_PORT || "8081"); | ||
|
|
||
| function sendJson(res, payload, status = 200) { | ||
| const body = Buffer.from(JSON.stringify(payload)); | ||
| res.writeHead(status, { | ||
| "Content-Type": "application/json", | ||
| "Content-Length": String(body.length), | ||
| }); | ||
| res.end(body); | ||
| } | ||
|
|
||
| function sendText(res, payload, status = 200) { | ||
| const body = Buffer.from(payload, "utf-8"); | ||
| res.writeHead(status, { | ||
| "Content-Type": "text/plain; charset=utf-8", | ||
| "Content-Length": String(body.length), | ||
| }); | ||
| res.end(body); | ||
| } | ||
|
|
||
| function readBody(req) { | ||
| return new Promise((resolve) => { | ||
| const chunks = []; | ||
| req.on("data", (chunk) => chunks.push(chunk)); | ||
| req.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8"))); | ||
| req.on("error", () => resolve("")); | ||
| }); | ||
| } | ||
|
|
||
| function mockPost(id) { | ||
| return { id, title: `Mock Post ${id}`, body: `Body for post ${id}`, userId: ((id - 1) % 10) + 1 }; | ||
| } | ||
|
|
||
| const server = http.createServer(async (req, res) => { | ||
| const url = new URL(req.url || "/", `http://localhost:${port}`); | ||
| const path = url.pathname; | ||
| const method = req.method || "GET"; | ||
|
|
||
| if (path === "/health") { | ||
| return sendJson(res, { status: "ok" }); | ||
| } | ||
|
|
||
| if (method === "GET" && path === "/posts/1") { | ||
| return sendJson(res, mockPost(1)); | ||
| } | ||
|
|
||
| if (method === "GET" && path === "/posts") { | ||
| const limit = Number(url.searchParams.get("_limit") || "5"); | ||
| const posts = Array.from({ length: limit }, (_, i) => mockPost(i + 1)); | ||
| return sendJson(res, posts); | ||
| } | ||
|
|
||
| if (method === "GET" && path === "/users") { | ||
| return sendJson( | ||
| res, | ||
| Array.from({ length: 10 }, (_, i) => ({ | ||
| id: i + 1, | ||
| name: `User ${i + 1}`, | ||
| username: `user${i + 1}`, | ||
| email: `user${i + 1}@example.com`, | ||
| })), | ||
| ); | ||
| } | ||
|
|
||
| if (method === "POST" && path === "/posts") { | ||
| const raw = await readBody(req); | ||
| let parsed = {}; | ||
| try { | ||
| parsed = raw ? JSON.parse(raw) : {}; | ||
| } catch { | ||
| parsed = {}; | ||
| } | ||
| return sendJson( | ||
| res, | ||
| { | ||
| id: 101, | ||
| title: parsed.title || "mock-title", | ||
| body: parsed.body || "", | ||
| userId: parsed.userId || 1, | ||
| test: parsed.test || undefined, | ||
| }, | ||
| 201, | ||
| ); | ||
| } | ||
|
|
||
| if (method === "GET" && path === "/robots.txt") { | ||
| return sendText(res, "User-agent: *\nDisallow: /deny\n"); | ||
| } | ||
|
|
||
| if (method === "GET" && url.searchParams.get("format") === "j1") { | ||
| const location = decodeURIComponent(path.replace(/^\/+/, "") || "San Francisco"); | ||
| return sendJson(res, { | ||
| current_condition: [ | ||
| { | ||
| temp_F: "72", | ||
| humidity: "55", | ||
| localObsDateTime: "2026-02-26 07:00 PM", | ||
| weatherDesc: [{ value: `Clear (${location})` }], | ||
| pressure: "1015", | ||
| }, | ||
| ], | ||
| }); | ||
| } | ||
|
|
||
| return sendJson(res, { error: `No mock route for ${method} ${path}` }, 404); | ||
| }); | ||
|
|
||
| server.listen(port, "0.0.0.0", () => { | ||
| console.log(`Mock upstream listening on :${port}`); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.