speedkey 0.1.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.
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Copyright Valkey GLIDE Project Contributors - SPDX Identifier: Apache-2.0
3
+ */
4
+ export type LevelOptions = "error" | "warn" | "info" | "debug" | "trace" | "off";
5
+ /**
6
+ * A singleton class that allows logging which is consistent with logs from the internal GLIDE core.
7
+ * The logger can be set up in 2 ways -
8
+ * 1. By calling {@link init}, which configures the logger only if it wasn't previously configured.
9
+ * 2. By calling {@link setLoggerConfig}, which replaces the existing configuration, and means that new logs
10
+ * will not be saved with the logs that were sent before the call. The previous logs will remain unchanged.
11
+ * If none of these functions are called, the first log attempt will initialize a new logger with default configuration.
12
+ */
13
+ export declare class Logger {
14
+ private static _instance;
15
+ private static logger_level;
16
+ private constructor();
17
+ /**
18
+ * Logs the provided message if the provided log level is lower then the logger level.
19
+ *
20
+ * @param logLevel - The log level of the provided message.
21
+ * @param logIdentifier - The log identifier should give the log a context.
22
+ * @param message - The message to log.
23
+ * @param err - The exception or error to log.
24
+ */
25
+ static log(logLevel: LevelOptions, logIdentifier: string, message: string, err?: Error): void;
26
+ /**
27
+ * Initialize a logger if it wasn't initialized before - this method is meant to be used when there is no intention to
28
+ * replace an existing logger.
29
+ * The logger will filter all logs with a level lower than the given level.
30
+ * If given a fileName argument, will write the logs to files postfixed with fileName. If fileName isn't provided,
31
+ * the logs will be written to the console.
32
+ *
33
+ * @param level - Set the logger level to one of [ERROR, WARN, INFO, DEBUG, TRACE, OFF].
34
+ * If log level isn't provided, the logger will be configured with default configuration.
35
+ * To turn off logging completely, set the level to level "off".
36
+ * @param fileName - If provided the target of the logs will be the file mentioned.
37
+ * Otherwise, logs will be printed to the console.
38
+ */
39
+ static init(level?: LevelOptions, fileName?: string): void;
40
+ /**
41
+ * Creates a new logger instance and configure it with the provided log level and file name.
42
+ *
43
+ * @param level - Set the logger level to one of [ERROR, WARN, INFO, DEBUG, TRACE, OFF].
44
+ * @param fileName - The target of the logs will be the file mentioned.
45
+ */
46
+ static setLoggerConfig(level: LevelOptions, fileName?: string): void;
47
+ }
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright Valkey GLIDE Project Contributors - SPDX Identifier: Apache-2.0
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Logger = void 0;
7
+ const _1 = require(".");
8
+ const LEVEL = new Map([
9
+ ["error", 0 /* Level.Error */],
10
+ ["warn", 1 /* Level.Warn */],
11
+ ["info", 2 /* Level.Info */],
12
+ ["debug", 3 /* Level.Debug */],
13
+ ["trace", 4 /* Level.Trace */],
14
+ ["off", 5 /* Level.Off */],
15
+ [undefined, undefined],
16
+ ]);
17
+ /**
18
+ * A singleton class that allows logging which is consistent with logs from the internal GLIDE core.
19
+ * The logger can be set up in 2 ways -
20
+ * 1. By calling {@link init}, which configures the logger only if it wasn't previously configured.
21
+ * 2. By calling {@link setLoggerConfig}, which replaces the existing configuration, and means that new logs
22
+ * will not be saved with the logs that were sent before the call. The previous logs will remain unchanged.
23
+ * If none of these functions are called, the first log attempt will initialize a new logger with default configuration.
24
+ */
25
+ class Logger {
26
+ static _instance;
27
+ static logger_level = 0;
28
+ constructor(level, fileName) {
29
+ Logger.logger_level = (0, _1.InitInternalLogger)(LEVEL.get(level), fileName);
30
+ }
31
+ /**
32
+ * Logs the provided message if the provided log level is lower then the logger level.
33
+ *
34
+ * @param logLevel - The log level of the provided message.
35
+ * @param logIdentifier - The log identifier should give the log a context.
36
+ * @param message - The message to log.
37
+ * @param err - The exception or error to log.
38
+ */
39
+ static log(logLevel, logIdentifier, message, err) {
40
+ if (!Logger._instance) {
41
+ new Logger();
42
+ }
43
+ if (err) {
44
+ message += `: ${err.stack}`;
45
+ }
46
+ const level = LEVEL.get(logLevel) || 0;
47
+ if (!(level <= Logger.logger_level))
48
+ return;
49
+ (0, _1.log)(level, logIdentifier, message);
50
+ }
51
+ /**
52
+ * Initialize a logger if it wasn't initialized before - this method is meant to be used when there is no intention to
53
+ * replace an existing logger.
54
+ * The logger will filter all logs with a level lower than the given level.
55
+ * If given a fileName argument, will write the logs to files postfixed with fileName. If fileName isn't provided,
56
+ * the logs will be written to the console.
57
+ *
58
+ * @param level - Set the logger level to one of [ERROR, WARN, INFO, DEBUG, TRACE, OFF].
59
+ * If log level isn't provided, the logger will be configured with default configuration.
60
+ * To turn off logging completely, set the level to level "off".
61
+ * @param fileName - If provided the target of the logs will be the file mentioned.
62
+ * Otherwise, logs will be printed to the console.
63
+ */
64
+ static init(level, fileName) {
65
+ if (!this._instance) {
66
+ this._instance = new this(level, fileName);
67
+ }
68
+ }
69
+ /**
70
+ * Creates a new logger instance and configure it with the provided log level and file name.
71
+ *
72
+ * @param level - Set the logger level to one of [ERROR, WARN, INFO, DEBUG, TRACE, OFF].
73
+ * @param fileName - The target of the logs will be the file mentioned.
74
+ */
75
+ static setLoggerConfig(level, fileName) {
76
+ this._instance = new this(level, fileName);
77
+ }
78
+ }
79
+ exports.Logger = Logger;
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Copyright Valkey GLIDE Project Contributors - SPDX Identifier: Apache-2.0
3
+ */
4
+ import { OpenTelemetryConfig } from ".";
5
+ /**
6
+ * ⚠️ OpenTelemetry can only be initialized once per process. Calling `OpenTelemetry.init()` more than once will be ignored.
7
+ * If you need to change configuration, restart the process with new settings.
8
+ * ### OpenTelemetry
9
+ *
10
+ * - **openTelemetryConfig**: Use this object to configure OpenTelemetry exporters and options.
11
+ * - **traces**: (optional) Configure trace exporting.
12
+ * - **endpoint**: The collector endpoint for traces. Supported protocols:
13
+ * - `http://` or `https://` for HTTP/HTTPS
14
+ * - `grpc://` for gRPC
15
+ * - `file://` for local file export (see below)
16
+ * - **samplePercentage**: (optional) The percentage of requests to sample and create a span for, used to measure command duration. Must be between 0 and 100. Defaults to 1 if not specified.
17
+ * Note: There is a tradeoff between sampling percentage and performance. Higher sampling percentages will provide more detailed telemetry data but will impact performance.
18
+ * It is recommended to keep this number low (1-5%) in production environments unless you have specific needs for higher sampling rates.
19
+ * - **metrics**: (optional) Configure metrics exporting.
20
+ * - **endpoint**: The collector endpoint for metrics. Same protocol rules as above.
21
+ * - **flushIntervalMs**: (optional) Interval in milliseconds for flushing data to the collector. Must be a positive integer. Defaults to 5000ms if not specified.
22
+ *
23
+ * #### File Exporter Details
24
+ * - For `file://` endpoints:
25
+ * - The path must start with `file://` (e.g., `file:///tmp/otel` or `file:///tmp/otel/traces.json`).
26
+ * - If the path is a directory or lacks a file extension, data is written to `signals.json` in that directory.
27
+ * - If the path includes a filename with an extension, that file is used as-is.
28
+ * - The parent directory must already exist; otherwise, initialization will fail with an InvalidInput error.
29
+ * - If the target file exists, new data is appended (not overwritten).
30
+ *
31
+ * #### Validation Rules
32
+ * - `flushIntervalMs` must be a positive integer.
33
+ * - `samplePercentage` must be between 0 and 100.
34
+ * - File exporter paths must start with `file://` and have an existing parent directory.
35
+ * - Invalid configuration will throw an error synchronously when calling `OpenTelemetry.init()`.
36
+ */
37
+ export declare class OpenTelemetry {
38
+ private static _instance;
39
+ private static openTelemetryConfig;
40
+ /**
41
+ * Singleton class for managing OpenTelemetry configuration and operations.
42
+ * This class provides a centralized way to initialize OpenTelemetry and control
43
+ * sampling behavior at runtime.
44
+ *
45
+ * Example usage:
46
+ * ```typescript
47
+ * import { OpenTelemetry, OpenTelemetryConfig, OpenTelemetryTracesConfig, OpenTelemetryMetricsConfig } from "@valkey/valkey-glide";
48
+ *
49
+ * let tracesConfig: OpenTelemetryTracesConfig = {
50
+ * endpoint: "http://localhost:4318/v1/traces",
51
+ * samplePercentage: 10, // Optional, defaults to 1. Can also be changed at runtime via setSamplePercentage().
52
+ * };
53
+ * let metricsConfig: OpenTelemetryMetricsConfig = {
54
+ * endpoint: "http://localhost:4318/v1/metrics",
55
+ * };
56
+
57
+ * let config : OpenTelemetryConfig = {
58
+ * traces: tracesConfig,
59
+ * metrics: metricsConfig,
60
+ * flushIntervalMs: 1000, // Optional, defaults to 5000
61
+ * };
62
+ * OpenTelemetry.init(config);
63
+ *
64
+ * ```
65
+ *
66
+ * @remarks
67
+ * OpenTelemetry can only be initialized once per process. Subsequent calls to
68
+ * init() will be ignored. This is by design, as OpenTelemetry is a global
69
+ * resource that should be configured once at application startup.
70
+ *
71
+ * Initialize the OpenTelemetry instance
72
+ * @param openTelemetryConfig - The OpenTelemetry configuration
73
+ */
74
+ static init(openTelemetryConfig: OpenTelemetryConfig): void;
75
+ private static internalInit;
76
+ /**
77
+ * Check if the OpenTelemetry instance is initialized
78
+ * @returns True if the OpenTelemetry instance is initialized, false otherwise
79
+ */
80
+ static isInitialized(): boolean;
81
+ /**
82
+ * Get the sample percentage for traces
83
+ * @returns The sample percentage for traces only if OpenTelemetry is initialized and the traces config is set, otherwise undefined.
84
+ */
85
+ static getSamplePercentage(): number | undefined;
86
+ /**
87
+ * Determines if the current request should be sampled for OpenTelemetry tracing.
88
+ * Uses the configured sample percentage to randomly decide whether to create a span for this request.
89
+ * @returns true if the request should be sampled, false otherwise
90
+ */
91
+ static shouldSample(): boolean;
92
+ /**
93
+ * Set the percentage of requests to be sampled and traced. Must be a value between 0 and 100.
94
+ * This setting only affects traces, not metrics.
95
+ * @param percentage - The sample percentage 0-100
96
+ * @throws Error if OpenTelemetry is not initialized or traces config is not set
97
+ * @remarks
98
+ * This method can be called at runtime to change the sampling percentage without reinitializing OpenTelemetry.
99
+ */
100
+ static setSamplePercentage(percentage: number): void;
101
+ }
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright Valkey GLIDE Project Contributors - SPDX Identifier: Apache-2.0
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.OpenTelemetry = void 0;
7
+ const _1 = require(".");
8
+ /**
9
+ * ⚠️ OpenTelemetry can only be initialized once per process. Calling `OpenTelemetry.init()` more than once will be ignored.
10
+ * If you need to change configuration, restart the process with new settings.
11
+ * ### OpenTelemetry
12
+ *
13
+ * - **openTelemetryConfig**: Use this object to configure OpenTelemetry exporters and options.
14
+ * - **traces**: (optional) Configure trace exporting.
15
+ * - **endpoint**: The collector endpoint for traces. Supported protocols:
16
+ * - `http://` or `https://` for HTTP/HTTPS
17
+ * - `grpc://` for gRPC
18
+ * - `file://` for local file export (see below)
19
+ * - **samplePercentage**: (optional) The percentage of requests to sample and create a span for, used to measure command duration. Must be between 0 and 100. Defaults to 1 if not specified.
20
+ * Note: There is a tradeoff between sampling percentage and performance. Higher sampling percentages will provide more detailed telemetry data but will impact performance.
21
+ * It is recommended to keep this number low (1-5%) in production environments unless you have specific needs for higher sampling rates.
22
+ * - **metrics**: (optional) Configure metrics exporting.
23
+ * - **endpoint**: The collector endpoint for metrics. Same protocol rules as above.
24
+ * - **flushIntervalMs**: (optional) Interval in milliseconds for flushing data to the collector. Must be a positive integer. Defaults to 5000ms if not specified.
25
+ *
26
+ * #### File Exporter Details
27
+ * - For `file://` endpoints:
28
+ * - The path must start with `file://` (e.g., `file:///tmp/otel` or `file:///tmp/otel/traces.json`).
29
+ * - If the path is a directory or lacks a file extension, data is written to `signals.json` in that directory.
30
+ * - If the path includes a filename with an extension, that file is used as-is.
31
+ * - The parent directory must already exist; otherwise, initialization will fail with an InvalidInput error.
32
+ * - If the target file exists, new data is appended (not overwritten).
33
+ *
34
+ * #### Validation Rules
35
+ * - `flushIntervalMs` must be a positive integer.
36
+ * - `samplePercentage` must be between 0 and 100.
37
+ * - File exporter paths must start with `file://` and have an existing parent directory.
38
+ * - Invalid configuration will throw an error synchronously when calling `OpenTelemetry.init()`.
39
+ */
40
+ class OpenTelemetry {
41
+ static _instance = null;
42
+ static openTelemetryConfig = null;
43
+ /**
44
+ * Singleton class for managing OpenTelemetry configuration and operations.
45
+ * This class provides a centralized way to initialize OpenTelemetry and control
46
+ * sampling behavior at runtime.
47
+ *
48
+ * Example usage:
49
+ * ```typescript
50
+ * import { OpenTelemetry, OpenTelemetryConfig, OpenTelemetryTracesConfig, OpenTelemetryMetricsConfig } from "@valkey/valkey-glide";
51
+ *
52
+ * let tracesConfig: OpenTelemetryTracesConfig = {
53
+ * endpoint: "http://localhost:4318/v1/traces",
54
+ * samplePercentage: 10, // Optional, defaults to 1. Can also be changed at runtime via setSamplePercentage().
55
+ * };
56
+ * let metricsConfig: OpenTelemetryMetricsConfig = {
57
+ * endpoint: "http://localhost:4318/v1/metrics",
58
+ * };
59
+
60
+ * let config : OpenTelemetryConfig = {
61
+ * traces: tracesConfig,
62
+ * metrics: metricsConfig,
63
+ * flushIntervalMs: 1000, // Optional, defaults to 5000
64
+ * };
65
+ * OpenTelemetry.init(config);
66
+ *
67
+ * ```
68
+ *
69
+ * @remarks
70
+ * OpenTelemetry can only be initialized once per process. Subsequent calls to
71
+ * init() will be ignored. This is by design, as OpenTelemetry is a global
72
+ * resource that should be configured once at application startup.
73
+ *
74
+ * Initialize the OpenTelemetry instance
75
+ * @param openTelemetryConfig - The OpenTelemetry configuration
76
+ */
77
+ static init(openTelemetryConfig) {
78
+ if (!this._instance) {
79
+ this.internalInit(openTelemetryConfig);
80
+ _1.Logger.log("info", "GlideOpenTelemetry", "OpenTelemetry initialized with config: " +
81
+ JSON.stringify(openTelemetryConfig));
82
+ return;
83
+ }
84
+ _1.Logger.log("warn", "GlideOpenTelemetry", "OpenTelemetry already initialized - ignoring new configuration");
85
+ }
86
+ static internalInit(openTelemetryConfig) {
87
+ this.openTelemetryConfig = openTelemetryConfig;
88
+ (0, _1.InitOpenTelemetry)(openTelemetryConfig);
89
+ this._instance = new OpenTelemetry();
90
+ }
91
+ /**
92
+ * Check if the OpenTelemetry instance is initialized
93
+ * @returns True if the OpenTelemetry instance is initialized, false otherwise
94
+ */
95
+ static isInitialized() {
96
+ return this._instance != null;
97
+ }
98
+ /**
99
+ * Get the sample percentage for traces
100
+ * @returns The sample percentage for traces only if OpenTelemetry is initialized and the traces config is set, otherwise undefined.
101
+ */
102
+ static getSamplePercentage() {
103
+ return this.openTelemetryConfig?.traces?.samplePercentage;
104
+ }
105
+ /**
106
+ * Determines if the current request should be sampled for OpenTelemetry tracing.
107
+ * Uses the configured sample percentage to randomly decide whether to create a span for this request.
108
+ * @returns true if the request should be sampled, false otherwise
109
+ */
110
+ static shouldSample() {
111
+ const percentage = this.getSamplePercentage();
112
+ return (this.isInitialized() &&
113
+ percentage !== undefined &&
114
+ Math.random() * 100 < percentage);
115
+ }
116
+ /**
117
+ * Set the percentage of requests to be sampled and traced. Must be a value between 0 and 100.
118
+ * This setting only affects traces, not metrics.
119
+ * @param percentage - The sample percentage 0-100
120
+ * @throws Error if OpenTelemetry is not initialized or traces config is not set
121
+ * @remarks
122
+ * This method can be called at runtime to change the sampling percentage without reinitializing OpenTelemetry.
123
+ */
124
+ static setSamplePercentage(percentage) {
125
+ if (!this.openTelemetryConfig || !this.openTelemetryConfig.traces) {
126
+ throw new _1.ConfigurationError("OpenTelemetry config traces not initialized");
127
+ }
128
+ if (percentage < 0 || percentage > 100) {
129
+ throw new _1.ConfigurationError("Sample percentage must be between 0 and 100");
130
+ }
131
+ this.openTelemetryConfig.traces.samplePercentage = percentage;
132
+ }
133
+ }
134
+ exports.OpenTelemetry = OpenTelemetry;