@encore.dev/sdk 0.0.0 → 2.0.0-beta.4

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 (250) hide show
  1. package/LICENSE +362 -0
  2. package/README.md +122 -2
  3. package/app_meta.test.ts +134 -0
  4. package/app_meta.ts +186 -0
  5. package/config/config.test.ts +381 -0
  6. package/config/config.ts +178 -0
  7. package/config/mod.ts +14 -0
  8. package/config/secrets.ts +147 -0
  9. package/config/value.ts +243 -0
  10. package/cron/mod.ts +23 -0
  11. package/dist/app_meta.d.ts +93 -0
  12. package/dist/app_meta.js +65 -0
  13. package/dist/app_meta.js.map +1 -0
  14. package/dist/config/config.d.ts +105 -0
  15. package/dist/config/config.js +87 -0
  16. package/dist/config/config.js.map +1 -0
  17. package/dist/config/mod.d.ts +4 -0
  18. package/dist/config/mod.js +3 -0
  19. package/dist/config/mod.js.map +1 -0
  20. package/dist/config/secrets.d.ts +92 -0
  21. package/dist/config/secrets.js +80 -0
  22. package/dist/config/secrets.js.map +1 -0
  23. package/dist/config/value.d.ts +51 -0
  24. package/dist/config/value.js +178 -0
  25. package/dist/config/value.js.map +1 -0
  26. package/dist/cron/mod.d.ts +22 -0
  27. package/dist/cron/mod.js +9 -0
  28. package/dist/cron/mod.js.map +1 -0
  29. package/dist/internal/otel/backend.d.ts +50 -0
  30. package/dist/internal/otel/backend.js +2 -0
  31. package/dist/internal/otel/backend.js.map +1 -0
  32. package/dist/internal/otel/context.d.ts +10 -0
  33. package/dist/internal/otel/context.js +34 -0
  34. package/dist/internal/otel/context.js.map +1 -0
  35. package/dist/internal/otel/context_manager.d.ts +22 -0
  36. package/dist/internal/otel/context_manager.js +120 -0
  37. package/dist/internal/otel/context_manager.js.map +1 -0
  38. package/dist/internal/otel/encode.d.ts +112 -0
  39. package/dist/internal/otel/encode.js +290 -0
  40. package/dist/internal/otel/encode.js.map +1 -0
  41. package/dist/internal/otel/index.d.ts +9 -0
  42. package/dist/internal/otel/index.js +9 -0
  43. package/dist/internal/otel/index.js.map +1 -0
  44. package/dist/internal/otel/meter.d.ts +73 -0
  45. package/dist/internal/otel/meter.js +265 -0
  46. package/dist/internal/otel/meter.js.map +1 -0
  47. package/dist/internal/otel/propagator.d.ts +14 -0
  48. package/dist/internal/otel/propagator.js +61 -0
  49. package/dist/internal/otel/propagator.js.map +1 -0
  50. package/dist/internal/otel/provider.d.ts +9 -0
  51. package/dist/internal/otel/provider.js +19 -0
  52. package/dist/internal/otel/provider.js.map +1 -0
  53. package/dist/internal/otel/request_context.d.ts +11 -0
  54. package/dist/internal/otel/request_context.js +20 -0
  55. package/dist/internal/otel/request_context.js.map +1 -0
  56. package/dist/internal/otel/span.d.ts +61 -0
  57. package/dist/internal/otel/span.js +206 -0
  58. package/dist/internal/otel/span.js.map +1 -0
  59. package/dist/internal/otel/tracer.d.ts +15 -0
  60. package/dist/internal/otel/tracer.js +65 -0
  61. package/dist/internal/otel/tracer.js.map +1 -0
  62. package/dist/internal/reqtrack/mod.d.ts +6 -0
  63. package/dist/internal/reqtrack/mod.js +28 -0
  64. package/dist/internal/reqtrack/mod.js.map +1 -0
  65. package/dist/internal/runtime/meter.d.ts +11 -0
  66. package/dist/internal/runtime/meter.js +22 -0
  67. package/dist/internal/runtime/meter.js.map +1 -0
  68. package/dist/internal/runtime/mod.d.ts +12 -0
  69. package/dist/internal/runtime/mod.js +28 -0
  70. package/dist/internal/runtime/mod.js.map +1 -0
  71. package/dist/internal/runtime/napi/napi.cjs +122 -0
  72. package/dist/internal/runtime/napi/napi.d.cts +601 -0
  73. package/dist/internal/runtime/shutdown.d.ts +13 -0
  74. package/dist/internal/runtime/shutdown.js +56 -0
  75. package/dist/internal/runtime/shutdown.js.map +1 -0
  76. package/dist/internal/utils/constraints.d.ts +9 -0
  77. package/dist/internal/utils/constraints.js +2 -0
  78. package/dist/internal/utils/constraints.js.map +1 -0
  79. package/dist/log/index.d.ts +39 -0
  80. package/dist/log/index.js +44 -0
  81. package/dist/log/index.js.map +1 -0
  82. package/dist/log/logger.d.ts +123 -0
  83. package/dist/log/logger.js +203 -0
  84. package/dist/log/logger.js.map +1 -0
  85. package/dist/log/runtime.d.ts +19 -0
  86. package/dist/log/runtime.js +22 -0
  87. package/dist/log/runtime.js.map +1 -0
  88. package/dist/log/stderr.d.ts +9 -0
  89. package/dist/log/stderr.js +25 -0
  90. package/dist/log/stderr.js.map +1 -0
  91. package/dist/metrics/mod.d.ts +315 -0
  92. package/dist/metrics/mod.js +488 -0
  93. package/dist/metrics/mod.js.map +1 -0
  94. package/dist/mod.d.ts +6 -0
  95. package/dist/mod.js +4 -0
  96. package/dist/mod.js.map +1 -0
  97. package/dist/otel.d.ts +9 -0
  98. package/dist/otel.js +13 -0
  99. package/dist/otel.js.map +1 -0
  100. package/dist/pubsub/encoding.d.ts +3 -0
  101. package/dist/pubsub/encoding.js +10 -0
  102. package/dist/pubsub/encoding.js.map +1 -0
  103. package/dist/pubsub/mod.d.ts +6 -0
  104. package/dist/pubsub/mod.js +3 -0
  105. package/dist/pubsub/mod.js.map +1 -0
  106. package/dist/pubsub/refs.d.ts +12 -0
  107. package/dist/pubsub/refs.js +11 -0
  108. package/dist/pubsub/refs.js.map +1 -0
  109. package/dist/pubsub/subscription.d.ts +128 -0
  110. package/dist/pubsub/subscription.js +39 -0
  111. package/dist/pubsub/subscription.js.map +1 -0
  112. package/dist/pubsub/topic.d.ts +148 -0
  113. package/dist/pubsub/topic.js +164 -0
  114. package/dist/pubsub/topic.js.map +1 -0
  115. package/dist/req_meta.d.ts +47 -0
  116. package/dist/req_meta.js +26 -0
  117. package/dist/req_meta.js.map +1 -0
  118. package/dist/services/index.d.ts +7 -0
  119. package/dist/services/index.js +17 -0
  120. package/dist/services/index.js.map +1 -0
  121. package/dist/shutdown/mod.d.ts +23 -0
  122. package/dist/shutdown/mod.js +24 -0
  123. package/dist/shutdown/mod.js.map +1 -0
  124. package/dist/storage/objects/bucket.d.ts +216 -0
  125. package/dist/storage/objects/bucket.js +123 -0
  126. package/dist/storage/objects/bucket.js.map +1 -0
  127. package/dist/storage/objects/error.d.ts +14 -0
  128. package/dist/storage/objects/error.js +81 -0
  129. package/dist/storage/objects/error.js.map +1 -0
  130. package/dist/storage/objects/mod.d.ts +4 -0
  131. package/dist/storage/objects/mod.js +3 -0
  132. package/dist/storage/objects/mod.js.map +1 -0
  133. package/dist/storage/objects/refs.d.ts +31 -0
  134. package/dist/storage/objects/refs.js +20 -0
  135. package/dist/storage/objects/refs.js.map +1 -0
  136. package/dist/storage/postgres/database.d.ts +295 -0
  137. package/dist/storage/postgres/database.js +378 -0
  138. package/dist/storage/postgres/database.js.map +1 -0
  139. package/dist/storage/postgres/mod.d.ts +2 -0
  140. package/dist/storage/postgres/mod.js +2 -0
  141. package/dist/storage/postgres/mod.js.map +1 -0
  142. package/dist/storage/redis/commands.d.ts +573 -0
  143. package/dist/storage/redis/commands.js +637 -0
  144. package/dist/storage/redis/commands.js.map +1 -0
  145. package/dist/storage/redis/database.d.ts +302 -0
  146. package/dist/storage/redis/database.js +336 -0
  147. package/dist/storage/redis/database.js.map +1 -0
  148. package/dist/storage/redis/mod.d.ts +88 -0
  149. package/dist/storage/redis/mod.js +84 -0
  150. package/dist/storage/redis/mod.js.map +1 -0
  151. package/dist/storage/redis/native.d.ts +8 -0
  152. package/dist/storage/redis/native.js +11 -0
  153. package/dist/storage/redis/native.js.map +1 -0
  154. package/dist/storage/redis/options.d.ts +89 -0
  155. package/dist/storage/redis/options.js +53 -0
  156. package/dist/storage/redis/options.js.map +1 -0
  157. package/dist/storage/redis/pubsub.d.ts +53 -0
  158. package/dist/storage/redis/pubsub.js +88 -0
  159. package/dist/storage/redis/pubsub.js.map +1 -0
  160. package/dist/storage/redis/reply.d.ts +256 -0
  161. package/dist/storage/redis/reply.js +572 -0
  162. package/dist/storage/redis/reply.js.map +1 -0
  163. package/dist/storage/redis/scan.d.ts +11 -0
  164. package/dist/storage/redis/scan.js +76 -0
  165. package/dist/storage/redis/scan.js.map +1 -0
  166. package/dist/storage/redis/script.d.ts +91 -0
  167. package/dist/storage/redis/script.js +143 -0
  168. package/dist/storage/redis/script.js.map +1 -0
  169. package/dist/storage/redis/target.d.ts +47 -0
  170. package/dist/storage/redis/target.js +82 -0
  171. package/dist/storage/redis/target.js.map +1 -0
  172. package/dist/storage/redis/wire.d.ts +105 -0
  173. package/dist/storage/redis/wire.js +333 -0
  174. package/dist/storage/redis/wire.js.map +1 -0
  175. package/dist/tsconfig.build.tsbuildinfo +1 -0
  176. package/dist/types/mod.d.ts +42 -0
  177. package/dist/types/mod.js +65 -0
  178. package/dist/types/mod.js.map +1 -0
  179. package/internal/otel/backend.ts +60 -0
  180. package/internal/otel/context.test.ts +70 -0
  181. package/internal/otel/context.ts +48 -0
  182. package/internal/otel/context_manager.test.ts +154 -0
  183. package/internal/otel/context_manager.ts +141 -0
  184. package/internal/otel/encode.test.ts +266 -0
  185. package/internal/otel/encode.ts +408 -0
  186. package/internal/otel/index.ts +20 -0
  187. package/internal/otel/meter.test.ts +231 -0
  188. package/internal/otel/meter.ts +332 -0
  189. package/internal/otel/propagator.test.ts +105 -0
  190. package/internal/otel/propagator.ts +68 -0
  191. package/internal/otel/provider.ts +23 -0
  192. package/internal/otel/request_context.ts +32 -0
  193. package/internal/otel/span.ts +252 -0
  194. package/internal/otel/tracer.test.ts +352 -0
  195. package/internal/otel/tracer.ts +104 -0
  196. package/internal/reqtrack/mod.ts +39 -0
  197. package/internal/runtime/meter.ts +26 -0
  198. package/internal/runtime/mod.ts +41 -0
  199. package/internal/runtime/napi/napi.cjs +122 -0
  200. package/internal/runtime/napi/napi.d.cts +601 -0
  201. package/internal/runtime/shutdown.test.ts +248 -0
  202. package/internal/runtime/shutdown.ts +64 -0
  203. package/internal/utils/constraints.ts +12 -0
  204. package/log/index.ts +107 -0
  205. package/log/logger.test.ts +194 -0
  206. package/log/logger.ts +308 -0
  207. package/log/runtime.test.ts +65 -0
  208. package/log/runtime.ts +40 -0
  209. package/log/stderr.test.ts +23 -0
  210. package/log/stderr.ts +24 -0
  211. package/metrics/export.test.ts +337 -0
  212. package/metrics/mod.test.ts +180 -0
  213. package/metrics/mod.ts +619 -0
  214. package/mod.ts +22 -0
  215. package/otel.test.ts +84 -0
  216. package/otel.ts +17 -0
  217. package/package.json +121 -5
  218. package/pubsub/encoding.ts +8 -0
  219. package/pubsub/mod.ts +14 -0
  220. package/pubsub/pubsub.test.ts +186 -0
  221. package/pubsub/refs.ts +22 -0
  222. package/pubsub/subscription.ts +180 -0
  223. package/pubsub/topic.test.ts +121 -0
  224. package/pubsub/topic.ts +212 -0
  225. package/req_meta.ts +75 -0
  226. package/services/index.test.ts +30 -0
  227. package/services/index.ts +16 -0
  228. package/shutdown/mod.ts +24 -0
  229. package/storage/objects/bucket.ts +338 -0
  230. package/storage/objects/error.ts +94 -0
  231. package/storage/objects/mod.ts +35 -0
  232. package/storage/objects/refs.ts +69 -0
  233. package/storage/postgres/database.integration.test.ts +175 -0
  234. package/storage/postgres/database.test.ts +241 -0
  235. package/storage/postgres/database.ts +497 -0
  236. package/storage/postgres/mod.ts +15 -0
  237. package/storage/redis/commands.ts +1221 -0
  238. package/storage/redis/database.ts +466 -0
  239. package/storage/redis/mod.ts +135 -0
  240. package/storage/redis/native.ts +11 -0
  241. package/storage/redis/options.ts +119 -0
  242. package/storage/redis/pubsub.ts +92 -0
  243. package/storage/redis/redis.test.ts +706 -0
  244. package/storage/redis/reply.ts +705 -0
  245. package/storage/redis/runtime.test.ts +233 -0
  246. package/storage/redis/scan.ts +125 -0
  247. package/storage/redis/script.ts +162 -0
  248. package/storage/redis/target.ts +131 -0
  249. package/storage/redis/wire.ts +369 -0
  250. package/types/mod.ts +92 -0
@@ -0,0 +1,408 @@
1
+ // The packed span buffers. The layout is documented by its decoder,
2
+ // `crates/encore_telemetry/src/packed.rs`.
3
+
4
+ import type {
5
+ Attributes,
6
+ HrTime,
7
+ Link,
8
+ SpanContext,
9
+ TimeInput,
10
+ } from '@opentelemetry/api';
11
+
12
+ export const VERSION = 1;
13
+ export const HEADER_LEN = 120;
14
+ export const ATTR_LEN = 24;
15
+ export const ITEM_LEN = 8;
16
+ export const EVENT_LEN = 24;
17
+ export const LINK_LEN = 48;
18
+
19
+ /** Length of a span context buffer: trace id, span id, flags. */
20
+ export const CTX_LEN = 25;
21
+
22
+ /** Bounds the buffer; the runtime enforces the real limits. */
23
+ export const MAX_COUNT = 128;
24
+
25
+ export const TYPE_STR = 0;
26
+ export const TYPE_BOOL = 1;
27
+ export const TYPE_I64 = 2;
28
+ export const TYPE_F64 = 3;
29
+ export const TYPE_STR_ARRAY = 4;
30
+ export const TYPE_BOOL_ARRAY = 5;
31
+ export const TYPE_I64_ARRAY = 6;
32
+ export const TYPE_F64_ARRAY = 7;
33
+
34
+ const I64_MAX = (1n << 63n) - 1n;
35
+ const I64_MIN = -(1n << 63n);
36
+
37
+ type Value =
38
+ | {t: typeof TYPE_STR; v: string}
39
+ | {t: typeof TYPE_BOOL; v: boolean}
40
+ | {t: typeof TYPE_I64; v: bigint}
41
+ | {t: typeof TYPE_F64; v: number}
42
+ | {t: typeof TYPE_STR_ARRAY; v: string[]}
43
+ | {t: typeof TYPE_BOOL_ARRAY; v: boolean[]}
44
+ | {t: typeof TYPE_I64_ARRAY; v: bigint[]}
45
+ | {t: typeof TYPE_F64_ARRAY; v: number[]};
46
+
47
+ interface Entry {
48
+ key: string;
49
+ value: Value;
50
+ }
51
+
52
+ function clampI64(v: bigint): bigint {
53
+ return v > I64_MAX ? I64_MAX : v < I64_MIN ? I64_MIN : v;
54
+ }
55
+
56
+ function isInt(v: unknown): boolean {
57
+ return typeof v === 'bigint' || Number.isSafeInteger(v);
58
+ }
59
+
60
+ /** An attribute value as a packed value; `undefined` when unsupported. */
61
+ export function toValue(v: unknown): Value | undefined {
62
+ switch (typeof v) {
63
+ case 'string':
64
+ return {t: TYPE_STR, v};
65
+ case 'boolean':
66
+ return {t: TYPE_BOOL, v};
67
+ case 'number':
68
+ return Number.isSafeInteger(v)
69
+ ? {t: TYPE_I64, v: BigInt(v)}
70
+ : {t: TYPE_F64, v};
71
+ case 'bigint':
72
+ return {t: TYPE_I64, v: clampI64(v)};
73
+ case 'object':
74
+ if (Array.isArray(v)) return arrayValue(v);
75
+ return undefined;
76
+ default:
77
+ return undefined;
78
+ }
79
+ }
80
+
81
+ /** Typed by the first non-null item; items of other types are dropped. */
82
+ function arrayValue(arr: unknown[]): Value | undefined {
83
+ const first = arr.find(x => x != null);
84
+ switch (typeof first) {
85
+ case 'undefined':
86
+ case 'string':
87
+ return {
88
+ t: TYPE_STR_ARRAY,
89
+ v: arr.filter((x): x is string => typeof x === 'string'),
90
+ };
91
+ case 'boolean':
92
+ return {
93
+ t: TYPE_BOOL_ARRAY,
94
+ v: arr.filter((x): x is boolean => typeof x === 'boolean'),
95
+ };
96
+ case 'number':
97
+ case 'bigint': {
98
+ const nums = arr.filter(
99
+ (x): x is number | bigint =>
100
+ typeof x === 'number' || typeof x === 'bigint',
101
+ );
102
+ return nums.every(isInt)
103
+ ? {t: TYPE_I64_ARRAY, v: nums.map(x => clampI64(BigInt(x)))}
104
+ : {t: TYPE_F64_ARRAY, v: nums.map(Number)};
105
+ }
106
+ default:
107
+ return undefined;
108
+ }
109
+ }
110
+
111
+ /** An instrumentation scope. */
112
+ export interface Scope {
113
+ name: string;
114
+ version?: string;
115
+ }
116
+
117
+ /** The span-level fields of a packed buffer. */
118
+ export interface PackedHeader {
119
+ scope: Scope;
120
+ name: string;
121
+ kind: number;
122
+ statusCode: number;
123
+ /** Read for ERROR only. */
124
+ statusMessage?: string;
125
+ tracestate?: string;
126
+ /** 25-byte span context; zeros when absent. */
127
+ ctx?: Buffer;
128
+ /** 8 bytes; zeros when absent. */
129
+ parentSpanId?: Buffer;
130
+ startUnixNanos?: bigint;
131
+ startMonoNanos?: bigint;
132
+ /** Zero or absent: the runtime's clock. */
133
+ endUnixNanos?: bigint;
134
+ }
135
+
136
+ type Ref = (off: number, data: string) => void;
137
+
138
+ interface EventRec {
139
+ name: string;
140
+ timeUnixNanos: bigint;
141
+ first: number;
142
+ count: number;
143
+ }
144
+
145
+ interface LinkRec {
146
+ ctx: Buffer;
147
+ tracestate: string;
148
+ first: number;
149
+ count: number;
150
+ }
151
+
152
+ /** Builds one packed buffer. Span attributes first, then events and links
153
+ * in any order, then `finish`. */
154
+ export class PackedWriter {
155
+ private readonly attrs: Entry[] = [];
156
+ private spanAttrCount = 0;
157
+ private readonly events: EventRec[] = [];
158
+ private readonly links: LinkRec[] = [];
159
+
160
+ spanAttrs(attrs: Attributes | undefined): this {
161
+ if (this.attrs.length > 0 || this.events.length || this.links.length) {
162
+ throw new Error('span attributes must be written first');
163
+ }
164
+ this.pushAttrs(attrs);
165
+ this.spanAttrCount = this.attrs.length;
166
+ return this;
167
+ }
168
+
169
+ event(name: string, timeUnixNanos: bigint, attrs?: Attributes): this {
170
+ if (this.events.length >= MAX_COUNT) return this;
171
+ const [first, count] = this.pushAttrs(attrs);
172
+ this.events.push({name, timeUnixNanos, first, count});
173
+ return this;
174
+ }
175
+
176
+ /** `ctx`: 25 bytes. */
177
+ link(ctx: Buffer, tracestate: string, attrs?: Attributes): this {
178
+ if (this.links.length >= MAX_COUNT) return this;
179
+ const [first, count] = this.pushAttrs(attrs);
180
+ this.links.push({ctx, tracestate, first, count});
181
+ return this;
182
+ }
183
+
184
+ private pushAttrs(attrs: Attributes | undefined): [number, number] {
185
+ const first = this.attrs.length;
186
+ if (attrs) {
187
+ let n = 0;
188
+ for (const key of Object.keys(attrs)) {
189
+ if (n >= MAX_COUNT) break;
190
+ const value = toValue(attrs[key]);
191
+ if (value === undefined) continue;
192
+ this.attrs.push({key, value});
193
+ n++;
194
+ }
195
+ }
196
+ return [first, this.attrs.length - first];
197
+ }
198
+
199
+ finish(h: PackedHeader): Buffer {
200
+ return this.pack(HEADER_LEN, (fixed, ref, itemCount) => {
201
+ fixed[0] = VERSION;
202
+ fixed[1] = h.kind;
203
+ fixed[2] = h.statusCode;
204
+ fixed[3] = h.ctx ? h.ctx[24]! : 0;
205
+ fixed.writeUInt32LE(this.spanAttrCount, 4);
206
+ fixed.writeUInt32LE(this.attrs.length, 8);
207
+ fixed.writeUInt32LE(itemCount, 12);
208
+ fixed.writeUInt32LE(this.events.length, 16);
209
+ fixed.writeUInt32LE(this.links.length, 20);
210
+ ref(24, h.name);
211
+ ref(32, h.statusMessage ?? '');
212
+ ref(40, h.tracestate ?? '');
213
+ ref(104, h.scope.name);
214
+ ref(112, h.scope.version ?? '');
215
+ if (h.ctx) h.ctx.copy(fixed, 48, 0, 24);
216
+ if (h.parentSpanId) h.parentSpanId.copy(fixed, 72, 0, 8);
217
+ fixed.writeBigUInt64LE(h.startUnixNanos ?? 0n, 80);
218
+ fixed.writeBigUInt64LE(h.startMonoNanos ?? 0n, 88);
219
+ fixed.writeBigUInt64LE(h.endUnixNanos ?? 0n, 96);
220
+ });
221
+ }
222
+
223
+ /** Lays out header, attributes, items, events, links, and the data
224
+ * table. `header` runs first, so its strings lead the table. */
225
+ private pack(
226
+ headerLen: number,
227
+ header: (fixed: Buffer, ref: Ref, itemCount: number) => void,
228
+ ): Buffer {
229
+ const attrs = this.attrs;
230
+ let itemCount = 0;
231
+ for (const a of attrs) {
232
+ if (a.value.t >= TYPE_STR_ARRAY)
233
+ itemCount += (a.value.v as unknown[]).length;
234
+ }
235
+ const attrsOff = headerLen;
236
+ const itemsOff = attrsOff + attrs.length * ATTR_LEN;
237
+ const eventsOff = itemsOff + itemCount * ITEM_LEN;
238
+ const linksOff = eventsOff + this.events.length * EVENT_LEN;
239
+ const tableOff = linksOff + this.links.length * LINK_LEN;
240
+
241
+ const fixed = Buffer.alloc(tableOff);
242
+ const table: string[] = [];
243
+ let tableLen = 0;
244
+ const ref: Ref = (off, data) => {
245
+ const n = Buffer.byteLength(data, 'utf8');
246
+ fixed.writeUInt32LE(tableLen, off);
247
+ fixed.writeUInt32LE(n, off + 4);
248
+ if (n > 0) {
249
+ table.push(data);
250
+ tableLen += n;
251
+ }
252
+ };
253
+
254
+ header(fixed, ref, itemCount);
255
+
256
+ let item = 0;
257
+ const items = <T>(
258
+ v: number,
259
+ xs: T[],
260
+ write: (off: number, x: T) => void,
261
+ ) => {
262
+ fixed.writeUInt32LE(item, v);
263
+ fixed.writeUInt32LE(xs.length, v + 4);
264
+ for (const x of xs) write(itemsOff + item++ * ITEM_LEN, x);
265
+ };
266
+ attrs.forEach((a, i) => {
267
+ const off = attrsOff + i * ATTR_LEN;
268
+ ref(off, a.key);
269
+ fixed[off + 8] = a.value.t;
270
+ const v = off + 16;
271
+ switch (a.value.t) {
272
+ case TYPE_STR:
273
+ ref(v, a.value.v);
274
+ break;
275
+ case TYPE_BOOL:
276
+ fixed[v] = a.value.v ? 1 : 0;
277
+ break;
278
+ case TYPE_I64:
279
+ fixed.writeBigInt64LE(a.value.v, v);
280
+ break;
281
+ case TYPE_F64:
282
+ fixed.writeDoubleLE(a.value.v, v);
283
+ break;
284
+ case TYPE_STR_ARRAY:
285
+ items(v, a.value.v, ref);
286
+ break;
287
+ case TYPE_BOOL_ARRAY:
288
+ items(v, a.value.v, (o, x) => (fixed[o] = x ? 1 : 0));
289
+ break;
290
+ case TYPE_I64_ARRAY:
291
+ items(v, a.value.v, (o, x) => fixed.writeBigInt64LE(x, o));
292
+ break;
293
+ case TYPE_F64_ARRAY:
294
+ items(v, a.value.v, (o, x) => fixed.writeDoubleLE(x, o));
295
+ break;
296
+ }
297
+ });
298
+
299
+ this.events.forEach((e, i) => {
300
+ const off = eventsOff + i * EVENT_LEN;
301
+ ref(off, e.name);
302
+ fixed.writeBigUInt64LE(e.timeUnixNanos, off + 8);
303
+ fixed.writeUInt32LE(e.first, off + 16);
304
+ fixed.writeUInt32LE(e.count, off + 20);
305
+ });
306
+
307
+ this.links.forEach((l, i) => {
308
+ const off = linksOff + i * LINK_LEN;
309
+ l.ctx.copy(fixed, off, 0, CTX_LEN);
310
+ ref(off + 28, l.tracestate);
311
+ fixed.writeUInt32LE(l.first, off + 36);
312
+ fixed.writeUInt32LE(l.count, off + 40);
313
+ });
314
+
315
+ const out = Buffer.allocUnsafe(tableOff + tableLen);
316
+ fixed.copy(out, 0);
317
+ let off = tableOff;
318
+ for (const d of table) off += out.write(d, off, 'utf8');
319
+ return out;
320
+ }
321
+ }
322
+
323
+ /** The 25-byte buffer of a hex span context. */
324
+ export function ctxBytes(sc: SpanContext): Buffer {
325
+ const buf = Buffer.alloc(CTX_LEN);
326
+ buf.write(sc.traceId, 0, 16, 'hex');
327
+ buf.write(sc.spanId, 16, 8, 'hex');
328
+ buf[24] = sc.traceFlags & 0xff;
329
+ return buf;
330
+ }
331
+
332
+ function writeLinks(w: PackedWriter, links: readonly Link[] | undefined) {
333
+ for (const l of links ?? []) {
334
+ w.link(
335
+ ctxBytes(l.context),
336
+ l.context.traceState?.serialize() ?? '',
337
+ l.attributes,
338
+ );
339
+ }
340
+ }
341
+
342
+ /** The start buffer: scope, attributes, and links; other fields zero. */
343
+ export function encodeStart(
344
+ scope: Scope,
345
+ attrs: Attributes | undefined,
346
+ links: readonly Link[] | undefined,
347
+ ): Buffer {
348
+ const w = new PackedWriter().spanAttrs(attrs);
349
+ writeLinks(w, links);
350
+ return w.finish({scope, name: '', kind: 0, statusCode: 0});
351
+ }
352
+
353
+ export interface PackedEvent {
354
+ name: string;
355
+ timeUnixNanos: bigint;
356
+ attributes?: Attributes;
357
+ }
358
+
359
+ /** Everything a finished span carries. */
360
+ export interface PackedSpanEnd extends PackedHeader {
361
+ ctx: Buffer;
362
+ attributes: Attributes;
363
+ events: readonly PackedEvent[];
364
+ links: readonly Link[];
365
+ }
366
+
367
+ /** The end buffer of a finished span. */
368
+ export function encodeEnd(span: PackedSpanEnd): Buffer {
369
+ const w = new PackedWriter().spanAttrs(span.attributes);
370
+ for (const e of span.events) w.event(e.name, e.timeUnixNanos, e.attributes);
371
+ writeLinks(w, span.links);
372
+ return w.finish(span);
373
+ }
374
+
375
+ // Wall clock in nanoseconds, from a monotonic source anchored once.
376
+ const anchor = BigInt(Date.now()) * 1_000_000n - process.hrtime.bigint();
377
+
378
+ export function nowUnixNanos(): bigint {
379
+ return anchor + process.hrtime.bigint();
380
+ }
381
+
382
+ function isHrTime(t: unknown): t is HrTime {
383
+ return (
384
+ Array.isArray(t) &&
385
+ t.length === 2 &&
386
+ typeof t[0] === 'number' &&
387
+ typeof t[1] === 'number'
388
+ );
389
+ }
390
+
391
+ export function isTimeInput(t: unknown): t is TimeInput {
392
+ return isHrTime(t) || typeof t === 'number' || t instanceof Date;
393
+ }
394
+
395
+ function millisToNanos(ms: number): bigint {
396
+ const whole = Math.trunc(ms);
397
+ return BigInt(whole) * 1_000_000n + BigInt(Math.round((ms - whole) * 1e6));
398
+ }
399
+
400
+ /** Unix nanoseconds of a time input. Numbers are epoch milliseconds, or
401
+ * `performance.now()` offsets when not above `performance.now()`, as in
402
+ * the OTel SDK. */
403
+ export function timeToUnixNanos(t: TimeInput): bigint {
404
+ if (isHrTime(t))
405
+ return BigInt(t[0]) * 1_000_000_000n + BigInt(Math.trunc(t[1]));
406
+ if (t instanceof Date) return BigInt(t.getTime()) * 1_000_000n;
407
+ return millisToNanos(t <= performance.now() ? performance.timeOrigin + t : t);
408
+ }
@@ -0,0 +1,20 @@
1
+ export type {
2
+ Backend,
3
+ CollectReply,
4
+ InstrumentHandle,
5
+ InstrumentOptions,
6
+ MeterBackend,
7
+ } from './backend';
8
+ export {activeContext, installContextManager, withContext} from './context';
9
+ export {ContextManager} from './context_manager';
10
+ export {W3CPropagator, formatTraceparent, parseTraceparent} from './propagator';
11
+ export {Meter, MeterProvider} from './meter';
12
+ export {TracerProvider} from './provider';
13
+ export {
14
+ activeCtxBytes,
15
+ ENCORE_REQUEST_KEY,
16
+ getRequestFromContext,
17
+ withRequestContext,
18
+ } from './request_context';
19
+ export {Span} from './span';
20
+ export {Tracer} from './tracer';
@@ -0,0 +1,231 @@
1
+ import {beforeEach, describe, expect, test} from 'bun:test';
2
+ import {
3
+ ROOT_CONTEXT,
4
+ trace,
5
+ TraceFlags,
6
+ ValueType,
7
+ type ObservableResult,
8
+ } from '@opentelemetry/api';
9
+ import type {
10
+ CollectReply,
11
+ InstrumentHandle,
12
+ InstrumentOptions,
13
+ MeterBackend,
14
+ } from './backend';
15
+ import {MeterProvider} from './meter';
16
+
17
+ interface Recorded {
18
+ id: number;
19
+ value: number;
20
+ attrs?: string;
21
+ span?: Buffer;
22
+ }
23
+
24
+ class FakeMeters implements MeterBackend {
25
+ registered: InstrumentOptions[] = [];
26
+ recorded: Recorded[] = [];
27
+ collectors: ((reply: CollectReply) => void)[] = [];
28
+
29
+ instrument(opts: InstrumentOptions): InstrumentHandle {
30
+ const id = this.registered.push(opts) - 1;
31
+ const recorded = this.recorded;
32
+ return {
33
+ id,
34
+ record(value, attrs, span) {
35
+ recorded.push({id, value, attrs, span});
36
+ },
37
+ };
38
+ }
39
+
40
+ addCollector(collect: (reply: CollectReply) => void) {
41
+ this.collectors.push(collect);
42
+ }
43
+
44
+ /** Runs the collector, resolving with what it sends; it has
45
+ * `timeout` milliseconds to. */
46
+ collect(timeout = 1000): Promise<[number[], number[], string[]]> {
47
+ return new Promise(resolve =>
48
+ this.collectors[0]!({timeout, send: (...args) => resolve(args)}),
49
+ );
50
+ }
51
+ }
52
+
53
+ let backend: FakeMeters;
54
+ let provider: MeterProvider;
55
+
56
+ beforeEach(() => {
57
+ backend = new FakeMeters();
58
+ provider = new MeterProvider(backend);
59
+ });
60
+
61
+ const TRACE_ID = '0af7651916cd43dd8448eb211c80319c';
62
+ const SPAN_ID = 'b7ad6b7169203331';
63
+
64
+ describe('Meter', () => {
65
+ test('is one per name, version and schema URL', () => {
66
+ expect(provider.getMeter('a\0b', 'c')).not.toBe(
67
+ provider.getMeter('a', 'b\0c'),
68
+ );
69
+ });
70
+
71
+ test("registers instruments in the meter's scope", () => {
72
+ const meter = provider.getMeter('lib', '1.2.3', {schemaUrl: 's'});
73
+ expect(provider.getMeter('lib', '1.2.3', {schemaUrl: 's'})).toBe(meter);
74
+ meter.createCounter('c', {unit: '{req}', description: 'd'});
75
+ meter.createUpDownCounter('u', {valueType: ValueType.INT});
76
+ meter.createHistogram('h', {
77
+ advice: {explicitBucketBoundaries: [1, 2]},
78
+ });
79
+ meter.createGauge('g');
80
+ meter.createObservableCounter('oc');
81
+ meter.createObservableUpDownCounter('ou');
82
+ meter.createObservableGauge('og');
83
+ expect(backend.registered).toEqual([
84
+ {
85
+ scopeName: 'lib',
86
+ scopeVersion: '1.2.3',
87
+ scopeSchemaUrl: 's',
88
+ kind: 0,
89
+ number: 2,
90
+ name: 'c',
91
+ unit: '{req}',
92
+ description: 'd',
93
+ boundaries: undefined,
94
+ },
95
+ ...[
96
+ [1, 0, 'u', undefined],
97
+ [2, 2, 'h', [1, 2]],
98
+ [3, 2, 'g', undefined],
99
+ [4, 2, 'oc', undefined],
100
+ [5, 2, 'ou', undefined],
101
+ [6, 2, 'og', undefined],
102
+ ].map(([kind, number, name, boundaries]) => ({
103
+ scopeName: 'lib',
104
+ scopeVersion: '1.2.3',
105
+ scopeSchemaUrl: 's',
106
+ kind,
107
+ number,
108
+ name,
109
+ unit: undefined,
110
+ description: undefined,
111
+ boundaries,
112
+ })),
113
+ ]);
114
+ });
115
+
116
+ test('records each measurement with its attributes as JSON', () => {
117
+ const meter = provider.getMeter('lib');
118
+ const counter = meter.createCounter('c');
119
+ const histogram = meter.createHistogram('h');
120
+ counter.add(1);
121
+ counter.add(2, {route: '/x', ok: true, n: 3});
122
+ histogram.record(0.5, {});
123
+ expect(backend.recorded).toEqual([
124
+ {id: 0, value: 1, attrs: undefined, span: undefined},
125
+ {
126
+ id: 0,
127
+ value: 2,
128
+ attrs: '{"route":"/x","ok":true,"n":3}',
129
+ span: undefined,
130
+ },
131
+ {id: 1, value: 0.5, attrs: '{}', span: undefined},
132
+ ]);
133
+ });
134
+
135
+ test('passes the span a measurement is taken in when sampled', () => {
136
+ const counter = provider.getMeter('lib').createCounter('c');
137
+ const ctx = (traceFlags: number) =>
138
+ trace.setSpanContext(ROOT_CONTEXT, {
139
+ traceId: TRACE_ID,
140
+ spanId: SPAN_ID,
141
+ traceFlags,
142
+ });
143
+ counter.add(1, undefined, ctx(TraceFlags.SAMPLED));
144
+ counter.add(1, undefined, ctx(TraceFlags.NONE));
145
+ const span = backend.recorded[0]!.span!;
146
+ expect(span.toString('hex')).toBe(`${TRACE_ID}${SPAN_ID}01`);
147
+ expect(backend.recorded[1]!.span).toBeUndefined();
148
+ });
149
+ });
150
+
151
+ describe('observable instruments', () => {
152
+ test('adds one collector, with the first callback', () => {
153
+ const meter = provider.getMeter('lib');
154
+ const gauge = meter.createObservableGauge('g');
155
+ expect(backend.collectors).toHaveLength(0);
156
+ gauge.addCallback(() => {});
157
+ meter.createObservableCounter('c').addCallback(() => {});
158
+ expect(backend.collectors).toHaveLength(1);
159
+ });
160
+
161
+ test("a collection replies with every callback's observations", async () => {
162
+ const meter = provider.getMeter('lib');
163
+ const gauge = meter.createObservableGauge('g');
164
+ const counter = meter.createObservableCounter('c');
165
+ const other = provider.getMeter('other').createObservableUpDownCounter('u');
166
+ gauge.addCallback(r => r.observe(1, {a: 'x'}));
167
+ gauge.addCallback(r => r.observe(2));
168
+ counter.addCallback(() => {
169
+ throw new Error('boom');
170
+ });
171
+ meter.addBatchObservableCallback(
172
+ r => {
173
+ r.observe(counter, 10);
174
+ r.observe(other, 20, {b: 1});
175
+ // Not one of the batch's: ignored.
176
+ r.observe(gauge, 30);
177
+ },
178
+ [counter, other],
179
+ );
180
+ expect(await backend.collect()).toEqual([
181
+ [0, 0, 1, 2],
182
+ [1, 2, 10, 20],
183
+ ['{"a":"x"}', '', '', '{"b":1}'],
184
+ ]);
185
+ });
186
+
187
+ test('waits for callbacks returning promises', async () => {
188
+ const gauge = provider.getMeter('lib').createObservableGauge('g');
189
+ let late: ObservableResult | undefined;
190
+ gauge.addCallback(async r => {
191
+ await new Promise(resolve => setTimeout(resolve, 5));
192
+ r.observe(1);
193
+ late = r;
194
+ });
195
+ expect(await backend.collect()).toEqual([[0], [1], ['']]);
196
+ // Observations after the reply are dropped.
197
+ late!.observe(2);
198
+ });
199
+
200
+ test('replies by the deadline without callbacks still pending', async () => {
201
+ const meter = provider.getMeter('lib');
202
+ meter
203
+ .createObservableGauge('hung')
204
+ .addCallback(() => new Promise(() => {}));
205
+ let n = 0;
206
+ meter.createObservableCounter('ok').addCallback(async r => r.observe(++n));
207
+ let late: ObservableResult | undefined;
208
+ meter.createObservableGauge('late').addCallback(async r => {
209
+ late = r;
210
+ await new Promise(resolve => setTimeout(resolve, 200));
211
+ });
212
+ expect(await backend.collect(20)).toEqual([[1], [1], ['']]);
213
+ expect(await backend.collect(20)).toEqual([[1], [2], ['']]);
214
+ // Observations after the reply are dropped.
215
+ late!.observe(3);
216
+ });
217
+
218
+ test('removed callbacks no longer run', async () => {
219
+ const meter = provider.getMeter('lib');
220
+ const gauge = meter.createObservableGauge('g');
221
+ const cb = (r: ObservableResult) => r.observe(1);
222
+ const batch = () => {
223
+ throw new Error('not removed');
224
+ };
225
+ gauge.addCallback(cb);
226
+ meter.addBatchObservableCallback(batch, [gauge]);
227
+ gauge.removeCallback(cb);
228
+ meter.removeBatchObservableCallback(batch, [gauge]);
229
+ expect(await backend.collect()).toEqual([[], [], []]);
230
+ });
231
+ });