@graphql-yoga/plugin-apollo-usage-report 0.0.1-alpha-20240710084647-0e18c8e7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2018-2020 Graphcool
4
+ Copyright (c) 2020-2021 Prisma
5
+ Copyright (c) 2021- The Guild
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/cjs/index.js ADDED
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useApolloUsageReport = useApolloUsageReport;
4
+ exports.hashSHA256 = hashSHA256;
5
+ const apollo_graphql_1 = require("apollo-graphql");
6
+ const apollo_reporting_protobuf_1 = require("apollo-reporting-protobuf");
7
+ const graphql_1 = require("graphql");
8
+ const graphql_yoga_1 = require("graphql-yoga");
9
+ const plugin_apollo_inline_trace_1 = require("@graphql-yoga/plugin-apollo-inline-trace");
10
+ const fetch_1 = require("@whatwg-node/fetch");
11
+ const DEFAULT_REPORTING_ENDPOINT = 'https://usage-reporting.api.apollographql.com/api/ingress/traces';
12
+ function useApolloUsageReport(options = {}) {
13
+ const [instrumentation, ctxForReq] = (0, plugin_apollo_inline_trace_1.useApolloInstrumentation)(options);
14
+ const { graphRef = process.env['APOLLO_GRAPH_REF'], apiKey = process.env['APOLLO_KEY'], endpoint = DEFAULT_REPORTING_ENDPOINT, } = options;
15
+ let logger;
16
+ let schemaId;
17
+ return {
18
+ onPluginInit({ addPlugin }) {
19
+ addPlugin(instrumentation);
20
+ addPlugin({
21
+ async onYogaInit(args) {
22
+ logger = Object.fromEntries(Object.entries(args.yoga.logger).map(([level, log]) => [
23
+ level,
24
+ (...args) => log('[ApolloUsageReport]', ...args),
25
+ ]));
26
+ if (!apiKey) {
27
+ throw new Error(`[ApolloUsageReport] Missing API key. Please provide one in plugin options or with 'APOLLO_KEY' environment variable.`);
28
+ }
29
+ if (!graphRef) {
30
+ throw new Error(`[ApolloUsageReport] Missing Graph Ref. Please provide one in plugin options or with 'APOLLO_GRAPH_REF' environment variable.`);
31
+ }
32
+ logger.debug('using', { apiKey, graphRef });
33
+ },
34
+ async onSchemaChange({ schema }) {
35
+ if (schema) {
36
+ schemaId = await hashSHA256((0, graphql_1.printSchema)(schema));
37
+ }
38
+ },
39
+ onParse() {
40
+ return ({ result, context: { request, params } }) => {
41
+ const ctx = ctxForReq.get(request);
42
+ if (!ctx) {
43
+ logger.debug('ctx not found during parsing');
44
+ return;
45
+ }
46
+ const { operationName } = params;
47
+ const signature = (0, apollo_graphql_1.defaultUsageReportingSignature)(result, operationName || '');
48
+ ctx.operationKey = `# ${operationName || '-'}\n${signature}`;
49
+ ctx.schemaId = schemaId;
50
+ };
51
+ },
52
+ async onResultProcess(args) {
53
+ const ctx = ctxForReq.get(args.request);
54
+ if (!ctx?.operationKey || !ctx?.schemaId) {
55
+ logger.debug('ctx not found during result processing:', ctx);
56
+ return;
57
+ }
58
+ // TODO: Handle async iterables ?
59
+ if ((0, graphql_yoga_1.isAsyncIterable)(args.result)) {
60
+ logger.debug('async iterable results not implemented for now');
61
+ return;
62
+ }
63
+ (0, fetch_1.fetch)(endpoint, {
64
+ method: 'POST',
65
+ headers: {
66
+ 'content-type': 'application/protobuf',
67
+ // The presence of the api key is already checked at Yoga initialization time
68
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
69
+ 'x-api-key': apiKey,
70
+ accept: 'application/json',
71
+ },
72
+ body: apollo_reporting_protobuf_1.Report.encode({
73
+ header: {
74
+ graphRef,
75
+ executableSchemaId: ctx.schemaId,
76
+ },
77
+ operationCount: 1,
78
+ tracesPerQuery: {
79
+ [ctx.operationKey]: {
80
+ trace: [ctx.trace],
81
+ },
82
+ },
83
+ }).finish(),
84
+ }).then(async (response) => {
85
+ if (response.ok) {
86
+ logger.debug('Traces sent:', await response.text());
87
+ }
88
+ else {
89
+ logger.error('Failed to send trace:', await response.text());
90
+ }
91
+ });
92
+ },
93
+ });
94
+ },
95
+ };
96
+ }
97
+ async function hashSHA256(str, api = globalThis) {
98
+ const { crypto, TextEncoder } = api;
99
+ const textEncoder = new TextEncoder();
100
+ const utf8 = textEncoder.encode(str);
101
+ const hashBuffer = await crypto.subtle.digest('SHA-256', utf8);
102
+ let hashHex = '';
103
+ for (const bytes of new Uint8Array(hashBuffer)) {
104
+ hashHex += bytes.toString(16).padStart(2, '0');
105
+ }
106
+ return hashHex;
107
+ }
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
package/esm/index.js ADDED
@@ -0,0 +1,103 @@
1
+ import { defaultUsageReportingSignature } from 'apollo-graphql';
2
+ import { Report } from 'apollo-reporting-protobuf';
3
+ import { printSchema } from 'graphql';
4
+ import { isAsyncIterable } from 'graphql-yoga';
5
+ import { useApolloInstrumentation, } from '@graphql-yoga/plugin-apollo-inline-trace';
6
+ import { fetch } from '@whatwg-node/fetch';
7
+ const DEFAULT_REPORTING_ENDPOINT = 'https://usage-reporting.api.apollographql.com/api/ingress/traces';
8
+ export function useApolloUsageReport(options = {}) {
9
+ const [instrumentation, ctxForReq] = useApolloInstrumentation(options);
10
+ const { graphRef = process.env['APOLLO_GRAPH_REF'], apiKey = process.env['APOLLO_KEY'], endpoint = DEFAULT_REPORTING_ENDPOINT, } = options;
11
+ let logger;
12
+ let schemaId;
13
+ return {
14
+ onPluginInit({ addPlugin }) {
15
+ addPlugin(instrumentation);
16
+ addPlugin({
17
+ async onYogaInit(args) {
18
+ logger = Object.fromEntries(Object.entries(args.yoga.logger).map(([level, log]) => [
19
+ level,
20
+ (...args) => log('[ApolloUsageReport]', ...args),
21
+ ]));
22
+ if (!apiKey) {
23
+ throw new Error(`[ApolloUsageReport] Missing API key. Please provide one in plugin options or with 'APOLLO_KEY' environment variable.`);
24
+ }
25
+ if (!graphRef) {
26
+ throw new Error(`[ApolloUsageReport] Missing Graph Ref. Please provide one in plugin options or with 'APOLLO_GRAPH_REF' environment variable.`);
27
+ }
28
+ logger.debug('using', { apiKey, graphRef });
29
+ },
30
+ async onSchemaChange({ schema }) {
31
+ if (schema) {
32
+ schemaId = await hashSHA256(printSchema(schema));
33
+ }
34
+ },
35
+ onParse() {
36
+ return ({ result, context: { request, params } }) => {
37
+ const ctx = ctxForReq.get(request);
38
+ if (!ctx) {
39
+ logger.debug('ctx not found during parsing');
40
+ return;
41
+ }
42
+ const { operationName } = params;
43
+ const signature = defaultUsageReportingSignature(result, operationName || '');
44
+ ctx.operationKey = `# ${operationName || '-'}\n${signature}`;
45
+ ctx.schemaId = schemaId;
46
+ };
47
+ },
48
+ async onResultProcess(args) {
49
+ const ctx = ctxForReq.get(args.request);
50
+ if (!ctx?.operationKey || !ctx?.schemaId) {
51
+ logger.debug('ctx not found during result processing:', ctx);
52
+ return;
53
+ }
54
+ // TODO: Handle async iterables ?
55
+ if (isAsyncIterable(args.result)) {
56
+ logger.debug('async iterable results not implemented for now');
57
+ return;
58
+ }
59
+ fetch(endpoint, {
60
+ method: 'POST',
61
+ headers: {
62
+ 'content-type': 'application/protobuf',
63
+ // The presence of the api key is already checked at Yoga initialization time
64
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
65
+ 'x-api-key': apiKey,
66
+ accept: 'application/json',
67
+ },
68
+ body: Report.encode({
69
+ header: {
70
+ graphRef,
71
+ executableSchemaId: ctx.schemaId,
72
+ },
73
+ operationCount: 1,
74
+ tracesPerQuery: {
75
+ [ctx.operationKey]: {
76
+ trace: [ctx.trace],
77
+ },
78
+ },
79
+ }).finish(),
80
+ }).then(async (response) => {
81
+ if (response.ok) {
82
+ logger.debug('Traces sent:', await response.text());
83
+ }
84
+ else {
85
+ logger.error('Failed to send trace:', await response.text());
86
+ }
87
+ });
88
+ },
89
+ });
90
+ },
91
+ };
92
+ }
93
+ export async function hashSHA256(str, api = globalThis) {
94
+ const { crypto, TextEncoder } = api;
95
+ const textEncoder = new TextEncoder();
96
+ const utf8 = textEncoder.encode(str);
97
+ const hashBuffer = await crypto.subtle.digest('SHA-256', utf8);
98
+ let hashHex = '';
99
+ for (const bytes of new Uint8Array(hashBuffer)) {
100
+ hashHex += bytes.toString(16).padStart(2, '0');
101
+ }
102
+ return hashHex;
103
+ }
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@graphql-yoga/plugin-apollo-usage-report",
3
+ "version": "0.0.1-alpha-20240710084647-0e18c8e7",
4
+ "description": "Apollo's GraphOS usage report plugin for GraphQL Yoga.",
5
+ "peerDependencies": {
6
+ "@graphql-tools/utils": "^10.0.0",
7
+ "@whatwg-node/fetch": "^0.9.17",
8
+ "graphql": "^15.2.0 || ^16.0.0",
9
+ "graphql-yoga": "^5.6.1-alpha-20240710084647-0e18c8e7"
10
+ },
11
+ "dependencies": {
12
+ "apollo-graphql": "^0.9.7",
13
+ "apollo-reporting-protobuf": "^3.3.2",
14
+ "tslib": "^2.5.2",
15
+ "@graphql-yoga/plugin-apollo-inline-trace": "^3.6.1-alpha-20240710084647-0e18c8e7"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "https://github.com/dotansimha/graphql-yoga.git",
20
+ "directory": "packages/plugins/apollo-usage-report"
21
+ },
22
+ "author": "Valentin Cocaud <v.cocaud@gmail.com>",
23
+ "license": "MIT",
24
+ "engines": {
25
+ "node": ">=18.0.0"
26
+ },
27
+ "main": "cjs/index.js",
28
+ "module": "esm/index.js",
29
+ "typings": "typings/index.d.ts",
30
+ "typescript": {
31
+ "definition": "typings/index.d.ts"
32
+ },
33
+ "type": "module",
34
+ "exports": {
35
+ ".": {
36
+ "require": {
37
+ "types": "./typings/index.d.cts",
38
+ "default": "./cjs/index.js"
39
+ },
40
+ "import": {
41
+ "types": "./typings/index.d.ts",
42
+ "default": "./esm/index.js"
43
+ },
44
+ "default": {
45
+ "types": "./typings/index.d.ts",
46
+ "default": "./esm/index.js"
47
+ }
48
+ },
49
+ "./package.json": "./package.json"
50
+ }
51
+ }
@@ -0,0 +1,34 @@
1
+ import { Plugin } from 'graphql-yoga';
2
+ import { ApolloInlineTracePluginOptions } from '@graphql-yoga/plugin-apollo-inline-trace';
3
+ type ApolloUsageReportOptions = ApolloInlineTracePluginOptions & {
4
+ /**
5
+ * The graph ref of the managed federation graph.
6
+ * It is composed of the graph ID and the variant (`<YOUR_GRAPH_ID>@<VARIANT>`).
7
+ *
8
+ * If not provided, `APOLLO_GRAPH_REF` environment variable is used.
9
+ *
10
+ * You can find a a graph's ref at the top of its Schema Reference page in Apollo Studio.
11
+ */
12
+ graphRef?: string;
13
+ /**
14
+ * The API key to use to authenticate with the managed federation up link.
15
+ * It needs at least the `service:read` permission.
16
+ *
17
+ * If not provided, `APOLLO_KEY` environment variable will be used instead.
18
+ *
19
+ * [Learn how to create an API key](https://www.apollographql.com/docs/federation/v1/managed-federation/setup#4-connect-the-gateway-to-studio)
20
+ */
21
+ apiKey?: string;
22
+ /**
23
+ * Usage report endpoint
24
+ *
25
+ * Defaults to GraphOS endpoint (https://usage-reporting.api.apollographql.com/api/ingress/traces)
26
+ */
27
+ endpoint?: string;
28
+ };
29
+ export declare function useApolloUsageReport(options?: ApolloUsageReportOptions): Plugin;
30
+ export declare function hashSHA256(str: string, api?: {
31
+ crypto: Crypto;
32
+ TextEncoder: (typeof globalThis)['TextEncoder'];
33
+ }): Promise<string>;
34
+ export {};
@@ -0,0 +1,34 @@
1
+ import { Plugin } from 'graphql-yoga';
2
+ import { ApolloInlineTracePluginOptions } from '@graphql-yoga/plugin-apollo-inline-trace';
3
+ type ApolloUsageReportOptions = ApolloInlineTracePluginOptions & {
4
+ /**
5
+ * The graph ref of the managed federation graph.
6
+ * It is composed of the graph ID and the variant (`<YOUR_GRAPH_ID>@<VARIANT>`).
7
+ *
8
+ * If not provided, `APOLLO_GRAPH_REF` environment variable is used.
9
+ *
10
+ * You can find a a graph's ref at the top of its Schema Reference page in Apollo Studio.
11
+ */
12
+ graphRef?: string;
13
+ /**
14
+ * The API key to use to authenticate with the managed federation up link.
15
+ * It needs at least the `service:read` permission.
16
+ *
17
+ * If not provided, `APOLLO_KEY` environment variable will be used instead.
18
+ *
19
+ * [Learn how to create an API key](https://www.apollographql.com/docs/federation/v1/managed-federation/setup#4-connect-the-gateway-to-studio)
20
+ */
21
+ apiKey?: string;
22
+ /**
23
+ * Usage report endpoint
24
+ *
25
+ * Defaults to GraphOS endpoint (https://usage-reporting.api.apollographql.com/api/ingress/traces)
26
+ */
27
+ endpoint?: string;
28
+ };
29
+ export declare function useApolloUsageReport(options?: ApolloUsageReportOptions): Plugin;
30
+ export declare function hashSHA256(str: string, api?: {
31
+ crypto: Crypto;
32
+ TextEncoder: (typeof globalThis)['TextEncoder'];
33
+ }): Promise<string>;
34
+ export {};