@lambdaorm/lib 3.8.1 → 3.9.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.
Files changed (98) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +3 -3
  3. package/connection/infrastructure/adapters/base/connectionPool.d.ts +3 -0
  4. package/connection/infrastructure/adapters/base/connectionPool.d.ts.map +1 -1
  5. package/connection/infrastructure/adapters/base/connectionPool.js +17 -0
  6. package/connection/infrastructure/adapters/base/connectionPool.js.map +1 -1
  7. package/execution/application/services/executor.d.ts.map +1 -1
  8. package/execution/application/services/executor.js +9 -1
  9. package/execution/application/services/executor.js.map +1 -1
  10. package/execution/application/services/queryExecutor/queryExecutor.d.ts +4 -0
  11. package/execution/application/services/queryExecutor/queryExecutor.d.ts.map +1 -1
  12. package/execution/application/services/queryExecutor/queryExecutor.js +48 -0
  13. package/execution/application/services/queryExecutor/queryExecutor.js.map +1 -1
  14. package/execution/domain/errors.d.ts +3 -0
  15. package/execution/domain/errors.d.ts.map +1 -1
  16. package/execution/domain/errors.js +2 -0
  17. package/execution/domain/errors.js.map +1 -1
  18. package/expressions/application/facade.js +1 -1
  19. package/expressions/application/facade.js.map +1 -1
  20. package/expressions/application/services/queryBuilder.d.ts +3 -1
  21. package/expressions/application/services/queryBuilder.d.ts.map +1 -1
  22. package/expressions/application/services/queryBuilder.js +8 -1
  23. package/expressions/application/services/queryBuilder.js.map +1 -1
  24. package/expressions/application/services/queryBuilderCacheDecorator.d.ts.map +1 -1
  25. package/expressions/application/services/queryBuilderCacheDecorator.js +7 -3
  26. package/expressions/application/services/queryBuilderCacheDecorator.js.map +1 -1
  27. package/expressions/application/useCases/execute.d.ts.map +1 -1
  28. package/expressions/application/useCases/execute.js +7 -3
  29. package/expressions/application/useCases/execute.js.map +1 -1
  30. package/expressions/application/useCases/transaction.d.ts +3 -1
  31. package/expressions/application/useCases/transaction.d.ts.map +1 -1
  32. package/expressions/application/useCases/transaction.js +7 -3
  33. package/expressions/application/useCases/transaction.js.map +1 -1
  34. package/language/domain/ports/DmlBuilder.d.ts +2 -0
  35. package/language/domain/ports/DmlBuilder.d.ts.map +1 -1
  36. package/orm/infrastructure/orm.d.ts +9 -0
  37. package/orm/infrastructure/orm.d.ts.map +1 -1
  38. package/orm/infrastructure/orm.js +41 -0
  39. package/orm/infrastructure/orm.js.map +1 -1
  40. package/package.json +72 -3
  41. package/query/domain/query.d.ts +2 -0
  42. package/query/domain/query.d.ts.map +1 -1
  43. package/query/domain/query.js.map +1 -1
  44. package/sentence/infrastructure/adapters/NoSql/NoSqlDmlBuilder.d.ts.map +1 -1
  45. package/sentence/infrastructure/adapters/NoSql/NoSqlDmlBuilder.js +3 -0
  46. package/sentence/infrastructure/adapters/NoSql/NoSqlDmlBuilder.js.map +1 -1
  47. package/sentence/infrastructure/adapters/base/dmlBuilder.d.ts +2 -0
  48. package/sentence/infrastructure/adapters/base/dmlBuilder.d.ts.map +1 -1
  49. package/sentence/infrastructure/adapters/base/dmlBuilder.js +5 -0
  50. package/sentence/infrastructure/adapters/base/dmlBuilder.js.map +1 -1
  51. package/shared/infrastructure/helper.d.ts +3 -0
  52. package/shared/infrastructure/helper.d.ts.map +1 -1
  53. package/shared/infrastructure/helper.js +2 -0
  54. package/shared/infrastructure/helper.js.map +1 -1
  55. package/shared/infrastructure/index.d.ts +1 -0
  56. package/shared/infrastructure/index.d.ts.map +1 -1
  57. package/shared/infrastructure/index.js +1 -0
  58. package/shared/infrastructure/index.js.map +1 -1
  59. package/shared/infrastructure/observability/index.d.ts +7 -0
  60. package/shared/infrastructure/observability/index.d.ts.map +1 -0
  61. package/shared/infrastructure/observability/index.js +23 -0
  62. package/shared/infrastructure/observability/index.js.map +1 -0
  63. package/shared/infrastructure/observability/ruleBasedSpanProcessor.d.ts +60 -0
  64. package/shared/infrastructure/observability/ruleBasedSpanProcessor.d.ts.map +1 -0
  65. package/shared/infrastructure/observability/ruleBasedSpanProcessor.js +131 -0
  66. package/shared/infrastructure/observability/ruleBasedSpanProcessor.js.map +1 -0
  67. package/shared/infrastructure/observability/sanitizer.d.ts +7 -0
  68. package/shared/infrastructure/observability/sanitizer.d.ts.map +1 -0
  69. package/shared/infrastructure/observability/sanitizer.js +43 -0
  70. package/shared/infrastructure/observability/sanitizer.js.map +1 -0
  71. package/shared/infrastructure/observability/sdk.d.ts +47 -0
  72. package/shared/infrastructure/observability/sdk.d.ts.map +1 -0
  73. package/shared/infrastructure/observability/sdk.js +251 -0
  74. package/shared/infrastructure/observability/sdk.js.map +1 -0
  75. package/shared/infrastructure/observability/semconv.d.ts +50 -0
  76. package/shared/infrastructure/observability/semconv.d.ts.map +1 -0
  77. package/shared/infrastructure/observability/semconv.js +81 -0
  78. package/shared/infrastructure/observability/semconv.js.map +1 -0
  79. package/shared/infrastructure/observability/telemetry.d.ts +103 -0
  80. package/shared/infrastructure/observability/telemetry.d.ts.map +1 -0
  81. package/shared/infrastructure/observability/telemetry.js +408 -0
  82. package/shared/infrastructure/observability/telemetry.js.map +1 -0
  83. package/shared/infrastructure/observability/traceRules.d.ts +56 -0
  84. package/shared/infrastructure/observability/traceRules.d.ts.map +1 -0
  85. package/shared/infrastructure/observability/traceRules.js +68 -0
  86. package/shared/infrastructure/observability/traceRules.js.map +1 -0
  87. package/stage/application/facade.d.ts +8 -0
  88. package/stage/application/facade.d.ts.map +1 -1
  89. package/stage/application/facade.js +27 -11
  90. package/stage/application/facade.js.map +1 -1
  91. package/stage/application/services/schemaEventService.d.ts +29 -0
  92. package/stage/application/services/schemaEventService.d.ts.map +1 -0
  93. package/stage/application/services/schemaEventService.js +123 -0
  94. package/stage/application/services/schemaEventService.js.map +1 -0
  95. package/stage/application/services/stateService.d.ts +9 -2
  96. package/stage/application/services/stateService.d.ts.map +1 -1
  97. package/stage/application/services/stateService.js +20 -0
  98. package/stage/application/services/stateService.js.map +1 -1
@@ -0,0 +1,50 @@
1
+ import { Dialect } from '@lambdaorm/base';
2
+ /** The attributes of the OpenTelemetry conventions for databases, and the ones of λORM (prefix lambdaorm.) */
3
+ export declare const ATTR: {
4
+ readonly DB_SYSTEM_NAME: "db.system.name";
5
+ readonly DB_NAMESPACE: "db.namespace";
6
+ readonly DB_COLLECTION_NAME: "db.collection.name";
7
+ readonly DB_OPERATION_NAME: "db.operation.name";
8
+ readonly DB_QUERY_TEXT: "db.query.text";
9
+ readonly DB_RESPONSE_RETURNED_ROWS: "db.response.returned_rows";
10
+ readonly SERVER_ADDRESS: "server.address";
11
+ readonly SERVER_PORT: "server.port";
12
+ readonly ERROR_TYPE: "error.type";
13
+ readonly POOL_NAME: "db.client.connection.pool.name";
14
+ readonly CONNECTION_STATE: "db.client.connection.state";
15
+ readonly ENDUSER_ID: "enduser.id";
16
+ readonly SCHEMA: "lambdaorm.schema";
17
+ readonly STAGE: "lambdaorm.stage";
18
+ readonly ENTITY: "lambdaorm.entity";
19
+ readonly ACTION: "lambdaorm.action";
20
+ readonly CATEGORY: "lambdaorm.category";
21
+ readonly SOURCE: "lambdaorm.source";
22
+ readonly DIALECT: "lambdaorm.dialect";
23
+ readonly EXPRESSION: "lambdaorm.expression";
24
+ readonly ROWS: "lambdaorm.rows";
25
+ readonly CACHE_HIT: "lambdaorm.cache.hit";
26
+ readonly CONSTRAINT: "lambdaorm.constraint";
27
+ readonly TRANSACTION_RESULT: "lambdaorm.transaction.result";
28
+ readonly STAGE_ACTION: "lambdaorm.stage.action";
29
+ readonly CHANGE_KIND: "lambdaorm.change.kind";
30
+ };
31
+ /** The metrics (docs/OBSERVABILITY.md §6) */
32
+ export declare const METRIC: {
33
+ readonly OPERATION_DURATION: "db.client.operation.duration";
34
+ readonly RETURNED_ROWS: "db.client.response.returned_rows";
35
+ readonly CONNECTION_COUNT: "db.client.connection.count";
36
+ readonly CONNECTION_WAIT_TIME: "db.client.connection.wait_time";
37
+ readonly QUERY_DURATION: "lambdaorm.query.duration";
38
+ readonly COMPILE_DURATION: "lambdaorm.query.compile.duration";
39
+ readonly CONSTRAINT_VIOLATIONS: "lambdaorm.constraint.violations";
40
+ readonly TRANSACTION_DURATION: "lambdaorm.transaction.duration";
41
+ readonly STAGE_DURATION: "lambdaorm.stage.operation.duration";
42
+ readonly SCHEMA_LOAD_DURATION: "lambdaorm.schema.load.duration";
43
+ readonly SCHEMA_CHANGES: "lambdaorm.schema.changes";
44
+ };
45
+ /** db.system.name of each dialect, the value of the conventions; lambdaorm.dialect keeps the name of λORM */
46
+ export declare const DB_SYSTEM_NAMES: Record<Dialect, string>;
47
+ export declare const dbSystemName: (dialect: string) => string;
48
+ /** db.operation.name: the SQL verb (SELECT, INSERT…), or the command of MongoDB */
49
+ export declare const dbOperationName: (dialect: string, action: string, category: string) => string;
50
+ //# sourceMappingURL=semconv.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"semconv.d.ts","sourceRoot":"","sources":["../../../../../src/lib/shared/infrastructure/observability/semconv.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAkB,MAAM,iBAAiB,CAAA;AAEzD,8GAA8G;AAC9G,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BP,CAAA;AAEV,6CAA6C;AAC7C,eAAO,MAAM,MAAM;;;;;;;;;;;;CAYT,CAAA;AAEV,6GAA6G;AAC7G,eAAO,MAAM,eAAe,EAAE,MAAM,CAAC,OAAO,EAAE,MAAM,CASnD,CAAA;AAED,eAAO,MAAM,YAAY,GAAI,SAAS,MAAM,KAAG,MAA4D,CAAA;AAe3G,mFAAmF;AACnF,eAAO,MAAM,eAAe,GAAI,SAAS,MAAM,EAAE,QAAQ,MAAM,EAAE,UAAU,MAAM,KAAG,MAKnF,CAAA"}
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.dbOperationName = exports.dbSystemName = exports.DB_SYSTEM_NAMES = exports.METRIC = exports.ATTR = void 0;
4
+ const base_1 = require("@lambdaorm/base");
5
+ /** The attributes of the OpenTelemetry conventions for databases, and the ones of λORM (prefix lambdaorm.) */
6
+ exports.ATTR = {
7
+ DB_SYSTEM_NAME: 'db.system.name',
8
+ DB_NAMESPACE: 'db.namespace',
9
+ DB_COLLECTION_NAME: 'db.collection.name',
10
+ DB_OPERATION_NAME: 'db.operation.name',
11
+ DB_QUERY_TEXT: 'db.query.text',
12
+ DB_RESPONSE_RETURNED_ROWS: 'db.response.returned_rows',
13
+ SERVER_ADDRESS: 'server.address',
14
+ SERVER_PORT: 'server.port',
15
+ ERROR_TYPE: 'error.type',
16
+ POOL_NAME: 'db.client.connection.pool.name',
17
+ CONNECTION_STATE: 'db.client.connection.state',
18
+ ENDUSER_ID: 'enduser.id',
19
+ SCHEMA: 'lambdaorm.schema',
20
+ STAGE: 'lambdaorm.stage',
21
+ ENTITY: 'lambdaorm.entity',
22
+ ACTION: 'lambdaorm.action',
23
+ CATEGORY: 'lambdaorm.category',
24
+ SOURCE: 'lambdaorm.source',
25
+ DIALECT: 'lambdaorm.dialect',
26
+ EXPRESSION: 'lambdaorm.expression',
27
+ ROWS: 'lambdaorm.rows',
28
+ CACHE_HIT: 'lambdaorm.cache.hit',
29
+ CONSTRAINT: 'lambdaorm.constraint',
30
+ TRANSACTION_RESULT: 'lambdaorm.transaction.result',
31
+ STAGE_ACTION: 'lambdaorm.stage.action',
32
+ CHANGE_KIND: 'lambdaorm.change.kind'
33
+ };
34
+ /** The metrics (docs/OBSERVABILITY.md §6) */
35
+ exports.METRIC = {
36
+ OPERATION_DURATION: 'db.client.operation.duration',
37
+ RETURNED_ROWS: 'db.client.response.returned_rows',
38
+ CONNECTION_COUNT: 'db.client.connection.count',
39
+ CONNECTION_WAIT_TIME: 'db.client.connection.wait_time',
40
+ QUERY_DURATION: 'lambdaorm.query.duration',
41
+ COMPILE_DURATION: 'lambdaorm.query.compile.duration',
42
+ CONSTRAINT_VIOLATIONS: 'lambdaorm.constraint.violations',
43
+ TRANSACTION_DURATION: 'lambdaorm.transaction.duration',
44
+ STAGE_DURATION: 'lambdaorm.stage.operation.duration',
45
+ SCHEMA_LOAD_DURATION: 'lambdaorm.schema.load.duration',
46
+ SCHEMA_CHANGES: 'lambdaorm.schema.changes'
47
+ };
48
+ /** db.system.name of each dialect, the value of the conventions; lambdaorm.dialect keeps the name of λORM */
49
+ exports.DB_SYSTEM_NAMES = {
50
+ [base_1.Dialect.PostgreSQL]: 'postgresql',
51
+ [base_1.Dialect.MySQL]: 'mysql',
52
+ [base_1.Dialect.MariaDB]: 'mariadb',
53
+ [base_1.Dialect.SqlServer]: 'microsoft.sql_server',
54
+ [base_1.Dialect.Oracle]: 'oracle.db',
55
+ [base_1.Dialect.MongoDB]: 'mongodb',
56
+ [base_1.Dialect.SqlLite]: 'sqlite',
57
+ [base_1.Dialect.SQLjs]: 'sqlite'
58
+ };
59
+ const dbSystemName = (dialect) => exports.DB_SYSTEM_NAMES[dialect] ?? 'other_sql';
60
+ exports.dbSystemName = dbSystemName;
61
+ /** the command of MongoDB for each action (its convention names the command) */
62
+ const MONGO_OPERATIONS = {
63
+ [base_1.SentenceAction.select]: 'find',
64
+ [base_1.SentenceAction.insert]: 'insert',
65
+ [base_1.SentenceAction.insertConditional]: 'insert',
66
+ [base_1.SentenceAction.bulkInsert]: 'insert',
67
+ [base_1.SentenceAction.update]: 'update',
68
+ [base_1.SentenceAction.upsert]: 'update',
69
+ [base_1.SentenceAction.bulkMerge]: 'update',
70
+ [base_1.SentenceAction.delete]: 'delete',
71
+ [base_1.SentenceAction.bulkDelete]: 'delete'
72
+ };
73
+ /** db.operation.name: the SQL verb (SELECT, INSERT…), or the command of MongoDB */
74
+ const dbOperationName = (dialect, action, category) => {
75
+ if (dialect === base_1.Dialect.MongoDB) {
76
+ return MONGO_OPERATIONS[action] ?? action;
77
+ }
78
+ return (category || action).toUpperCase();
79
+ };
80
+ exports.dbOperationName = dbOperationName;
81
+ //# sourceMappingURL=semconv.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"semconv.js","sourceRoot":"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,MAAM,CAAA;IAC5D,CAAC;IACD,OAAO,CAAC,QAAQ,IAAI,MAAM,CAAC,CAAC,WAAW,EAAE,CAAA;AAC1C,CAAC,CAAA;AALY,QAAA,eAAe,mBAK3B"}
@@ -0,0 +1,103 @@
1
+ import { Span, SpanKind, Tracer, Meter, Attributes } from '@opentelemetry/api';
2
+ import { Expressions } from '3xpr';
3
+ import { ResolvedObservability, QueryTextMode, Actor } from '@lambdaorm/base';
4
+ export declare const SCOPE_NAME = "@lambdaorm/lib";
5
+ /** what a span or a metric needs of a sentence (a Query of λORM) */
6
+ export interface SentenceTelemetry {
7
+ entity: string;
8
+ action: string;
9
+ category: string;
10
+ type?: string;
11
+ dialect: string;
12
+ source: string;
13
+ sentence: string;
14
+ /** the sentence with its constants as parameters, when it was built (queryText: sanitized) */
15
+ sanitized?: string;
16
+ includes?: {
17
+ query: SentenceTelemetry;
18
+ }[];
19
+ }
20
+ /** the table (or collection) of the entity in the source, for db.collection.name */
21
+ export interface SentenceTarget {
22
+ collection?: string;
23
+ }
24
+ export interface ServerInfo {
25
+ address?: string;
26
+ port?: number;
27
+ namespace?: string;
28
+ }
29
+ /** an object whose connections in use can be counted (a pool of a source) */
30
+ export interface TrackedPool {
31
+ readonly name: string;
32
+ readonly used: number;
33
+ }
34
+ /** error.type: the code of the database when there is one, if not the name of the error */
35
+ export declare const errorType: (error: any) => string;
36
+ /**
37
+ * The spans and metrics of λORM, with the API of OpenTelemetry: without an SDK they do nothing. Disabled (the default,
38
+ * and without infrastructure.observability) every method runs what it receives and nothing else.
39
+ */
40
+ export declare class Telemetry {
41
+ private config?;
42
+ private schema;
43
+ private _tracer?;
44
+ private _meter?;
45
+ private instruments?;
46
+ private readonly pools;
47
+ private rules?;
48
+ /** set by compiled(), read right after the (synchronous) build of the expression */
49
+ private lastCacheHit?;
50
+ /** set from the schema loaded (and the OTEL_* variables); can be called again when the schema is reloaded */
51
+ configure(config: ResolvedObservability | undefined, schema?: string, exp?: Expressions, warn?: (message: string) => void): void;
52
+ get tracing(): boolean;
53
+ get measuring(): boolean;
54
+ get active(): boolean;
55
+ get queryText(): QueryTextMode;
56
+ /** build the sanitized text of the sentences when compiling (only if a span will use it) */
57
+ get sanitizeSentences(): boolean;
58
+ get tracer(): Tracer;
59
+ get meter(): Meter;
60
+ /** runs fn inside a span when tracing; the span ends with fn, with the error recorded (without data) if it fails */
61
+ span<T>(name: string, kind: SpanKind, attributes: Attributes, fn: (span?: Span) => Promise<T>, startTime?: number): Promise<T>;
62
+ /**
63
+ * the root span of an expression (lambdaorm.execute) and lambdaorm.query.duration. The span starts after compiling
64
+ * (the rules need the entity and the action) with the time of before compiling. The rules decide before running when
65
+ * they can: no span at all when no rule can keep it; if not, they decide when it ends (lambdaorm.trace.record).
66
+ */
67
+ execute<T, Q extends SentenceTelemetry>(expression: string, options: {
68
+ stage?: string;
69
+ actor?: Actor;
70
+ }, build: () => Q, run: (query: Q) => Promise<T>): Promise<T>;
71
+ /** compiling an expression to sentences (lambdaorm.query.compile.duration, lambdaorm.cache.hit) */
72
+ compiled(seconds: number, cacheHit: boolean): void;
73
+ /** a span of the database for a sentence sent to a source, db.client.operation.duration and returned_rows */
74
+ sentence<T>(query: SentenceTelemetry, stage: string | undefined, server: ServerInfo & SentenceTarget, run: () => Promise<T>): Promise<T>;
75
+ /** a transaction (lambdaorm.transaction): commit when run ends, rollback when it fails */
76
+ transaction<T>(stage: string | undefined, run: () => Promise<T>): Promise<T>;
77
+ /** a command of a stage (lambdaorm.stage.<action>) and lambdaorm.stage.operation.duration */
78
+ stage<T>(action: string, stage: string | undefined, run: () => Promise<T>): Promise<T>;
79
+ /** a constraint of the model that rejected a value (lambdaorm.constraint.violations) */
80
+ constraintViolation(entity: string, constraint: string): void;
81
+ /** a schema.change (lambdaorm.schema.changes) */
82
+ schemaChanged(kind: string): void;
83
+ /** loading and extending the schema (lambdaorm.schema.load.duration) */
84
+ schemaLoaded(seconds: number): void;
85
+ /** the time to get a connection of a pool (db.client.connection.wait_time) */
86
+ connectionAcquired(pool: string, seconds: number): void;
87
+ /** the pool is counted by db.client.connection.count while it is tracked */
88
+ trackPool(pool: TrackedPool): void;
89
+ untrackPool(pool: TrackedPool): void;
90
+ private createInstruments;
91
+ private queryAttributes;
92
+ private entityFiltered;
93
+ private expressionText;
94
+ private sentenceText;
95
+ /** the variables of the rules that the sentence gives (the ones of the condition of a source of a stage) */
96
+ private sentenceVariables;
97
+ /** the sources the expression touches: the one of its sentence and the ones of its includes */
98
+ private sources;
99
+ private rows;
100
+ }
101
+ /** a telemetry that does nothing, for the helpers built without one (tests) */
102
+ export declare const DISABLED_TELEMETRY: Telemetry;
103
+ //# sourceMappingURL=telemetry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"telemetry.d.ts","sourceRoot":"","sources":["../../../../../src/lib/shared/infrastructure/observability/telemetry.ts"],"names":[],"mappings":"AAAA,OAAO,EACqC,IAAI,EAAE,QAAQ,EAAkB,MAAM,EAAE,KAAK,EAAsB,UAAU,EAExH,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EAAE,WAAW,EAAE,MAAM,MAAM,CAAA;AAClC,OAAO,EAAE,qBAAqB,EAAE,aAAa,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAA;AAS7E,eAAO,MAAM,UAAU,mBAAmB,CAAA;AAU1C,oEAAoE;AACpE,MAAM,WAAW,iBAAiB;IACjC,MAAM,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,MAAM,CAAA;IACd,QAAQ,EAAE,MAAM,CAAA;IAChB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,OAAO,EAAE,MAAM,CAAA;IACf,MAAM,EAAE,MAAM,CAAA;IACd,QAAQ,EAAE,MAAM,CAAA;IAChB,8FAA8F;IAC9F,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,QAAQ,CAAC,EAAE;QAAE,KAAK,EAAE,iBAAiB,CAAA;KAAE,EAAE,CAAA;CACzC;AAED,oFAAoF;AACpF,MAAM,WAAW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AAM,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI;IAIrE,iDAAiD;IAC1C,aAAa,CAAE,IAAI,EAAE,MAAM,GAAG,IAAI;IAIzC,wEAAwE;IACjE,YAAY,CAAE,OAAO,EAAE,MAAM,GAAG,IAAI;IAI3C,8EAA8E;IACvE,kBAAkB,CAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI;IAI/D,4EAA4E;IACrE,SAAS,CAAE,IAAI,EAAE,WAAW,GAAG,IAAI;IAInC,WAAW,CAAE,IAAI,EAAE,WAAW,GAAG,IAAI;IAI5C,OAAO,CAAC,iBAAiB;IAwBzB,OAAO,CAAC,eAAe;IAIvB,OAAO,CAAC,cAAc;IAOtB,OAAO,CAAC,cAAc;IAQtB,OAAO,CAAC,YAAY;IASpB,4GAA4G;IAC5G,OAAO,CAAC,iBAAiB;IAgBzB,+FAA+F;IAC/F,OAAO,CAAC,OAAO;IAQf,OAAO,CAAC,IAAI;CAKZ;AAED,+EAA+E;AAC/E,eAAO,MAAM,kBAAkB,WAAkB,CAAA"}
@@ -0,0 +1,408 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DISABLED_TELEMETRY = exports.Telemetry = exports.errorType = exports.SCOPE_NAME = void 0;
4
+ const api_1 = require("@opentelemetry/api");
5
+ const semconv_1 = require("./semconv");
6
+ const sanitizer_1 = require("./sanitizer");
7
+ const traceRules_1 = require("./traceRules");
8
+ const ruleBasedSpanProcessor_1 = require("./ruleBasedSpanProcessor");
9
+ /** inside an expression that the rules don't trace: no span of λORM is created */
10
+ const TRACE_OFF = (0, api_1.createContextKey)('lambdaorm.trace.off');
11
+ exports.SCOPE_NAME = '@lambdaorm/lib';
12
+ const SCOPE_VERSION = (() => {
13
+ try {
14
+ // src/lib/shared/infrastructure/observability and build/lib/shared/infrastructure/observability: five levels
15
+ return require('../../../../../package.json').version;
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ })();
21
+ /** error.type: the code of the database when there is one, if not the name of the error */
22
+ const errorType = (error) => {
23
+ if (error && typeof error.code === 'string' && error.code !== '')
24
+ return error.code;
25
+ return error?.name || error?.constructor?.name || 'Error';
26
+ };
27
+ exports.errorType = errorType;
28
+ /**
29
+ * The message of an error that can go in a span: the errors of λORM carry the data of the sentence in their message
30
+ * (they can be personal data), so only their name goes, and the constraint for a ValidationError.
31
+ */
32
+ const safeMessage = (error) => {
33
+ if (error?.constraint)
34
+ return `${error.name}: ${error.constraint}`;
35
+ return (0, exports.errorType)(error);
36
+ };
37
+ /**
38
+ * The spans and metrics of λORM, with the API of OpenTelemetry: without an SDK they do nothing. Disabled (the default,
39
+ * and without infrastructure.observability) every method runs what it receives and nothing else.
40
+ */
41
+ class Telemetry {
42
+ constructor() {
43
+ this.schema = '';
44
+ this.pools = new Set();
45
+ }
46
+ /** set from the schema loaded (and the OTEL_* variables); can be called again when the schema is reloaded */
47
+ configure(config, schema = '', exp, warn) {
48
+ this.config = config;
49
+ this.schema = schema;
50
+ this.rules = config && exp ? new traceRules_1.TraceRules(config.traces.rules, exp, warn) : undefined;
51
+ this.instruments = undefined;
52
+ // taken again: the providers may have changed (an SDK started for this schema)
53
+ this._tracer = undefined;
54
+ this._meter = undefined;
55
+ if (this.measuring) {
56
+ this.createInstruments();
57
+ }
58
+ }
59
+ get tracing() {
60
+ return this.config?.traces.enabled === true;
61
+ }
62
+ get measuring() {
63
+ return this.config?.metrics.enabled === true;
64
+ }
65
+ get active() {
66
+ return this.tracing || this.measuring;
67
+ }
68
+ get queryText() {
69
+ return this.config?.traces.queryText ?? 'sanitized';
70
+ }
71
+ /** build the sanitized text of the sentences when compiling (only if a span will use it) */
72
+ get sanitizeSentences() {
73
+ return this.tracing && this.queryText === 'sanitized';
74
+ }
75
+ get tracer() {
76
+ if (!this._tracer)
77
+ this._tracer = api_1.trace.getTracer(exports.SCOPE_NAME, SCOPE_VERSION);
78
+ return this._tracer;
79
+ }
80
+ get meter() {
81
+ if (!this._meter)
82
+ this._meter = api_1.metrics.getMeter(exports.SCOPE_NAME, SCOPE_VERSION);
83
+ return this._meter;
84
+ }
85
+ /** runs fn inside a span when tracing; the span ends with fn, with the error recorded (without data) if it fails */
86
+ async span(name, kind, attributes, fn, startTime) {
87
+ if (!this.tracing || api_1.context.active().getValue(TRACE_OFF) === true) {
88
+ return fn(undefined);
89
+ }
90
+ return this.tracer.startActiveSpan(name, { kind, attributes, startTime }, async (span) => {
91
+ try {
92
+ return await fn(span);
93
+ }
94
+ catch (error) {
95
+ span.setAttribute(semconv_1.ATTR.ERROR_TYPE, (0, exports.errorType)(error));
96
+ span.recordException({ name: error?.name ?? 'Error', message: safeMessage(error) });
97
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: safeMessage(error) });
98
+ throw error;
99
+ }
100
+ finally {
101
+ span.end();
102
+ }
103
+ });
104
+ }
105
+ /**
106
+ * the root span of an expression (lambdaorm.execute) and lambdaorm.query.duration. The span starts after compiling
107
+ * (the rules need the entity and the action) with the time of before compiling. The rules decide before running when
108
+ * they can: no span at all when no rule can keep it; if not, they decide when it ends (lambdaorm.trace.record).
109
+ */
110
+ async execute(expression, options, build, run) {
111
+ const stage = options.stage;
112
+ // enduser.id: the credential, or an id of the user; never an email
113
+ const user = options.actor?.credential ?? options.actor?.user ?? null;
114
+ if (!this.active) {
115
+ return run(build());
116
+ }
117
+ const start = performance.now();
118
+ const startTime = Date.now();
119
+ const attributes = { [semconv_1.ATTR.SCHEMA]: this.schema };
120
+ if (stage)
121
+ attributes[semconv_1.ATTR.STAGE] = stage;
122
+ let query;
123
+ let error;
124
+ try {
125
+ this.lastCacheHit = undefined;
126
+ query = build();
127
+ const cacheHit = this.lastCacheHit;
128
+ const tracing = this.tracing && api_1.context.active().getValue(TRACE_OFF) !== true;
129
+ const sentence = tracing ? this.sentenceVariables(query, stage) : undefined;
130
+ const decision = sentence && this.rules ? this.rules.before(sentence) : { kind: 'decided', record: true, rule: -1 };
131
+ if (!tracing || (decision.kind === 'decided' && !decision.record)) {
132
+ return tracing
133
+ ? await api_1.context.with(api_1.context.active().setValue(TRACE_OFF, true), () => run(query))
134
+ : await run(query);
135
+ }
136
+ const spanAttributes = { ...attributes, ...this.queryAttributes(query) };
137
+ if (cacheHit !== undefined)
138
+ spanAttributes[semconv_1.ATTR.CACHE_HIT] = cacheHit;
139
+ const text = this.expressionText(expression);
140
+ if (text !== undefined)
141
+ spanAttributes[semconv_1.ATTR.EXPRESSION] = text;
142
+ if (user)
143
+ spanAttributes[semconv_1.ATTR.ENDUSER_ID] = user;
144
+ if (decision.kind === 'decided') {
145
+ spanAttributes[ruleBasedSpanProcessor_1.TRACE_RECORD] = true;
146
+ spanAttributes[ruleBasedSpanProcessor_1.TRACE_RULE] = decision.rule;
147
+ }
148
+ const _query = query;
149
+ return await this.span('lambdaorm.execute', api_1.SpanKind.INTERNAL, spanAttributes, async (span) => {
150
+ let result;
151
+ let failure;
152
+ try {
153
+ result = await run(_query);
154
+ return result;
155
+ }
156
+ catch (e) {
157
+ failure = e;
158
+ throw e;
159
+ }
160
+ finally {
161
+ const rows = this.rows(result);
162
+ if (span && rows !== undefined)
163
+ span.setAttribute(semconv_1.ATTR.ROWS, rows);
164
+ if (span && decision.kind === 'pending' && this.rules && sentence) {
165
+ const final = this.rules.after(decision.from, {
166
+ ...sentence,
167
+ sources: this.sources(_query),
168
+ durationMs: performance.now() - start,
169
+ rows: rows ?? null,
170
+ error: failure ? (0, exports.errorType)(failure) : null,
171
+ user
172
+ });
173
+ span.setAttribute(ruleBasedSpanProcessor_1.TRACE_RECORD, final.record);
174
+ span.setAttribute(ruleBasedSpanProcessor_1.TRACE_RULE, final.rule);
175
+ }
176
+ }
177
+ }, startTime);
178
+ }
179
+ catch (e) {
180
+ error = e;
181
+ throw e;
182
+ }
183
+ finally {
184
+ if (this.instruments) {
185
+ const metric = { ...attributes, ...(query ? this.queryAttributes(query) : {}) };
186
+ if (error)
187
+ metric[semconv_1.ATTR.ERROR_TYPE] = (0, exports.errorType)(error);
188
+ this.instruments.queryDuration.record((performance.now() - start) / 1000, this.entityFiltered(metric));
189
+ }
190
+ }
191
+ }
192
+ /** compiling an expression to sentences (lambdaorm.query.compile.duration, lambdaorm.cache.hit) */
193
+ compiled(seconds, cacheHit) {
194
+ this.lastCacheHit = cacheHit;
195
+ this.instruments?.compileDuration.record(seconds, { [semconv_1.ATTR.SCHEMA]: this.schema, [semconv_1.ATTR.CACHE_HIT]: cacheHit });
196
+ }
197
+ /** a span of the database for a sentence sent to a source, db.client.operation.duration and returned_rows */
198
+ async sentence(query, stage, server, run) {
199
+ if (!this.active) {
200
+ return run();
201
+ }
202
+ const start = performance.now();
203
+ const operation = (0, semconv_1.dbOperationName)(query.dialect, query.action, query.category);
204
+ const attributes = {
205
+ [semconv_1.ATTR.DB_SYSTEM_NAME]: (0, semconv_1.dbSystemName)(query.dialect),
206
+ [semconv_1.ATTR.DIALECT]: query.dialect,
207
+ [semconv_1.ATTR.DB_OPERATION_NAME]: operation,
208
+ [semconv_1.ATTR.SOURCE]: query.source
209
+ };
210
+ const collection = server.collection ?? query.entity;
211
+ if (collection)
212
+ attributes[semconv_1.ATTR.DB_COLLECTION_NAME] = collection;
213
+ if (stage)
214
+ attributes[semconv_1.ATTR.STAGE] = stage;
215
+ if (server.namespace)
216
+ attributes[semconv_1.ATTR.DB_NAMESPACE] = server.namespace;
217
+ if (server.address)
218
+ attributes[semconv_1.ATTR.SERVER_ADDRESS] = server.address;
219
+ let error;
220
+ let result;
221
+ try {
222
+ const spanAttributes = { ...attributes };
223
+ if (server.port)
224
+ spanAttributes[semconv_1.ATTR.SERVER_PORT] = server.port;
225
+ if (query.entity)
226
+ spanAttributes[semconv_1.ATTR.ENTITY] = query.entity;
227
+ const text = this.sentenceText(query);
228
+ if (text !== undefined)
229
+ spanAttributes[semconv_1.ATTR.DB_QUERY_TEXT] = text;
230
+ const name = collection ? `${operation} ${collection}` : operation;
231
+ result = await this.span(name, api_1.SpanKind.CLIENT, spanAttributes, async (span) => {
232
+ const value = await run();
233
+ if (span) {
234
+ if (Array.isArray(value))
235
+ span.setAttribute(semconv_1.ATTR.DB_RESPONSE_RETURNED_ROWS, value.length);
236
+ else if (typeof value === 'number')
237
+ span.setAttribute(semconv_1.ATTR.ROWS, value);
238
+ }
239
+ return value;
240
+ });
241
+ return result;
242
+ }
243
+ catch (e) {
244
+ error = e;
245
+ throw e;
246
+ }
247
+ finally {
248
+ if (this.instruments) {
249
+ if (error)
250
+ attributes[semconv_1.ATTR.ERROR_TYPE] = (0, exports.errorType)(error);
251
+ this.instruments.operationDuration.record((performance.now() - start) / 1000, attributes);
252
+ if (Array.isArray(result)) {
253
+ this.instruments.returnedRows.record(result.length, attributes);
254
+ }
255
+ }
256
+ }
257
+ }
258
+ /** a transaction (lambdaorm.transaction): commit when run ends, rollback when it fails */
259
+ async transaction(stage, run) {
260
+ if (!this.active) {
261
+ return run();
262
+ }
263
+ const start = performance.now();
264
+ const attributes = { [semconv_1.ATTR.SCHEMA]: this.schema };
265
+ if (stage)
266
+ attributes[semconv_1.ATTR.STAGE] = stage;
267
+ let failed = false;
268
+ try {
269
+ return await this.span('lambdaorm.transaction', api_1.SpanKind.INTERNAL, attributes, async () => run());
270
+ }
271
+ catch (error) {
272
+ failed = true;
273
+ throw error;
274
+ }
275
+ finally {
276
+ this.instruments?.transactionDuration.record((performance.now() - start) / 1000, { ...attributes, [semconv_1.ATTR.TRANSACTION_RESULT]: failed ? 'rollback' : 'commit' });
277
+ }
278
+ }
279
+ /** a command of a stage (lambdaorm.stage.<action>) and lambdaorm.stage.operation.duration */
280
+ async stage(action, stage, run) {
281
+ if (!this.active) {
282
+ return run();
283
+ }
284
+ const start = performance.now();
285
+ const attributes = { [semconv_1.ATTR.SCHEMA]: this.schema, [semconv_1.ATTR.STAGE_ACTION]: action };
286
+ if (stage)
287
+ attributes[semconv_1.ATTR.STAGE] = stage;
288
+ let error;
289
+ try {
290
+ return await this.span(`lambdaorm.stage.${action}`, api_1.SpanKind.INTERNAL, attributes, async () => run());
291
+ }
292
+ catch (e) {
293
+ error = e;
294
+ throw e;
295
+ }
296
+ finally {
297
+ const metric = { ...attributes };
298
+ if (error)
299
+ metric[semconv_1.ATTR.ERROR_TYPE] = (0, exports.errorType)(error);
300
+ this.instruments?.stageDuration.record((performance.now() - start) / 1000, metric);
301
+ }
302
+ }
303
+ /** a constraint of the model that rejected a value (lambdaorm.constraint.violations) */
304
+ constraintViolation(entity, constraint) {
305
+ this.instruments?.constraintViolations.add(1, this.entityFiltered({ [semconv_1.ATTR.ENTITY]: entity, [semconv_1.ATTR.CONSTRAINT]: constraint }));
306
+ }
307
+ /** a schema.change (lambdaorm.schema.changes) */
308
+ schemaChanged(kind) {
309
+ this.instruments?.schemaChanges.add(1, { [semconv_1.ATTR.SCHEMA]: this.schema, [semconv_1.ATTR.CHANGE_KIND]: kind });
310
+ }
311
+ /** loading and extending the schema (lambdaorm.schema.load.duration) */
312
+ schemaLoaded(seconds) {
313
+ this.instruments?.schemaLoadDuration.record(seconds, { [semconv_1.ATTR.SCHEMA]: this.schema });
314
+ }
315
+ /** the time to get a connection of a pool (db.client.connection.wait_time) */
316
+ connectionAcquired(pool, seconds) {
317
+ this.instruments?.connectionWait.record(seconds, { [semconv_1.ATTR.POOL_NAME]: pool });
318
+ }
319
+ /** the pool is counted by db.client.connection.count while it is tracked */
320
+ trackPool(pool) {
321
+ this.pools.add(pool);
322
+ }
323
+ untrackPool(pool) {
324
+ this.pools.delete(pool);
325
+ }
326
+ createInstruments() {
327
+ const buckets = this.config?.metrics.histogramBuckets;
328
+ const histogram = (name, description, unit = 's', advice = true) => this.meter.createHistogram(name, { description, unit, advice: advice && buckets ? { explicitBucketBoundaries: buckets } : undefined });
329
+ this.instruments = {
330
+ operationDuration: histogram(semconv_1.METRIC.OPERATION_DURATION, 'Duration of database client operations'),
331
+ returnedRows: histogram(semconv_1.METRIC.RETURNED_ROWS, 'The actual number of records returned by the database operation', '{row}', false),
332
+ connectionWait: histogram(semconv_1.METRIC.CONNECTION_WAIT_TIME, 'The time it took to obtain an open connection from the pool'),
333
+ queryDuration: histogram(semconv_1.METRIC.QUERY_DURATION, 'The whole expression: compile, plan and run on all its sources'),
334
+ compileDuration: histogram(semconv_1.METRIC.COMPILE_DURATION, 'Compiling an expression to sentences'),
335
+ constraintViolations: this.meter.createCounter(semconv_1.METRIC.CONSTRAINT_VIOLATIONS, { description: 'Constraints of the model that rejected a value', unit: '{violation}' }),
336
+ transactionDuration: histogram(semconv_1.METRIC.TRANSACTION_DURATION, 'Transactions'),
337
+ stageDuration: histogram(semconv_1.METRIC.STAGE_DURATION, 'Commands of a stage'),
338
+ schemaLoadDuration: histogram(semconv_1.METRIC.SCHEMA_LOAD_DURATION, 'Loading and extending the schema'),
339
+ schemaChanges: this.meter.createCounter(semconv_1.METRIC.SCHEMA_CHANGES, { description: 'Changes of the schema (the events schema.change)', unit: '{change}' })
340
+ };
341
+ const count = this.meter.createObservableUpDownCounter(semconv_1.METRIC.CONNECTION_COUNT, { description: 'The number of connections that are currently in state described by the state attribute', unit: '{connection}' });
342
+ count.addCallback((result) => {
343
+ for (const pool of this.pools) {
344
+ result.observe(pool.used, { [semconv_1.ATTR.POOL_NAME]: pool.name, [semconv_1.ATTR.CONNECTION_STATE]: 'used' });
345
+ }
346
+ });
347
+ }
348
+ queryAttributes(query) {
349
+ return { [semconv_1.ATTR.ENTITY]: query.entity, [semconv_1.ATTR.ACTION]: query.action, [semconv_1.ATTR.CATEGORY]: query.category };
350
+ }
351
+ entityFiltered(attributes) {
352
+ if (this.config?.metrics.entityAttribute === false) {
353
+ delete attributes[semconv_1.ATTR.ENTITY];
354
+ }
355
+ return attributes;
356
+ }
357
+ expressionText(expression) {
358
+ switch (this.queryText) {
359
+ case 'full': return expression;
360
+ case 'sanitized': return (0, sanitizer_1.sanitizeExpression)(expression);
361
+ default: return undefined;
362
+ }
363
+ }
364
+ sentenceText(query) {
365
+ switch (this.queryText) {
366
+ case 'full': return query.sentence;
367
+ // without the sanitized text (compiled before tracing was on) nothing goes: never the sentence with its values
368
+ case 'sanitized': return query.sanitized;
369
+ default: return undefined;
370
+ }
371
+ }
372
+ /** the variables of the rules that the sentence gives (the ones of the condition of a source of a stage) */
373
+ sentenceVariables(query, stage) {
374
+ const read = query.category === 'select';
375
+ return {
376
+ entity: query.entity,
377
+ action: query.action,
378
+ category: query.category,
379
+ type: query.type ?? '',
380
+ read,
381
+ write: !read,
382
+ ddl: query.type === 'ddl',
383
+ dml: query.type === 'dml' || query.type === 'dql',
384
+ schema: this.schema,
385
+ stage: stage ?? ''
386
+ };
387
+ }
388
+ /** the sources the expression touches: the one of its sentence and the ones of its includes */
389
+ sources(query, found = new Set()) {
390
+ if (query.source)
391
+ found.add(query.source);
392
+ for (const include of query.includes ?? []) {
393
+ this.sources(include.query, found);
394
+ }
395
+ return [...found];
396
+ }
397
+ rows(result) {
398
+ if (Array.isArray(result))
399
+ return result.length;
400
+ if (typeof result === 'number')
401
+ return result;
402
+ return undefined;
403
+ }
404
+ }
405
+ exports.Telemetry = Telemetry;
406
+ /** a telemetry that does nothing, for the helpers built without one (tests) */
407
+ exports.DISABLED_TELEMETRY = new Telemetry();
408
+ //# sourceMappingURL=telemetry.js.map