mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(appsync): implement JS subscription filter helper (#7442)
This commit is contained in:
1 parent
851a7521a7
commit
be50db39ab
2 files changed
+298
-1
No files matched your search
@@ -37,6 +37,7 @@ const UTILS_DIR = path.join(ROOT, 'node_modules', '@aws-appsync', 'utils');
|
||||
// - in code *or in a comment* - ends the string and the sidecar fails to boot with a SyntaxError.
|
||||
// Escape them (\` and \${) or write around them.
|
||||
const UTILS_INDEX = `
|
||||
import { Buffer } from 'node:buffer';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
const ERROR_MARKER = Symbol.for('floci.appsync.error');
|
||||
const RETURN_MARKER = Symbol.for('floci.appsync.earlyReturn');
|
||||
@@ -100,6 +101,120 @@ const unsupported = (name) => () => {
|
||||
'FlociUnsupported');
|
||||
};
|
||||
|
||||
// Local safety budgets bound expansion in the shared resolver process, not AWS protocol limits.
|
||||
const MAX_SUBSCRIPTION_FILTER_GROUPS = 1000;
|
||||
const MAX_SUBSCRIPTION_FILTER_ENTRIES = 10000;
|
||||
const MAX_SUBSCRIPTION_FILTER_OUTPUT_BYTES = 5 * 1024 * 1024;
|
||||
const filterJsonBytes = new WeakMap();
|
||||
const requireFilterGroupBudget = (count) => {
|
||||
if (count > MAX_SUBSCRIPTION_FILTER_GROUPS) {
|
||||
throw new RangeError('subscription filter exceeds ' + MAX_SUBSCRIPTION_FILTER_GROUPS + ' groups');
|
||||
}
|
||||
};
|
||||
const countFilterEntries = (groups) => groups.reduce((count, group) => count + group.length, 0);
|
||||
const requireFilterEntryBudget = (count) => {
|
||||
if (count > MAX_SUBSCRIPTION_FILTER_ENTRIES) {
|
||||
throw new RangeError('subscription filter exceeds ' + MAX_SUBSCRIPTION_FILTER_ENTRIES
|
||||
+ ' filter entries');
|
||||
}
|
||||
};
|
||||
const countFilterJsonBytes = (groups) => {
|
||||
let total = 0;
|
||||
for (const group of groups) {
|
||||
for (const filter of group) {
|
||||
let filterBytes = filterJsonBytes.get(filter);
|
||||
if (filterBytes === undefined) {
|
||||
filterBytes = Buffer.byteLength(JSON.stringify(filter));
|
||||
filterJsonBytes.set(filter, filterBytes);
|
||||
}
|
||||
total += filterBytes;
|
||||
if (total > MAX_SUBSCRIPTION_FILTER_OUTPUT_BYTES) {
|
||||
return MAX_SUBSCRIPTION_FILTER_OUTPUT_BYTES + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return total;
|
||||
};
|
||||
const requireFilterOutputBudget = (groups, entries, filterBytes) => {
|
||||
// Wrapper and comma allowance exceeds the JSON structure's actual per-group overhead.
|
||||
if (filterBytes + 2 * entries + 32 * groups + 32 > MAX_SUBSCRIPTION_FILTER_OUTPUT_BYTES) {
|
||||
throw new RangeError('subscription filter exceeds '
|
||||
+ MAX_SUBSCRIPTION_FILTER_OUTPUT_BYTES + ' output bytes');
|
||||
}
|
||||
};
|
||||
|
||||
const joinFilterGroups = (left, right) => {
|
||||
const groupCount = left.length * right.length;
|
||||
const entryCount = countFilterEntries(left) * right.length
|
||||
+ countFilterEntries(right) * left.length;
|
||||
requireFilterGroupBudget(groupCount);
|
||||
requireFilterEntryBudget(entryCount);
|
||||
requireFilterOutputBudget(groupCount, entryCount,
|
||||
countFilterJsonBytes(left) * right.length + countFilterJsonBytes(right) * left.length);
|
||||
return left.flatMap((base) => right.map((branch) => [...base, ...branch]));
|
||||
};
|
||||
|
||||
const expandSubscriptionFilter = (input, ignored) => {
|
||||
if (input === null || typeof input !== 'object' || Array.isArray(input)) {
|
||||
return [];
|
||||
}
|
||||
let groups = [[]];
|
||||
for (const [field, conditions] of Object.entries(input)) {
|
||||
let alternatives = [];
|
||||
if (field === 'and' && Array.isArray(conditions)) {
|
||||
let combined = [[]];
|
||||
for (const condition of conditions) {
|
||||
const nested = expandSubscriptionFilter(condition, ignored);
|
||||
if (nested.length) {
|
||||
combined = joinFilterGroups(combined, nested);
|
||||
}
|
||||
}
|
||||
alternatives = combined.filter((filters) => filters.length);
|
||||
} else if (field === 'or' && Array.isArray(conditions)) {
|
||||
for (const condition of conditions) {
|
||||
const nested = expandSubscriptionFilter(condition, ignored);
|
||||
const groupCount = alternatives.length + nested.length;
|
||||
const entryCount = countFilterEntries(alternatives) + countFilterEntries(nested);
|
||||
requireFilterGroupBudget(groupCount);
|
||||
requireFilterEntryBudget(entryCount);
|
||||
requireFilterOutputBudget(groupCount, entryCount,
|
||||
countFilterJsonBytes(alternatives) + countFilterJsonBytes(nested));
|
||||
alternatives.push(...nested);
|
||||
}
|
||||
} else if (!ignored.has(field) && conditions !== null
|
||||
&& typeof conditions === 'object' && !Array.isArray(conditions)) {
|
||||
for (const [operator, value] of Object.entries(conditions)) {
|
||||
requireFilterGroupBudget(alternatives.length + 1);
|
||||
alternatives.push([{ fieldName: field, operator, value }]);
|
||||
}
|
||||
}
|
||||
if (alternatives.length) {
|
||||
groups = joinFilterGroups(groups, alternatives);
|
||||
}
|
||||
}
|
||||
return groups.filter((filters) => filters.length);
|
||||
};
|
||||
|
||||
const toSubscriptionFilter = (input, ignoredFields = [], rules = {}) => {
|
||||
if (input === null) {
|
||||
return null;
|
||||
}
|
||||
const base = expandSubscriptionFilter(input, new Set(ignoredFields ?? []));
|
||||
const strict = [];
|
||||
if (rules !== null && typeof rules === 'object' && !Array.isArray(rules)) {
|
||||
for (const [fieldName, conditions] of Object.entries(rules)) {
|
||||
if (conditions !== null && typeof conditions === 'object' && !Array.isArray(conditions)) {
|
||||
for (const [operator, value] of Object.entries(conditions)) {
|
||||
requireFilterGroupBudget(strict.length + 1);
|
||||
strict.push([{ fieldName, operator, value }]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const groups = strict.length ? joinFilterGroups(base.length ? base : [[]], strict) : base;
|
||||
return { filterGroup: groups.map((filters) => ({ filters })) };
|
||||
};
|
||||
|
||||
export const util = {
|
||||
error(message, type, data, errorInfo) { throw new TemplateError(message, type, data, errorInfo); },
|
||||
appendError(message, type, data, errorInfo) {
|
||||
@@ -179,7 +294,8 @@ export const util = {
|
||||
},
|
||||
transform: {
|
||||
toDynamoDBFilterExpression: unsupported('transform.toDynamoDBFilterExpression'),
|
||||
toElasticsearchQueryDSL: unsupported('transform.toElasticsearchQueryDSL')
|
||||
toElasticsearchQueryDSL: unsupported('transform.toElasticsearchQueryDSL'),
|
||||
toSubscriptionFilter
|
||||
},
|
||||
str: {
|
||||
normalize: (v, form) => String(v).normalize(
|
||||
|
||||
+181
@@ -77,6 +77,7 @@ class AppSyncJsResolverDockerIntegrationTest {
|
||||
taggedRawInvalidEscapeHole: String
|
||||
untaggedInvalidEscape: String
|
||||
normalizeString: String
|
||||
subscriptionFilter(mode: Int): String
|
||||
}
|
||||
""";
|
||||
|
||||
@@ -384,6 +385,94 @@ class AppSyncJsResolverDockerIntegrationTest {
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String SUBSCRIPTION_FILTER_RESOLVER = """
|
||||
import { util } from "@aws-appsync/utils";
|
||||
export function request(ctx) {
|
||||
return { payload: null };
|
||||
}
|
||||
export function response(ctx) {
|
||||
const mode = ctx.args.mode;
|
||||
let filter = { score: { lte: 50, gte: 20 }, owner: { eq: "ignored" } };
|
||||
let ignored = ["owner"];
|
||||
let rules = { owner: { eq: "A" } };
|
||||
if (mode === 1 || mode === 2) {
|
||||
filter = {};
|
||||
ignored = [];
|
||||
rules = {};
|
||||
for (let i = 0; i < (mode === 1 ? 9 : 30); i++) {
|
||||
filter["field" + i] = { eq: i, ne: i };
|
||||
}
|
||||
} else if (mode === 3 || mode === 4 || mode === 6 || mode === 7) {
|
||||
const branches = [];
|
||||
for (let i = 0; i < (mode === 4 ? 1001 : 1000); i++) {
|
||||
branches.push({ branch: { eq: i } });
|
||||
}
|
||||
filter = { or: branches };
|
||||
ignored = [];
|
||||
rules = {};
|
||||
if (mode === 6 || mode === 7) {
|
||||
for (let i = 0; i < (mode === 6 ? 9 : 10); i++) {
|
||||
filter["field" + i] = { eq: i };
|
||||
}
|
||||
}
|
||||
} else if (mode === 5) {
|
||||
filter = {};
|
||||
ignored = [];
|
||||
rules = {};
|
||||
for (let i = 0; i < 1001; i++) {
|
||||
rules["field" + i] = { eq: i };
|
||||
}
|
||||
} else if (mode === 8) {
|
||||
filter = { payload: { eq: "x".repeat(2 * 1024 * 1024) } };
|
||||
ignored = [];
|
||||
rules = {};
|
||||
} else if (mode === 9) {
|
||||
const operators = {};
|
||||
for (let i = 0; i < 1000; i++) {
|
||||
operators["operator" + i] = "x".repeat(6144);
|
||||
}
|
||||
filter = { payload: operators };
|
||||
ignored = [];
|
||||
rules = {};
|
||||
} else if (mode === 10) {
|
||||
filter = { status: { eq: "open" } };
|
||||
} else if (mode === 11) {
|
||||
filter = { status: { eq: "open" }, priority: { ge: 3 } };
|
||||
} else if (mode === 12) {
|
||||
filter = { score: { lte: 50, gte: 20 } };
|
||||
} else if (mode === 13) {
|
||||
filter = {};
|
||||
} else if (mode === 14) {
|
||||
filter = null;
|
||||
} else if (mode === 15 || mode === 16) {
|
||||
filter = { score: { lte: 50, gte: 20 }, and: [
|
||||
{ title: { ne: "Book1" } },
|
||||
{ or: [{ author: { eq: "Admin" } }, { published: { eq: false } }] }
|
||||
] };
|
||||
if (mode === 16) {
|
||||
ignored = ["score", "author"];
|
||||
}
|
||||
} else if (mode === 17) {
|
||||
filter = { status: { eq: "open" } };
|
||||
rules = { priority: { ge: 7 }, owner: { eq: "A" } };
|
||||
}
|
||||
if (mode >= 10 && mode <= 17 && mode !== 16) {
|
||||
ignored = [];
|
||||
}
|
||||
if (mode >= 10 && mode <= 16) {
|
||||
rules = {};
|
||||
}
|
||||
const result = util.transform.toSubscriptionFilter(filter, ignored, rules);
|
||||
if (mode === 1 || mode === 3 || mode === 6) {
|
||||
return result.filterGroup.length + "/" + result.filterGroup[0].filters.length;
|
||||
}
|
||||
if (mode === 8) {
|
||||
return String(result.filterGroup[0].filters[0].value.length);
|
||||
}
|
||||
return JSON.stringify(result);
|
||||
}
|
||||
""";
|
||||
|
||||
@BeforeAll
|
||||
static void configure() {
|
||||
SidecarContainersProfile.requireDockerAndImage("floci.services.appsync.graphql-image");
|
||||
@@ -439,6 +528,7 @@ class AppSyncJsResolverDockerIntegrationTest {
|
||||
createUnitResolver(apiId, "Query", "untaggedInvalidEscape", "local",
|
||||
UNTAGGED_INVALID_ESCAPE_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "normalizeString", "local", NORMALIZE_STRING_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "subscriptionFilter", "local", SUBSCRIPTION_FILTER_RESOLVER);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -517,6 +607,82 @@ class AppSyncJsResolverDockerIntegrationTest {
|
||||
));
|
||||
}
|
||||
|
||||
@Test
|
||||
void subscriptionFilterHelperExpandsBranchesThroughTheJsResolver() {
|
||||
query("{ subscriptionFilter }")
|
||||
.statusCode(200)
|
||||
.body("errors", nullValue())
|
||||
.body("data.subscriptionFilter", equalTo("{\"filterGroup\":[{\"filters\":["
|
||||
+ "{\"fieldName\":\"score\",\"operator\":\"lte\",\"value\":50},"
|
||||
+ "{\"fieldName\":\"owner\",\"operator\":\"eq\",\"value\":\"A\"}]},"
|
||||
+ "{\"filters\":[{\"fieldName\":\"score\",\"operator\":\"gte\",\"value\":20},"
|
||||
+ "{\"fieldName\":\"owner\",\"operator\":\"eq\",\"value\":\"A\"}]}]}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void subscriptionFilterHelperKeepsBasicAndNestedShapes() {
|
||||
assertSubscriptionFilter(10, "{\"filterGroup\":[{\"filters\":["
|
||||
+ "{\"fieldName\":\"status\",\"operator\":\"eq\",\"value\":\"open\"}]}]}");
|
||||
assertSubscriptionFilter(11, "{\"filterGroup\":[{\"filters\":["
|
||||
+ "{\"fieldName\":\"status\",\"operator\":\"eq\",\"value\":\"open\"},"
|
||||
+ "{\"fieldName\":\"priority\",\"operator\":\"ge\",\"value\":3}]}]}");
|
||||
assertSubscriptionFilter(12, "{\"filterGroup\":[{\"filters\":["
|
||||
+ "{\"fieldName\":\"score\",\"operator\":\"lte\",\"value\":50}]},"
|
||||
+ "{\"filters\":[{\"fieldName\":\"score\",\"operator\":\"gte\",\"value\":20}]}]}");
|
||||
assertSubscriptionFilter(13, "{\"filterGroup\":[]}");
|
||||
assertSubscriptionFilter(14, "null");
|
||||
assertSubscriptionFilter(15, "{\"filterGroup\":[{\"filters\":["
|
||||
+ "{\"fieldName\":\"score\",\"operator\":\"lte\",\"value\":50},"
|
||||
+ "{\"fieldName\":\"title\",\"operator\":\"ne\",\"value\":\"Book1\"},"
|
||||
+ "{\"fieldName\":\"author\",\"operator\":\"eq\",\"value\":\"Admin\"}]},"
|
||||
+ "{\"filters\":[{\"fieldName\":\"score\",\"operator\":\"lte\",\"value\":50},"
|
||||
+ "{\"fieldName\":\"title\",\"operator\":\"ne\",\"value\":\"Book1\"},"
|
||||
+ "{\"fieldName\":\"published\",\"operator\":\"eq\",\"value\":false}]},"
|
||||
+ "{\"filters\":[{\"fieldName\":\"score\",\"operator\":\"gte\",\"value\":20},"
|
||||
+ "{\"fieldName\":\"title\",\"operator\":\"ne\",\"value\":\"Book1\"},"
|
||||
+ "{\"fieldName\":\"author\",\"operator\":\"eq\",\"value\":\"Admin\"}]},"
|
||||
+ "{\"filters\":[{\"fieldName\":\"score\",\"operator\":\"gte\",\"value\":20},"
|
||||
+ "{\"fieldName\":\"title\",\"operator\":\"ne\",\"value\":\"Book1\"},"
|
||||
+ "{\"fieldName\":\"published\",\"operator\":\"eq\",\"value\":false}]}]}");
|
||||
assertSubscriptionFilter(16, "{\"filterGroup\":[{\"filters\":["
|
||||
+ "{\"fieldName\":\"title\",\"operator\":\"ne\",\"value\":\"Book1\"},"
|
||||
+ "{\"fieldName\":\"published\",\"operator\":\"eq\",\"value\":false}]}]}");
|
||||
assertSubscriptionFilter(17, "{\"filterGroup\":[{\"filters\":["
|
||||
+ "{\"fieldName\":\"status\",\"operator\":\"eq\",\"value\":\"open\"},"
|
||||
+ "{\"fieldName\":\"priority\",\"operator\":\"ge\",\"value\":7}]},"
|
||||
+ "{\"filters\":[{\"fieldName\":\"status\",\"operator\":\"eq\",\"value\":\"open\"},"
|
||||
+ "{\"fieldName\":\"owner\",\"operator\":\"eq\",\"value\":\"A\"}]}]}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void subscriptionFilterBudgetAllowsBoundedExpansion() {
|
||||
query("{ subscriptionFilter(mode: 1) }")
|
||||
.statusCode(200)
|
||||
.body("errors", nullValue())
|
||||
.body("data.subscriptionFilter", equalTo("512/9"));
|
||||
query("{ subscriptionFilter(mode: 3) }")
|
||||
.statusCode(200)
|
||||
.body("errors", nullValue())
|
||||
.body("data.subscriptionFilter", equalTo("1000/1"));
|
||||
query("{ subscriptionFilter(mode: 6) }")
|
||||
.statusCode(200)
|
||||
.body("errors", nullValue())
|
||||
.body("data.subscriptionFilter", equalTo("1000/10"));
|
||||
query("{ subscriptionFilter(mode: 8) }")
|
||||
.statusCode(200)
|
||||
.body("errors", nullValue())
|
||||
.body("data.subscriptionFilter", equalTo("2097152"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void subscriptionFilterBudgetRejectsExcessiveExpansion() {
|
||||
assertSubscriptionFilterBudgetError(2, "subscription filter exceeds 1000 groups");
|
||||
assertSubscriptionFilterBudgetError(4, "subscription filter exceeds 1000 groups");
|
||||
assertSubscriptionFilterBudgetError(5, "subscription filter exceeds 1000 groups");
|
||||
assertSubscriptionFilterBudgetError(7, "subscription filter exceeds 10000 filter entries");
|
||||
assertSubscriptionFilterBudgetError(9, "subscription filter exceeds 5242880 output bytes");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExplicitNullArgumentReachesTheResolverInsteadOfFailingTheBatch() {
|
||||
// nextToken: null is ordinary GraphQL, and an explicit null is not the same as an absent
|
||||
@@ -781,6 +947,21 @@ class AppSyncJsResolverDockerIntegrationTest {
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
private void assertSubscriptionFilter(int mode, String expected) {
|
||||
query("{ subscriptionFilter(mode: " + mode + ") }")
|
||||
.statusCode(200)
|
||||
.body("errors", nullValue())
|
||||
.body("data.subscriptionFilter", equalTo(expected));
|
||||
}
|
||||
|
||||
private void assertSubscriptionFilterBudgetError(int mode, String message) {
|
||||
query("{ subscriptionFilter(mode: " + mode + ") }")
|
||||
.statusCode(200)
|
||||
.body("data.subscriptionFilter", nullValue())
|
||||
.body("errors[0].errorType", equalTo("RangeError"))
|
||||
.body("errors[0].message", containsString(message));
|
||||
}
|
||||
|
||||
private ValidatableResponse query(String graphql) {
|
||||
return given()
|
||||
.header("x-api-key", apiKey)
|
||||
|
||||
Reference in new issue
Block a user