Skip to content

Commit 79363ad

Browse files
authored
Merge pull request DeusData#2495 from DeusData/fix/issue-598-graphql-route-name
fix(pipeline): key GraphQL routes by operation name
2 parents 5a9f6e7 + 92cb0ec commit 79363ad

4 files changed

Lines changed: 308 additions & 25 deletions

File tree

‎internal/cbm/service_patterns.c‎

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -870,6 +870,139 @@ bool cbm_service_pattern_is_http_route_literal(const char *literal, const char *
870870
return true;
871871
}
872872

873+
/* ── GraphQL operation identity (#598) ─────────────────────────── */
874+
875+
static bool gql_name_start(unsigned char c) {
876+
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_';
877+
}
878+
879+
static bool gql_name_char(unsigned char c) {
880+
return gql_name_start(c) || (c >= '0' && c <= '9');
881+
}
882+
883+
/* Skip one lexical unit whose braces are not structure: a # comment, a "..."
884+
* or """...""" string, or a JS ${...} template interpolation. Returns p
885+
* unchanged when p starts none of them. */
886+
static const char *gql_skip_opaque(const char *p) {
887+
if (*p == '#') {
888+
while (*p && *p != '\n' && *p != '\r') {
889+
p++;
890+
}
891+
return p;
892+
}
893+
if (strncmp(p, "\"\"\"", 3) == 0) {
894+
const char *end = strstr(p + 3, "\"\"\"");
895+
return end ? end + 3 : p + strlen(p);
896+
}
897+
if (*p == '"') {
898+
p++;
899+
while (*p && *p != '"') {
900+
p += (*p == '\\' && p[1]) ? 2 : 1;
901+
}
902+
return *p ? p + 1 : p;
903+
}
904+
if (p[0] == '$' && p[1] == '{') {
905+
int depth = 1;
906+
p += 2;
907+
while (*p && depth > 0) {
908+
depth += (*p == '{') - (*p == '}');
909+
p++;
910+
}
911+
return p;
912+
}
913+
return p;
914+
}
915+
916+
/* Skip GraphQL "ignored tokens" (whitespace, commas, comments). */
917+
static const char *gql_skip_ignored(const char *p) {
918+
for (;;) {
919+
while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || *p == ',') {
920+
p++;
921+
}
922+
if (*p != '#') {
923+
return p;
924+
}
925+
p = gql_skip_opaque(p);
926+
}
927+
}
928+
929+
/* Copy the Name token at p (bounded). Returns false when p is not a Name. */
930+
static bool gql_copy_name(const char *p, char *name_buf, size_t name_sz) {
931+
if (!gql_name_start((unsigned char)*p) || !name_buf || name_sz == 0) {
932+
return false;
933+
}
934+
size_t n = 0;
935+
while (gql_name_char((unsigned char)p[n]) && n + 1 < name_sz) {
936+
name_buf[n] = p[n];
937+
n++;
938+
}
939+
name_buf[n] = '\0';
940+
return true;
941+
}
942+
943+
static const char *gql_operation_keyword(const char *tok, size_t len) {
944+
static const char *const kws[] = {"query", "mutation", "subscription", NULL};
945+
for (int i = 0; kws[i]; i++) {
946+
if (strlen(kws[i]) == len && strncmp(tok, kws[i], len) == 0) {
947+
return kws[i];
948+
}
949+
}
950+
return NULL;
951+
}
952+
953+
bool cbm_service_pattern_graphql_operation(const char *doc, const char **op_type, char *name_buf,
954+
size_t name_sz) {
955+
*op_type = "operation";
956+
if (name_buf && name_sz > 0) {
957+
name_buf[0] = '\0';
958+
}
959+
if (!doc) {
960+
return false;
961+
}
962+
int depth = 0;
963+
bool in_fragment = false;
964+
const char *p = doc;
965+
while (*p) {
966+
const char *q = gql_skip_opaque(p);
967+
if (q != p) {
968+
p = q;
969+
continue;
970+
}
971+
unsigned char c = (unsigned char)*p;
972+
if (c == '{' && depth == 0 && !in_fragment) {
973+
*op_type = "query"; /* `{ ... }` shorthand is an anonymous query */
974+
return false;
975+
}
976+
if (c == '{' || c == '}') {
977+
depth += (c == '{') ? 1 : -1;
978+
depth = depth < 0 ? 0 : depth;
979+
in_fragment = in_fragment && depth > 0;
980+
p++;
981+
continue;
982+
}
983+
if (depth > 0 || in_fragment || !gql_name_start(c)) {
984+
p++;
985+
continue;
986+
}
987+
const char *tok = p;
988+
while (gql_name_char((unsigned char)*p)) {
989+
p++;
990+
}
991+
size_t len = (size_t)(p - tok);
992+
if (len == strlen("fragment") && strncmp(tok, "fragment", len) == 0) {
993+
in_fragment = true;
994+
continue;
995+
}
996+
const char *kw = gql_operation_keyword(tok, len);
997+
if (!kw) {
998+
return false; /* not a GraphQL document (URL, dict key, variable ...) */
999+
}
1000+
*op_type = kw;
1001+
return gql_copy_name(gql_skip_ignored(p), name_buf, name_sz);
1002+
}
1003+
return false;
1004+
}
1005+
8731006
/* ── Public API ────────────────────────────────────────────────── */
8741007

8751008
/* Per-worker TLS cache of cbm_service_pattern_match results.

‎internal/cbm/service_patterns.h‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
#define CBM_SERVICE_PATTERNS_H
1313

1414
#include <stdbool.h>
15+
#include <stddef.h>
1516

1617
/* Edge type returned by pattern match. */
1718
typedef enum {
@@ -77,4 +78,17 @@ const char *cbm_service_pattern_route_method(const char *callee_name);
7778
* Returns NULL if not an async pattern. */
7879
const char *cbm_service_pattern_broker(const char *resolved_qn);
7980

81+
/* GraphQL operation identity of a client call argument (#598).
82+
* Scans `doc` as a GraphQL document (skipping comments, strings, `${...}`
83+
* template interpolations and leading fragment definitions) and reports the
84+
* first operation: *op_type is "query", "mutation" or "subscription" ("query"
85+
* for the `{ ... }` shorthand). Returns true and writes the operation name to
86+
* name_buf when the operation is named. Returns false for an anonymous
87+
* operation, or with *op_type = "operation" when `doc` is not a GraphQL
88+
* document (NULL, a URL, a bare word such as a dict key ...). The operation
89+
* text itself is never copied, so callers can key Routes on a bounded
90+
* identity. */
91+
bool cbm_service_pattern_graphql_operation(const char *doc, const char **op_type, char *name_buf,
92+
size_t name_sz);
93+
8094
#endif /* CBM_SERVICE_PATTERNS_H */

‎src/pipeline/pass_parallel.c‎

Lines changed: 28 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2447,40 +2447,43 @@ static void emit_grpc_edge(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *source, cons
24472447
cbm_gbuf_insert_edge(gbuf, source->id, route_id, "GRPC_CALLS", props);
24482448
}
24492449

2450-
/* Emit GRAPHQL_CALLS edge. Extract operation from first string arg if available. */
2450+
/* Emit GRAPHQL_CALLS edge. The Route is keyed by the operation NAME only
2451+
* (#598), never by the operation text:
2452+
* named operation -> __graphql__<Name> name "<Name>"
2453+
* anonymous query/mutation/ -> __graphql__<type>__anonymous name "(anonymous <type>)"
2454+
* subscription (incl. the `{ ... }` query shorthand)
2455+
* no GraphQL document -> __graphql__operation__anonymous name "(anonymous operation)"
2456+
* (URL, variable, missing string argument)
2457+
* Keys are bounded by the GraphQL Name grammar and deterministic. */
24512458
static void emit_graphql_edge(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *source, const CBMCall *call,
24522459
const cbm_resolution_t *res) {
2453-
const char *op = call->first_string_arg;
2454-
if (!op || !op[0]) {
2455-
op = call->callee_name;
2456-
}
2457-
/* Try to extract a query/mutation name from the operation string */
2458-
char op_name[CBM_SZ_256];
2459-
snprintf(op_name, sizeof(op_name), "%s", op);
2460-
/* Trim leading whitespace and "query "/"mutation " prefix */
2461-
const char *p = op_name;
2462-
while (*p == ' ' || *p == '\t' || *p == '\n') {
2463-
p++;
2464-
}
2465-
if (strncmp(p, "query ", CBM_SZ_6) == 0) {
2466-
p += CBM_SZ_6;
2467-
} else if (strncmp(p, "mutation ", CBM_SZ_8) == 0) {
2468-
p += CBM_SZ_8;
2469-
}
2460+
const char *op_type = "operation";
2461+
char op_name[CBM_SZ_128];
2462+
bool named = cbm_service_pattern_graphql_operation(call->first_string_arg, &op_type, op_name,
2463+
sizeof(op_name));
24702464

2471-
char route_qn[CBM_SZ_512];
2472-
snprintf(route_qn, sizeof(route_qn), "__graphql__%s", p);
2465+
char route_name[CBM_SZ_256];
2466+
char route_qn[CBM_SZ_256];
2467+
if (named) {
2468+
snprintf(route_name, sizeof(route_name), "%s", op_name);
2469+
snprintf(route_qn, sizeof(route_qn), "__graphql__%s", op_name);
2470+
} else {
2471+
snprintf(route_name, sizeof(route_name), "(anonymous %s)", op_type);
2472+
snprintf(route_qn, sizeof(route_qn), "__graphql__%s__anonymous", op_type);
2473+
}
24732474

2474-
int64_t route_id =
2475-
cbm_gbuf_upsert_node(gbuf, "Route", p, route_qn, "", 0, 0, "{\"source\":\"graphql\"}");
2475+
int64_t route_id = cbm_gbuf_upsert_node(gbuf, "Route", route_name, route_qn, "", 0, 0,
2476+
"{\"source\":\"graphql\"}");
24762477

24772478
char esc_c[CBM_SZ_256];
24782479
char esc_op[CBM_SZ_512];
24792480
cbm_json_escape(esc_c, sizeof(esc_c), call->callee_name);
2480-
cbm_json_escape(esc_op, sizeof(esc_op), p);
2481+
cbm_json_escape(esc_op, sizeof(esc_op), route_name);
24812482
char props[CBM_SZ_1K];
2482-
snprintf(props, sizeof(props), "{\"callee\":\"%s\",\"operation\":\"%s\",\"confidence\":%.2f}",
2483-
esc_c, esc_op, res->confidence);
2483+
snprintf(props, sizeof(props),
2484+
"{\"callee\":\"%s\",\"operation\":\"%s\",\"operation_type\":\"%s\","
2485+
"\"confidence\":%.2f}",
2486+
esc_c, esc_op, op_type, res->confidence);
24842487
cbm_gbuf_insert_edge(gbuf, source->id, route_id, "GRAPHQL_CALLS", props);
24852488
}
24862489

‎tests/test_edge_types_probe.c‎

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
#include "test_framework.h"
4444
#include "test_helpers.h"
4545
#include "cbm.h"
46+
#include "service_patterns.h"
4647
#include <mcp/mcp.h>
4748
#include <store/store.h>
4849
#include <pipeline/pipeline.h>
@@ -244,6 +245,136 @@ static cbm_store_t *et_index_parallel(EtProj *lp, const EtFile *meaningful, int
244245
return et_index_files(lp, files, n);
245246
}
246247

248+
/* #598: a call that resolves to a GraphQL client used to name its Route after
249+
* the WHOLE operation text (minus a leading "query "/"mutation "), so an
250+
* anonymous `query { ... }` became one long Route and even a named operation
251+
* carried its variables and selection set in the name. GraphQL Routes are now
252+
* keyed by operation name only; anonymous operations share one bounded key per
253+
* operation type. The Route set is asserted exactly (QN + name). Parallel path
254+
* only: GRAPHQL_CALLS is emitted by pass_parallel.c. */
255+
typedef struct {
256+
const char *qn;
257+
const char *name;
258+
} EtGqlRoute;
259+
260+
static int et_graphql_routes_exact(const EtFile *files, int nfiles, const EtGqlRoute *want,
261+
int nwant) {
262+
EtProj lp;
263+
cbm_store_t *store = et_index_parallel(&lp, files, nfiles);
264+
cbm_node_t *nodes = NULL;
265+
int node_count = 0;
266+
int ok = store != NULL;
267+
int got = 0;
268+
if (!store || cbm_store_find_nodes_by_label(store, lp.project, "Route", &nodes, &node_count) !=
269+
CBM_STORE_OK) {
270+
ok = 0;
271+
}
272+
for (int ni = 0; nodes && ni < node_count; ni++) {
273+
const char *qn = nodes[ni].qualified_name ? nodes[ni].qualified_name : "";
274+
const char *name = nodes[ni].name ? nodes[ni].name : "";
275+
if (strncmp(qn, "__graphql__", 11) != 0) {
276+
continue;
277+
}
278+
got++;
279+
int matched = 0;
280+
for (int wi = 0; wi < nwant; wi++) {
281+
if (strcmp(qn, want[wi].qn) == 0 && strcmp(name, want[wi].name) == 0) {
282+
matched = 1;
283+
break;
284+
}
285+
}
286+
/* Operation text (selection sets, variables) must never leak into a key. */
287+
if (!matched || strchr(qn, '{') || strchr(name, '{') || strlen(qn) > 160) {
288+
fprintf(stderr, " [ET-GQL] unexpected Route qn='%s' name='%s'\n", qn, name);
289+
ok = 0;
290+
}
291+
}
292+
if (got != nwant) {
293+
fprintf(stderr, " [ET-GQL] FAIL graphql routes expected=%d actual=%d\n", nwant, got);
294+
ok = 0;
295+
}
296+
int edges = store ? cbm_store_count_edges_by_type(store, lp.project, "GRAPHQL_CALLS") : -1;
297+
if (edges < nwant) {
298+
fprintf(stderr, " [ET-GQL] FAIL GRAPHQL_CALLS=%d expected>=%d\n", edges, nwant);
299+
ok = 0;
300+
}
301+
cbm_store_free_nodes(nodes, node_count);
302+
et_cleanup(&lp, store);
303+
return ok;
304+
}
305+
306+
TEST(graphql_route_keyed_by_operation_name_issue598) {
307+
static const EtFile f[] = {
308+
{"graphql/client.py", "def gql(query):\n return query\n"},
309+
{"api/ops.py",
310+
"from graphql.client import gql\n\n\n"
311+
"def get_user():\n"
312+
" return gql('query GetUser($id: ID!) { user(id: $id) { name } }')\n\n\n"
313+
"def update_user():\n"
314+
" return gql('mutation UpdateUser($id: ID!) { updateUser(id: $id) { id } }')\n\n\n"
315+
"def list_users():\n"
316+
" return gql('fragment U on User { id } query ListUsers { users { ...U } }')\n\n\n"
317+
"def on_event():\n"
318+
" return gql('subscription OnEvent { event { id } }')\n\n\n"
319+
"def products():\n"
320+
" return gql('query { products(search: \"x\") { items { sku } } }')\n\n\n"
321+
"def orders():\n"
322+
" return gql('{ orders { id total } }')\n\n\n"
323+
"def logout():\n"
324+
" return gql('mutation { logout }')\n"}};
325+
static const EtGqlRoute want[] = {
326+
{"__graphql__GetUser", "GetUser"},
327+
{"__graphql__UpdateUser", "UpdateUser"},
328+
{"__graphql__ListUsers", "ListUsers"},
329+
{"__graphql__OnEvent", "OnEvent"},
330+
/* products + orders: `query { }` and the `{ }` shorthand are both
331+
* anonymous queries and share one key. */
332+
{"__graphql__query__anonymous", "(anonymous query)"},
333+
{"__graphql__mutation__anonymous", "(anonymous mutation)"},
334+
};
335+
ASSERT_TRUE(et_graphql_routes_exact(f, (int)(sizeof(f) / sizeof(f[0])), want,
336+
(int)(sizeof(want) / sizeof(want[0]))));
337+
PASS();
338+
}
339+
340+
/* #598 parser edges the end-to-end fixture cannot reach through one language's
341+
* string extraction: comments/strings/interpolations that contain braces, a
342+
* bare word, non-document arguments and name truncation. */
343+
TEST(graphql_operation_identity_parser_issue598) {
344+
const char *type = NULL;
345+
char name[16];
346+
static const struct {
347+
const char *doc;
348+
int named;
349+
const char *type;
350+
const char *name;
351+
} cases[] = {
352+
{"# fetch { all }\nquery Q1 { a }", 1, "query", "Q1"},
353+
{"${UserFields} query WithFrag($id: ID) { u { ...UserFields } }", 1, "query", "WithFrag"},
354+
{"fragment F on T @dir(x: \"{\") { a } mutation M2 { b }", 1, "mutation", "M2"},
355+
{"\"\"\"doc { brace\"\"\" subscription S3 { c }", 1, "subscription", "S3"},
356+
{" query \n ( $x: Int ) { a }", 0, "query", ""},
357+
{" { viewer { id } }", 0, "query", ""},
358+
{"query GetUserByIdentifier { a }", 1, "query", "GetUserByIdenti"}, /* bounded */
359+
{"data", 0, "operation", ""}, /* a bare word is not evidence of an operation */
360+
{"https://api.example.com/graphql", 0, "operation", ""},
361+
{"/graphql", 0, "operation", ""},
362+
{"", 0, "operation", ""},
363+
};
364+
for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
365+
bool named = cbm_service_pattern_graphql_operation(cases[i].doc, &type, name, sizeof(name));
366+
if ((int)named != cases[i].named || strcmp(type, cases[i].type) != 0 ||
367+
strcmp(name, cases[i].name) != 0) {
368+
fprintf(stderr, " [ET-GQL] case %zu '%s' -> named=%d type=%s name=%s\n", i,
369+
cases[i].doc, (int)named, type, name);
370+
ASSERT_TRUE(0);
371+
}
372+
}
373+
ASSERT_FALSE(cbm_service_pattern_graphql_operation(NULL, &type, name, sizeof(name)));
374+
ASSERT_STR_EQ(type, "operation");
375+
PASS();
376+
}
377+
247378
/* #1085: count CALLS edges whose target node has `name`, indexing via the
248379
* PARALLEL path (et_index_parallel pads to >50 files). The per-file TS resolver
249380
* used to treat a raw tsconfig alias as a confident target. That false row made
@@ -1982,6 +2113,8 @@ TEST(routes_express_get_survives_xlang_guard_parallel) {
19822113
SUITE(edge_types_probe) {
19832114
/* HANDLES — route→handler across web frameworks */
19842115
RUN_TEST(calls_jsx_component_via_tsconfig_alias_parallel_issue1085);
2116+
RUN_TEST(graphql_route_keyed_by_operation_name_issue598);
2117+
RUN_TEST(graphql_operation_identity_parser_issue598);
19852118
RUN_TEST(handles_flask_python);
19862119
RUN_TEST(handles_fastapi_python);
19872120
RUN_TEST(handles_drf_action_python);

0 commit comments

Comments
 (0)