Class: ApolloStudioTracing::NodeMap

Inherits:
Object
  • Object
show all
Defined in:
lib/apollo-studio-tracing/node_map.rb

Overview

NodeMap stores a flat map of trace nodes by stringified paths (i.e. “_entities.0.id”) for fast lookup when we need to alter nodes (to add end times or errors.)

When adding a node to the NodeMap, it will create any missing parent nodes and ensure the tree is consistent.

Only the “root” node is attached to the trace extension.

Constant Summary collapse

ROOT_KEY =
''

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeNodeMap

Returns a new instance of NodeMap.



18
19
20
21
22
# File 'lib/apollo-studio-tracing/node_map.rb', line 18

def initialize
  @nodes = {
    ROOT_KEY => ApolloStudioTracing::Node.new,
  }
end

Instance Attribute Details

#nodesObject (readonly)

Returns the value of attribute nodes.



17
18
19
# File 'lib/apollo-studio-tracing/node_map.rb', line 17

def nodes
  @nodes
end

Instance Method Details

#add(path) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/apollo-studio-tracing/node_map.rb', line 32

def add(path)
  node = ApolloStudioTracing::Node.new
  node_key = path.join('.')
  key = path.last

  case key
  when String # field
    node.response_name = key
  when Integer # index of an array
    node.index = key
  end

  nodes[node_key] = node

  # find or create a parent node and add this node to its children
  parent_path = path[0..-2]
  parent_node = nodes[parent_path.join('.')] || add(parent_path)
  parent_node.child << node

  node
end

#add_error(error) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/apollo-studio-tracing/node_map.rb', line 54

def add_error(error)
  path = array_wrap(error['path']).join('.')
  node = nodes[path] || root

  locations = array_wrap(error['locations']).map do |location|
    ApolloStudioTracing::Location.new(location)
  end

  node.error << ApolloStudioTracing::Error.new(
    message: error['message'],
    location: locations,
    json: JSON.dump(error),
  )
end

#array_wrap(object) ⇒ Object



69
70
71
72
73
74
75
76
77
# File 'lib/apollo-studio-tracing/node_map.rb', line 69

def array_wrap(object)
  if object.nil?
    []
  elsif object.respond_to?(:to_ary)
    object.to_ary || [object]
  else
    [object]
  end
end

#node_for_path(path) ⇒ Object



28
29
30
# File 'lib/apollo-studio-tracing/node_map.rb', line 28

def node_for_path(path)
  nodes[array_wrap(path).join('.')]
end

#rootObject



24
25
26
# File 'lib/apollo-studio-tracing/node_map.rb', line 24

def root
  nodes[ROOT_KEY]
end