-
Notifications
You must be signed in to change notification settings - Fork 156
fix(parser): allow SQS envelopes to handle non-JSON strings #3513
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
10 commits
Select commit
Hold shift + click to select a range
5503d4a
fix(parser): allow SQS envelopes to handle non-JSON strings
dreamorosi 09e1090
chore: add placehoder test
dreamorosi 6a4d34d
chore: add placehoder coverage ignore
dreamorosi 8cf4cdc
tests: complete unit tests
dreamorosi f0ec81c
improv: wrap json parsing in parse method
dreamorosi b1f4de7
fix: regression in error cause
dreamorosi 989c834
improv: remove some duplication
dreamorosi ce3cc3b
refactor: remove further duplication
dreamorosi dc2d2a5
Merge branch 'main' into fix/sqs_envelopes
dreamorosi e8837f8
Merge branch 'main' into fix/sqs_envelopes
dreamorosi 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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,185 @@ | ||
import { ZodError, type ZodIssue, type ZodSchema, type z } from 'zod'; | ||
import { ParseError } from '../errors.js'; | ||
import { SnsSqsNotificationSchema } from '../schemas/sns.js'; | ||
import { SqsSchema } from '../schemas/sqs.js'; | ||
import type { ParsedResult, SnsSqsNotification } from '../types/index.js'; | ||
import { envelopeDiscriminator } from './envelope.js'; | ||
|
||
const createError = (index: number, issues: ZodIssue[]) => ({ | ||
issues: issues.map((issue) => ({ | ||
...issue, | ||
path: ['Records', index, 'body', ...issue.path], | ||
})), | ||
}); | ||
|
||
type ParseStepSuccess<T> = { | ||
success: true; | ||
data: T; | ||
}; | ||
|
||
type ParseStepError = { | ||
success: false; | ||
error: { issues: ZodIssue[] }; | ||
}; | ||
|
||
type ParseStepResult<T> = ParseStepSuccess<T> | ParseStepError; | ||
|
||
const parseStep = <U>( | ||
parser: (data: unknown) => z.SafeParseReturnType<unknown, U>, | ||
data: unknown, | ||
index: number | ||
): ParseStepResult<U> => { | ||
const result = parser(data); | ||
return result.success | ||
? { success: true, data: result.data } | ||
: { | ||
success: false, | ||
error: createError(index, result.error.issues), | ||
}; | ||
}; | ||
|
||
/** | ||
* SNS plus SQS Envelope to extract array of Records | ||
* | ||
* Published messages from SNS to SQS has a slightly different payload structure | ||
* than regular SNS messages, and when sent to SQS, they are stringified into the | ||
* `body` field of each SQS record. | ||
* | ||
* To parse the `Message` field of the SNS notification, we need to: | ||
* 1. Parse SQS schema with incoming data | ||
* 2. `JSON.parse()` the SNS payload and parse against SNS Notification schema | ||
* 3. Finally, parse the payload against the provided schema | ||
*/ | ||
export const SnsSqsEnvelope = { | ||
/** | ||
* This is a discriminator to differentiate whether an envelope returns an array or an object | ||
* @hidden | ||
*/ | ||
[envelopeDiscriminator]: 'array' as const, | ||
parse<T extends ZodSchema>(data: unknown, schema: T): z.infer<T>[] { | ||
let parsedEnvelope: z.infer<typeof SqsSchema>; | ||
try { | ||
parsedEnvelope = SqsSchema.parse(data); | ||
} catch (error) { | ||
throw new ParseError('Failed to parse SQS Envelope', { | ||
cause: error as Error, | ||
}); | ||
} | ||
|
||
return parsedEnvelope.Records.map((record, recordIndex) => { | ||
try { | ||
return schema.parse( | ||
SnsSqsNotificationSchema.parse(JSON.parse(record.body)).Message | ||
); | ||
} catch (error) { | ||
throw new ParseError( | ||
`Failed to parse SQS Record at index ${recordIndex}`, | ||
{ | ||
cause: new ZodError( | ||
error instanceof ZodError | ||
? (error as ZodError).issues.map((issue) => ({ | ||
...issue, | ||
path: ['Records', recordIndex, 'body', ...issue.path], | ||
})) | ||
: [ | ||
{ | ||
code: 'custom', | ||
message: 'Invalid JSON', | ||
path: ['Records', recordIndex, 'body'], | ||
}, | ||
] | ||
), | ||
} | ||
); | ||
} | ||
}); | ||
}, | ||
|
||
safeParse<T extends ZodSchema>( | ||
data: unknown, | ||
schema: T | ||
): ParsedResult<unknown, z.infer<T>[]> { | ||
const parsedEnvelope = SqsSchema.safeParse(data); | ||
if (!parsedEnvelope.success) { | ||
return { | ||
success: false, | ||
error: new ParseError('Failed to parse SQS envelope', { | ||
cause: parsedEnvelope.error, | ||
}), | ||
originalEvent: data, | ||
}; | ||
} | ||
|
||
const parseRecord = ( | ||
record: { body: string }, | ||
index: number | ||
): ParseStepResult<z.infer<T>> => { | ||
try { | ||
const body = JSON.parse(record.body); | ||
const notification = parseStep<SnsSqsNotification>( | ||
(data) => SnsSqsNotificationSchema.safeParse(data), | ||
body, | ||
index | ||
); | ||
if (!notification.success) return notification; | ||
|
||
return parseStep<z.infer<T>>( | ||
(data) => schema.safeParse(data), | ||
notification.data.Message, | ||
index | ||
); | ||
} catch { | ||
return { | ||
success: false, | ||
error: createError(index, [ | ||
{ | ||
code: 'custom', | ||
message: 'Invalid JSON', | ||
path: [], | ||
}, | ||
]), | ||
}; | ||
} | ||
}; | ||
|
||
const result = parsedEnvelope.data.Records.reduce<{ | ||
success: boolean; | ||
records: z.infer<T>[]; | ||
errors: { | ||
[key: number | string]: { issues: ZodIssue[] }; | ||
}; | ||
}>( | ||
(acc, record, index) => { | ||
const parsed = parseRecord(record, index); | ||
if (!parsed.success) { | ||
acc.success = false; | ||
acc.errors[index] = parsed.error; | ||
} else { | ||
acc.records.push(parsed.data); | ||
} | ||
return acc; | ||
}, | ||
{ success: true, records: [], errors: {} } | ||
); | ||
|
||
if (result.success) { | ||
return { success: true, data: result.records }; | ||
} | ||
|
||
const indexes = Object.keys(result.errors); | ||
const errorMessage = | ||
indexes.length > 1 | ||
? `Failed to parse SQS Records at indexes ${indexes.join(', ')}` | ||
: `Failed to parse SQS Record at index ${indexes[0]}`; | ||
|
||
return { | ||
success: false, | ||
error: new ParseError(errorMessage, { | ||
cause: new ZodError( | ||
Object.values(result.errors).flatMap((e) => e.issues) | ||
), | ||
}), | ||
originalEvent: data, | ||
}; | ||
}, | ||
}; |
Oops, something went wrong.
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.