Cookbook > Быстрая и простая отладка подграфа с использованием форков

Быстрая и простая отладка подграфа с использованием форков

Reading time: 4 min

As with many systems processing large amounts of data, The Graph's Indexers (Graph Nodes) may take quite some time to sync-up your subgraph with the target blockchain. The discrepancy between quick changes with the purpose of debugging and long wait times needed for indexing is extremely counterproductive and we are well aware of that. This is why we are introducing subgraph forking, developed by LimeChain, and in this article I will show you how this feature can be used to substantially speed-up subgraph debugging!

И так, что это?

Ссылка на этот раздел

Subgraph forking - это процесс ленивой выборки объектов из _ хранилища другого _ подграфа (обычно удаленного).

В контексте отладки форкинга подграфа позволяет вам отлаживать ваш проблемный подграф в блоке X без необходимости ждать синхронизации с блоком X.

When you deploy a subgraph to a remote Graph Node for indexing and it fails at block X, the good news is that the Graph Node will still serve GraphQL queries using its store, which is synced-up to block X. That's great! This means we can take advantage of this "up-to-date" store to fix the bugs arising when indexing block X.

In a nutshell, we are going to fork the failing subgraph from a remote Graph Node that is guaranteed to have the subgraph indexed up to block X in order to provide the locally deployed subgraph being debugged at block X an up-to-date view of the indexing state.

Пожалуйста, покажите мне какой-нибудь код!

Ссылка на этот раздел

To stay focused on subgraph debugging, let's keep things simple and run along with the example-subgraph indexing the Ethereum Gravity smart contract.

Вот обработчики, установленные для индексирования Gravatars, совершенно без ошибок:

export function handleNewGravatar(event: NewGravatar): void {
let gravatar = new Gravatar(event.params.id.toHex().toString())
gravatar.owner = event.params.owner
gravatar.displayName = event.params.displayName
gravatar.imageUrl = event.params.imageUrl
gravatar.save()
}
export function handleUpdatedGravatar(event: UpdatedGravatar): void {
let gravatar = Gravatar.load(event.params.id.toI32().toString())
if (gravatar == null) {
log.critical('Gravatar not found!', [])
return
}
gravatar.owner = event.params.owner
gravatar.displayName = event.params.displayName
gravatar.imageUrl = event.params.imageUrl
gravatar.save()
}

Oops, how unfortunate, when I deploy my perfect looking subgraph to Subgraph Studio it fails with the "Gravatar not found!" error.

Обычный способ попытаться исправить это:

  1. Внести изменения в источник сопоставлений, которые, по вашему мнению, решат проблему (в то время как я знаю, что это не так).
  2. Re-deploy the subgraph to Subgraph Studio (or another remote Graph Node).
  3. Подождать, пока он синхронизируется.
  4. Если он снова сломается, вернуться к пункту 1, в противном случае: Ура!

Это действительно довольно знакомо для обычного процесса отладки, но есть один шаг, который ужасно замедляет процесс: 3. Подождите, пока он синхронизируется.

Используя форк подграфа, мы можем существенно исключить этот шаг. Вот как это выглядит:

  1. Spin-up a local Graph Node with the appropriate fork-base set.
  2. Внесите изменения в источник сопоставлений, которые, по вашему мнению, решат проблему.
  3. Deploy to the local Graph Node, forking the failing subgraph and starting from the problematic block.
  4. Если он снова сломается, вернитесь к пункту 1, в противном случае: Ура!

Сейчас у вас может появиться 2 вопроса:

  1. fork-base что???
  2. Форкнуть кого?!

И я вам отвечаю:

  1. fork-base - это "базовый" URL, такой, что при добавлении идентификатора подграфа результирующий URL (<fork-base>/<subgraph-id>) является допустимым эндпоинтом GraphQL для хранилища подграфа.
  2. Форк - это просто, особо не нужно потеть:
$ graph deploy <subgraph-name> --debug-fork <subgraph-id> --ipfs http://localhost:5001 --node http://localhost:8020

Кроме того, не забудьте установить в поле DataSources.source.startBlock в манифесте подграфа номер проблемного блока, чтобы вы могли пропустить индексацию ненужных блоков и воспользоваться преимуществами fork!

Итак, вот что я делаю:

  1. I spin-up a local Graph Node (here is how to do it) with the fork-base option set to: https://api.thegraph.com/subgraphs/id/, since I will fork a subgraph, the buggy one I deployed earlier, from Subgraph Studio.
$ cargo run -p graph-node --release -- \
--postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \
--ethereum-rpc NETWORK_NAME:[CAPABILITIES]:URL \
--ipfs 127.0.0.1:5001
--fork-base https://api.thegraph.com/subgraphs/id/
  1. После тщательной проверки я замечаю, что существует несоответствие в представлениях id, используемых при индексации Gravatars в моих двух обработчиках. В то время как handleNewGravatar преобразует его в шестнадцатеричное значение (event.params.id.toHex()), handleUpdatedGravatar использует int32 (event.params.id.toI32()), который вызывает handleUpdatedGravatar панику с сообщением "Gravatar not found!". Я заставляю их обоих преобразовать идентификатор в шестнадцатеричное значение.
  2. After I made the changes I deploy my subgraph to the local Graph Node, forking the failing subgraph and setting dataSources.source.startBlock to 6190343 in subgraph.yaml:
$ graph deploy gravity --debug-fork QmNp169tKvomnH3cPXTfGg4ZEhAHA6kEq5oy1XDqAxqHmW --ipfs http://localhost:5001 --node http://localhost:8020
  1. I inspect the logs produced by the local Graph Node and, Hooray!, everything seems to be working.
  2. I deploy my now bug-free subgraph to a remote Graph Node and live happily ever after! (no potatoes tho)
Редактировать страницу

Предыдущий
Python (Subgrounds)
Следующий
Создание субграфов на NEAR
Редактировать страницу