Skip to content
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

feat: merge redirect chains #232

Merged
merged 7 commits into from
Oct 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/codegen/codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { generateOptions } from './options'
import { getContentTypeWithCharsetHeader } from '@/utils/headers'
import { REQUIRED_IMPORTS } from '@/constants/imports'
import { generateImportStatement } from './imports'
import { mergeRedirects } from './codegen.utils'

interface GenerateScriptParams {
recording: GroupedProxyData
Expand Down Expand Up @@ -65,8 +66,9 @@ export function generateVUCode(

const groupSnippets = groups
.map(([groupName, recording]) => {
const mergedRecording = mergeRedirects(recording)
const requestSnippets = generateRequestSnippets(
recording,
mergedRecording,
rules,
correlationStateMap,
sequentialIdGenerator,
Expand Down
118 changes: 117 additions & 1 deletion src/codegen/codegen.utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { describe, expect, it } from 'vitest'

import { stringify } from './codegen.utils'
import { mergeRedirects, stringify } from './codegen.utils'
import {
createRequest,
createResponse,
createProxyData,
} from '@/test/factories/proxyData'

describe('Code generation - utils', () => {
describe('stringify', () => {
Expand Down Expand Up @@ -88,4 +93,115 @@ describe('Code generation - utils', () => {
)
})
})

describe('mergeRedirects', () => {
const createRedirectMock = (id: string, from: string, to: string) => {
const request = createRequest({ url: from })
const response = createResponse({
statusCode: 301,
headers: [['location', to]],
})
return createProxyData({ id, request, response })
}

it('should resolve redirect chains with absolute URLs', () => {
const first = createRedirectMock(
'1',
'http://first.com',
'http://second.com'
)
const last = createProxyData({
id: '4',
request: createRequest({ url: 'http://last.com' }),
response: createResponse({ content: "I'm the last one" }),
})

const recording = [
first,
createRedirectMock('2', 'http://second.com', 'http://third.com'),
createRedirectMock('3', 'http://third.com', 'http://last.com'),
last,
]

expect(mergeRedirects(recording)).toEqual([
{ ...first, response: last.response },
])
})

it('should resolve redirect chains with relative path', () => {
const first = createRedirectMock('1', 'http://domain.com', '/second')
const last = createProxyData({
id: '4',
request: createRequest({ url: 'http://domain.com/last' }),
response: createResponse({ content: "I'm the last one" }),
})

const recording = [
first,
createRedirectMock('2', 'http://domain.com/second', '/third'),
createRedirectMock('3', 'http://domain.com/third', '/last'),
last,
]

expect(mergeRedirects(recording)).toEqual([
{ ...first, response: last.response },
])
})

it('should resolve redirect chains that are out of order', () => {
const from = createRedirectMock('1', 'http://a.com', 'http://b.com')
const nonRedirect = createProxyData({ id: '2' })
const to = createProxyData({
id: '3',
request: createRequest({ url: 'http://b.com' }),
response: createResponse({ content: "I'm the final response" }),
})

// "from" and "to" are not in order
const recording = [from, nonRedirect, to]

expect(mergeRedirects(recording)).toEqual([
{ ...from, response: to.response },
nonRedirect,
])
})

it("should resolve redirects to the same URL that don't belong to the redirect chain", () => {
// request to "b.com" is made more than once
// ensures that the redirect chain is not resolved with the wrong request
const requestB = createProxyData({
id: '1',
request: createRequest({ url: 'http://b.com' }),
response: createResponse({ content: "I don't come from a redirect" }),
})
const redirectFromAToB = createRedirectMock(
'2',
'http://a.com',
'http://b.com'
)
const requestBFromRedirect = createProxyData({
id: '3',
request: createRequest({ url: 'http://b.com' }),
response: createResponse({ content: "I'm redirected from a.com" }),
})

const recording = [requestB, redirectFromAToB, requestBFromRedirect]

expect(mergeRedirects(recording)).toEqual([
requestB,
{ ...redirectFromAToB, response: requestBFromRedirect.response },
])
})

it('should not change the request if a redirect is not found', () => {
const redirect = createRedirectMock(
'1',
'http://first.com',
'http://not-present-in-recording.com'
)
const recording = [redirect, createProxyData({ id: '2' })]

expect(mergeRedirects(recording)).toEqual(recording)
})
})
})
90 changes: 90 additions & 0 deletions src/codegen/codegen.utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { ProxyData } from '@/types'
import { getLocationHeader } from '@/utils/headers'

// TODO: find a well-maintained library for this
export function stringify(value: unknown): string {
if (typeof value === 'string') {
Expand All @@ -19,3 +22,90 @@ export function stringify(value: unknown): string {

return `${value}`
}

function isRedirect(response: ProxyData['response']) {
if (!response) return false
return [301, 302].includes(response.statusCode)
}

function isValidUrl(url: string) {
try {
new URL(url)
return true
} catch {
return false
}
}

function getRedirectUrl(
request: ProxyData['request'],
response: ProxyData['response']
) {
if (!response || !isRedirect(response)) return undefined
const location = getLocationHeader(response.headers)

if (!location) return undefined
if (isValidUrl(location)) return location

return buildLocationUrl(request, location)
}

function buildLocationUrl(request: ProxyData['request'], location: string) {
const { protocol, host } = new URL(request.url)
return `${protocol}//${host}${location}`
}

export function mergeRedirects(recording: ProxyData[]) {
const result = []
const processed = new Set()

for (const item of recording) {
const { response, request, id } = item

// Skip requests that have been processed
if (processed.has(id)) {
continue
}

// Requests without response don't need to be merged
if (!response) {
result.push(item)
processed.add(id)
continue
}

// Requests that are not redirects don't need to be merged
if (!isRedirect(response)) {
result.push(item)
processed.add(id)
continue
}

let finalResponse: ProxyData['response'] = response
let nextUrl = getRedirectUrl(request, response)

// Find the final response by following the redirect chain
while (nextUrl) {
// Find request that corresponds to the next URL in the chain and that haven't been processed yet
const nextRequest = recording.find(
(req) => req.request.url === nextUrl && !processed.has(req.id)
)
if (nextRequest) {
processed.add(nextRequest.id)
finalResponse = nextRequest.response
nextUrl = getRedirectUrl(request, finalResponse)
} else {
break
}
}

result.push({
...item,
response: finalResponse,
})

processed.add(id)
}

return result
}
9 changes: 9 additions & 0 deletions src/utils/headers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,12 @@ export function upsertHeader(
[key, value],
]
}

/**
* Returns the value of the location header
* @example
* application/json
*/
export function getLocationHeader(headers: Header[]) {
return getHeaderValues(headers, 'location')[0]
}