libo11y 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,442 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Libo11y
4
+ module Internal
5
+ # SQL statement text for telemetry: a lexer that removes every literal and
6
+ # comment, and a summary of the statement's operation and table. It is a
7
+ # port of go/o11ysql/internal/sqltext and works on bytes as that does, so
8
+ # both give the same text for the same statement.
9
+ module SqlText
10
+ DIALECTS = %i[standard mysql sqlite].freeze
11
+ MAX_COLLECTION_BYTES = 128
12
+ MAX_QUERY_TEXT_BYTES = 4096
13
+
14
+ OPERATIONS = Set.new(
15
+ %w[
16
+ SELECT INSERT UPDATE DELETE MERGE REPLACE UPSERT CREATE ALTER DROP TRUNCATE CALL EXEC EXECUTE
17
+ BEGIN COMMIT ROLLBACK SAVEPOINT RELEASE PRAGMA VACUUM ANALYZE EXPLAIN SHOW SET
18
+ ]
19
+ ).freeze
20
+ UPDATE_CLAUSE = Set.new(%w[FOR KEY DO THEN OR BEFORE AFTER OF]).freeze
21
+ TABLE_MODIFIERS = Set.new(%w[ONLY LOW_PRIORITY IGNORE]).freeze
22
+
23
+ QUOTE = "'".ord
24
+ DQUOTE = '"'.ord
25
+ BACKTICK = "`".ord
26
+ BACKSLASH = "\\".ord
27
+ DOLLAR = "$".ord
28
+ DOT = ".".ord
29
+ STAR = "*".ord
30
+ SLASH = "/".ord
31
+ DASH = "-".ord
32
+ HASH = "#".ord
33
+ COLON = ":".ord
34
+ QUESTION = "?".ord
35
+ LPAREN = "(".ord
36
+ RPAREN = ")".ord
37
+ LBRACKET = "[".ord
38
+ RBRACKET = "]".ord
39
+ BANG = "!".ord
40
+ PLUS = "+".ord
41
+ AT = "@".ord
42
+ UNDERSCORE = "_".ord
43
+ NEWLINE = "\n".ord
44
+ SPACE = " ".ord
45
+ private_constant :QUOTE, :DQUOTE, :BACKTICK, :BACKSLASH, :DOLLAR, :DOT, :STAR, :SLASH, :DASH, :HASH, :COLON,
46
+ :QUESTION, :LPAREN, :RPAREN, :LBRACKET, :RBRACKET, :BANG, :PLUS, :AT, :UNDERSCORE, :NEWLINE, :SPACE
47
+
48
+ module_function
49
+
50
+ # Returns query with every literal replaced by "?" and every comment by
51
+ # one space. Names, placeholders and operators stay. The result has the
52
+ # encoding of query, and bytes that are not UTF-8 pass through as part
53
+ # of a name.
54
+ def sanitize(query, dialect = :standard)
55
+ raise ArgumentError, "libo11y: unknown SQL dialect #{dialect.inspect}" unless DIALECTS.include?(dialect)
56
+
57
+ s = query.b
58
+ out = +"".b
59
+ mysql = dialect == :mysql
60
+ sqlite = dialect == :sqlite
61
+ pg = !mysql && !sqlite
62
+ in_versioned = false # inside a MySQL /*! ... */ comment, whose body is SQL
63
+ i = 0
64
+ n = s.bytesize
65
+ while i < n
66
+ c = s.getbyte(i)
67
+ nx = s.getbyte(i + 1)
68
+ if c == QUOTE
69
+ i, = skip_quoted(s, i, QUOTE, mysql)
70
+ out << "?"
71
+ elsif pg && [69, 101].include?(c) && nx == QUOTE # E'...' escape string
72
+ i, = skip_quoted(s, i + 1, QUOTE, true)
73
+ out << "?"
74
+ elsif c == DQUOTE && !pg
75
+ i, = skip_quoted(s, i, DQUOTE, mysql)
76
+ out << "?"
77
+ elsif c == DQUOTE || (c == BACKTICK && !pg) || (c == LBRACKET && sqlite)
78
+ finish, closed = skip_quoted_name(s, i)
79
+ # An unterminated name may hold anything.
80
+ out << (closed ? s.byteslice(i, finish - i) : "?")
81
+ i = finish
82
+ elsif (c == DASH && nx == DASH && (!mysql || mysql_dash_comment?(s, i))) || (c == HASH && mysql)
83
+ i = skip_line(s, i)
84
+ out << " "
85
+ elsif c == SLASH && nx == STAR
86
+ finish = mysql ? skip_versioned_open(s, i) : nil
87
+ if finish
88
+ in_versioned = true
89
+ i = finish
90
+ else
91
+ i = skip_block(s, i, pg)
92
+ end
93
+ out << " "
94
+ elsif in_versioned && c == STAR && nx == SLASH
95
+ in_versioned = false
96
+ i += 2
97
+ out << " "
98
+ elsif pg && c == DOLLAR
99
+ finish = skip_dollar_quoted(s, i)
100
+ if finish
101
+ out << "?"
102
+ else
103
+ finish = skip_digits(s, i + 1) # $1 placeholder, or a lone $
104
+ out << s.byteslice(i, finish - i)
105
+ end
106
+ i = finish
107
+ elsif sqlite && [DOLLAR, AT, COLON, HASH].include?(c)
108
+ finish, plain = skip_sqlite_parameter(s, i)
109
+ out << if finish == i + 1
110
+ c.chr # no name follows, so not a parameter
111
+ elsif plain
112
+ s.byteslice(i, finish - i)
113
+ else
114
+ "?" # a $name(...) suffix may hold anything
115
+ end
116
+ i = finish
117
+ elsif sqlite && c == QUESTION
118
+ finish = skip_digits(s, i + 1) # ?1 placeholder
119
+ out << s.byteslice(i, finish - i)
120
+ i = finish
121
+ elsif ident_start?(c) || (mysql && c == DOLLAR)
122
+ finish = skip_ident(s, i)
123
+ out << s.byteslice(i, finish - i)
124
+ i = finish
125
+ elsif digit?(c) || (c == DOT && digit?(nx))
126
+ i = skip_number(s, i)
127
+ out << "?"
128
+ else
129
+ out << c.chr
130
+ i += 1
131
+ end
132
+ end
133
+ out.force_encoding(query.encoding)
134
+ end
135
+
136
+ # Returns [operation, collection] for sanitized statement text. The
137
+ # operation is the first keyword, upper case, when it is a known one.
138
+ # The collection is the one table the statement names, and is empty for
139
+ # a join of different tables, a subquery, or a table function. Both are
140
+ # empty when the statement starts with anything else.
141
+ def summarize(sanitized)
142
+ toks = tokenize(sanitized.b)
143
+ return ["", ""] if toks.empty?
144
+
145
+ operation = toks[0].upcase.force_encoding(Encoding::UTF_8)
146
+ return ["", ""] unless OPERATIONS.include?(operation)
147
+ return [operation, ""] if operation == "SHOW"
148
+
149
+ subquery = [] # per open parenthesis: whether it holds a subquery
150
+ collection = ""
151
+ last = toks.length
152
+ (0...(last - 1)).each do |k|
153
+ tok = toks[k]
154
+ if tok == "("
155
+ subquery << %w[SELECT WITH].include?(toks[k + 1].upcase)
156
+ next
157
+ elsif tok == ")"
158
+ subquery.pop
159
+ next
160
+ end
161
+ next if !subquery.empty? && !subquery.last # inside a call or a column list
162
+
163
+ keyword = tok.upcase
164
+ next unless names_table?(keyword, toks, k)
165
+
166
+ j = k + 1
167
+ j = skip_if_exists(toks, j) if keyword == "TABLE"
168
+ j += 2 if keyword == "UPDATE" && toks[j].casecmp?("OR") # SQLite's UPDATE OR IGNORE t
169
+ j += 1 while j < last && TABLE_MODIFIERS.include?(toks[j].upcase)
170
+ # A subquery or something unrecognized.
171
+ return [operation, ""] if j >= last || !name_start?(toks[j].getbyte(0))
172
+ # A list of tables, or a table function.
173
+ return [operation, ""] if j + 1 < last && (toks[j + 1] == "," || (toks[j + 1] == "(" && %w[FROM JOIN].include?(keyword)))
174
+
175
+ name = unquote_name(toks[j])
176
+ return [operation, ""] if !collection.empty? && collection != name
177
+
178
+ collection = name
179
+ end
180
+ return [operation, ""] if collection.bytesize > MAX_COLLECTION_BYTES
181
+
182
+ [operation, String.new(collection, encoding: Encoding::UTF_8).scrub]
183
+ end
184
+
185
+ # Returns the longest prefix of text that has at most max_bytes bytes
186
+ # and ends on a character boundary. Cutting sanitized text cannot expose
187
+ # a literal, because every literal is already gone.
188
+ def truncate(text, max_bytes = MAX_QUERY_TEXT_BYTES)
189
+ return text if text.bytesize <= max_bytes
190
+
191
+ cut = max_bytes
192
+ cut -= 1 while cut.positive? && (text.getbyte(cut) & 0xC0) == 0x80
193
+ text.byteslice(0, cut)
194
+ end
195
+
196
+ def names_table?(keyword, toks, k)
197
+ prev = k.positive? ? toks[k - 1].upcase : ""
198
+ case keyword
199
+ when "JOIN", "INTO", "TABLE" then true
200
+ when "FROM" then prev != "DISTINCT" # a IS DISTINCT FROM b compares values
201
+ when "UPDATE" then !UPDATE_CLAUSE.include?(prev)
202
+ else false
203
+ end
204
+ end
205
+
206
+ def skip_if_exists(toks, j)
207
+ last = toks.length
208
+ return j if j >= last || !toks[j].casecmp?("IF")
209
+
210
+ j += 1
211
+ j += 1 if j < last && toks[j].casecmp?("NOT")
212
+ return j + 1 if j < last && toks[j].casecmp?("EXISTS")
213
+
214
+ last
215
+ end
216
+
217
+ def unquote_name(tok)
218
+ return tok.dup unless tok.include?('"') || tok.include?("`")
219
+
220
+ out = +"".b
221
+ i = 0
222
+ n = tok.bytesize
223
+ while i < n
224
+ q = tok.getbyte(i)
225
+ if q != DQUOTE && q != BACKTICK
226
+ out << q.chr
227
+ i += 1
228
+ next
229
+ end
230
+ finish, closed = skip_quoted(tok, i, q, false)
231
+ inner = tok.byteslice(i + 1, (closed ? finish - 1 : finish) - (i + 1))
232
+ out << inner.gsub(q.chr * 2, q.chr)
233
+ i = finish
234
+ end
235
+ out
236
+ end
237
+
238
+ def tokenize(s)
239
+ toks = []
240
+ i = 0
241
+ n = s.bytesize
242
+ while i < n
243
+ c = s.getbyte(i)
244
+ if [SPACE, 9, 10, 13].include?(c)
245
+ i += 1
246
+ elsif name_start?(c)
247
+ finish = skip_name(s, i)
248
+ toks << s.byteslice(i, finish - i)
249
+ i = finish
250
+ else
251
+ toks << c.chr
252
+ i += 1
253
+ end
254
+ end
255
+ toks
256
+ end
257
+
258
+ def skip_name(s, i)
259
+ n = s.bytesize
260
+ loop do
261
+ c = s.getbyte(i)
262
+ i = if [DQUOTE, BACKTICK].include?(c)
263
+ skip_quoted(s, i, c, false).first
264
+ else
265
+ skip_ident(s, i)
266
+ end
267
+ return i unless i + 1 < n && s.getbyte(i) == DOT && name_start?(s.getbyte(i + 1))
268
+
269
+ i += 1
270
+ end
271
+ end
272
+
273
+ def name_start?(c)
274
+ ident_start?(c) || c == DQUOTE || c == BACKTICK
275
+ end
276
+
277
+ def ident_start?(c)
278
+ return false if c.nil?
279
+
280
+ c == UNDERSCORE || c.between?(97, 122) || c.between?(65, 90) || c >= 0x80
281
+ end
282
+
283
+ def ident_part?(c)
284
+ ident_start?(c) || digit?(c)
285
+ end
286
+
287
+ def ident_cont?(c)
288
+ ident_part?(c) || c == DOLLAR
289
+ end
290
+
291
+ def digit?(c)
292
+ !c.nil? && c.between?(48, 57)
293
+ end
294
+
295
+ def space?(c)
296
+ [SPACE, 9, 10, 12, 13].include?(c)
297
+ end
298
+
299
+ def skip_ident(s, i)
300
+ i += 1
301
+ n = s.bytesize
302
+ i += 1 while i < n && ident_cont?(s.getbyte(i))
303
+ i
304
+ end
305
+
306
+ def skip_digits(s, i)
307
+ n = s.bytesize
308
+ i += 1 while i < n && digit?(s.getbyte(i))
309
+ i
310
+ end
311
+
312
+ # Returns the index after the literal that opens at i, and whether it
313
+ # was closed. A doubled quote is an escaped quote. With backslash, a
314
+ # backslash escapes the next byte.
315
+ def skip_quoted(s, i, quote, backslash)
316
+ n = s.bytesize
317
+ j = i + 1
318
+ while j < n
319
+ c = s.getbyte(j)
320
+ if c == BACKSLASH
321
+ j += 1 if backslash
322
+ elsif c == quote
323
+ return [j + 1, true] unless j + 1 < n && s.getbyte(j + 1) == quote
324
+
325
+ j += 1
326
+ end
327
+ j += 1
328
+ end
329
+ [n, false]
330
+ end
331
+
332
+ def skip_quoted_name(s, i)
333
+ return skip_quoted(s, i, s.getbyte(i), false) unless s.getbyte(i) == LBRACKET
334
+
335
+ close = s.index("]".b, i + 1)
336
+ close ? [close + 1, true] : [s.bytesize, false]
337
+ end
338
+
339
+ # MySQL reads -- as a comment only before whitespace or a control byte.
340
+ def mysql_dash_comment?(s, i)
341
+ return true if i + 2 >= s.bytesize
342
+
343
+ c = s.getbyte(i + 2)
344
+ c <= SPACE || c == 0x7f
345
+ end
346
+
347
+ def skip_line(s, i)
348
+ s.index("\n".b, i) || s.bytesize
349
+ end
350
+
351
+ def skip_block(s, i, nested)
352
+ depth = 0
353
+ j = i
354
+ n = s.bytesize
355
+ while j + 1 < n
356
+ a = s.getbyte(j)
357
+ b = s.getbyte(j + 1)
358
+ if a == SLASH && b == STAR && (nested || depth.zero?)
359
+ depth += 1
360
+ j += 2
361
+ elsif a == STAR && b == SLASH
362
+ depth -= 1
363
+ j += 2
364
+ return j if depth.zero?
365
+ else
366
+ j += 1
367
+ end
368
+ end
369
+ n
370
+ end
371
+
372
+ # Returns the index after a MySQL /*!12345 or MariaDB /*M!12345 opener,
373
+ # or nil when the comment at i is an ordinary one.
374
+ def skip_versioned_open(s, i)
375
+ j = i + 2
376
+ j += 1 if s.getbyte(j) == 77
377
+ return nil unless s.getbyte(j) == BANG
378
+
379
+ skip_digits(s, j + 1)
380
+ end
381
+
382
+ # Returns the index after the dollar-quoted string that opens at i, or
383
+ # nil when the $ opens none. An unterminated one runs to the end.
384
+ def skip_dollar_quoted(s, i)
385
+ n = s.bytesize
386
+ j = i + 1
387
+ if j < n && ident_start?(s.getbyte(j))
388
+ j += 1
389
+ j += 1 while j < n && ident_part?(s.getbyte(j))
390
+ end
391
+ return nil unless s.getbyte(j) == DOLLAR
392
+
393
+ tag = s.byteslice(i, j + 1 - i)
394
+ close = s.index(tag, j + 1)
395
+ close ? close + tag.bytesize : n
396
+ end
397
+
398
+ # Returns the index after the SQLite parameter that opens at i, and
399
+ # whether it is a plain name. A $name(...) suffix is not plain.
400
+ def skip_sqlite_parameter(s, i)
401
+ n = s.bytesize
402
+ j = i + 1
403
+ count = 0
404
+ while j < n
405
+ c = s.getbyte(j)
406
+ if ident_cont?(c)
407
+ count += 1
408
+ j += 1
409
+ elsif c == LPAREN && count.positive?
410
+ j += 1
411
+ j += 1 while j < n && s.getbyte(j) != RPAREN && !space?(s.getbyte(j))
412
+ j += 1 if s.getbyte(j) == RPAREN
413
+ return [j, false]
414
+ elsif c == COLON && s.getbyte(j + 1) == COLON
415
+ j += 2
416
+ else
417
+ break
418
+ end
419
+ end
420
+ count.zero? ? [i + 1, true] : [j, true]
421
+ end
422
+
423
+ def skip_number(s, i)
424
+ hex = s.getbyte(i) == 48 && [120, 88].include?(s.getbyte(i + 1))
425
+ n = s.bytesize
426
+ i += 1
427
+ while i < n
428
+ c = s.getbyte(i)
429
+ exponent = [101, 69].include?(c)
430
+ # 1E'...' is a number and then an escape string.
431
+ return i if !hex && exponent && s.getbyte(i + 1) == QUOTE
432
+
433
+ signed = [PLUS, DASH].include?(c) && [101, 69].include?(s.getbyte(i - 1)) && digit?(s.getbyte(i + 1))
434
+ return i unless ident_part?(c) || c == DOT || signed
435
+
436
+ i += 1
437
+ end
438
+ i
439
+ end
440
+ end
441
+ end
442
+ end
@@ -0,0 +1,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Libo11y
4
+ # Sentinel passed to `env:` for hermetic mode (no ambient OTEL_* env vars read).
5
+ HERMETIC = Object.new.freeze
6
+
7
+ module PIIMode
8
+ DROP = :drop
9
+ HASH = :hash
10
+ ALLOW = :allow
11
+ ALL = [DROP, HASH, ALLOW].freeze
12
+ end
13
+
14
+ module ExemplarFilter
15
+ TRACE_BASED = :trace_based
16
+ ALWAYS_ON = :always_on
17
+ ALWAYS_OFF = :always_off
18
+ ALL = [TRACE_BASED, ALWAYS_ON, ALWAYS_OFF].freeze
19
+ end
20
+
21
+ ShutdownReport = Data.define(:traces_error, :metrics_error, :logs_error) do
22
+ def ok?
23
+ traces_error.nil? && metrics_error.nil? && logs_error.nil?
24
+ end
25
+
26
+ def errors
27
+ {
28
+ traces: traces_error,
29
+ metrics: metrics_error,
30
+ logs: logs_error
31
+ }.compact
32
+ end
33
+ end
34
+
35
+ Options = Struct.new(
36
+ :service_name,
37
+ :version,
38
+ :environment,
39
+ :service_namespace,
40
+ :service_instance_id,
41
+ :extra_environments,
42
+ :strict_identity,
43
+ :resource_attributes,
44
+ :build_info,
45
+ :build_info_enabled,
46
+ :env,
47
+ :pii_mode,
48
+ :pii_hash_key,
49
+ :app_registries,
50
+ :attr_replacer,
51
+ :propagators,
52
+ :baggage_egress_allow,
53
+ :sampler,
54
+ :exemplar_filter,
55
+ :histogram_buckets,
56
+ :views,
57
+ :runtime_metrics,
58
+ :console_writer,
59
+ :console_enabled,
60
+ :console_level,
61
+ :extra_log_sinks,
62
+ :span_exporter,
63
+ :span_processors,
64
+ :metric_reader,
65
+ :log_exporter,
66
+ :log_processors,
67
+ :shutdown_timeout,
68
+ keyword_init: true
69
+ ) do
70
+ def initialize(**kwargs)
71
+ defaults = {
72
+ extra_environments: [],
73
+ strict_identity: true,
74
+ resource_attributes: {},
75
+ build_info_enabled: true,
76
+ env: nil,
77
+ pii_mode: PIIMode::DROP,
78
+ app_registries: nil,
79
+ runtime_metrics: true,
80
+ console_enabled: true,
81
+ console_level: ::Logger::INFO,
82
+ extra_log_sinks: [],
83
+ span_processors: [],
84
+ log_processors: [],
85
+ shutdown_timeout: 5.0
86
+ }
87
+ super(**defaults.merge(kwargs))
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "opentelemetry"
4
+
5
+ module Libo11y
6
+ # Child-process environment and framed-map propagation (TRACEPARENT/TRACESTATE only; never baggage).
7
+ module Proc
8
+ TRACEPARENT_ENV = "TRACEPARENT"
9
+ TRACESTATE_ENV = "TRACESTATE"
10
+
11
+ module_function
12
+
13
+ def env_carrier(context: OpenTelemetry::Context.current)
14
+ carrier = {}
15
+ OpenTelemetry::Trace::Propagation::TraceContext.text_map_propagator.inject(carrier, context: context)
16
+ out = {}
17
+ out[TRACEPARENT_ENV] = carrier["traceparent"] if carrier["traceparent"]
18
+ out[TRACESTATE_ENV] = carrier["tracestate"] if carrier["tracestate"]
19
+ out
20
+ end
21
+
22
+ def child_env(base_env = ENV.to_h, context: OpenTelemetry::Context.current)
23
+ result = base_env.dup
24
+ result.delete(TRACEPARENT_ENV)
25
+ result.delete(TRACESTATE_ENV)
26
+ result.merge!(env_carrier(context: context))
27
+ result
28
+ end
29
+
30
+ def extract_env(env_map = ENV, context: OpenTelemetry::Context.current)
31
+ carrier = {}
32
+ tp = env_map[TRACEPARENT_ENV]
33
+ ts = env_map[TRACESTATE_ENV]
34
+ carrier["traceparent"] = tp if tp && !tp.empty?
35
+ carrier["tracestate"] = ts if ts && !ts.empty?
36
+ OpenTelemetry::Trace::Propagation::TraceContext.text_map_propagator.extract(carrier, context: context)
37
+ end
38
+
39
+ def inject_frame(frame = {}, telemetry: nil, context: OpenTelemetry::Context.current)
40
+ propagator = telemetry ? telemetry.propagator : OpenTelemetry.propagation
41
+ propagator.inject(frame, context: context)
42
+ frame
43
+ end
44
+
45
+ def extract_frame(frame, telemetry: nil, context: OpenTelemetry::Context.current)
46
+ propagator = telemetry ? telemetry.propagator : OpenTelemetry.propagation
47
+ propagator.extract(frame, context: context)
48
+ end
49
+ end
50
+ end