@faststore/api 2.0.163-alpha.0 → 2.0.165-alpha.0

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/dist/api.esm.js CHANGED
@@ -4,12 +4,21 @@ import DataLoader from 'dataloader';
4
4
  import pLimit from 'p-limit';
5
5
  import deepEquals from 'fast-deep-equal';
6
6
  import crypto from 'crypto';
7
- import { GraphQLScalarType, print } from 'graphql';
7
+ import { GraphQLScalarType, print, Kind as Kind$1 } from 'graphql';
8
8
  import { Kind } from 'graphql/language';
9
9
  import { mapSchema, MapperKind, getDirective } from '@graphql-tools/utils';
10
+ import { BasicTracerProvider, SimpleSpanProcessor, ConsoleSpanExporter } from '@opentelemetry/sdk-trace-base';
11
+ import { Resource } from '@opentelemetry/resources';
12
+ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';
13
+ import { LoggerProvider, SimpleLogRecordProcessor, ConsoleLogRecordExporter } from '@opentelemetry/sdk-logs';
14
+ import { OTLPLogsExporter } from '@opentelemetry/exporter-logs-otlp-grpc';
15
+ import { isAsyncIterable } from '@envelop/core';
16
+ import { useOnResolve } from '@envelop/on-resolve';
17
+ import { trace, context, SpanKind } from '@opentelemetry/api';
18
+ import { SeverityNumber } from '@opentelemetry/api-logs';
10
19
 
11
20
  var name = "@faststore/api";
12
- var version = "2.0.162-alpha.0";
21
+ var version = "2.0.163-alpha.0";
13
22
  var license = "MIT";
14
23
  var main = "dist/index.js";
15
24
  var typings = "dist/index.d.ts";
@@ -31,7 +40,12 @@ var scripts = {
31
40
  generate: "graphql-codegen --config codegen.yml"
32
41
  };
33
42
  var dependencies = {
43
+ "@envelop/on-resolve": "^2.0.6",
34
44
  "@graphql-tools/schema": "^8.2.0",
45
+ "@opentelemetry/exporter-logs-otlp-grpc": "^0.39.1",
46
+ "@opentelemetry/exporter-trace-otlp-grpc": "^0.39.1",
47
+ "@opentelemetry/sdk-logs": "^0.39.1",
48
+ "@opentelemetry/sdk-trace-base": "^1.13.0",
35
49
  "@rollup/plugin-graphql": "^1.0.0",
36
50
  dataloader: "^2.1.0",
37
51
  "fast-deep-equal": "^3.1.3",
@@ -41,6 +55,7 @@ var dependencies = {
41
55
  var devDependencies = {
42
56
  "@faststore/eslint-config": "^2.0.104-alpha.0",
43
57
  "@faststore/shared": "^2.0.104-alpha.0",
58
+ "@envelop/core": "^2.6.0",
44
59
  "@graphql-codegen/cli": "2.2.0",
45
60
  "@graphql-codegen/typescript": "2.2.2",
46
61
  "@types/express": "^4.17.16",
@@ -56,6 +71,7 @@ var devDependencies = {
56
71
  typescript: "^4.4.2"
57
72
  };
58
73
  var peerDependencies = {
74
+ "@envelop/core": "^1 || ^2",
59
75
  graphql: "^15.6.0"
60
76
  };
61
77
  var packageJson = {
@@ -2528,6 +2544,242 @@ const directive = {
2528
2544
  })
2529
2545
  };
2530
2546
 
2547
+ var AttributeName;
2548
+ (function (AttributeName) {
2549
+ AttributeName["EXECUTION_ERROR"] = "graphql.error";
2550
+ AttributeName["EXECUTION_RESULT"] = "graphql.result";
2551
+ AttributeName["RESOLVER_EXECUTION_ERROR"] = "graphql.resolver.error";
2552
+ AttributeName["RESOLVER_EXCEPTION"] = "graphql.resolver.exception";
2553
+ AttributeName["RESOLVER_FIELD_NAME"] = "graphql.resolver.fieldName";
2554
+ AttributeName["RESOLVER_TYPE_NAME"] = "graphql.resolver.typeName";
2555
+ AttributeName["RESOLVER_RESULT_TYPE"] = "graphql.resolver.resultType";
2556
+ AttributeName["RESOLVER_ARGS"] = "graphql.resolver.args";
2557
+ AttributeName["EXECUTION_OPERATION_NAME"] = "graphql.operation.name";
2558
+ AttributeName["EXECUTION_OPERATION_TYPE"] = "graphql.operation.type";
2559
+ AttributeName["EXECUTION_OPERATION_DOCUMENT"] = "graphql.document";
2560
+ AttributeName["EXECUTION_VARIABLES"] = "graphql.variables";
2561
+ })(AttributeName || (AttributeName = {}));
2562
+ const tracingSpanSymbol = /*#__PURE__*/Symbol('OPEN_TELEMETRY_GRAPHQL');
2563
+ function getResolverSpanKey(path) {
2564
+ const nodes = [];
2565
+ // If the first node (after reversed, it will be the last one) is an integer, that is, identifies a list,
2566
+ // we don't want to include it in the key. Note that this will only happen when analysing .prev paths in
2567
+ // a list of elements. We just want to remove the initial node that is a integer, not all of them.
2568
+ //
2569
+ // Nodes with keys 6bc73341b2a183fc::product::image::0::url would not be able to find
2570
+ // parents with key 6bc73341b2a183fc::product::image because of the "0" list index -
2571
+ // it would search for 6bc73341b2a183fc::product::image::0
2572
+ let currentPath = nodes.length === 0 && Number.isInteger(path.key) ? path.prev : path;
2573
+ while (currentPath) {
2574
+ nodes.push(currentPath.key);
2575
+ currentPath = currentPath.prev;
2576
+ }
2577
+ return [...nodes].reverse().join('.');
2578
+ }
2579
+ const getFaststoreTelemetryPlugin = (tracingProvider, loggerProvider, serviceName, experimentalSendLogs) => {
2580
+ return function useFaststoreTelemetry() {
2581
+ const tracer = tracingProvider.getTracer(serviceName);
2582
+ const logger = loggerProvider.getLogger(serviceName);
2583
+ const resolverContextsByRootSpans = {};
2584
+ return {
2585
+ onPluginInit({
2586
+ addPlugin
2587
+ }) {
2588
+ addPlugin(
2589
+ // eslint-disable-next-line
2590
+ useOnResolve(({
2591
+ info,
2592
+ context: context$1
2593
+ }) => {
2594
+ if (context$1 && typeof context$1 === 'object' && context$1[tracingSpanSymbol]) {
2595
+ var _path$prev, _path$prev2;
2596
+ tracer.getActiveSpanProcessor();
2597
+ const rootContextSpanId = context$1[tracingSpanSymbol].spanContext().spanId;
2598
+ const {
2599
+ fieldName,
2600
+ returnType,
2601
+ parentType,
2602
+ path
2603
+ } = info;
2604
+ const previousResolverSpanKey = path.prev && getResolverSpanKey(path.prev);
2605
+ let ctx = null;
2606
+ if (previousResolverSpanKey && resolverContextsByRootSpans[rootContextSpanId][previousResolverSpanKey]) {
2607
+ ctx = resolverContextsByRootSpans[rootContextSpanId][previousResolverSpanKey];
2608
+ } else {
2609
+ var _resolverContextsByRo;
2610
+ ctx = trace.setSpan(context.active(), context$1[tracingSpanSymbol]);
2611
+ resolverContextsByRootSpans[rootContextSpanId] = (_resolverContextsByRo = resolverContextsByRootSpans[rootContextSpanId]) != null ? _resolverContextsByRo : {};
2612
+ }
2613
+ const resolverIndexInList = Number.isInteger((_path$prev = path.prev) == null ? void 0 : _path$prev.key) ? `[${(_path$prev2 = path.prev) == null ? void 0 : _path$prev2.key}]` : '';
2614
+ const resolverSpan = tracer.startSpan(`${parentType.toString()}.${fieldName}${resolverIndexInList}`, {
2615
+ attributes: {
2616
+ [AttributeName.RESOLVER_FIELD_NAME]: fieldName,
2617
+ [AttributeName.RESOLVER_TYPE_NAME]: parentType.toString(),
2618
+ [AttributeName.RESOLVER_RESULT_TYPE]: returnType.toString(),
2619
+ 'meta.span.path': getResolverSpanKey(path)
2620
+ }
2621
+ }, ctx);
2622
+ const resolverCtx = trace.setSpan(ctx, resolverSpan);
2623
+ resolverContextsByRootSpans[rootContextSpanId][getResolverSpanKey(path)] = resolverCtx;
2624
+ return ({
2625
+ result
2626
+ }) => {
2627
+ if (result instanceof Error) {
2628
+ resolverSpan.setAttributes({
2629
+ error: true,
2630
+ 'exception.category': AttributeName.RESOLVER_EXECUTION_ERROR,
2631
+ 'exception.message': result.message,
2632
+ 'exception.type': result.name
2633
+ });
2634
+ resolverSpan.recordException(result);
2635
+ }
2636
+ resolverSpan.end();
2637
+ };
2638
+ }
2639
+ return () => {};
2640
+ }));
2641
+ },
2642
+ onExecute({
2643
+ args,
2644
+ extendContext
2645
+ }) {
2646
+ var _args$document$defini, _args$operationName;
2647
+ const operationType = (_args$document$defini = args.document.definitions.filter(def => def.kind === Kind$1.OPERATION_DEFINITION).map(def => def.operation)) == null ? void 0 : _args$document$defini[0];
2648
+ // Span name according to Semantic Conventions
2649
+ // https://github.com/open-telemetry/semantic-conventions
2650
+ let spanName = 'GraphQL Operation';
2651
+ if (operationType && args.operationName) {
2652
+ spanName = `${operationType} ${args.operationName}`;
2653
+ } else if (operationType && !args.operationName) {
2654
+ spanName = operationType;
2655
+ }
2656
+ const executionSpan = tracer.startSpan(spanName, {
2657
+ kind: SpanKind.SERVER,
2658
+ attributes: {
2659
+ [AttributeName.EXECUTION_OPERATION_NAME]: (_args$operationName = args.operationName) != null ? _args$operationName : undefined,
2660
+ [AttributeName.EXECUTION_OPERATION_TYPE]: operationType != null ? operationType : undefined,
2661
+ [AttributeName.EXECUTION_OPERATION_DOCUMENT]: print(args.document)
2662
+ }
2663
+ });
2664
+ const executeContext = context.active();
2665
+ const resultCbs = {
2666
+ onExecuteDone({
2667
+ result
2668
+ }) {
2669
+ var _args$operationName2, _args$variableValues;
2670
+ if (isAsyncIterable(result)) {
2671
+ executionSpan.end();
2672
+ // eslint-disable-next-line no-console
2673
+ console.warn(`Plugin "newrelic" encountered a AsyncIterator which is not supported yet, so tracing data is not available for the operation.`);
2674
+ return;
2675
+ }
2676
+ const logRecord = {
2677
+ context: executeContext,
2678
+ attributes: {
2679
+ 'service.name': 'faststore-api',
2680
+ 'service.version': '1.12.38',
2681
+ 'service.name_and_version': 'faststore-api@1.12.38',
2682
+ 'vtex.search_index': 'faststore_beta_api',
2683
+ [AttributeName.EXECUTION_OPERATION_NAME]: (_args$operationName2 = args.operationName) != null ? _args$operationName2 : undefined,
2684
+ [AttributeName.EXECUTION_OPERATION_DOCUMENT]: print(args.document),
2685
+ [AttributeName.EXECUTION_VARIABLES]: JSON.stringify((_args$variableValues = args.variableValues) != null ? _args$variableValues : {})
2686
+ }
2687
+ };
2688
+ if (typeof result.data !== 'undefined' && !(result.errors && result.errors.length > 0)) {
2689
+ logRecord.severityNumber = SeverityNumber.INFO;
2690
+ logRecord.severityText = 'Info';
2691
+ logRecord.attributes[AttributeName.EXECUTION_RESULT] = JSON.stringify(result);
2692
+ }
2693
+ if (result.errors && result.errors.length > 0) {
2694
+ logRecord.severityNumber = SeverityNumber.ERROR;
2695
+ logRecord.severityText = 'Error';
2696
+ logRecord.attributes[AttributeName.EXECUTION_ERROR] = JSON.stringify(result.errors);
2697
+ executionSpan.setAttributes({
2698
+ error: true,
2699
+ 'exception.category': AttributeName.EXECUTION_ERROR,
2700
+ 'exception.message': JSON.stringify(result.errors)
2701
+ });
2702
+ }
2703
+ if (experimentalSendLogs) {
2704
+ logger.emit(logRecord);
2705
+ }
2706
+ executionSpan.end();
2707
+ }
2708
+ };
2709
+ extendContext({
2710
+ [tracingSpanSymbol]: executionSpan
2711
+ });
2712
+ return resultCbs;
2713
+ }
2714
+ };
2715
+ };
2716
+ };
2717
+
2718
+ const FASTSTORE_API_VERSION = packageJson.version;
2719
+ // TODO: These urls are hardcoded for now, but they should be configurable via ENV variables
2720
+ // They are only acessible from within the VTEX network, so they are not a security risk
2721
+ const TRACE_COLLECTOR_URL = 'opentelemetry-collector.vtex.systems';
2722
+ const TRACE_COLLECTOR_URL_DEV = 'opentelemetry-collector-beta.vtex.systems';
2723
+ const LOG_COLLECTOR_URL = 'opentelemetry-collector.vtex.systems';
2724
+ function getTelemetry(APIOptions, telemetryOptions) {
2725
+ var _telemetryOptions$exp;
2726
+ const honeycombCollectorOptions = {
2727
+ url: (telemetryOptions == null ? void 0 : telemetryOptions.mode) === 'dev' ? TRACE_COLLECTOR_URL_DEV : TRACE_COLLECTOR_URL
2728
+ };
2729
+ const openSearchCollectorOptions = {
2730
+ url: LOG_COLLECTOR_URL
2731
+ };
2732
+ // Create a new tracer provider
2733
+ const tracerProvider = new BasicTracerProvider({
2734
+ resource: new Resource({
2735
+ 'service.name': 'faststore-api',
2736
+ 'service.version': FASTSTORE_API_VERSION,
2737
+ 'service.name_and_version': `faststore-api@${FASTSTORE_API_VERSION}`,
2738
+ platform: APIOptions.platform,
2739
+ [`${APIOptions.platform}.account`]: APIOptions.account,
2740
+ [`${APIOptions.platform}.environment`]: APIOptions.environment,
2741
+ // TODO: include the following properties in the logs
2742
+ // [`${APIOptions.platform}.options.hideUnavailableItems`]:
2743
+ // APIOptions.hideUnavailableItems,
2744
+ // [`${APIOptions.platform}.flags.enableOrderFormSync`]:
2745
+ // APIOptions.flags?.enableOrderFormSync,
2746
+ // channel: APIOptions.channel,
2747
+ locale: APIOptions.locale
2748
+ })
2749
+ });
2750
+ const loggerProvider = new LoggerProvider();
2751
+ // Create trace exporter
2752
+ const honeycombExporter = new OTLPTraceExporter(honeycombCollectorOptions);
2753
+ // Create log exporter
2754
+ const openSearchExporter = new OTLPLogsExporter(openSearchCollectorOptions);
2755
+ // Set up a span processor to export spans to Honeycomb
2756
+ const honeyCombSpanProcessor = new SimpleSpanProcessor(honeycombExporter);
2757
+ // Set up a log record processor to export spans to OpenSearch
2758
+ const openSearchLogProcessor = new SimpleLogRecordProcessor(openSearchExporter);
2759
+ // Register the span processor with the tracer provider
2760
+ tracerProvider.addSpanProcessor(honeyCombSpanProcessor);
2761
+ // Register the log record processor with the log provider
2762
+ loggerProvider.addLogRecordProcessor(openSearchLogProcessor);
2763
+ if ((telemetryOptions == null ? void 0 : telemetryOptions.mode) === 'verbose' || (telemetryOptions == null ? void 0 : telemetryOptions.mode) === 'dev') {
2764
+ // Set up a console exporter for verbose mode
2765
+ const consoleExporter = new ConsoleSpanExporter();
2766
+ const verboseTraceProcessor = new SimpleSpanProcessor(consoleExporter);
2767
+ // Set up processors for verbose mode
2768
+ const consoleLogExporter = new ConsoleLogRecordExporter();
2769
+ const veboseLogRecordExporter = new SimpleLogRecordProcessor(consoleLogExporter);
2770
+ tracerProvider.addSpanProcessor(verboseTraceProcessor);
2771
+ loggerProvider.addLogRecordProcessor(veboseLogRecordExporter);
2772
+ }
2773
+ const useFaststoreTelemetry = getFaststoreTelemetryPlugin(
2774
+ // The @opentelemetry/sdk-trace-base was renamed from @opentelemetry/tracing but the
2775
+ // envelop plugin doesn't support this change yet. This causes the class type to be incompatible,
2776
+ // even if they are the same. https://github.com/n1ru4l/envelop/issues/1610
2777
+ tracerProvider, loggerProvider, 'faststore-api', (_telemetryOptions$exp = telemetryOptions == null ? void 0 : telemetryOptions.experimentalSendLogs) != null ? _telemetryOptions$exp : false);
2778
+ return {
2779
+ useFaststoreTelemetry
2780
+ };
2781
+ }
2782
+
2531
2783
  const platforms = {
2532
2784
  vtex: {
2533
2785
  getResolvers: getResolvers,
@@ -2546,5 +2798,5 @@ const getSchema = async options => {
2546
2798
  return directives.reduce((s, d) => d.transformer(s), schema);
2547
2799
  };
2548
2800
 
2549
- export { BadRequestError, NotFoundError, getContextFactory$1 as getContextFactory, getResolvers$1 as getResolvers, getSchema, getTypeDefs, isBadRequestError, isFastStoreError, isNotFoundError, stringify$1 as stringifyCacheControl };
2801
+ export { BadRequestError, NotFoundError, getContextFactory$1 as getContextFactory, getResolvers$1 as getResolvers, getSchema, getTelemetry, getTypeDefs, isBadRequestError, isFastStoreError, isNotFoundError, stringify$1 as stringifyCacheControl };
2550
2802
  //# sourceMappingURL=api.esm.js.map