Class: ApolloFederation::Tracing::NodeMap

Inherits:
Object
  • Object
show all
Defined in:
lib/apollo-federation/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.



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

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

Instance Attribute Details

#nodesObject (readonly)

Returns the value of attribute nodes.



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

def nodes
  @nodes
end

Instance Method Details

#add(path) ⇒ Object



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

def add(path)
  node = ApolloFederation::Tracing::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



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

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

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

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

#array_wrap(object) ⇒ Object



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

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



29
30
31
# File 'lib/apollo-federation/tracing/node_map.rb', line 29

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

#rootObject



25
26
27
# File 'lib/apollo-federation/tracing/node_map.rb', line 25

def root
  nodes[ROOT_KEY]
end