Skip to content
This repository was archived by the owner on Oct 29, 2021. It is now read-only.

Commit ee35fd8

Browse files
committed
improves comments readability & adds a TODO
1 parent 4a4b359 commit ee35fd8

File tree

1 file changed

+57
-77
lines changed

1 file changed

+57
-77
lines changed

influxdb_store.go

+57-77
Original file line numberDiff line numberDiff line change
@@ -55,35 +55,32 @@ type InfluxDBStore struct {
5555
}
5656

5757
func (in *InfluxDBStore) Collect(id SpanID, anns ...Annotation) error {
58-
// Find a span's point, if found it will be rewritten with new annotations(`anns`)
59-
// if not found, a new span's point will be created.
58+
// Find a span's point, if found it will be rewritten with new given annotations(`anns`)
59+
// if not found, a new span's point will be write to `in.dbName`.
6060
p, err := in.findSpanPoint(id)
6161
if err != nil {
6262
return err
6363
}
6464

65-
// trace_id, span_id & parent_id are set as tags
66-
// because InfluxDB tags are indexed & those values
67-
// are used later on queries.
65+
// trace_id, span_id & parent_id are mostly used as part of the "where" part on queries so
66+
// to have performant queries these are set as tags(InfluxDB indexes tags).
6867
tags := map[string]string{
6968
"trace_id": id.Trace.String(),
7069
"span_id": id.Span.String(),
7170
"parent_id": id.Parent.String(),
7271
}
7372

74-
// Saving annotations as InfluxDB measurement spans fields
75-
// which are not indexed.
73+
// Annotations `anns` are set as fields(InfluxDB does not index fields).
7674
fields := make(map[string]interface{}, len(anns))
7775
for _, ann := range anns {
7876
fields[ann.Key] = string(ann.Value)
7977
}
8078

81-
if p != nil { // span exists on DB.
79+
if p != nil { // span exists on `in.dbName`.
8280
p.Measurement = spanMeasurementName
8381
p.Tags = tags
8482

85-
// Using extendFields & withoutEmptyFields in order to have
86-
// pointFields that only contains:
83+
// Using extendFields & withoutEmptyFields in order to have pointFields that only contains:
8784
// - Fields that are not saved on DB.
8885
// - Fields that are saved but have empty values.
8986
fields := extendFields(fields, withoutEmptyFields(p.Fields))
@@ -98,18 +95,18 @@ func (in *InfluxDBStore) Collect(id SpanID, anns ...Annotation) error {
9895
p.Fields = fields
9996
} else { // new span to be saved on DB.
10097

101-
// A field `schemasFieldName` contains all the schemas found on `anns`.
98+
// `schemasFieldName` field contains all the schemas found on `anns`.
10299
// Eg. fields[schemasFieldName] = "HTTPClient,HTTPServer"
103100
fields[schemasFieldName] = schemasFromAnnotations(anns)
104101
p = &influxDBClient.Point{
105102
Measurement: spanMeasurementName,
106-
Tags: tags, // indexed metadata.
107-
Fields: fields, // non-indexed metadata.
103+
Tags: tags,
104+
Fields: fields,
108105
Time: time.Now().UTC(),
109106
}
110107
}
111108

112-
// InfluxDB point represents a single span.
109+
// A single point represents one span.
113110
pts := []influxDBClient.Point{*p}
114111
bps := influxDBClient.BatchPoints{
115112
Points: pts,
@@ -138,7 +135,7 @@ func (in *InfluxDBStore) Trace(id ID) (*Trace, error) {
138135
return nil, errors.New("trace not found")
139136
}
140137

141-
// Iterate over series(spans) to create trace children's & set trace fields.
138+
// Iterate over series(spans) to set `trace` fields.
142139
var rootSpanSet bool
143140
for _, s := range result.Series {
144141
var isRootSpan bool
@@ -186,7 +183,7 @@ func (in *InfluxDBStore) Traces() ([]*Trace, error) {
186183
// Cache to keep track of traces to be returned.
187184
tracesCache := make(map[ID]*Trace, 0)
188185

189-
// Iterate over series(spans) to create traces.
186+
// Iterate over series(spans) to create root traces.
190187
for _, s := range rootSpansResult.Series {
191188
span, err := newSpanFromRow(&s)
192189
if err != nil {
@@ -218,15 +215,14 @@ func (in *InfluxDBStore) Traces() ([]*Trace, error) {
218215
i += 1
219216
}
220217

221-
// Queries for all children spans of the traces to be returned.
218+
// Queries for all children spans of the root traces.
222219
childrenSpansQuery := fmt.Sprintf("SELECT * FROM spans %s GROUP BY *", where)
223220
childrenSpansResult, err := in.executeOneQuery(childrenSpansQuery)
224221
if err != nil {
225222
return nil, err
226223
}
227224

228-
// Iterate over series(children spans) to create sub-traces
229-
// and associates sub-traces with it's parent trace.
225+
// Iterate over series(children spans) to set sub-traces to it's corresponding root trace.
230226
for _, s := range childrenSpansResult.Series {
231227
span, err := newSpanFromRow(&s)
232228
if err != nil {
@@ -268,7 +264,7 @@ func (in *InfluxDBStore) createDBIfNotExists() error {
268264
}
269265
}
270266

271-
// If no errors query execution was successfully - either DB was created or already exists.
267+
// If there are no errors, query execution was successfully - either DB was created or already exists.
272268
response, err := in.con.Query(influxDBClient.Query{Command: q})
273269
if err != nil {
274270
return err
@@ -279,8 +275,7 @@ func (in *InfluxDBStore) createDBIfNotExists() error {
279275
return nil
280276
}
281277

282-
// createAdminUserIfNotExists creates an admin user
283-
// using `in.adminUser` credentials if does not exist.
278+
// createAdminUserIfNotExists finds admin user(`in.adminUser`) if not found it's created.
284279
func (in *InfluxDBStore) createAdminUserIfNotExists() error {
285280
userInfo, err := in.server.MetaClient.Authenticate(in.adminUser.Username, in.adminUser.Password)
286281
if err == influxDBErrors.ErrUserNotFound {
@@ -291,7 +286,7 @@ func (in *InfluxDBStore) createAdminUserIfNotExists() error {
291286
} else {
292287
return err
293288
}
294-
if !userInfo.Admin {
289+
if !userInfo.Admin { // must be admin user.
295290
return errors.New("failed to validate InfluxDB user type, found non-admin user")
296291
}
297292
return nil
@@ -366,6 +361,9 @@ func (in *InfluxDBStore) init(server *influxDBServer.Server) error {
366361
if err != nil {
367362
return err
368363
}
364+
365+
// TODO: Upgrade to client v2, see: github.com/influxdata/influxdb/blob/master/client/v2/client.go
366+
// We're currently using v1.
369367
con, err := influxDBClient.NewClient(influxDBClient.Config{
370368
URL: *url,
371369
Username: in.adminUser.Username,
@@ -391,7 +389,8 @@ func (in *InfluxDBStore) init(server *influxDBServer.Server) error {
391389
if err := in.createDBIfNotExists(); err != nil {
392390
return err
393391
}
394-
// TODO: support specifying the number of traces per page.
392+
393+
// TODO: let lib users decide `in.tracesPerPage` through InfluxDBStoreConfig.
395394
in.tracesPerPage = defaultTracesPerPage
396395
return nil
397396
}
@@ -423,18 +422,15 @@ func annotationsFromRow(r *influxDBModels.Row) (*Annotations, error) {
423422
fields = r.Values[0]
424423
}
425424

426-
// len(r.Values) cannot be greater than 1.
427-
// Values[0] is the slice containing a span's
428-
// annotation values.
425+
// `len(r.Values)` cannot be greater than 1. `r.Values[0]` is an slice containing annotation values.
429426
if len(r.Values) > 1 {
430427
return nil, errors.New("unexpected multiple row values")
431428
}
432429
annotations := make(Annotations, 0)
433430

434-
// Iterates over fields which represent span's annotation values.
431+
// Iterates over fields, each field represents an `Annotation.Value`.
435432
for i, field := range fields {
436-
// It is safe to do column[0] (eg. 'Server.Request.Method')
437-
// matches fields[0] (eg. 'GET')
433+
// It's safe to do that column[0] (eg. 'Server.Request.Method') matches fields[0] (eg. 'GET').
438434
key := r.Columns[i]
439435
var value []byte
440436
switch field.(type) {
@@ -464,42 +460,31 @@ func extendFields(dst, src pointFields) pointFields {
464460
return dst
465461
}
466462

467-
// filterSchemas returns `Annotations` with items taken from `anns`.
468-
// It finds the annotation with key: `schemaFieldName`, which is later use
469-
// to discard schema related annotations not present on it's value.
463+
// filterSchemas returns `Annotations` which contains items taken from `anns`.
464+
// Some items from `anns` won't be included(those which were not saved by `InfluxDBStore.Collect(...)`).
470465
func filterSchemas(anns []Annotation) Annotations {
471466
var annotations Annotations
472467

473-
// Finds the annotation with key `schemasFieldName`.
468+
// Finds an annotation which: `Annotation.Key` is equal to `schemasFieldName`.
474469
schemasAnn := findSchemasAnnotation(anns)
475470

476-
// Convert it to a string slice which contains the schemas.
471+
// Converts `schemasAnn.Value` into slice of strings, each item is a schema.
477472
// Eg. schemas := []string{"HTTPClient", "HTTPServer"}
478473
schemas := strings.Split(string(schemasAnn.Value), schemasFieldSeparator)
479474

480-
// Iterate over `anns` to check if each annotation is a schema related one
481-
// if so it's added to the `annotations` be returned, but only if it's present
482-
// on `schemas`.
483-
// If annotation is not schema related, it's added to annotations returned.
475+
// Iterates over `anns` to check if each annotation should be included or not to the `annotations` be returned.
484476
for _, a := range anns {
485-
if strings.HasPrefix(a.Key, schemaPrefix) {
486-
schema := a.Key[len(schemaPrefix):]
487-
488-
// If schema does not exists; annotation `a` is not added to
489-
// the `annotations` be returned because it was not saved
490-
// by `Collect(...)`.
491-
// But exists because InfluxDB returns all fields(annotations)
492-
// even those ones not explicit written by `Collect(...)`.
493-
//
494-
// Eg. if point "a" is written with a field "foo" &
495-
// point "b" with a field "bar" (both "a" & "b" written in the
496-
// same measurement), when querying for those points the result
497-
// will contain two fields "foo" & "bar", even though field "bar"
498-
// was not present when writing Point "a".
499-
if schemaExists(schema, schemas) {
500-
// Schema exists, meaning `Collect(...)` method
501-
// saved this annotation.
477+
if strings.HasPrefix(a.Key, schemaPrefix) { // Check if current annotation is schema related one.
478+
schema := a.Key[len(schemaPrefix):] // Excludes the schema prefix part.
479+
480+
// Checks if `schema` exists in `schemas`, if so means current annotation was saved by `InfluxDBStore.Collect(...)`.
481+
// If does not exist it means current annotation is empty on `InfluxDBStore.dbName` but still included within a query result.
482+
// Eg. If point "f" with a field "foo" & point "b" with a field "bar" are written to the same InfluxDB measurement
483+
// and later queried, the result will include two fields: "foo" & "bar" for both points, even though each was written with one field.
484+
if schemaExists(schema, schemas) { // Saved by `InfluxDBStore.Collect(...)` so should be added.
502485
annotations = append(annotations, a)
486+
} else { // Do not add current annotation, is empty & not saved by `InfluxDBStore.Collect(...)`.
487+
continue
503488
}
504489
} else {
505490
// Not a schema related annotation so just add it.
@@ -519,8 +504,7 @@ func schemaExists(schema string, schemas []string) bool {
519504
return false
520505
}
521506

522-
// findSchemasAnnotation finds & returns an annotation
523-
// with key: `schemasFieldName`.
507+
// findSchemasAnnotation finds & returns an annotation which: `Annotation.Key` is equal to `schemasFieldName`.
524508
func findSchemasAnnotation(anns []Annotation) *Annotation {
525509
for _, a := range anns {
526510
if a.Key == schemasFieldName {
@@ -530,35 +514,31 @@ func findSchemasAnnotation(anns []Annotation) *Annotation {
530514
return nil
531515
}
532516

533-
// mergeSchemasField merges new and old which are a set of schemas(strings)
534-
// separated by `schemasFieldSeparator` - eg. "HTTPClient,HTTPServer"
517+
// mergeSchemasField merges new and old which are a set of schemas(strings) separated by `schemasFieldSeparator`.
535518
// Returns the result of merging new & old without duplications.
536519
func mergeSchemasField(new, old interface{}) (string, error) {
537-
// Since both new and old are same data structures
538-
// (a set of strings separated by `schemasFieldSeparator`)
539-
// same code logic is applied.
520+
// Since new and old have the same data structures(a set of strings separated by `schemasFieldSeparator`).
521+
// So same logic is applied to both.
540522
fields := []interface{}{new, old}
541523
var strFields []string
542524

543-
// Iterate over fields in order to cast each to string type
544-
// and append it to `strFields` for later usage.
525+
// Iterates over fields to convert each into a string and appends it to `strFields` for later usage.
545526
for _, field := range fields {
546527
switch field.(type) {
547528
case string:
548529
strFields = append(strFields, field.(string))
549530
case nil:
550531
continue
551532
default:
552-
return "", fmt.Errorf("unexpected event field type: %v", reflect.TypeOf(field))
533+
return "", fmt.Errorf("unexpected schema field type: %v", reflect.TypeOf(field))
553534
}
554535
}
555536

556-
// Cache for schemas; used to keep track of non duplicated schemas
557-
// to be returned.
537+
// Schemas cache, used to keep track schemas to be returned(without duplications).
558538
schemas := make(map[string]string, 0)
559539

560-
// Iterate over `strFields` to transform each to a slice([]string)
561-
// which each element is an schema that are added to schemas cache.
540+
// Iterates over `strFields` to convert each into a slice([]string), then iterates over it in order to
541+
// add each to `schemas` if not present already.
562542
for _, strField := range strFields {
563543
if strField == "" {
564544
continue
@@ -576,25 +556,25 @@ func mergeSchemasField(new, old interface{}) (string, error) {
576556
result = append(result, k)
577557
}
578558

579-
// Return a string which contains all the schemas separated by `schemasFieldSeparator`.
559+
// Returns a string which contains all the schemas separated by `schemasFieldSeparator`.
580560
return strings.Join(result, schemasFieldSeparator), nil
581561
}
582562

583-
// schemasFromAnnotations finds schemas in `anns` and builds a data structure
584-
// which is a set of all schemas found, those are separated by `schemasFieldSeparator`
585-
// and returned as string.
563+
// schemasFromAnnotations returns a string(a set of schemas(strings) separated by `schemasFieldSeparator`) - eg. "HTTPClient,HTTPServer,name".
564+
// Each schema is extracted from each `Annotation.Key` from `anns`.
586565
func schemasFromAnnotations(anns []Annotation) string {
587566
var schemas []string
588567
for _, ann := range anns {
589-
if strings.HasPrefix(ann.Key, schemaPrefix) { // Check if is an annotation for a schema.
568+
569+
// Checks if current annotation is schema related.
570+
if strings.HasPrefix(ann.Key, schemaPrefix) {
590571
schemas = append(schemas, ann.Key[len(schemaPrefix):])
591572
}
592573
}
593574
return strings.Join(schemas, schemasFieldSeparator)
594575
}
595576

596-
// withoutEmptyFields returns a pointFields without
597-
// those fields that has empty values.
577+
// withoutEmptyFields filters `pf` and returns `pointFields` excluding those that have empty values.
598578
func withoutEmptyFields(pf pointFields) pointFields {
599579
r := make(pointFields, 0)
600580
for k, v := range pf {

0 commit comments

Comments
 (0)