# All files / src/indexer-management/resolvers indexer-status.ts

9.38% Statements 6/64
0% Branches 0/20
0% Functions 0/25
9.84% Lines 6/61

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229

    3x
    3x

    3x

    3x

    3x

    3x

     /* eslint-disable @typescript-eslint/ban-types */

    import geohash from 'ngeohash'
    import gql from 'graphql-tag'
    import { IndexerManagementResolverContext } from '../client'
    import { SubgraphDeploymentID } from '@graphprotocol/common-ts'

    interface Test {
      test: (url: string) => string
      run: (url: string) => Promise<void>
      possibleActions: (url: string) => string[]
    }

    interface TestResult {
      test: string
      error: string | null
      possibleActions: string[]
    }

    const testURL = async (
      url: string,
      tests: Test[],
    ): Promise<{ url: string; ok: boolean; tests: TestResult[] }> => {
      const results = []

      for (const test of tests) {
        const cmd = test.test(url)

        try {
          await test.run(url)

          results.push({
            test: cmd,
            error: null,
            possibleActions: [],
          })
        } catch (e) {
          results.push({
            test: cmd,
            error: e.message,
            possibleActions: test.possibleActions(url),
          })
        }
      }

      return { url, tests: results, ok: !results.find((result) => result.error !== null) }
    }

    const URL_VALIDATION_TEST: Test = {
      test: () => `URL validation`,
      run: async (url) => {
        new URL(url)
      },
      possibleActions: (url) => [`Make sure ${url} is a valid URL`],
    }

    export default {
      indexerRegistration: async (
        _: {},
        { address, contracts }: IndexerManagementResolverContext,
      ): Promise<object | null> => {
        const registered = await contracts.serviceRegistry.isRegistered(address)

        if (registered) {
          const service = await contracts.serviceRegistry.services(address)
          return {
            address,
            url: service.url,
            location: geohash.decode(service.geohash),
            registered,
            __typename: 'IndexerRegistration',
          }
        } else {
          return {
            address,
            url: null,
            registered,
            location: null,
            __typename: 'IndexerRegistration',
          }
        }
      },

      indexerDeployments: async (
        _: {},
        { indexingStatusResolver }: IndexerManagementResolverContext,
      ): Promise<object | null> => {
        const result = await indexingStatusResolver.indexingStatus([])
        return result.map((status) => ({
          ...status,
          subgraphDeployment: status.subgraphDeployment.ipfsHash,
        }))
      },

      indexerAllocations: async (
        _: {},
        { address, networkSubgraph }: IndexerManagementResolverContext,
      ): Promise<object | null> => {
        const result = await networkSubgraph.query(
          gql`
            query allocations($indexer: String!) {
              indexer(id: $indexer) {
                allocations(where: { status: Active }, orderDirection: desc) {
                  id
                  allocatedTokens
                  createdAtBlockHash
                  createdAtEpoch
                  closedAtEpoch
                  subgraphDeployment {
                    id
                    stakedTokens
                    signalAmount
                  }
                }
              }
            }
          `,
          { indexer: address.toLowerCase() },
        )
        if (result.error) {
          throw new Error(`Falied to query allocations: ${result.error}`)
        }
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        return result.data.indexer.allocations.map((allocation: any) => ({
          ...allocation,
          subgraphDeployment: new SubgraphDeploymentID(allocation.subgraphDeployment.id)
            .ipfsHash,
          signalAmount: allocation.subgraphDeployment.signalAmount,
          stakedTokens: allocation.subgraphDeployment.stakedTokens,
        }))
      },

      indexerEndpoints: async (
        _: {},
        { address, contracts, logger }: IndexerManagementResolverContext,
      ): Promise<object | null> => {
        const endpoints = {
          service: {
            url: null as string | null,
            healthy: false,
            tests: [] as TestResult[],
          },
          status: {
            url: null as string | null,
            healthy: false,
            tests: [] as TestResult[],
          },
        }

        try {
          const service = await contracts.serviceRegistry.services(address)

          if (service) {
            {
              const { url, tests, ok } = await testURL(service.url, [
                URL_VALIDATION_TEST,
                {
                  test: (url) => `http get ${url}`,
                  run: async (url) => {
                    const response = await fetch(url)
                    if (!response.ok) {
                      throw new Error(
                        `Returned status ${response.status}: ${
                          response.body ? response.body.toString() : 'No data returned'
                        }`,
                      )
                    }
                  },
                  possibleActions: (url) => [
                    `Make sure ${url} can be resolved and reached from this machine`,
                    `Make sure the port of ${url} is set up correctly`,
                    `Make sure the test command returns an HTTP status code < 400`,
                  ],
                },
              ])

              endpoints.service.url = url
              endpoints.service.healthy = ok
              endpoints.service.tests = tests
            }

            {
              const statusURL = endpoints.service.url.endsWith('/')
                ? endpoints.service.url.substring(0, endpoints.service.url.length - 1) +
                  '/status'
                : endpoints.service.url + '/status'

              const { url, tests, ok } = await testURL(statusURL, [
                URL_VALIDATION_TEST,
                {
                  test: (url) => `http post ${url} query="{ indexingStatuses { subgraph } }"`,
                  run: async (url) => {
                    const response = await fetch(url, {
                      method: 'POST',
                      headers: { 'content-type': 'application/json' },
                      body: JSON.stringify({ query: '{ indexingStatuses { subgraph } }' }),
                    })
                    if (!response.ok) {
                      throw new Error(
                        `Returned status ${response.status}: ${
                          response.body ? response.body.toString() : 'No data returned'
                        }`,
                      )
                    }
                  },
                  possibleActions: (url) => [
                    `Make sure ${url} can be reached from this machine`,
                    `Make sure the port of ${url} is set up correctly`,
                    `Make sure ${url} is the /status endpoint of indexer-service`,
                    `Make sure the test command returns an HTTP status code < 400`,
                    `Make sure the test command returns a valid GraphQL response`,
                  ],
                },
              ])

              endpoints.status.url = url
              endpoints.status.healthy = ok
              endpoints.status.tests = tests
            }
          }
        } catch (err) {
          // Return empty endpoints
          logger?.warn(`Failed to detect service endpoints`, { err })
        }

        return endpoints
      },
    }