forked from cerc-io/ipld-eth-server
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0a7a7d999 | ||
|
|
7d6629e5b4 | ||
|
|
d761f88b30 | ||
|
|
948246cf83 | ||
|
|
e11f2c8c59 | ||
|
|
95fa6280c5 | ||
|
|
fd126c7bea | ||
|
|
f292888195 | ||
|
|
adf91df23a | ||
|
|
ede6ad1c8f | ||
|
|
ee13d5c1df | ||
|
|
eb2b3a0263 | ||
|
|
5088574437 | ||
|
|
d61f4f3cb4 | ||
|
|
1a455741ce | ||
|
|
180c2d963e | ||
|
|
2598704690 | ||
|
|
e2909797fc | ||
|
|
79765c7998 | ||
|
|
9c6549258e | ||
|
|
b4cdf76905 | ||
|
|
622ea44a6f | ||
|
|
d947c8f30a | ||
|
|
481988cb08 | ||
|
|
4580f0fc2e | ||
|
|
eba52442ec | ||
|
|
7ddf728db2 | ||
|
|
829a581727 | ||
|
|
fa03716cb2 | ||
|
|
bd3e841e21 | ||
|
|
8dc9ddf65e | ||
|
|
7d1b334bda | ||
|
|
ade1429ce3 | ||
|
|
5d1ba5903c | ||
|
|
a49f5d7582 | ||
|
|
436d9b9cb1 | ||
|
|
f7d520c933 | ||
|
|
e1a0d894a2 | ||
|
|
ba81766f6c | ||
|
|
b96f6c4d31 | ||
|
|
c5cfa85f4c | ||
|
|
702e839f5b | ||
|
|
ca354de229 |
+2
-5
@@ -5,21 +5,18 @@ go:
|
|||||||
services:
|
services:
|
||||||
- postgresql
|
- postgresql
|
||||||
addons:
|
addons:
|
||||||
postgresql: '9.6'
|
postgresql: '11.2'
|
||||||
go_import_path: github.com/vulcanize/vulcanizedb
|
go_import_path: github.com/vulcanize/vulcanizedb
|
||||||
before_install:
|
before_install:
|
||||||
- make installtools
|
- make installtools
|
||||||
- bash ./scripts/install-postgres-10.sh
|
- bash ./scripts/install-postgres-11.sh
|
||||||
- curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
|
- curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
|
||||||
- echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
|
- echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
|
||||||
- sudo apt-get update && sudo apt-get install yarn
|
- sudo apt-get update && sudo apt-get install yarn
|
||||||
before_script:
|
before_script:
|
||||||
- sudo -u postgres createdb vulcanize_private
|
- sudo -u postgres createdb vulcanize_private
|
||||||
- make migrate NAME=vulcanize_private
|
- make migrate NAME=vulcanize_private
|
||||||
- cd postgraphile && yarn
|
|
||||||
script:
|
script:
|
||||||
- yarn test
|
|
||||||
- cd ../
|
|
||||||
- make test
|
- make test
|
||||||
- make integrationtest
|
- make integrationtest
|
||||||
notifications:
|
notifications:
|
||||||
|
|||||||
@@ -7,35 +7,40 @@
|
|||||||
|
|
||||||
|
|
||||||
## Table of Contents
|
## Table of Contents
|
||||||
1. [Background](../staging/README.md#background)
|
1. [Background](#background)
|
||||||
1. [Dependencies](../staging/README.md#dependencies)
|
1. [Install](#install)
|
||||||
1. [Install](../staging/README.md#install)
|
1. [Usage](#usage)
|
||||||
1. [Usage](../staging/README.md#usage)
|
1. [Contributing](#contributing)
|
||||||
1. [Tests](../staging/README.md#tests)
|
1. [License](#license)
|
||||||
1. [API](../staging/README.md#API)
|
|
||||||
1. [Contributing](../staging/README.md#contributing)
|
|
||||||
1. [License](../staging/README.md#license)
|
|
||||||
|
|
||||||
|
|
||||||
## Background
|
## Background
|
||||||
The same data structures and encodings that make Ethereum an effective and trust-less distributed virtual machine
|
The same data structures and encodings that make Ethereum an effective and trust-less distributed virtual machine
|
||||||
complicate data accessibility and usability for dApp developers. VulcanizeDB improves Ethereum data accessibility by
|
complicate data accessibility and usability for dApp developers. VulcanizeDB improves Ethereum data accessibility by
|
||||||
providing a suite of tools to ease the extraction and transformation of data into a more useful state.
|
providing a suite of tools to ease the extraction and transformation of data into a more useful state, including
|
||||||
|
allowing for exposing aggregate data from a suite of smart contracts.
|
||||||
|
|
||||||
|
VulanizeDB includes processes that sync, transform and expose data. Syncing involves
|
||||||
|
querying an Ethereum node and then persisting core data into a Postgres database. Transforming focuses on using previously synced data to
|
||||||
|
query for and transform log event and storage data for specifically configured smart contract addresses. Exposing data is a matter of getting
|
||||||
|
data from VulcanizeDB's underlying Postgres database and making it accessible.
|
||||||
|
|
||||||
## Dependencies
|

|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
1. [Dependencies](#dependencies)
|
||||||
|
1. [Building the project](#building-the-project)
|
||||||
|
1. [Setting up the database](#setting-up-the-database)
|
||||||
|
1. [Configuring a synced Ethereum node](#configuring-a-synced-ethereum-node)
|
||||||
|
|
||||||
|
### Dependencies
|
||||||
- Go 1.11+
|
- Go 1.11+
|
||||||
- Postgres 10.6
|
- Postgres 11.2
|
||||||
- Ethereum Node
|
- Ethereum Node
|
||||||
- [Go Ethereum](https://ethereum.github.io/go-ethereum/downloads/) (1.8.23+)
|
- [Go Ethereum](https://ethereum.github.io/go-ethereum/downloads/) (1.8.23+)
|
||||||
- [Parity 1.8.11+](https://github.com/paritytech/parity/releases)
|
- [Parity 1.8.11+](https://github.com/paritytech/parity/releases)
|
||||||
|
|
||||||
|
|
||||||
## Install
|
|
||||||
1. [Building the project](../staging/README.md#building-the-project)
|
|
||||||
1. [Setting up the database](../staging/README.md#setting-up-the-database)
|
|
||||||
1. [Configuring a synced Ethereum node](../staging/README.md#configuring-a-synced-ethereum-node)
|
|
||||||
|
|
||||||
### Building the project
|
### Building the project
|
||||||
Download the codebase to your local `GOPATH` via:
|
Download the codebase to your local `GOPATH` via:
|
||||||
|
|
||||||
@@ -68,7 +73,8 @@ It can be additionally helpful to add `$GOPATH/bin` to your shell's `$PATH`.
|
|||||||
|
|
||||||
* See below for configuring additional environments
|
* See below for configuring additional environments
|
||||||
|
|
||||||
In some cases (such as recent Ubuntu systems), it may be necessary to overcome failures of password authentication from localhost. To allow access on Ubuntu, set localhost connections via hostname, ipv4, and ipv6 from peer/md5 to trust in: /etc/postgresql/<version>/pg_hba.conf
|
In some cases (such as recent Ubuntu systems), it may be necessary to overcome failures of password authentication from
|
||||||
|
localhost. To allow access on Ubuntu, set localhost connections via hostname, ipv4, and ipv6 from peer/md5 to trust in: /etc/postgresql/<version>/pg_hba.conf
|
||||||
|
|
||||||
(It should be noted that trusted auth should only be enabled on systems without sensitive data in them: development and local test databases)
|
(It should be noted that trusted auth should only be enabled on systems without sensitive data in them: development and local test databases)
|
||||||
|
|
||||||
@@ -80,8 +86,9 @@ In some cases (such as recent Ubuntu systems), it may be necessary to overcome f
|
|||||||
- The IPC file is called `geth.ipc`.
|
- The IPC file is called `geth.ipc`.
|
||||||
- The geth IPC file path is printed to the console when you start geth.
|
- The geth IPC file path is printed to the console when you start geth.
|
||||||
- The default location is:
|
- The default location is:
|
||||||
- Mac: `<full home path>/Library/Ethereum`
|
- Mac: `<full home path>/Library/Ethereum/geth.ipc`
|
||||||
- Linux: `<full home path>/ethereum/geth.ipc`
|
- Linux: `<full home path>/ethereum/geth.ipc`
|
||||||
|
- Note: the geth.ipc file may not exist until you've started the geth process
|
||||||
|
|
||||||
- For Parity:
|
- For Parity:
|
||||||
- The IPC file is called `jsonrpc.ipc`.
|
- The IPC file is called `jsonrpc.ipc`.
|
||||||
@@ -98,27 +105,35 @@ In some cases (such as recent Ubuntu systems), it may be necessary to overcome f
|
|||||||
|
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
Usage is broken up into two processes:
|
As mentioned above, VulcanizeDB's processes can be split into three categories: syncing, transforming and exposing data.
|
||||||
|
|
||||||
### Data syncing
|
### Data syncing
|
||||||
To provide data for transformations, raw Ethereum data must first be synced into vDB.
|
To provide data for transformations, raw Ethereum data must first be synced into VulcanizeDB.
|
||||||
This is accomplished through the use of the `headerSync`, `sync`, or `coldImport` commands.
|
This is accomplished through the use of the `headerSync`, `fullSync`, or `coldImport` commands.
|
||||||
These commands are described in detail [here](../staging/documentation/sync.md).
|
These commands are described in detail [here](documentation/data-syncing.md).
|
||||||
|
|
||||||
### Data transformation
|
### Data transformation
|
||||||
Contract watchers use the raw data that has been synced into Postgres to filter out and apply transformations to specific data of interest.
|
Data transformation uses the raw data that has been synced into Postgres to filter out and apply transformations to
|
||||||
|
specific data of interest. Since there are different types of data that may be useful for observing smart contracts, it
|
||||||
|
follows that there are different ways to transform this data. We've started by categorizing this into Generic and
|
||||||
|
Custom transformers:
|
||||||
|
|
||||||
There is a built-in `contractWatcher` command which provides generic transformation of most contract data.
|
- Generic Contract Transformer: Generic contract transformation can be done using a built-in command,
|
||||||
The `contractWatcher` command is described further [here](../staging/documentation/contractWatcher.md).
|
`contractWatcher`, which transforms contract events provided the contract's ABI is available. It also
|
||||||
|
provides some state variable coverage by automating polling of public methods, with some restrictions.
|
||||||
|
`contractWatcher` is described further [here](documentation/generic-transformer.md).
|
||||||
|
|
||||||
In many cases a custom transformer or set of transformers will need to be written to provide complete or more comprehensive coverage or to optimize other aspects of the output for a specific end-use.
|
- Custom Transformers: In many cases custom transformers will need to be written to provide
|
||||||
In this case we have provided the `compose`, `execute`, and `composeAndExecute` commands for running custom transformers from external repositories.
|
more comprehensive coverage of contract data. In this case we have provided the `compose`, `execute`, and
|
||||||
|
`composeAndExecute` commands for running custom transformers from external repositories. Documentation on how to write,
|
||||||
|
build and run custom transformers as Go plugins can be found
|
||||||
|
[here](documentation/custom-transformers.md).
|
||||||
|
|
||||||
Usage of the `compose`, `execute`, and `composeAndExecute` commands is described further [here](../staging/documentation/composeAndExecute.md).
|
### Exposing the data
|
||||||
|
[Postgraphile](https://www.graphile.org/postgraphile/) is used to expose GraphQL endpoints for our database schemas, this is described in detail [here](documentation/postgraphile.md).
|
||||||
|
|
||||||
Documentation on how to build custom transformers to work with these commands can be found [here](../staging/documentation/transformers.md).
|
|
||||||
|
|
||||||
## Tests
|
### Tests
|
||||||
- Replace the empty `ipcPath` in the `environments/infura.toml` with a path to a full node's eth_jsonrpc endpoint (e.g. local geth node ipc path or infura url)
|
- Replace the empty `ipcPath` in the `environments/infura.toml` with a path to a full node's eth_jsonrpc endpoint (e.g. local geth node ipc path or infura url)
|
||||||
- Note: integration tests require configuration with an archival node
|
- Note: integration tests require configuration with an archival node
|
||||||
- `createdb vulcanize_private` will create the test db
|
- `createdb vulcanize_private` will create the test db
|
||||||
@@ -126,15 +141,13 @@ Documentation on how to build custom transformers to work with these commands ca
|
|||||||
- `make test` will run the unit tests and skip the integration tests
|
- `make test` will run the unit tests and skip the integration tests
|
||||||
- `make integrationtest` will run just the integration tests
|
- `make integrationtest` will run just the integration tests
|
||||||
|
|
||||||
## API
|
|
||||||
[Postgraphile](https://www.graphile.org/postgraphile/) is used to expose GraphQL endpoints for our database schemas, this is described in detail [here](../staging/postgraphile/README.md).
|
|
||||||
|
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
Contributions are welcome! For more on this, please see [here](../staging/documentation/contributing.md).
|
Contributions are welcome!
|
||||||
|
|
||||||
Small note: If editing the Readme, please conform to the [standard-readme specification](https://github.com/RichardLitt/standard-readme).
|
VulcanizeDB follows the [Contributor Covenant Code of Conduct](https://www.contributor-covenant.org/version/1/4/code-of-conduct).
|
||||||
|
|
||||||
|
For more information on contributing, please see [here](documentation/contributing.md).
|
||||||
|
|
||||||
## License
|
## License
|
||||||
[AGPL-3.0](../staging/LICENSE) © Vulcanize Inc
|
[AGPL-3.0](LICENSE) © Vulcanize Inc
|
||||||
@@ -193,5 +193,5 @@ func composeAndExecute() {
|
|||||||
func init() {
|
func init() {
|
||||||
rootCmd.AddCommand(composeAndExecuteCmd)
|
rootCmd.AddCommand(composeAndExecuteCmd)
|
||||||
composeAndExecuteCmd.Flags().BoolVarP(&recheckHeadersArg, "recheck-headers", "r", false, "whether to re-check headers for watched events")
|
composeAndExecuteCmd.Flags().BoolVarP(&recheckHeadersArg, "recheck-headers", "r", false, "whether to re-check headers for watched events")
|
||||||
composeAndExecuteCmd.Flags().DurationVarP(&queueRecheckInterval, "queue-recheck-interval", "q", 5*time.Minute, "how often to recheck queued storage diffs")
|
composeAndExecuteCmd.Flags().DurationVarP(&queueRecheckInterval, "queue-recheck-interval", "q", 5*time.Minute, "interval duration for rechecking queued storage diffs (ex: 5m30s)")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ import (
|
|||||||
|
|
||||||
st "github.com/vulcanize/vulcanizedb/libraries/shared/transformer"
|
st "github.com/vulcanize/vulcanizedb/libraries/shared/transformer"
|
||||||
ft "github.com/vulcanize/vulcanizedb/pkg/contract_watcher/full/transformer"
|
ft "github.com/vulcanize/vulcanizedb/pkg/contract_watcher/full/transformer"
|
||||||
lt "github.com/vulcanize/vulcanizedb/pkg/contract_watcher/header/transformer"
|
ht "github.com/vulcanize/vulcanizedb/pkg/contract_watcher/header/transformer"
|
||||||
"github.com/vulcanize/vulcanizedb/utils"
|
"github.com/vulcanize/vulcanizedb/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -99,7 +99,7 @@ func contractWatcher() {
|
|||||||
con.PrepConfig()
|
con.PrepConfig()
|
||||||
switch mode {
|
switch mode {
|
||||||
case "header":
|
case "header":
|
||||||
t = lt.NewTransformer(con, blockChain, &db)
|
t = ht.NewTransformer(con, blockChain, &db)
|
||||||
case "full":
|
case "full":
|
||||||
t = ft.NewTransformer(con, blockChain, &db)
|
t = ft.NewTransformer(con, blockChain, &db)
|
||||||
default:
|
default:
|
||||||
|
|||||||
+1
-1
@@ -139,7 +139,7 @@ func execute() {
|
|||||||
func init() {
|
func init() {
|
||||||
rootCmd.AddCommand(executeCmd)
|
rootCmd.AddCommand(executeCmd)
|
||||||
executeCmd.Flags().BoolVarP(&recheckHeadersArg, "recheck-headers", "r", false, "whether to re-check headers for watched events")
|
executeCmd.Flags().BoolVarP(&recheckHeadersArg, "recheck-headers", "r", false, "whether to re-check headers for watched events")
|
||||||
executeCmd.Flags().DurationVarP(&queueRecheckInterval, "queue-recheck-interval", "q", 5*time.Minute, "how often to recheck queued storage diffs")
|
executeCmd.Flags().DurationVarP(&queueRecheckInterval, "queue-recheck-interval", "q", 5*time.Minute, "interval duration for rechecking queued storage diffs (ex: 5m30s)")
|
||||||
}
|
}
|
||||||
|
|
||||||
type Exporter interface {
|
type Exporter interface {
|
||||||
|
|||||||
@@ -29,14 +29,14 @@ import (
|
|||||||
"github.com/vulcanize/vulcanizedb/utils"
|
"github.com/vulcanize/vulcanizedb/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
// syncCmd represents the sync command
|
// fullSyncCmd represents the fullSync command
|
||||||
var syncCmd = &cobra.Command{
|
var fullSyncCmd = &cobra.Command{
|
||||||
Use: "sync",
|
Use: "fullSync",
|
||||||
Short: "Syncs VulcanizeDB with local ethereum node",
|
Short: "Syncs VulcanizeDB with local ethereum node",
|
||||||
Long: `Syncs VulcanizeDB with local ethereum node. Populates
|
Long: `Syncs VulcanizeDB with local ethereum node. Populates
|
||||||
Postgres with blocks, transactions, receipts, and logs.
|
Postgres with blocks, transactions, receipts, and logs.
|
||||||
|
|
||||||
./vulcanizedb sync --starting-block-number 0 --config public.toml
|
./vulcanizedb fullSync --starting-block-number 0 --config public.toml
|
||||||
|
|
||||||
Expects ethereum node to be running and requires a .toml config:
|
Expects ethereum node to be running and requires a .toml config:
|
||||||
|
|
||||||
@@ -49,14 +49,14 @@ Expects ethereum node to be running and requires a .toml config:
|
|||||||
ipcPath = "/Users/user/Library/Ethereum/geth.ipc"
|
ipcPath = "/Users/user/Library/Ethereum/geth.ipc"
|
||||||
`,
|
`,
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
sync()
|
fullSync()
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
rootCmd.AddCommand(syncCmd)
|
rootCmd.AddCommand(fullSyncCmd)
|
||||||
|
|
||||||
syncCmd.Flags().Int64VarP(&startingBlockNumber, "starting-block-number", "s", 0, "Block number to start syncing from")
|
fullSyncCmd.Flags().Int64VarP(&startingBlockNumber, "starting-block-number", "s", 0, "Block number to start syncing from")
|
||||||
}
|
}
|
||||||
|
|
||||||
func backFillAllBlocks(blockchain core.BlockChain, blockRepository datastore.BlockRepository, missingBlocksPopulated chan int, startingBlockNumber int64) {
|
func backFillAllBlocks(blockchain core.BlockChain, blockRepository datastore.BlockRepository, missingBlocksPopulated chan int, startingBlockNumber int64) {
|
||||||
@@ -67,20 +67,20 @@ func backFillAllBlocks(blockchain core.BlockChain, blockRepository datastore.Blo
|
|||||||
missingBlocksPopulated <- populated
|
missingBlocksPopulated <- populated
|
||||||
}
|
}
|
||||||
|
|
||||||
func sync() {
|
func fullSync() {
|
||||||
ticker := time.NewTicker(pollingInterval)
|
ticker := time.NewTicker(pollingInterval)
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
|
|
||||||
blockChain := getBlockChain()
|
blockChain := getBlockChain()
|
||||||
lastBlock, err := blockChain.LastBlock()
|
lastBlock, err := blockChain.LastBlock()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("sync: Error getting last block: ", err)
|
log.Error("fullSync: Error getting last block: ", err)
|
||||||
}
|
}
|
||||||
if lastBlock.Int64() == 0 {
|
if lastBlock.Int64() == 0 {
|
||||||
log.Fatal("geth initial: state sync not finished")
|
log.Fatal("geth initial: state sync not finished")
|
||||||
}
|
}
|
||||||
if startingBlockNumber > lastBlock.Int64() {
|
if startingBlockNumber > lastBlock.Int64() {
|
||||||
log.Fatal("sync: starting block number > current block number")
|
log.Fatal("fullSync: starting block number > current block number")
|
||||||
}
|
}
|
||||||
|
|
||||||
db := utils.LoadPostgres(databaseConfig, blockChain.Node())
|
db := utils.LoadPostgres(databaseConfig, blockChain.Node())
|
||||||
@@ -94,7 +94,7 @@ func sync() {
|
|||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
window, err := validator.ValidateBlocks()
|
window, err := validator.ValidateBlocks()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("sync: error in validateBlocks: ", err)
|
log.Error("fullSync: error in validateBlocks: ", err)
|
||||||
}
|
}
|
||||||
log.Info(window.GetString())
|
log.Info(window.GetString())
|
||||||
case <-missingBlocksPopulated:
|
case <-missingBlocksPopulated:
|
||||||
@@ -5,7 +5,8 @@ CREATE TABLE public.queued_storage (
|
|||||||
block_hash BYTEA,
|
block_hash BYTEA,
|
||||||
contract BYTEA,
|
contract BYTEA,
|
||||||
storage_key BYTEA,
|
storage_key BYTEA,
|
||||||
storage_value BYTEA
|
storage_value BYTEA,
|
||||||
|
UNIQUE (block_height, block_hash, contract, storage_key, storage_value)
|
||||||
);
|
);
|
||||||
|
|
||||||
-- +goose Down
|
-- +goose Down
|
||||||
|
|||||||
+11
-16
@@ -2,8 +2,8 @@
|
|||||||
-- PostgreSQL database dump
|
-- PostgreSQL database dump
|
||||||
--
|
--
|
||||||
|
|
||||||
-- Dumped from database version 10.6
|
-- Dumped from database version 11.3
|
||||||
-- Dumped by pg_dump version 10.6
|
-- Dumped by pg_dump version 11.3
|
||||||
|
|
||||||
SET statement_timeout = 0;
|
SET statement_timeout = 0;
|
||||||
SET lock_timeout = 0;
|
SET lock_timeout = 0;
|
||||||
@@ -12,23 +12,10 @@ SET client_encoding = 'UTF8';
|
|||||||
SET standard_conforming_strings = on;
|
SET standard_conforming_strings = on;
|
||||||
SELECT pg_catalog.set_config('search_path', '', false);
|
SELECT pg_catalog.set_config('search_path', '', false);
|
||||||
SET check_function_bodies = false;
|
SET check_function_bodies = false;
|
||||||
|
SET xmloption = content;
|
||||||
SET client_min_messages = warning;
|
SET client_min_messages = warning;
|
||||||
SET row_security = off;
|
SET row_security = off;
|
||||||
|
|
||||||
--
|
|
||||||
-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner: -
|
|
||||||
--
|
|
||||||
|
|
||||||
CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
|
|
||||||
|
|
||||||
|
|
||||||
--
|
|
||||||
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: -
|
|
||||||
--
|
|
||||||
|
|
||||||
COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
|
|
||||||
|
|
||||||
|
|
||||||
SET default_tablespace = '';
|
SET default_tablespace = '';
|
||||||
|
|
||||||
SET default_with_oids = false;
|
SET default_with_oids = false;
|
||||||
@@ -803,6 +790,14 @@ ALTER TABLE ONLY public.eth_nodes
|
|||||||
ADD CONSTRAINT nodes_pkey PRIMARY KEY (id);
|
ADD CONSTRAINT nodes_pkey PRIMARY KEY (id);
|
||||||
|
|
||||||
|
|
||||||
|
--
|
||||||
|
-- Name: queued_storage queued_storage_block_height_block_hash_contract_storage_key_key; Type: CONSTRAINT; Schema: public; Owner: -
|
||||||
|
--
|
||||||
|
|
||||||
|
ALTER TABLE ONLY public.queued_storage
|
||||||
|
ADD CONSTRAINT queued_storage_block_height_block_hash_contract_storage_key_key UNIQUE (block_height, block_hash, contract, storage_key, storage_value);
|
||||||
|
|
||||||
|
|
||||||
--
|
--
|
||||||
-- Name: queued_storage queued_storage_pkey; Type: CONSTRAINT; Schema: public; Owner: -
|
-- Name: queued_storage queued_storage_pkey; Type: CONSTRAINT; Schema: public; Owner: -
|
||||||
--
|
--
|
||||||
|
|||||||
@@ -1,11 +1,50 @@
|
|||||||
# Contribution guidelines
|
# Contribution guidelines
|
||||||
|
|
||||||
Contributions are welcome! In addition to core contributions, developers are encouraged to build their own custom transformers which
|
Contributions are welcome! Please open an Issues or Pull Request for any changes.
|
||||||
can be run together with other custom transformers using the [composeAndExeucte](../../staging/documentation/composeAndExecute.md) command.
|
|
||||||
|
In addition to core contributions, developers are encouraged to build their own custom transformers which
|
||||||
|
can be run together with other custom transformers using the [composeAndExecute](../../staging/documentation/custom-transformers.md) command.
|
||||||
|
|
||||||
|
## Pull Requests
|
||||||
|
- `go fmt` is run as part of `make test` and `make integrationtest`, please make sure to check in the format changes.
|
||||||
|
- Ensure that new code is well tested, including integration testing if applicable.
|
||||||
|
- Make sure the build is passing.
|
||||||
|
- Update the README or any [documentation files](./) as necessary. If editing the Readme, please
|
||||||
|
conform to the
|
||||||
|
[standard-readme specification](https://github.com/RichardLitt/standard-readme).
|
||||||
|
- Once a Pull Request has received two approvals it can be merged in by a core developer.
|
||||||
|
|
||||||
## Creating a new migration file
|
## Creating a new migration file
|
||||||
1. `make new_migration NAME=add_columnA_to_table1`
|
1. `make new_migration NAME=add_columnA_to_table1`
|
||||||
- This will create a new timestamped migration file in `db/migrations`
|
- This will create a new timestamped migration file in `db/migrations`
|
||||||
1. Write the migration code in the created file, under the respective `goose` pragma
|
1. Write the migration code in the created file, under the respective `goose` pragma
|
||||||
- Goose automatically runs each migration in a transaction; don't add `BEGIN` and `COMMIT` statements.
|
- Goose automatically runs each migration in a transaction; don't add `BEGIN` and `COMMIT` statements.
|
||||||
1. Core migrations should be committed in their `goose fix`ed form.
|
1. Core migrations should be committed in their `goose fix`ed form. To do this, run `make version_migrations` which
|
||||||
|
converts timestamped migrations to migrations versioned by an incremented integer.
|
||||||
|
|
||||||
|
## Diagrams
|
||||||
|
- Diagrams were created with [draw.io](https://www.draw.io).
|
||||||
|
- To update a diagram:
|
||||||
|
1. Go to [draw.io](https://www.draw.io).
|
||||||
|
1. Click on *File > Open from* and choose the location of the diagram you want to update.
|
||||||
|
1. Once open in draw.io, you may update it.
|
||||||
|
1. Export the diagram to this repository's directory and commit it.
|
||||||
|
|
||||||
|
|
||||||
|
## Generating the Changelog
|
||||||
|
We use [github-changelog-generator](https://github.com/github-changelog-generator/github-changelog-generator) to generate release Changelogs. To be consistent with previous Changelogs, the following flags should be passed to the command:
|
||||||
|
|
||||||
|
```
|
||||||
|
--user vulcanize
|
||||||
|
--project vulcanizedb
|
||||||
|
--token {YOUR_GITHUB_TOKEN}
|
||||||
|
--no-issues
|
||||||
|
--usernames-as-github-logins
|
||||||
|
--since-tag {PREVIOUS_RELEASE_TAG}
|
||||||
|
```
|
||||||
|
|
||||||
|
For more information on why your github token is needed, and how to generate it see [https://github
|
||||||
|
.com/github-changelog-generator/github-changelog-generator#github-token](https://github.com/github-changelog-generator/github-changelog-generator#github-token).
|
||||||
|
|
||||||
|
## Code of Conduct
|
||||||
|
VulcanizeDB follows the [Contributor Covenant Code of Conduct](https://www.contributor-covenant.org/version/1/4/code-of-conduct).
|
||||||
|
|||||||
@@ -1,44 +1,80 @@
|
|||||||
# composeAndExecute
|
# Custom Transformers
|
||||||
The `composeAndExecute` command is used to compose and execute over an arbitrary set of custom transformers.
|
When the capabilities of the generic `contractWatcher` are not sufficient, custom transformers tailored to a specific
|
||||||
This is accomplished by generating a Go pluggin which allows the `vulcanizedb` binary to link to external transformers, so
|
purpose can be leveraged.
|
||||||
long as they abide by one of the standard [interfaces](../staging/libraries/shared/transformer).
|
|
||||||
|
|
||||||
Additionally, there are separate `compose` and `execute` commands to allow pre-building and linking to a pre-built .so file.
|
Individual custom transformers can be composed together from any number of external repositories and executed as a
|
||||||
|
single process using the `compose` and `execute` commands or the `composeAndExecute` command. This is accomplished by
|
||||||
|
generating a Go plugin which allows the `vulcanizedb` binary to link to the external transformers, so long as they
|
||||||
|
abide by one of the standard [interfaces](../staging/libraries/shared/transformer).
|
||||||
|
|
||||||
**NOTE:**
|
## Writing custom transformers
|
||||||
1. It is necessary that the .so file was built with the same exact dependencies that are present in the execution environment,
|
For help with writing different types of custom transformers please see below:
|
||||||
i.e. we need to `compose` and `execute` the plugin .so file with the same exact version of vulcanizeDB.
|
|
||||||
1. The plugin migrations are run during the plugin's composition. As such, if `execute` is used to run a prebuilt .so in a different
|
|
||||||
environment than the one it was composed in then the migrations for that plugin will first need to be manually ran against that environment's Postgres database.
|
|
||||||
|
|
||||||
These commands require Go 1.11+ and use [Go plugins](https://golang.org/pkg/plugin/) which only work on Unix-based systems.
|
Storage Transformers: transform data derived from contract storage tries
|
||||||
There is also an ongoing [conflict](https://github.com/golang/go/issues/20481) between Go plugins and the use vendored dependencies which
|
* [Guide](../../staging/libraries/shared/factories/storage/README.md)
|
||||||
imposes certain limitations on how the plugins are built.
|
* [Example](../../staging/libraries/shared/factories/storage/EXAMPLE.md)
|
||||||
|
|
||||||
## Commands
|
Event Transformers: transform data derived from Ethereum log events
|
||||||
The `compose` and `composeAndExecute` commands assume you are in the vulcanizdb directory located at your system's `$GOPATH`,
|
* [Guide](../../staging/libraries/shared/factories/event/README.md)
|
||||||
and that all of the transformer repositories for building the plugin are present at their `$GOPATH` directories.
|
* [Example 1](https://github.com/vulcanize/ens_transformers/tree/master/transformers/registar)
|
||||||
|
* [Example 2](https://github.com/vulcanize/ens_transformers/tree/master/transformers/registry)
|
||||||
|
* [Example 3](https://github.com/vulcanize/ens_transformers/tree/master/transformers/resolver)
|
||||||
|
|
||||||
The `execute` command does not require the plugin transformer dependencies be located in their
|
Contract Transformers: transform data derived from Ethereum log events and use it to poll public contract methods
|
||||||
`$GOPATH` directories, instead it expects a prebuilt .so file (of the name specified in the config file)
|
* [Example 1](https://github.com/vulcanize/account_transformers)
|
||||||
to be in `$GOPATH/src/github.com/vulcanize/vulcanizedb/plugins/` and, as noted above, also expects the plugin
|
* [Example 2](https://github.com/vulcanize/ens_transformers/tree/master/transformers/domain_records)
|
||||||
db migrations to have already been ran against the database.
|
|
||||||
|
|
||||||
compose:
|
## Preparing custom transformers to work as part of a plugin
|
||||||
|
To plug in an external transformer we need to:
|
||||||
|
|
||||||
`./vulcanizedb compose --config=./environments/config_name.toml`
|
1. Create a package that exports a variable `TransformerInitializer`, `StorageTransformerInitializer`, or `ContractTransformerInitializer` that are of type [TransformerInitializer](../staging/libraries/shared/transformer/event_transformer.go#L33)
|
||||||
|
or [StorageTransformerInitializer](../../staging/libraries/shared/transformer/storage_transformer.go#L31),
|
||||||
|
or [ContractTransformerInitializer](../../staging/libraries/shared/transformer/contract_transformer.go#L31), respectively
|
||||||
|
2. Design the transformers to work in the context of their [event](../staging/libraries/shared/watcher/event_watcher.go#L83),
|
||||||
|
[storage](../../staging/libraries/shared/watcher/storage_watcher.go#L53),
|
||||||
|
or [contract](../../staging/libraries/shared/watcher/contract_watcher.go#L68) watcher execution modes
|
||||||
|
3. Create db migrations to run against vulcanizeDB so that we can store the transformer output
|
||||||
|
* Do not `goose fix` the transformer migrations, this is to ensure they are always ran after the core vulcanizedb migrations which are kept in their fixed form
|
||||||
|
* Specify migration locations for each transformer in the config with the `exporter.transformer.migrations` fields
|
||||||
|
* If the base vDB migrations occupy this path as well, they need to be in their `goose fix`ed form
|
||||||
|
as they are [here](../../staging/db/migrations)
|
||||||
|
|
||||||
execute:
|
To update a plugin repository with changes to the core vulcanizedb repository, run `dep ensure` to update its dependencies.
|
||||||
|
|
||||||
`./vulcanizedb execute --config=./environments/config_name.toml`
|
## Building and Running Custom Transformers
|
||||||
|
### Commands
|
||||||
|
* The `compose`, `execute`, `composeAndExecute` commands require Go 1.11+ and use [Go plugins](https://golang
|
||||||
|
.org/pkg/plugin/) which only work on Unix-based systems.
|
||||||
|
|
||||||
composeAndExecute:
|
* There is an ongoing [conflict](https://github.com/golang/go/issues/20481) between Go plugins and the use of vendored
|
||||||
|
dependencies which imposes certain limitations on how the plugins are built.
|
||||||
|
|
||||||
`./vulcanizedb composeAndExecute --config=./environments/config_name.toml`
|
* Separate `compose` and `execute` commands allow pre-building and linking to the pre-built .so file. So, if
|
||||||
|
these are run independently, instead of using `composeAndExecute`, a couple of things need to be considered:
|
||||||
|
* It is necessary that the .so file was built with the same exact dependencies that are present in the execution
|
||||||
|
environment, i.e. we need to `compose` and `execute` the plugin .so file with the same exact version of vulcanizeDB.
|
||||||
|
* The plugin migrations are run during the plugin's composition. As such, if `execute` is used to run a prebuilt .so
|
||||||
|
in a different environment than the one it was composed in, then the database structure will need to be loaded
|
||||||
|
into the environment's Postgres database. This can either be done by manually loading the plugin's schema into
|
||||||
|
Postgres, or by manually running the plugin's migrations.
|
||||||
|
|
||||||
|
* The `compose` and `composeAndExecute` commands assume you are in the vulcanizdb directory located at your system's
|
||||||
|
`$GOPATH`, and that the plugin dependencies are present at their `$GOPATH` directories.
|
||||||
|
|
||||||
## Flags
|
* The `execute` command does not require the plugin transformer dependencies be located in their `$GOPATH` directories,
|
||||||
|
instead it expects a .so file (of the name specified in the config file) to be in
|
||||||
|
`$GOPATH/src/github.com/vulcanize/vulcanizedb/plugins/` and, as noted above, also expects the plugin db migrations to
|
||||||
|
have already been ran against the database.
|
||||||
|
|
||||||
The `compose` and `composeAndExecute` commands can be passed optional flags to specify the operation of the watchers:
|
* Usage:
|
||||||
|
* compose: `./vulcanizedb compose --config=environments/config_name.toml`
|
||||||
|
|
||||||
|
* execute: `./vulcanizedb execute --config=environments/config_name.toml`
|
||||||
|
|
||||||
|
* composeAndExecute: `./vulcanizedb composeAndExecute --config=environments/config_name.toml`
|
||||||
|
|
||||||
|
### Flags
|
||||||
|
The `execute` and `composeAndExecute` commands can be passed optional flags to specify the operation of the watchers:
|
||||||
|
|
||||||
- `--recheck-headers`/`-r` - specifies whether to re-check headers for events after the header has already been queried for watched logs.
|
- `--recheck-headers`/`-r` - specifies whether to re-check headers for events after the header has already been queried for watched logs.
|
||||||
Can be useful for redundancy if you suspect that your node is not always returning all desired logs on every query.
|
Can be useful for redundancy if you suspect that your node is not always returning all desired logs on every query.
|
||||||
@@ -50,7 +86,7 @@ Defaults to `false`.
|
|||||||
Argument is expected to be a duration (integer measured in nanoseconds): e.g. `-q=10m30s` (for 10 minute, 30 second intervals).
|
Argument is expected to be a duration (integer measured in nanoseconds): e.g. `-q=10m30s` (for 10 minute, 30 second intervals).
|
||||||
Defaults to `5m` (5 minutes).
|
Defaults to `5m` (5 minutes).
|
||||||
|
|
||||||
## Configuration
|
### Configuration
|
||||||
A .toml config file is specified when executing the commands.
|
A .toml config file is specified when executing the commands.
|
||||||
The config provides information for composing a set of transformers from external repositories:
|
The config provides information for composing a set of transformers from external repositories:
|
||||||
|
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
# Syncing commands
|
||||||
|
These commands are used to sync raw Ethereum data into Postgres, with varying levels of data granularity.
|
||||||
|
|
||||||
|
## headerSync
|
||||||
|
Syncs block headers from a running Ethereum node into the VulcanizeDB table `headers`.
|
||||||
|
- Queries the Ethereum node using RPC calls.
|
||||||
|
- Validates headers from the last 15 blocks to ensure that data is up to date.
|
||||||
|
- Useful when you want a minimal baseline from which to track targeted data on the blockchain (e.g. individual smart
|
||||||
|
contract storage values or event logs).
|
||||||
|
- Handles chain reorgs by [validating the most recent blocks' hashes](../pkg/history/header_validator.go). If the hash is
|
||||||
|
different from what we have already stored in the database, the header record will be updated.
|
||||||
|
|
||||||
|
#### Usage
|
||||||
|
- Run: `./vulcanizedb headerSync --config <config.toml> --starting-block-number <block-number>`
|
||||||
|
- The config file must be formatted as follows, and should contain an ipc path to a running Ethereum node:
|
||||||
|
```toml
|
||||||
|
[database]
|
||||||
|
name = "vulcanize_public"
|
||||||
|
hostname = "localhost"
|
||||||
|
user = "vulcanize"
|
||||||
|
password = "vulcanize"
|
||||||
|
port = 5432
|
||||||
|
|
||||||
|
[client]
|
||||||
|
ipcPath = <path to a running Ethereum node>
|
||||||
|
```
|
||||||
|
- Alternatively, the ipc path can be passed as a flag instead `--client-ipcPath`.
|
||||||
|
|
||||||
|
## fullSync
|
||||||
|
Syncs blocks, transactions, receipts and logs from a running Ethereum node into VulcanizeDB tables named
|
||||||
|
`blocks`, `uncles`, `full_sync_transactions`, `full_sync_receipts` and `logs`.
|
||||||
|
- Queries the Ethereum node using RPC calls.
|
||||||
|
- Validates headers from the last 15 blocks to ensure that data is up to date.
|
||||||
|
- Useful when you want to maintain a broad cache of what's happening on the blockchain.
|
||||||
|
- Handles chain reorgs by [validating the most recent blocks' hashes](../pkg/history/header_validator.go). If the hash is
|
||||||
|
different from what we have already stored in the database, the header record will be updated.
|
||||||
|
|
||||||
|
#### Usage
|
||||||
|
- Run `./vulcanizedb fullSync --config <config.toml> --starting-block-number <block-number>`
|
||||||
|
- The config file must be formatted as follows, and should contain an ipc path to a running Ethereum node:
|
||||||
|
```toml
|
||||||
|
[database]
|
||||||
|
name = "vulcanize_public"
|
||||||
|
hostname = "localhost"
|
||||||
|
user = "vulcanize"
|
||||||
|
password = "vulcanize"
|
||||||
|
port = 5432
|
||||||
|
|
||||||
|
[client]
|
||||||
|
ipcPath = <path to a running Ethereum node>
|
||||||
|
```
|
||||||
|
- Alternatively, the ipc path can be passed as a flag instead `--client-ipcPath`.
|
||||||
|
|
||||||
|
*Please note, that if you are fast syncing your Ethereum node, wait for the initial sync to finish.*
|
||||||
|
|
||||||
|
## coldImport
|
||||||
|
Syncs VulcanizeDB from Geth's underlying LevelDB datastore and persists Ethereum blocks,
|
||||||
|
transactions, receipts and logs into VulcanizeDB tables named `blocks`, `uncles`,
|
||||||
|
`full_sync_transactions`, `full_sync_receipts` and `logs` respectively.
|
||||||
|
|
||||||
|
#### Usage
|
||||||
|
1. Ensure the Ethereum node you're point at is not running, and that it has synced to the desired block height.
|
||||||
|
1. Run `./vulcanizedb coldImport --config <config.toml>`
|
||||||
|
1. Optional flags:
|
||||||
|
- `--starting-block-number <block number>`/`-s <block number>`: block number to start syncing from
|
||||||
|
- `--ending-block-number <block number>`/`-e <block number>`: block number to sync to
|
||||||
|
- `--all`/`-a`: sync all missing blocks
|
||||||
|
|
||||||
|
The config file can be formatted as follows, and must contain the LevelDB path.
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[database]
|
||||||
|
name = "vulcanize_public"
|
||||||
|
hostname = "localhost"
|
||||||
|
user = "vulcanize"
|
||||||
|
password = "vulcanize"
|
||||||
|
port = 5432
|
||||||
|
|
||||||
|
[client]
|
||||||
|
leveldbpath = "/Users/user/Library/Ethereum/geth/chaindata"
|
||||||
|
```
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 52 KiB |
@@ -1,4 +1,4 @@
|
|||||||
# contractWatcher
|
# Generic Transformer
|
||||||
The `contractWatcher` command is a built-in generic contract watcher. It can watch any and all events for a given contract provided the contract's ABI is available.
|
The `contractWatcher` command is a built-in generic contract watcher. It can watch any and all events for a given contract provided the contract's ABI is available.
|
||||||
It also provides some state variable coverage by automating polling of public methods, with some restrictions:
|
It also provides some state variable coverage by automating polling of public methods, with some restrictions:
|
||||||
1. The method must have 2 or less arguments
|
1. The method must have 2 or less arguments
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# Postgraphile
|
||||||
|
|
||||||
|
You can expose VulcanizeDB data via [Postgraphile](https://github.com/graphile/postgraphile).
|
||||||
|
Check out [their documentation](https://www.graphile.org/postgraphile/) for the most up-to-date instructions on installing, running, and customizing Postgraphile.
|
||||||
|
|
||||||
|
## Simple Setup
|
||||||
|
|
||||||
|
As of April 30, 2019, you can run Postgraphile pointed at the default `vulcanize_public` database with the following commands:
|
||||||
|
|
||||||
|
```
|
||||||
|
npm install -g postgraphile
|
||||||
|
postgraphile --connection postgres://localhost/vulcanize_public --schema=public,custom --disable-default-mutations --no-ignore-rbac
|
||||||
|
```
|
||||||
|
|
||||||
|
Arguments:
|
||||||
|
- `--connection` specifies the database. The above command connects to the default `vulcanize_public` database
|
||||||
|
defined in [the example config](../environments/public.toml.example).
|
||||||
|
- `--schema` defines what schema(s) to expose. The above exposes the `public` schema (for core VulcanizeDB data) as well as a `custom` schema (where `custom` is the name of a schema defined in executed transformers).
|
||||||
|
- `--disable-default-mutations` prevents Postgraphile from exposing create, update, and delete operations on your data, which are otherwise enabled by default.
|
||||||
|
- `--no-ignore-rbac` ensures that Postgraphile will only expose the tables, columns, fields, and query functions that the user has explicit access to.
|
||||||
|
|
||||||
|
## Customizing Postgraphile
|
||||||
|
|
||||||
|
By default, Postgraphile will expose queries for all tables defined in your chosen database/schema(s), including [filtering](https://www.graphile.org/postgraphile/filtering/) and [auto-discovered relations](https://www.graphile.org/postgraphile/relations/).
|
||||||
|
|
||||||
|
If you'd like to expose more customized windows into your data, there are some techniques you can apply when writing migrations:
|
||||||
|
|
||||||
|
- [Computed columns](https://www.graphile.org/postgraphile/computed-columns/) enable you to derive additional fields from types defined in your database.
|
||||||
|
For example, you could write a function to expose a block header's state root over Postgraphile with a computed column - without modifying the `public.headers` table.
|
||||||
|
- [Custom queries](https://www.graphile.org/postgraphile/custom-queries/) enable you to provide on-demand access to more complex data (e.g. the product of joining and filtering several tables' data based on a passed argument).
|
||||||
|
For example, you could write a custom query to get the block timestamp for every transaction originating from a given address.
|
||||||
|
- [Subscriptions](https://www.graphile.org/postgraphile/subscriptions/) enable you to publish data as it is coming into your database.
|
||||||
|
|
||||||
|
The above list is not exhaustive - please see the Postgraphile documentation for a more comprehensive and up-to-date description of available features.
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# Repository Maintenance
|
||||||
|
|
||||||
|
## Diagrams
|
||||||
|
- Diagrams were created with [draw.io](draw.io).
|
||||||
|
- To update a diagram:
|
||||||
|
1. Go to [draw.io](draw.io).
|
||||||
|
1. Click on *File > Open from* and choose the location of the diagram you want to update.
|
||||||
|
1. Once open in draw.io, you may update it.
|
||||||
|
1. Export the diagram to this repository's directory and add commit it.
|
||||||
|
|
||||||
|
|
||||||
|
## Generating the Changelog
|
||||||
|
We use [github-changelog-generator](https://github.com/github-changelog-generator/github-changelog-generator) to
|
||||||
|
generate release Changelogs. To be consistent with previous Changelogs, the following flags should be passed to the
|
||||||
|
command:
|
||||||
|
|
||||||
|
```
|
||||||
|
--user vulcanize
|
||||||
|
--project vulcanizedb
|
||||||
|
--token {YOUR_GITHUB_TOKEN}
|
||||||
|
--no-issues
|
||||||
|
--usernames-as-github-logins
|
||||||
|
--since-tag {PREVIOUS_RELEASE_TAG}
|
||||||
|
```
|
||||||
|
|
||||||
|
More information on why your github token is needed, and how to generate it here:
|
||||||
|
https://github.com/github-changelog-generator/github-changelog-generator#github-token
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
# Syncing commands
|
|
||||||
These commands are used to sync raw Ethereum data into Postgres.
|
|
||||||
|
|
||||||
## headerSync
|
|
||||||
Syncs VulcanizeDB with the configured Ethereum node, populating only block headers.
|
|
||||||
This command is useful when you want a minimal baseline from which to track targeted data on the blockchain (e.g. individual smart contract storage values or event logs).
|
|
||||||
1. Start Ethereum node
|
|
||||||
1. In a separate terminal start VulcanizeDB:
|
|
||||||
- `./vulcanizedb headerSync --config <config.toml> --starting-block-number <block-number>`
|
|
||||||
|
|
||||||
## sync
|
|
||||||
Syncs VulcanizeDB with the configured Ethereum node, populating blocks, transactions, receipts, and logs.
|
|
||||||
This command is useful when you want to maintain a broad cache of what's happening on the blockchain.
|
|
||||||
1. Start Ethereum node (**if fast syncing your Ethereum node, wait for initial sync to finish**)
|
|
||||||
1. In a separate terminal start VulcanizeDB:
|
|
||||||
- `./vulcanizedb sync --config <config.toml> --starting-block-number <block-number>`
|
|
||||||
|
|
||||||
## coldImport
|
|
||||||
Sync VulcanizeDB from the LevelDB underlying a Geth node.
|
|
||||||
1. Assure node is not running, and that it has synced to the desired block height.
|
|
||||||
1. Start vulcanize_db
|
|
||||||
- `./vulcanizedb coldImport --config <config.toml>`
|
|
||||||
1. Optional flags:
|
|
||||||
- `--starting-block-number <block number>`/`-s <block number>`: block number to start syncing from
|
|
||||||
- `--ending-block-number <block number>`/`-e <block number>`: block number to sync to
|
|
||||||
- `--all`/`-a`: sync all missing blocks
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
# Custom transformers
|
|
||||||
When the capabilities of the generic `contractWatcher` are not sufficient, custom transformers tailored to a specific
|
|
||||||
purpose can be leveraged.
|
|
||||||
|
|
||||||
Individual transformers can be composed together from any number of external repositories and executed as a single process using
|
|
||||||
the `compose` and `execute` commands or the `composeAndExecute` command.
|
|
||||||
|
|
||||||
## Writing custom transformers
|
|
||||||
For help with writing different types of custom transformers for the `composeAndExecute` set of commands, please see the below:
|
|
||||||
|
|
||||||
Storage Transformers
|
|
||||||
* [Guide](../../staging/libraries/shared/factories/storage/README.md)
|
|
||||||
* [Example](../../staging/libraries/shared/factories/storage/EXAMPLE.md)
|
|
||||||
|
|
||||||
Event Transformers
|
|
||||||
* [Guide](../../staging/libraries/shared/factories/event/README.md)
|
|
||||||
* [Example 1](https://github.com/vulcanize/ens_transformers/tree/master/transformers/registar)
|
|
||||||
* [Example 2](https://github.com/vulcanize/ens_transformers/tree/master/transformers/registry)
|
|
||||||
* [Example 3](https://github.com/vulcanize/ens_transformers/tree/master/transformers/resolver)
|
|
||||||
|
|
||||||
Contract Transformers
|
|
||||||
* [Example 1](https://github.com/vulcanize/account_transformers)
|
|
||||||
* [Example 2](https://github.com/vulcanize/ens_transformers/tree/master/transformers/domain_records)
|
|
||||||
|
|
||||||
## Preparing custom transformers to work as part of a plugin
|
|
||||||
To plug in an external transformer we need to:
|
|
||||||
|
|
||||||
1. Create a package that exports a variable `TransformerInitializer`, `StorageTransformerInitializer`, or `ContractTransformerInitializer` that are of type [TransformerInitializer](../staging/libraries/shared/transformer/event_transformer.go#L33)
|
|
||||||
or [StorageTransformerInitializer](../../staging/libraries/shared/transformer/storage_transformer.go#L31),
|
|
||||||
or [ContractTransformerInitializer](../../staging/libraries/shared/transformer/contract_transformer.go#L31), respectively
|
|
||||||
2. Design the transformers to work in the context of their [event](../staging/libraries/shared/watcher/event_watcher.go#L83),
|
|
||||||
[storage](../../staging/libraries/shared/watcher/storage_watcher.go#L53),
|
|
||||||
or [contract](../../staging/libraries/shared/watcher/contract_watcher.go#L68) watcher execution modes
|
|
||||||
3. Create db migrations to run against vulcanizeDB so that we can store the transformer output
|
|
||||||
* Do not `goose fix` the transformer migrations, this is to ensure they are always ran after the core vulcanizedb migrations which are kept in their fixed form
|
|
||||||
* Specify migration locations for each transformer in the config with the `exporter.transformer.migrations` fields
|
|
||||||
* If the base vDB migrations occupy this path as well, they need to be in their `goose fix`ed form
|
|
||||||
as they are [here](../../staging/db/migrations)
|
|
||||||
|
|
||||||
To update a plugin repository with changes to the core vulcanizedb repository, run `dep ensure` to update its dependencies.
|
|
||||||
@@ -17,14 +17,11 @@
|
|||||||
package event
|
package event
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/vulcanize/vulcanizedb/pkg/core"
|
|
||||||
"github.com/vulcanize/vulcanizedb/pkg/datastore/postgres"
|
"github.com/vulcanize/vulcanizedb/pkg/datastore/postgres"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Repository interface {
|
type Repository interface {
|
||||||
Create(headerID int64, models []interface{}) error
|
Create(headerID int64, models []interface{}) error
|
||||||
MarkHeaderChecked(headerID int64) error
|
MarkHeaderChecked(headerID int64) error
|
||||||
MissingHeaders(startingBlockNumber, endingBlockNumber int64) ([]core.Header, error)
|
|
||||||
RecheckHeaders(startingBlockNumber, endingBlockNUmber int64) ([]core.Header, error)
|
|
||||||
SetDB(db *postgres.DB)
|
SetDB(db *postgres.DB)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ import (
|
|||||||
"github.com/ethereum/go-ethereum/core/types"
|
"github.com/ethereum/go-ethereum/core/types"
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
|
|
||||||
"github.com/vulcanize/vulcanizedb/libraries/shared/constants"
|
|
||||||
"github.com/vulcanize/vulcanizedb/libraries/shared/transformer"
|
"github.com/vulcanize/vulcanizedb/libraries/shared/transformer"
|
||||||
"github.com/vulcanize/vulcanizedb/pkg/core"
|
"github.com/vulcanize/vulcanizedb/pkg/core"
|
||||||
"github.com/vulcanize/vulcanizedb/pkg/datastore/postgres"
|
"github.com/vulcanize/vulcanizedb/pkg/datastore/postgres"
|
||||||
@@ -37,7 +36,7 @@ func (transformer Transformer) NewTransformer(db *postgres.DB) transformer.Event
|
|||||||
return transformer
|
return transformer
|
||||||
}
|
}
|
||||||
|
|
||||||
func (transformer Transformer) Execute(logs []types.Log, header core.Header, recheckHeaders constants.TransformerExecution) error {
|
func (transformer Transformer) Execute(logs []types.Log, header core.Header) error {
|
||||||
transformerName := transformer.Config.TransformerName
|
transformerName := transformer.Config.TransformerName
|
||||||
config := transformer.Config
|
config := transformer.Config
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ import (
|
|||||||
. "github.com/onsi/ginkgo"
|
. "github.com/onsi/ginkgo"
|
||||||
. "github.com/onsi/gomega"
|
. "github.com/onsi/gomega"
|
||||||
|
|
||||||
"github.com/vulcanize/vulcanizedb/libraries/shared/constants"
|
|
||||||
"github.com/vulcanize/vulcanizedb/libraries/shared/factories/event"
|
"github.com/vulcanize/vulcanizedb/libraries/shared/factories/event"
|
||||||
"github.com/vulcanize/vulcanizedb/libraries/shared/mocks"
|
"github.com/vulcanize/vulcanizedb/libraries/shared/mocks"
|
||||||
"github.com/vulcanize/vulcanizedb/libraries/shared/test_data"
|
"github.com/vulcanize/vulcanizedb/libraries/shared/test_data"
|
||||||
@@ -60,14 +59,14 @@ var _ = Describe("Transformer", func() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
It("marks header checked if no logs returned", func() {
|
It("marks header checked if no logs returned", func() {
|
||||||
err := t.Execute([]types.Log{}, headerOne, constants.HeaderMissing)
|
err := t.Execute([]types.Log{}, headerOne)
|
||||||
|
|
||||||
Expect(err).NotTo(HaveOccurred())
|
Expect(err).NotTo(HaveOccurred())
|
||||||
repository.AssertMarkHeaderCheckedCalledWith(headerOne.Id)
|
repository.AssertMarkHeaderCheckedCalledWith(headerOne.Id)
|
||||||
})
|
})
|
||||||
|
|
||||||
It("doesn't attempt to convert or persist an empty collection when there are no logs", func() {
|
It("doesn't attempt to convert or persist an empty collection when there are no logs", func() {
|
||||||
err := t.Execute([]types.Log{}, headerOne, constants.HeaderMissing)
|
err := t.Execute([]types.Log{}, headerOne)
|
||||||
|
|
||||||
Expect(err).NotTo(HaveOccurred())
|
Expect(err).NotTo(HaveOccurred())
|
||||||
Expect(converter.ToEntitiesCalledCounter).To(Equal(0))
|
Expect(converter.ToEntitiesCalledCounter).To(Equal(0))
|
||||||
@@ -76,7 +75,7 @@ var _ = Describe("Transformer", func() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
It("does not call repository.MarkCheckedHeader when there are logs", func() {
|
It("does not call repository.MarkCheckedHeader when there are logs", func() {
|
||||||
err := t.Execute(logs, headerOne, constants.HeaderMissing)
|
err := t.Execute(logs, headerOne)
|
||||||
|
|
||||||
Expect(err).NotTo(HaveOccurred())
|
Expect(err).NotTo(HaveOccurred())
|
||||||
repository.AssertMarkHeaderCheckedNotCalled()
|
repository.AssertMarkHeaderCheckedNotCalled()
|
||||||
@@ -85,14 +84,14 @@ var _ = Describe("Transformer", func() {
|
|||||||
It("returns error if marking header checked returns err", func() {
|
It("returns error if marking header checked returns err", func() {
|
||||||
repository.SetMarkHeaderCheckedError(fakes.FakeError)
|
repository.SetMarkHeaderCheckedError(fakes.FakeError)
|
||||||
|
|
||||||
err := t.Execute([]types.Log{}, headerOne, constants.HeaderMissing)
|
err := t.Execute([]types.Log{}, headerOne)
|
||||||
|
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
Expect(err).To(MatchError(fakes.FakeError))
|
Expect(err).To(MatchError(fakes.FakeError))
|
||||||
})
|
})
|
||||||
|
|
||||||
It("converts an eth log to an entity", func() {
|
It("converts an eth log to an entity", func() {
|
||||||
err := t.Execute(logs, headerOne, constants.HeaderMissing)
|
err := t.Execute(logs, headerOne)
|
||||||
|
|
||||||
Expect(err).NotTo(HaveOccurred())
|
Expect(err).NotTo(HaveOccurred())
|
||||||
Expect(converter.ContractAbi).To(Equal(config.ContractAbi))
|
Expect(converter.ContractAbi).To(Equal(config.ContractAbi))
|
||||||
@@ -102,7 +101,7 @@ var _ = Describe("Transformer", func() {
|
|||||||
It("returns an error if converter fails", func() {
|
It("returns an error if converter fails", func() {
|
||||||
converter.ToEntitiesError = fakes.FakeError
|
converter.ToEntitiesError = fakes.FakeError
|
||||||
|
|
||||||
err := t.Execute(logs, headerOne, constants.HeaderMissing)
|
err := t.Execute(logs, headerOne)
|
||||||
|
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
Expect(err).To(MatchError(fakes.FakeError))
|
Expect(err).To(MatchError(fakes.FakeError))
|
||||||
@@ -111,7 +110,7 @@ var _ = Describe("Transformer", func() {
|
|||||||
It("converts an entity to a model", func() {
|
It("converts an entity to a model", func() {
|
||||||
converter.EntitiesToReturn = []interface{}{test_data.GenericEntity{}}
|
converter.EntitiesToReturn = []interface{}{test_data.GenericEntity{}}
|
||||||
|
|
||||||
err := t.Execute(logs, headerOne, constants.HeaderMissing)
|
err := t.Execute(logs, headerOne)
|
||||||
|
|
||||||
Expect(err).NotTo(HaveOccurred())
|
Expect(err).NotTo(HaveOccurred())
|
||||||
Expect(converter.EntitiesToConvert[0]).To(Equal(test_data.GenericEntity{}))
|
Expect(converter.EntitiesToConvert[0]).To(Equal(test_data.GenericEntity{}))
|
||||||
@@ -121,7 +120,7 @@ var _ = Describe("Transformer", func() {
|
|||||||
converter.EntitiesToReturn = []interface{}{test_data.GenericEntity{}}
|
converter.EntitiesToReturn = []interface{}{test_data.GenericEntity{}}
|
||||||
converter.ToModelsError = fakes.FakeError
|
converter.ToModelsError = fakes.FakeError
|
||||||
|
|
||||||
err := t.Execute(logs, headerOne, constants.HeaderMissing)
|
err := t.Execute(logs, headerOne)
|
||||||
|
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
Expect(err).To(MatchError(fakes.FakeError))
|
Expect(err).To(MatchError(fakes.FakeError))
|
||||||
@@ -130,7 +129,7 @@ var _ = Describe("Transformer", func() {
|
|||||||
It("persists the record", func() {
|
It("persists the record", func() {
|
||||||
converter.ModelsToReturn = []interface{}{test_data.GenericModel{}}
|
converter.ModelsToReturn = []interface{}{test_data.GenericModel{}}
|
||||||
|
|
||||||
err := t.Execute(logs, headerOne, constants.HeaderMissing)
|
err := t.Execute(logs, headerOne)
|
||||||
|
|
||||||
Expect(err).NotTo(HaveOccurred())
|
Expect(err).NotTo(HaveOccurred())
|
||||||
Expect(repository.PassedHeaderID).To(Equal(headerOne.Id))
|
Expect(repository.PassedHeaderID).To(Equal(headerOne.Id))
|
||||||
@@ -139,7 +138,7 @@ var _ = Describe("Transformer", func() {
|
|||||||
|
|
||||||
It("returns error if persisting the record fails", func() {
|
It("returns error if persisting the record fails", func() {
|
||||||
repository.SetCreateError(fakes.FakeError)
|
repository.SetCreateError(fakes.FakeError)
|
||||||
err := t.Execute(logs, headerOne, constants.HeaderMissing)
|
err := t.Execute(logs, headerOne)
|
||||||
|
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
Expect(err).To(MatchError(fakes.FakeError))
|
Expect(err).To(MatchError(fakes.FakeError))
|
||||||
|
|||||||
@@ -100,6 +100,7 @@ type Repository interface {
|
|||||||
A contract-specific implementation of the repository interface enables the transformer to write the decoded storage value to the appropriate table in postgres.
|
A contract-specific implementation of the repository interface enables the transformer to write the decoded storage value to the appropriate table in postgres.
|
||||||
|
|
||||||
The `Create` function is expected to recognize and persist a given storage value by the variable's name, as indicated on the row's metadata.
|
The `Create` function is expected to recognize and persist a given storage value by the variable's name, as indicated on the row's metadata.
|
||||||
|
Note: we advise silently discarding duplicates in `Create` - as it's possible that you may read the same diff several times, and an error will trigger the storage watcher to queue that diff for later processing.
|
||||||
|
|
||||||
The `SetDB` function is required for the repository to connect to the database.
|
The `SetDB` function is required for the repository to connect to the database.
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ package mocks
|
|||||||
import (
|
import (
|
||||||
"github.com/ethereum/go-ethereum/core/types"
|
"github.com/ethereum/go-ethereum/core/types"
|
||||||
|
|
||||||
"github.com/vulcanize/vulcanizedb/libraries/shared/constants"
|
|
||||||
shared_t "github.com/vulcanize/vulcanizedb/libraries/shared/transformer"
|
shared_t "github.com/vulcanize/vulcanizedb/libraries/shared/transformer"
|
||||||
"github.com/vulcanize/vulcanizedb/pkg/core"
|
"github.com/vulcanize/vulcanizedb/pkg/core"
|
||||||
"github.com/vulcanize/vulcanizedb/pkg/datastore/postgres"
|
"github.com/vulcanize/vulcanizedb/pkg/datastore/postgres"
|
||||||
@@ -33,7 +32,7 @@ type MockTransformer struct {
|
|||||||
config shared_t.EventTransformerConfig
|
config shared_t.EventTransformerConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mh *MockTransformer) Execute(logs []types.Log, header core.Header, recheckHeaders constants.TransformerExecution) error {
|
func (mh *MockTransformer) Execute(logs []types.Log, header core.Header) error {
|
||||||
if mh.ExecuteError != nil {
|
if mh.ExecuteError != nil {
|
||||||
return mh.ExecuteError
|
return mh.ExecuteError
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -69,31 +69,6 @@ func MissingHeaders(startingBlockNumber, endingBlockNumber int64, db *postgres.D
|
|||||||
return result, err
|
return result, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func RecheckHeaders(startingBlockNumber, endingBlockNumber int64, db *postgres.DB, checkedHeadersColumn string) ([]core.Header, error) {
|
|
||||||
var result []core.Header
|
|
||||||
var query string
|
|
||||||
var err error
|
|
||||||
|
|
||||||
if endingBlockNumber == -1 {
|
|
||||||
query = `SELECT headers.id, headers.block_number, headers.hash FROM headers
|
|
||||||
LEFT JOIN checked_headers on headers.id = header_id
|
|
||||||
WHERE ` + checkedHeadersColumn + ` between 1 and ` + constants.RecheckHeaderCap + `
|
|
||||||
AND headers.block_number >= $1
|
|
||||||
AND headers.eth_node_fingerprint = $2`
|
|
||||||
err = db.Select(&result, query, startingBlockNumber, db.Node.ID)
|
|
||||||
} else {
|
|
||||||
query = `SELECT headers.id, headers.block_number, headers.hash FROM headers
|
|
||||||
LEFT JOIN checked_headers on headers.id = header_id
|
|
||||||
WHERE ` + checkedHeadersColumn + ` between 1 and ` + constants.RecheckHeaderCap + `
|
|
||||||
AND headers.block_number >= $1
|
|
||||||
AND headers.block_number <= $2
|
|
||||||
AND headers.eth_node_fingerprint = $3`
|
|
||||||
err = db.Select(&result, query, startingBlockNumber, endingBlockNumber, db.Node.ID)
|
|
||||||
}
|
|
||||||
|
|
||||||
return result, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetCheckedColumnNames(db *postgres.DB) ([]string, error) {
|
func GetCheckedColumnNames(db *postgres.DB) ([]string, error) {
|
||||||
// Query returns `[]driver.Value`, nullable polymorphic interface
|
// Query returns `[]driver.Value`, nullable polymorphic interface
|
||||||
var queryResult []driver.Value
|
var queryResult []driver.Value
|
||||||
@@ -121,37 +96,47 @@ func GetCheckedColumnNames(db *postgres.DB) ([]string, error) {
|
|||||||
return columnNames, nil
|
return columnNames, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Builds a SQL string that checks if any column value is 0, given the column names.
|
// Builds a SQL string that checks if any column should be checked/rechecked.
|
||||||
// Defaults to FALSE when no columns are provided.
|
// Defaults to FALSE when no columns are provided.
|
||||||
// Ex: ["columnA", "columnB"] => "NOT (columnA!=0 AND columnB!=0)"
|
// Ex: ["columnA", "columnB"] => "NOT (columnA!=0 AND columnB!=0)"
|
||||||
// [] => "FALSE"
|
// [] => "FALSE"
|
||||||
func CreateNotCheckedSQL(boolColumns []string, recheckHeaders constants.TransformerExecution) string {
|
func CreateHeaderCheckedPredicateSQL(boolColumns []string, recheckHeaders constants.TransformerExecution) string {
|
||||||
|
|
||||||
var result bytes.Buffer
|
|
||||||
|
|
||||||
if len(boolColumns) == 0 {
|
if len(boolColumns) == 0 {
|
||||||
return "FALSE"
|
return "FALSE"
|
||||||
}
|
}
|
||||||
|
|
||||||
result.WriteString("NOT (")
|
if recheckHeaders {
|
||||||
|
return createHeaderCheckedPredicateSQLForRecheckedHeaders(boolColumns)
|
||||||
|
} else {
|
||||||
|
return createHeaderCheckedPredicateSQLForMissingHeaders(boolColumns)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func createHeaderCheckedPredicateSQLForMissingHeaders(boolColumns []string) string {
|
||||||
|
var result bytes.Buffer
|
||||||
|
result.WriteString(" (")
|
||||||
|
|
||||||
// Loop excluding last column name
|
// Loop excluding last column name
|
||||||
for _, column := range boolColumns[:len(boolColumns)-1] {
|
for _, column := range boolColumns[:len(boolColumns)-1] {
|
||||||
|
result.WriteString(fmt.Sprintf("%v=0 OR ", column))
|
||||||
if recheckHeaders {
|
|
||||||
result.WriteString(fmt.Sprintf("%v>=%s AND ", column, constants.RecheckHeaderCap))
|
|
||||||
} else {
|
|
||||||
result.WriteString(fmt.Sprintf("%v!=0 AND ", column))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// No trailing "OR" for the last column name
|
result.WriteString(fmt.Sprintf("%v=0)", boolColumns[len(boolColumns)-1]))
|
||||||
if recheckHeaders {
|
|
||||||
result.WriteString(fmt.Sprintf("%v>=%s)", boolColumns[len(boolColumns)-1], constants.RecheckHeaderCap))
|
return result.String()
|
||||||
} else {
|
}
|
||||||
result.WriteString(fmt.Sprintf("%v!=0)", boolColumns[len(boolColumns)-1]))
|
|
||||||
|
func createHeaderCheckedPredicateSQLForRecheckedHeaders(boolColumns []string) string {
|
||||||
|
var result bytes.Buffer
|
||||||
|
result.WriteString(" (")
|
||||||
|
|
||||||
|
// Loop excluding last column name
|
||||||
|
for _, column := range boolColumns[:len(boolColumns)-1] {
|
||||||
|
result.WriteString(fmt.Sprintf("%v<%s OR ", column, constants.RecheckHeaderCap))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// No trailing "OR" for the last column name
|
||||||
|
result.WriteString(fmt.Sprintf("%v<%s)", boolColumns[len(boolColumns)-1], constants.RecheckHeaderCap))
|
||||||
|
|
||||||
return result.String()
|
return result.String()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,12 +36,12 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var _ = Describe("Repository", func() {
|
var _ = Describe("Repository", func() {
|
||||||
Describe("MarkHeaderChecked", func() {
|
var (
|
||||||
var (
|
checkedHeadersColumn string
|
||||||
checkedHeadersColumn string
|
db *postgres.DB
|
||||||
db *postgres.DB
|
)
|
||||||
)
|
|
||||||
|
|
||||||
|
Describe("MarkHeaderChecked", func() {
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
db = test_config.NewTestDB(test_config.NewTestNode())
|
db = test_config.NewTestDB(test_config.NewTestNode())
|
||||||
test_config.CleanTestDB(db)
|
test_config.CleanTestDB(db)
|
||||||
@@ -73,11 +73,6 @@ var _ = Describe("Repository", func() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
Describe("MarkHeaderCheckedInTransaction", func() {
|
Describe("MarkHeaderCheckedInTransaction", func() {
|
||||||
var (
|
|
||||||
checkedHeadersColumn string
|
|
||||||
db *postgres.DB
|
|
||||||
)
|
|
||||||
|
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
db = test_config.NewTestDB(test_config.NewTestNode())
|
db = test_config.NewTestDB(test_config.NewTestNode())
|
||||||
test_config.CleanTestDB(db)
|
test_config.CleanTestDB(db)
|
||||||
@@ -114,16 +109,17 @@ var _ = Describe("Repository", func() {
|
|||||||
|
|
||||||
Describe("MissingHeaders", func() {
|
Describe("MissingHeaders", func() {
|
||||||
var (
|
var (
|
||||||
db *postgres.DB
|
|
||||||
headerRepository datastore.HeaderRepository
|
headerRepository datastore.HeaderRepository
|
||||||
startingBlockNumber int64
|
startingBlockNumber int64
|
||||||
endingBlockNumber int64
|
endingBlockNumber int64
|
||||||
eventSpecificBlockNumber int64
|
eventSpecificBlockNumber int64
|
||||||
|
outOfRangeBlockNumber int64
|
||||||
blockNumbers []int64
|
blockNumbers []int64
|
||||||
headerIDs []int64
|
headerIDs []int64
|
||||||
notCheckedSQL string
|
notCheckedSQL string
|
||||||
err error
|
err error
|
||||||
hr r2.HeaderRepository
|
hr r2.HeaderRepository
|
||||||
|
columnNames []string
|
||||||
)
|
)
|
||||||
|
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
@@ -133,14 +129,14 @@ var _ = Describe("Repository", func() {
|
|||||||
hr = r2.NewHeaderRepository(db)
|
hr = r2.NewHeaderRepository(db)
|
||||||
hr.AddCheckColumns(getExpectedColumnNames())
|
hr.AddCheckColumns(getExpectedColumnNames())
|
||||||
|
|
||||||
columnNames, err := shared.GetCheckedColumnNames(db)
|
columnNames, err = shared.GetCheckedColumnNames(db)
|
||||||
Expect(err).NotTo(HaveOccurred())
|
Expect(err).NotTo(HaveOccurred())
|
||||||
notCheckedSQL = shared.CreateNotCheckedSQL(columnNames, constants.HeaderMissing)
|
notCheckedSQL = shared.CreateHeaderCheckedPredicateSQL(columnNames, constants.HeaderMissing)
|
||||||
|
|
||||||
startingBlockNumber = rand.Int63()
|
startingBlockNumber = rand.Int63()
|
||||||
eventSpecificBlockNumber = startingBlockNumber + 1
|
eventSpecificBlockNumber = startingBlockNumber + 1
|
||||||
endingBlockNumber = startingBlockNumber + 2
|
endingBlockNumber = startingBlockNumber + 2
|
||||||
outOfRangeBlockNumber := endingBlockNumber + 1
|
outOfRangeBlockNumber = endingBlockNumber + 1
|
||||||
|
|
||||||
blockNumbers = []int64{startingBlockNumber, eventSpecificBlockNumber, endingBlockNumber, outOfRangeBlockNumber}
|
blockNumbers = []int64{startingBlockNumber, eventSpecificBlockNumber, endingBlockNumber, outOfRangeBlockNumber}
|
||||||
|
|
||||||
@@ -157,6 +153,7 @@ var _ = Describe("Repository", func() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
It("only treats headers as checked if the event specific logs have been checked", func() {
|
It("only treats headers as checked if the event specific logs have been checked", func() {
|
||||||
|
//add a checked_header record, but don't mark it check for any of the columns
|
||||||
_, err = db.Exec(`INSERT INTO public.checked_headers (header_id) VALUES ($1)`, headerIDs[1])
|
_, err = db.Exec(`INSERT INTO public.checked_headers (header_id) VALUES ($1)`, headerIDs[1])
|
||||||
Expect(err).NotTo(HaveOccurred())
|
Expect(err).NotTo(HaveOccurred())
|
||||||
|
|
||||||
@@ -191,83 +188,47 @@ var _ = Describe("Repository", func() {
|
|||||||
Expect(nodeTwoMissingHeaders[0].BlockNumber).To(Or(Equal(startingBlockNumber+10), Equal(eventSpecificBlockNumber+10), Equal(endingBlockNumber+10)))
|
Expect(nodeTwoMissingHeaders[0].BlockNumber).To(Or(Equal(startingBlockNumber+10), Equal(eventSpecificBlockNumber+10), Equal(endingBlockNumber+10)))
|
||||||
Expect(nodeTwoMissingHeaders[1].BlockNumber).To(Or(Equal(startingBlockNumber+10), Equal(eventSpecificBlockNumber+10), Equal(endingBlockNumber+10)))
|
Expect(nodeTwoMissingHeaders[1].BlockNumber).To(Or(Equal(startingBlockNumber+10), Equal(eventSpecificBlockNumber+10), Equal(endingBlockNumber+10)))
|
||||||
})
|
})
|
||||||
})
|
|
||||||
|
|
||||||
Describe("RecheckHeaders", func() {
|
It("handles an ending block of -1 ", func() {
|
||||||
var (
|
endingBlock := int64(-1)
|
||||||
checkedHeadersColumn string
|
headers, err := shared.MissingHeaders(startingBlockNumber, endingBlock, db, notCheckedSQL)
|
||||||
db *postgres.DB
|
|
||||||
headerOneID, headerTwoID, headerThreeID, headerFourID int64
|
|
||||||
headerOneErr, headerTwoErr, headerThreeErr, headerFourErr error
|
|
||||||
)
|
|
||||||
|
|
||||||
BeforeEach(func() {
|
Expect(err).NotTo(HaveOccurred())
|
||||||
db = test_config.NewTestDB(test_config.NewTestNode())
|
Expect(len(headers)).To(Equal(4))
|
||||||
test_config.CleanTestDB(db)
|
Expect(headers[0].BlockNumber).To(Or(Equal(startingBlockNumber), Equal(endingBlockNumber), Equal(eventSpecificBlockNumber), Equal(outOfRangeBlockNumber)))
|
||||||
|
Expect(headers[1].BlockNumber).To(Or(Equal(startingBlockNumber), Equal(endingBlockNumber), Equal(eventSpecificBlockNumber), Equal(outOfRangeBlockNumber)))
|
||||||
|
Expect(headers[2].BlockNumber).To(Or(Equal(startingBlockNumber), Equal(endingBlockNumber), Equal(eventSpecificBlockNumber), Equal(outOfRangeBlockNumber)))
|
||||||
|
Expect(headers[3].BlockNumber).To(Or(Equal(startingBlockNumber), Equal(endingBlockNumber), Equal(eventSpecificBlockNumber), Equal(outOfRangeBlockNumber)))
|
||||||
|
|
||||||
// create header checked column
|
})
|
||||||
checkedHeadersColumn = "test_column_checked"
|
|
||||||
_, migrateErr := db.Exec(`ALTER TABLE public.checked_headers ADD COLUMN ` + checkedHeadersColumn + ` integer`)
|
|
||||||
Expect(migrateErr).NotTo(HaveOccurred())
|
|
||||||
|
|
||||||
// create headers
|
It("when a the `notCheckedSQL` argument allows for rechecks it returns headers where the checked count is less than the maximum", func() {
|
||||||
headerRepository := repositories.NewHeaderRepository(db)
|
columnName := columnNames[0]
|
||||||
headerOneID, headerOneErr = headerRepository.CreateOrUpdateHeader(fakes.GetFakeHeader(1))
|
recheckedSQL := shared.CreateHeaderCheckedPredicateSQL([]string{columnName}, constants.HeaderRecheck)
|
||||||
Expect(headerOneErr).NotTo(HaveOccurred())
|
// mark every header checked at least once
|
||||||
headerTwoID, headerTwoErr = headerRepository.CreateOrUpdateHeader(fakes.GetFakeHeader(2))
|
// header 4 is marked the maximum number of times, it it is not longer checked
|
||||||
Expect(headerTwoErr).NotTo(HaveOccurred())
|
|
||||||
headerThreeID, headerThreeErr = headerRepository.CreateOrUpdateHeader(fakes.GetFakeHeader(3))
|
|
||||||
Expect(headerThreeErr).NotTo(HaveOccurred())
|
|
||||||
headerFourID, headerFourErr = headerRepository.CreateOrUpdateHeader(fakes.GetFakeHeader(4))
|
|
||||||
Expect(headerFourErr).NotTo(HaveOccurred())
|
|
||||||
|
|
||||||
// mark every header checked at least once, with one fully rechecked (headerThree)
|
|
||||||
maxCheckCount, intConversionErr := strconv.Atoi(constants.RecheckHeaderCap)
|
maxCheckCount, intConversionErr := strconv.Atoi(constants.RecheckHeaderCap)
|
||||||
Expect(intConversionErr).NotTo(HaveOccurred())
|
Expect(intConversionErr).NotTo(HaveOccurred())
|
||||||
_, markHeaderOneCheckedErr := db.Exec(
|
|
||||||
`INSERT INTO public.checked_headers (header_id, `+checkedHeadersColumn+`) VALUES ($1, $2)`,
|
|
||||||
headerOneID, maxCheckCount)
|
|
||||||
Expect(markHeaderOneCheckedErr).NotTo(HaveOccurred())
|
|
||||||
_, markHeaderTwoCheckedErr := db.Exec(
|
|
||||||
`INSERT INTO public.checked_headers (header_id, `+checkedHeadersColumn+`) VALUES ($1, $2)`,
|
|
||||||
headerTwoID, maxCheckCount)
|
|
||||||
Expect(markHeaderTwoCheckedErr).NotTo(HaveOccurred())
|
|
||||||
_, markHeaderThreeCheckedErr := db.Exec(
|
|
||||||
`INSERT INTO public.checked_headers (header_id, `+checkedHeadersColumn+`) VALUES ($1, $2)`,
|
|
||||||
headerThreeID, maxCheckCount+1)
|
|
||||||
Expect(markHeaderThreeCheckedErr).NotTo(HaveOccurred())
|
|
||||||
_, markHeaderFourCheckedErr := db.Exec(
|
|
||||||
`INSERT INTO public.checked_headers (header_id, `+checkedHeadersColumn+`) VALUES ($1, $2)`,
|
|
||||||
headerFourID, maxCheckCount)
|
|
||||||
Expect(markHeaderFourCheckedErr).NotTo(HaveOccurred())
|
|
||||||
})
|
|
||||||
|
|
||||||
AfterEach(func() {
|
markHeaderOneErr := shared.MarkHeaderChecked(headerIDs[0], db, columnName)
|
||||||
_, cleanupMigrateErr := db.Exec(`ALTER TABLE public.checked_headers DROP COLUMN ` + checkedHeadersColumn)
|
Expect(markHeaderOneErr).NotTo(HaveOccurred())
|
||||||
Expect(cleanupMigrateErr).NotTo(HaveOccurred())
|
markHeaderTwoErr := shared.MarkHeaderChecked(headerIDs[1], db, columnName)
|
||||||
})
|
Expect(markHeaderTwoErr).NotTo(HaveOccurred())
|
||||||
|
markHeaderThreeErr := shared.MarkHeaderChecked(headerIDs[2], db, columnName)
|
||||||
|
Expect(markHeaderThreeErr).NotTo(HaveOccurred())
|
||||||
|
for i := 0; i <= maxCheckCount; i++ {
|
||||||
|
markHeaderFourErr := shared.MarkHeaderChecked(headerIDs[3], db, columnName)
|
||||||
|
Expect(markHeaderFourErr).NotTo(HaveOccurred())
|
||||||
|
}
|
||||||
|
|
||||||
Describe("when no ending block number (ending block number == -1)", func() {
|
headers, err := shared.MissingHeaders(1, -1, db, recheckedSQL)
|
||||||
It("returns all headers since starting block where checked count is less than cap", func() {
|
|
||||||
headers, err := shared.RecheckHeaders(1, -1, db, checkedHeadersColumn)
|
|
||||||
|
|
||||||
Expect(err).NotTo(HaveOccurred())
|
Expect(err).NotTo(HaveOccurred())
|
||||||
Expect(len(headers)).To(Equal(3))
|
Expect(len(headers)).To(Equal(3))
|
||||||
Expect(headers[0].Id).To(Or(Equal(headerOneID), Equal(headerTwoID), Equal(headerFourID)))
|
Expect(headers[0].Id).To(Or(Equal(headerIDs[0]), Equal(headerIDs[1]), Equal(headerIDs[2])))
|
||||||
Expect(headers[1].Id).To(Or(Equal(headerOneID), Equal(headerTwoID), Equal(headerFourID)))
|
Expect(headers[1].Id).To(Or(Equal(headerIDs[0]), Equal(headerIDs[1]), Equal(headerIDs[2])))
|
||||||
Expect(headers[2].Id).To(Or(Equal(headerOneID), Equal(headerTwoID), Equal(headerFourID)))
|
Expect(headers[2].Id).To(Or(Equal(headerIDs[0]), Equal(headerIDs[1]), Equal(headerIDs[2])))
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
Describe("when ending block number specified", func() {
|
|
||||||
It("returns headers between starting and ending block where checked count is less than cap", func() {
|
|
||||||
headers, err := shared.RecheckHeaders(1, 3, db, checkedHeadersColumn)
|
|
||||||
|
|
||||||
Expect(err).NotTo(HaveOccurred())
|
|
||||||
Expect(len(headers)).To(Equal(2))
|
|
||||||
Expect(headers[0].Id).To(Or(Equal(headerOneID), Equal(headerTwoID)))
|
|
||||||
Expect(headers[1].Id).To(Or(Equal(headerOneID), Equal(headerTwoID)))
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -285,32 +246,49 @@ var _ = Describe("Repository", func() {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
Describe("CreateNotCheckedSQL", func() {
|
Describe("CreateHeaderCheckedPredicateSQL", func() {
|
||||||
It("generates a correct SQL string for one column", func() {
|
Describe("for headers that haven't been checked for logs", func() {
|
||||||
columns := []string{"columnA"}
|
It("generates a correct SQL string for one column", func() {
|
||||||
expected := "NOT (columnA!=0)"
|
columns := []string{"columnA"}
|
||||||
actual := shared.CreateNotCheckedSQL(columns, constants.HeaderMissing)
|
expected := " (columnA=0)"
|
||||||
Expect(actual).To(Equal(expected))
|
actual := shared.CreateHeaderCheckedPredicateSQL(columns, constants.HeaderMissing)
|
||||||
|
Expect(actual).To(Equal(expected))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("generates a correct SQL string for several columns", func() {
|
||||||
|
columns := []string{"columnA", "columnB"}
|
||||||
|
expected := " (columnA=0 OR columnB=0)"
|
||||||
|
actual := shared.CreateHeaderCheckedPredicateSQL(columns, constants.HeaderMissing)
|
||||||
|
Expect(actual).To(Equal(expected))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("defaults to FALSE when there are no columns", func() {
|
||||||
|
expected := "FALSE"
|
||||||
|
actual := shared.CreateHeaderCheckedPredicateSQL([]string{}, constants.HeaderMissing)
|
||||||
|
Expect(actual).To(Equal(expected))
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
It("generates a correct SQL string for several columns", func() {
|
Describe("for headers that are being rechecked for logs", func() {
|
||||||
columns := []string{"columnA", "columnB"}
|
It("generates a correct SQL string for rechecking headers for one column", func() {
|
||||||
expected := "NOT (columnA!=0 AND columnB!=0)"
|
columns := []string{"columnA"}
|
||||||
actual := shared.CreateNotCheckedSQL(columns, constants.HeaderMissing)
|
expected := fmt.Sprintf(" (columnA<%s)", constants.RecheckHeaderCap)
|
||||||
Expect(actual).To(Equal(expected))
|
actual := shared.CreateHeaderCheckedPredicateSQL(columns, constants.HeaderRecheck)
|
||||||
})
|
Expect(actual).To(Equal(expected))
|
||||||
|
})
|
||||||
|
|
||||||
It("defaults to FALSE when there are no columns", func() {
|
It("generates a correct SQL string for rechecking headers for several columns", func() {
|
||||||
expected := "FALSE"
|
columns := []string{"columnA", "columnB"}
|
||||||
actual := shared.CreateNotCheckedSQL([]string{}, constants.HeaderMissing)
|
expected := fmt.Sprintf(" (columnA<%s OR columnB<%s)", constants.RecheckHeaderCap, constants.RecheckHeaderCap)
|
||||||
Expect(actual).To(Equal(expected))
|
actual := shared.CreateHeaderCheckedPredicateSQL(columns, constants.HeaderRecheck)
|
||||||
})
|
Expect(actual).To(Equal(expected))
|
||||||
|
})
|
||||||
|
|
||||||
It("generates a correct SQL string for rechecking headers", func() {
|
It("defaults to FALSE when there are no columns", func() {
|
||||||
columns := []string{"columnA", "columnB"}
|
expected := "FALSE"
|
||||||
expected := fmt.Sprintf("NOT (columnA>=%s AND columnB>=%s)", constants.RecheckHeaderCap, constants.RecheckHeaderCap)
|
actual := shared.CreateHeaderCheckedPredicateSQL([]string{}, constants.HeaderRecheck)
|
||||||
actual := shared.CreateNotCheckedSQL(columns, constants.HeaderRecheck)
|
Expect(actual).To(Equal(expected))
|
||||||
Expect(actual).To(Equal(expected))
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func GetMapping(indexOnContract, key string) common.Hash {
|
func GetMapping(indexOnContract, key string) common.Hash {
|
||||||
keyBytes := common.FromHex("0x" + key + indexOnContract)
|
keyBytes := common.FromHex(key + indexOnContract)
|
||||||
encoded := crypto.Keccak256(keyBytes)
|
encoded := crypto.Keccak256(keyBytes)
|
||||||
return common.BytesToHash(encoded)
|
return common.BytesToHash(encoded)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,16 @@ var _ = Describe("Mappings", func() {
|
|||||||
expectedStorageKey := common.HexToHash("0xee0c1b59a3856bafbfb8730e7694c4badc271eb5f01ce4a8d7a53d8a6499676f")
|
expectedStorageKey := common.HexToHash("0xee0c1b59a3856bafbfb8730e7694c4badc271eb5f01ce4a8d7a53d8a6499676f")
|
||||||
Expect(storageKey).To(Equal(expectedStorageKey))
|
Expect(storageKey).To(Equal(expectedStorageKey))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
It("returns same result if value includes hex prefix", func() {
|
||||||
|
indexOfMappingOnContract := storage.IndexZero
|
||||||
|
keyForDesiredValueInMapping := "0x1234567890abcdef"
|
||||||
|
|
||||||
|
storageKey := storage.GetMapping(indexOfMappingOnContract, keyForDesiredValueInMapping)
|
||||||
|
|
||||||
|
expectedStorageKey := common.HexToHash("0xee0c1b59a3856bafbfb8730e7694c4badc271eb5f01ce4a8d7a53d8a6499676f")
|
||||||
|
Expect(storageKey).To(Equal(expectedStorageKey))
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
Describe("GetNestedMapping", func() {
|
Describe("GetNestedMapping", func() {
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ func NewStorageQueue(db *postgres.DB) StorageQueue {
|
|||||||
func (queue StorageQueue) Add(row utils.StorageDiffRow) error {
|
func (queue StorageQueue) Add(row utils.StorageDiffRow) error {
|
||||||
_, err := queue.db.Exec(`INSERT INTO public.queued_storage (contract,
|
_, err := queue.db.Exec(`INSERT INTO public.queued_storage (contract,
|
||||||
block_hash, block_height, storage_key, storage_value) VALUES
|
block_hash, block_height, storage_key, storage_value) VALUES
|
||||||
($1, $2, $3, $4, $5)`, row.Contract.Bytes(), row.BlockHash.Bytes(),
|
($1, $2, $3, $4, $5) ON CONFLICT DO NOTHING`, row.Contract.Bytes(), row.BlockHash.Bytes(),
|
||||||
row.BlockHeight, row.StorageKey.Bytes(), row.StorageValue.Bytes())
|
row.BlockHeight, row.StorageKey.Bytes(), row.StorageValue.Bytes())
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,11 +49,22 @@ var _ = Describe("Storage queue", func() {
|
|||||||
Expect(addErr).NotTo(HaveOccurred())
|
Expect(addErr).NotTo(HaveOccurred())
|
||||||
})
|
})
|
||||||
|
|
||||||
It("adds a storage row to the db", func() {
|
Describe("Add", func() {
|
||||||
var result utils.StorageDiffRow
|
It("adds a storage row to the db", func() {
|
||||||
getErr := db.Get(&result, `SELECT contract, block_hash, block_height, storage_key, storage_value FROM public.queued_storage`)
|
var result utils.StorageDiffRow
|
||||||
Expect(getErr).NotTo(HaveOccurred())
|
getErr := db.Get(&result, `SELECT contract, block_hash, block_height, storage_key, storage_value FROM public.queued_storage`)
|
||||||
Expect(result).To(Equal(row))
|
Expect(getErr).NotTo(HaveOccurred())
|
||||||
|
Expect(result).To(Equal(row))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("does not duplicate storage rows", func() {
|
||||||
|
addErr := queue.Add(row)
|
||||||
|
Expect(addErr).NotTo(HaveOccurred())
|
||||||
|
var count int
|
||||||
|
getErr := db.Get(&count, `SELECT count(*) FROM public.queued_storage`)
|
||||||
|
Expect(getErr).NotTo(HaveOccurred())
|
||||||
|
Expect(count).To(Equal(1))
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
It("deletes storage row from db", func() {
|
It("deletes storage row from db", func() {
|
||||||
|
|||||||
@@ -17,12 +17,9 @@
|
|||||||
package utils
|
package utils
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
var ErrRowExists = errors.New("parsed row for storage diff already exists")
|
|
||||||
|
|
||||||
type ErrContractNotFound struct {
|
type ErrContractNotFound struct {
|
||||||
Contract string
|
Contract string
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,13 +20,12 @@ import (
|
|||||||
"github.com/ethereum/go-ethereum/common"
|
"github.com/ethereum/go-ethereum/common"
|
||||||
"github.com/ethereum/go-ethereum/core/types"
|
"github.com/ethereum/go-ethereum/core/types"
|
||||||
|
|
||||||
"github.com/vulcanize/vulcanizedb/libraries/shared/constants"
|
|
||||||
"github.com/vulcanize/vulcanizedb/pkg/core"
|
"github.com/vulcanize/vulcanizedb/pkg/core"
|
||||||
"github.com/vulcanize/vulcanizedb/pkg/datastore/postgres"
|
"github.com/vulcanize/vulcanizedb/pkg/datastore/postgres"
|
||||||
)
|
)
|
||||||
|
|
||||||
type EventTransformer interface {
|
type EventTransformer interface {
|
||||||
Execute(logs []types.Log, header core.Header, recheckHeaders constants.TransformerExecution) error
|
Execute(logs []types.Log, header core.Header) error
|
||||||
GetConfig() EventTransformerConfig
|
GetConfig() EventTransformerConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -96,7 +96,7 @@ func (watcher *EventWatcher) Execute(recheckHeaders constants.TransformerExecuti
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
notCheckedSQL := repository.CreateNotCheckedSQL(checkedColumnNames, recheckHeaders)
|
notCheckedSQL := repository.CreateHeaderCheckedPredicateSQL(checkedColumnNames, recheckHeaders)
|
||||||
|
|
||||||
missingHeaders, err := repository.MissingHeaders(*watcher.StartingBlock, -1, watcher.DB, notCheckedSQL)
|
missingHeaders, err := repository.MissingHeaders(*watcher.StartingBlock, -1, watcher.DB, notCheckedSQL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -134,7 +134,7 @@ func (watcher *EventWatcher) transformLogs(logs []types.Log, header core.Header)
|
|||||||
for _, t := range watcher.Transformers {
|
for _, t := range watcher.Transformers {
|
||||||
transformerName := t.GetConfig().TransformerName
|
transformerName := t.GetConfig().TransformerName
|
||||||
logChunk := chunkedLogs[transformerName]
|
logChunk := chunkedLogs[transformerName]
|
||||||
err := t.Execute(logChunk, header, constants.HeaderMissing)
|
err := t.Execute(logChunk, header)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logrus.Errorf("%v transformer failed to execute in watcher: %v", transformerName, err)
|
logrus.Errorf("%v transformer failed to execute in watcher: %v", transformerName, err)
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ func (storageWatcher StorageWatcher) processRow(row utils.StorageDiffRow) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
executeErr := storageTransformer.Execute(row)
|
executeErr := storageTransformer.Execute(row)
|
||||||
if executeErr != nil && executeErr != utils.ErrRowExists {
|
if executeErr != nil {
|
||||||
logrus.Warn(fmt.Sprintf("error executing storage transformer: %s", executeErr))
|
logrus.Warn(fmt.Sprintf("error executing storage transformer: %s", executeErr))
|
||||||
queueErr := storageWatcher.Queue.Add(row)
|
queueErr := storageWatcher.Queue.Add(row)
|
||||||
if queueErr != nil {
|
if queueErr != nil {
|
||||||
@@ -100,7 +100,7 @@ func (storageWatcher StorageWatcher) processQueue() {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
executeErr := storageTransformer.Execute(row)
|
executeErr := storageTransformer.Execute(row)
|
||||||
if executeErr == nil || executeErr == utils.ErrRowExists {
|
if executeErr == nil {
|
||||||
storageWatcher.deleteRow(row.Id)
|
storageWatcher.deleteRow(row.Id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -109,18 +109,6 @@ var _ = Describe("Storage Watcher", func() {
|
|||||||
close(done)
|
close(done)
|
||||||
})
|
})
|
||||||
|
|
||||||
It("does not queue row if transformer execution fails because row already exists", func(done Done) {
|
|
||||||
mockTransformer.ExecuteErr = utils.ErrRowExists
|
|
||||||
|
|
||||||
go storageWatcher.Execute(rows, errs, time.Hour)
|
|
||||||
|
|
||||||
Expect(<-errs).To(BeNil())
|
|
||||||
Consistently(func() bool {
|
|
||||||
return mockQueue.AddCalled
|
|
||||||
}).Should(BeFalse())
|
|
||||||
close(done)
|
|
||||||
})
|
|
||||||
|
|
||||||
It("queues row for later processing if transformer execution fails", func(done Done) {
|
It("queues row for later processing if transformer execution fails", func(done Done) {
|
||||||
mockTransformer.ExecuteErr = fakes.FakeError
|
mockTransformer.ExecuteErr = fakes.FakeError
|
||||||
|
|
||||||
@@ -199,17 +187,6 @@ var _ = Describe("Storage Watcher", func() {
|
|||||||
close(done)
|
close(done)
|
||||||
})
|
})
|
||||||
|
|
||||||
It("deletes row from queue if transformer execution errors because row already exists", func(done Done) {
|
|
||||||
mockTransformer.ExecuteErr = utils.ErrRowExists
|
|
||||||
|
|
||||||
go storageWatcher.Execute(rows, errs, time.Nanosecond)
|
|
||||||
|
|
||||||
Eventually(func() int {
|
|
||||||
return mockQueue.DeletePassedId
|
|
||||||
}).Should(Equal(row.Id))
|
|
||||||
close(done)
|
|
||||||
})
|
|
||||||
|
|
||||||
It("logs error if deleting persisted row fails", func(done Done) {
|
It("logs error if deleting persisted row fails", func(done Done) {
|
||||||
mockQueue.DeleteErr = fakes.FakeError
|
mockQueue.DeleteErr = fakes.FakeError
|
||||||
tempFile, fileErr := ioutil.TempFile("", "log")
|
tempFile, fileErr := ioutil.TempFile("", "log")
|
||||||
|
|||||||
@@ -164,7 +164,7 @@ func (tr *Transformer) Init() error {
|
|||||||
// Iterates through stored, initialized contract objects
|
// Iterates through stored, initialized contract objects
|
||||||
// Iterates through contract's event filters, grabbing watched event logs
|
// Iterates through contract's event filters, grabbing watched event logs
|
||||||
// Uses converter to convert logs into custom log type
|
// Uses converter to convert logs into custom log type
|
||||||
// Persists converted logs into custuom postgres tables
|
// Persists converted logs into custom postgres tables
|
||||||
// Calls selected methods, using token holder address generated during event log conversion
|
// Calls selected methods, using token holder address generated during event log conversion
|
||||||
func (tr *Transformer) Execute() error {
|
func (tr *Transformer) Execute() error {
|
||||||
if len(tr.Contracts) == 0 {
|
if len(tr.Contracts) == 0 {
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ type BlockChain interface {
|
|||||||
GetBlockByNumber(blockNumber int64) (Block, error)
|
GetBlockByNumber(blockNumber int64) (Block, error)
|
||||||
GetEthLogsWithCustomQuery(query ethereum.FilterQuery) ([]types.Log, error)
|
GetEthLogsWithCustomQuery(query ethereum.FilterQuery) ([]types.Log, error)
|
||||||
GetHeaderByNumber(blockNumber int64) (Header, error)
|
GetHeaderByNumber(blockNumber int64) (Header, error)
|
||||||
GetHeaderByNumbers(blockNumbers []int64) ([]Header, error)
|
GetHeadersByNumbers(blockNumbers []int64) ([]Header, error)
|
||||||
GetLogs(contract Contract, startingBlockNumber *big.Int, endingBlockNumber *big.Int) ([]Log, error)
|
GetLogs(contract Contract, startingBlockNumber *big.Int, endingBlockNumber *big.Int) ([]Log, error)
|
||||||
GetTransactions(transactionHashes []common.Hash) ([]TransactionModel, error)
|
GetTransactions(transactionHashes []common.Hash) ([]TransactionModel, error)
|
||||||
LastBlock() (*big.Int, error)
|
LastBlock() (*big.Int, error)
|
||||||
|
|||||||
@@ -98,7 +98,7 @@ func (chain *MockBlockChain) GetHeaderByNumber(blockNumber int64) (core.Header,
|
|||||||
return core.Header{BlockNumber: blockNumber}, nil
|
return core.Header{BlockNumber: blockNumber}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (chain *MockBlockChain) GetHeaderByNumbers(blockNumbers []int64) ([]core.Header, error) {
|
func (chain *MockBlockChain) GetHeadersByNumbers(blockNumbers []int64) ([]core.Header, error) {
|
||||||
var headers []core.Header
|
var headers []core.Header
|
||||||
for _, blockNumber := range blockNumbers {
|
for _, blockNumber := range blockNumbers {
|
||||||
var header = core.Header{BlockNumber: int64(blockNumber)}
|
var header = core.Header{BlockNumber: int64(blockNumber)}
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ func (blockChain *BlockChain) GetHeaderByNumber(blockNumber int64) (header core.
|
|||||||
return blockChain.getPOWHeader(blockNumber)
|
return blockChain.getPOWHeader(blockNumber)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (blockChain *BlockChain) GetHeaderByNumbers(blockNumbers []int64) (header []core.Header, err error) {
|
func (blockChain *BlockChain) GetHeadersByNumbers(blockNumbers []int64) (header []core.Header, err error) {
|
||||||
if blockChain.node.NetworkID == core.KOVAN_NETWORK_ID {
|
if blockChain.node.NetworkID == core.KOVAN_NETWORK_ID {
|
||||||
return blockChain.getPOAHeaders(blockNumbers)
|
return blockChain.getPOAHeaders(blockNumbers)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -93,7 +93,7 @@ var _ = Describe("Geth blockchain", func() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
It("fetches headers with multiple blocks", func() {
|
It("fetches headers with multiple blocks", func() {
|
||||||
_, err := blockChain.GetHeaderByNumbers([]int64{100, 99})
|
_, err := blockChain.GetHeadersByNumbers([]int64{100, 99})
|
||||||
|
|
||||||
Expect(err).NotTo(HaveOccurred())
|
Expect(err).NotTo(HaveOccurred())
|
||||||
mockRpcClient.AssertBatchCalledWith("eth_getBlockByNumber", 2)
|
mockRpcClient.AssertBatchCalledWith("eth_getBlockByNumber", 2)
|
||||||
@@ -139,7 +139,7 @@ var _ = Describe("Geth blockchain", func() {
|
|||||||
blockNumber := hexutil.Big(*big.NewInt(100))
|
blockNumber := hexutil.Big(*big.NewInt(100))
|
||||||
mockRpcClient.SetReturnPOAHeaders([]vulcCore.POAHeader{{Number: &blockNumber}})
|
mockRpcClient.SetReturnPOAHeaders([]vulcCore.POAHeader{{Number: &blockNumber}})
|
||||||
|
|
||||||
_, err := blockChain.GetHeaderByNumbers([]int64{100, 99})
|
_, err := blockChain.GetHeadersByNumbers([]int64{100, 99})
|
||||||
|
|
||||||
Expect(err).NotTo(HaveOccurred())
|
Expect(err).NotTo(HaveOccurred())
|
||||||
mockRpcClient.AssertBatchCalledWith("eth_getBlockByNumber", 2)
|
mockRpcClient.AssertBatchCalledWith("eth_getBlockByNumber", 2)
|
||||||
|
|||||||
@@ -24,14 +24,14 @@ import (
|
|||||||
"github.com/vulcanize/vulcanizedb/pkg/datastore/postgres/repositories"
|
"github.com/vulcanize/vulcanizedb/pkg/datastore/postgres/repositories"
|
||||||
)
|
)
|
||||||
|
|
||||||
func PopulateMissingHeaders(blockchain core.BlockChain, headerRepository datastore.HeaderRepository, startingBlockNumber int64) (int, error) {
|
func PopulateMissingHeaders(blockChain core.BlockChain, headerRepository datastore.HeaderRepository, startingBlockNumber int64) (int, error) {
|
||||||
lastBlock, err := blockchain.LastBlock()
|
lastBlock, err := blockChain.LastBlock()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("PopulateMissingHeaders: Error getting last block: ", err)
|
log.Error("PopulateMissingHeaders: Error getting last block: ", err)
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
|
|
||||||
blockNumbers, err := headerRepository.MissingBlockNumbers(startingBlockNumber, lastBlock.Int64(), blockchain.Node().ID)
|
blockNumbers, err := headerRepository.MissingBlockNumbers(startingBlockNumber, lastBlock.Int64(), blockChain.Node().ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("PopulateMissingHeaders: Error getting missing block numbers: ", err)
|
log.Error("PopulateMissingHeaders: Error getting missing block numbers: ", err)
|
||||||
return 0, err
|
return 0, err
|
||||||
@@ -40,7 +40,7 @@ func PopulateMissingHeaders(blockchain core.BlockChain, headerRepository datasto
|
|||||||
}
|
}
|
||||||
|
|
||||||
log.Printf("Backfilling %d blocks\n\n", len(blockNumbers))
|
log.Printf("Backfilling %d blocks\n\n", len(blockNumbers))
|
||||||
_, err = RetrieveAndUpdateHeaders(blockchain, headerRepository, blockNumbers)
|
_, err = RetrieveAndUpdateHeaders(blockChain, headerRepository, blockNumbers)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("PopulateMissingHeaders: Error getting/updating headers:", err)
|
log.Error("PopulateMissingHeaders: Error getting/updating headers:", err)
|
||||||
return 0, err
|
return 0, err
|
||||||
@@ -48,8 +48,8 @@ func PopulateMissingHeaders(blockchain core.BlockChain, headerRepository datasto
|
|||||||
return len(blockNumbers), nil
|
return len(blockNumbers), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func RetrieveAndUpdateHeaders(chain core.BlockChain, headerRepository datastore.HeaderRepository, blockNumbers []int64) (int, error) {
|
func RetrieveAndUpdateHeaders(blockChain core.BlockChain, headerRepository datastore.HeaderRepository, blockNumbers []int64) (int, error) {
|
||||||
headers, err := chain.GetHeaderByNumbers(blockNumbers)
|
headers, err := blockChain.GetHeadersByNumbers(blockNumbers)
|
||||||
for _, header := range headers {
|
for _, header := range headers {
|
||||||
_, err = headerRepository.CreateOrUpdateHeader(header)
|
_, err = headerRepository.CreateOrUpdateHeader(header)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
package-lock.json
|
|
||||||
yarn.lock
|
|
||||||
node_modules
|
|
||||||
Dockerfile
|
|
||||||
README.md
|
|
||||||
spec
|
|
||||||
.dockerignore
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
FROM mhart/alpine-node:10
|
|
||||||
RUN apk --update --no-cache add make g++ python findutils postgresql-dev
|
|
||||||
|
|
||||||
WORKDIR /app
|
|
||||||
COPY . /app
|
|
||||||
run yarn install
|
|
||||||
RUN ["./node_modules/typescript/bin/tsc"]
|
|
||||||
EXPOSE 3000
|
|
||||||
CMD ["node", "/app/build/dist/index.js"]
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
# Vulcanize GraphQL API
|
|
||||||
|
|
||||||
This application utilizes Postgraphile to expose GraphQL endpoints for exposure of the varied data that VulcanizeDB tracks.
|
|
||||||
|
|
||||||
## Docker use
|
|
||||||
_Note: currently this image is ~500MB large (unpacked)_
|
|
||||||
|
|
||||||
Build the docker image in this directory. Start the `GraphiQL` frontend by:
|
|
||||||
* Setting the env variables for the database connection: `DATABASE_HOST`,
|
|
||||||
`DATABASE_NAME`, `DATABASE_USER`, `DATABASE_PASSWORD` (and optionally
|
|
||||||
`DATABASE_PORT` if running on non-standard port).
|
|
||||||
* The specified user needs to be `superuser` on the vulcanizeDB database,
|
|
||||||
so postgraphile can setup watch fixtures keeping track of live schema
|
|
||||||
changes.
|
|
||||||
* To limit the amount of available queries in GraphQL, a restricted user can be used
|
|
||||||
for postgraphile introspection by adding env variables `GQ_USER` and `GQ_PASSWORD`.
|
|
||||||
* By doing `GRANT [SELECT | EXECUTE]` on tables/functions for this user,
|
|
||||||
you can selectively assign things you want available in GraphQL.
|
|
||||||
* You still need to pass in a superuser with `DATABASE_USER` & `DATABASE_PASSWORD` for
|
|
||||||
the postgraphile watch fixtures to work.
|
|
||||||
* By default, postgraphile publishes the `public` schema. This can be expanded with for example `GQ_SCHEMAS=public,maker`
|
|
||||||
* Run the container (ex. `docker run -e DATABASE_HOST=localhost -e DATABASE_NAME=my_database -e DATABASE_USER=superuser -e DATABASE_PASSWORD=superuser -e GQ_USER=graphql -e GQ_PASSWORD=graphql -e GQ_SCHEMAS=public,anotherSchema -d my-postgraphile-image`)
|
|
||||||
* GraphiQL frontend is available at `:3000/graphiql`
|
|
||||||
GraphQL endpoint is available at `:3000/graphql`
|
|
||||||
|
|
||||||
By default, this build will expose only the "public" schema and will disable mutations - to change mutation behaviour, you can use an optional config file `config.toml` and set the env var `POSTGRAPHILE_CONFIG_PATH` to point to its location. Example `toml`:
|
|
||||||
|
|
||||||
```
|
|
||||||
[database]
|
|
||||||
name = "vulcanize_public"
|
|
||||||
hostname = "localhost"
|
|
||||||
port = 5432
|
|
||||||
gq_schemas = ["public", "yourschema"]
|
|
||||||
gq_user = "graphql"
|
|
||||||
gq_password = "graphql"
|
|
||||||
disable_default_mutations = false
|
|
||||||
```
|
|
||||||
|
|
||||||
## Building
|
|
||||||
|
|
||||||
*This application assumes the use of the [Yarn package manager](https://yarnpkg.com/en/). The use of npm may produce unexpected results.*
|
|
||||||
|
|
||||||
Install dependencies with `yarn` and execute `yarn build`. The bundle produced by Webpack will be present in `build/dist/`.
|
|
||||||
|
|
||||||
## Running
|
|
||||||
|
|
||||||
Provide the built bundle to node as a runnable script: `node ./build/dist/vulcanize-postgraphile-server.js`
|
|
||||||
|
|
||||||
## Testing
|
|
||||||
|
|
||||||
Tests are executed via Jasmine with a console reporter via the `yarn test` task.
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "vulcanizedb",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"description": "",
|
|
||||||
"scripts": {
|
|
||||||
"build": "rm -rf ./build/dist && webpack --config=./webpack.config.js",
|
|
||||||
"lint": "tslint --project ./tsconfig.json --config ./tslint.json",
|
|
||||||
"start": "npm run build && node ./build/dist/vulcanize-postgraphile-server.js",
|
|
||||||
"dev": "./node_modules/typescript/bin/tsc && node build/dist/src/index.js",
|
|
||||||
"test": "rm -rf ./build/spec && tsc --build ./tsconfig.test.json && jasmine --config=./spec/support/jasmine.json",
|
|
||||||
"test:ci": "npm run lint && npm run test"
|
|
||||||
},
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/vulcanize/vulcanizedb.git"
|
|
||||||
},
|
|
||||||
"author": "Vulcanize, Inc.",
|
|
||||||
"license": "AGPL-3.0",
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/vulcanize/vulcanizedb/issues"
|
|
||||||
},
|
|
||||||
"homepage": "https://github.com/vulcanize/vulcanizedb",
|
|
||||||
"dependencies": {
|
|
||||||
"express-session": "1.15.6",
|
|
||||||
"graphql-subscriptions": "0.5.8",
|
|
||||||
"lodash": ">=4.17.11",
|
|
||||||
"passport": "0.4.0",
|
|
||||||
"pg": "6.4.2",
|
|
||||||
"pg-native": "3.0.0",
|
|
||||||
"postgraphile": "4.4.0-beta.11",
|
|
||||||
"subscriptions-transport-ws": "0.9.14",
|
|
||||||
"toml": "2.3.3"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/express": "4.16.0",
|
|
||||||
"@types/express-session": "1.15.10",
|
|
||||||
"@types/graphql": "^0.13.4",
|
|
||||||
"@types/jasmine": "2.8.8",
|
|
||||||
"@types/lodash": "4.14.116",
|
|
||||||
"@types/node": "^10.12.21",
|
|
||||||
"@types/passport": "0.4.6",
|
|
||||||
"@graphile-contrib/pg-simplify-inflector": "3.0.0",
|
|
||||||
"awesome-typescript-loader": "5.2.0",
|
|
||||||
"jasmine": "3.2.0",
|
|
||||||
"jasmine-ts-console-reporter": "3.1.1",
|
|
||||||
"source-map-loader": "0.2.4",
|
|
||||||
"tslint": "5.11.0",
|
|
||||||
"tslint-eslint-rules": "5.4.0",
|
|
||||||
"typescript": "3.0.1",
|
|
||||||
"webpack": "4.17.1",
|
|
||||||
"webpack-cli": "3.1.0",
|
|
||||||
"webpack-dev-server": ">=3.1.11"
|
|
||||||
},
|
|
||||||
"resolutions": {
|
|
||||||
"pg": "6.4.2"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
import { parseConfig } from '../../src/config/parse';
|
|
||||||
|
|
||||||
describe('parseConfig', () => {
|
|
||||||
let configPath: string;
|
|
||||||
let tomlContents: string;
|
|
||||||
let parsedToml: object;
|
|
||||||
let readCallback: jasmine.Spy;
|
|
||||||
let tomlParseCallback: jasmine.Spy;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
configPath = '/example/config/path.toml';
|
|
||||||
tomlContents = `[database]\nname = 'example_database'\n `
|
|
||||||
+ `hostname = 'example.com'\nport = 1234`;
|
|
||||||
|
|
||||||
parsedToml = {
|
|
||||||
database: {
|
|
||||||
hostname: 'example.com',
|
|
||||||
name: 'example_database',
|
|
||||||
port: '1234',
|
|
||||||
user: 'user',
|
|
||||||
password: 'password'
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
readCallback = jasmine.createSpy('readCallback');
|
|
||||||
readCallback.and.returnValue(tomlContents);
|
|
||||||
|
|
||||||
tomlParseCallback = jasmine.createSpy('tomlParseCallback');
|
|
||||||
tomlParseCallback.and.returnValue(parsedToml);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('provides the database host', () => {
|
|
||||||
const databaseConfig = parseConfig(
|
|
||||||
readCallback, tomlParseCallback, configPath);
|
|
||||||
|
|
||||||
expect(databaseConfig.host)
|
|
||||||
.toEqual('postgres://user:password@example.com:1234');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('provides the database name', () => {
|
|
||||||
const databaseConfig = parseConfig(
|
|
||||||
readCallback, tomlParseCallback, configPath);
|
|
||||||
|
|
||||||
expect(databaseConfig.database).toEqual('example_database');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('handles a missing config path', () => {
|
|
||||||
const failingCall = () =>
|
|
||||||
parseConfig(readCallback, tomlParseCallback, '');
|
|
||||||
|
|
||||||
tomlParseCallback.and.returnValue({
|
|
||||||
database: { hostname: 'example.com', name: 'example_database' }
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(failingCall).toThrow();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('handles a missing database host', () => {
|
|
||||||
const failingCall = () =>
|
|
||||||
parseConfig(readCallback, tomlParseCallback, configPath);
|
|
||||||
|
|
||||||
tomlParseCallback.and.returnValue({
|
|
||||||
database: { hostname: '', name: 'example_database' }
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(failingCall).toThrow();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('handles a missing database name', () => {
|
|
||||||
const failingCall = () =>
|
|
||||||
parseConfig(readCallback, tomlParseCallback, configPath);
|
|
||||||
|
|
||||||
tomlParseCallback.and.returnValue({
|
|
||||||
database: { hostname: 'example.com', name: '', port: '1234' }
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(failingCall).toThrow();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
// NOTE: This file helps Jasmine
|
|
||||||
// comprehend TS sourcemaps by installing a reporter
|
|
||||||
// specifically for TypeScript
|
|
||||||
const TSConsoleReporter = require('jasmine-ts-console-reporter');
|
|
||||||
|
|
||||||
jasmine.getEnv().clearReporters();
|
|
||||||
jasmine.getEnv().addReporter(new TSConsoleReporter());
|
|
||||||
@@ -1,106 +0,0 @@
|
|||||||
import { PassportStatic } from 'passport';
|
|
||||||
|
|
||||||
import { PostgraphileMiddleware } from '../../src/adapters/postgraphile';
|
|
||||||
import { buildServerConfig } from '../../src/server/config';
|
|
||||||
|
|
||||||
import {
|
|
||||||
DatabaseConfig,
|
|
||||||
ServerConfig,
|
|
||||||
ServerUtilities
|
|
||||||
} from '../../src/server/interface';
|
|
||||||
|
|
||||||
describe('buildServerConfig', () => {
|
|
||||||
let configParser: jasmine.Spy;
|
|
||||||
let postgraphileMiddleware: PostgraphileMiddleware;
|
|
||||||
let expressSessionHandler: jasmine.Spy;
|
|
||||||
let passportInitializer: jasmine.Spy;
|
|
||||||
let passportSessionHandler: jasmine.Spy;
|
|
||||||
let serverConfig: ServerConfig;
|
|
||||||
|
|
||||||
let serverUtilities: ServerUtilities;
|
|
||||||
let databaseConfig: DatabaseConfig;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
databaseConfig = {
|
|
||||||
host: 'example.com',
|
|
||||||
database: 'example_database',
|
|
||||||
schemas: ['public'],
|
|
||||||
ownerConnectionString: 'postgres://admin:admin@host',
|
|
||||||
disableDefaultMutations: true
|
|
||||||
};
|
|
||||||
|
|
||||||
postgraphileMiddleware = jasmine
|
|
||||||
.createSpyObj<PostgraphileMiddleware>(['call']);
|
|
||||||
|
|
||||||
serverUtilities = {
|
|
||||||
pluginHook: jasmine.createSpy('pluginHook'),
|
|
||||||
express: jasmine.createSpy('express'),
|
|
||||||
expressSession: jasmine.createSpy('expressSession'),
|
|
||||||
httpServerFactory: jasmine.createSpy('httpServerFactory'),
|
|
||||||
passport: jasmine.createSpyObj<PassportStatic>(['initialize', 'session']),
|
|
||||||
postgraphile: jasmine.createSpy('postgraphile')
|
|
||||||
};
|
|
||||||
|
|
||||||
const rawConfig: object = { exampleOption: 'example value' };
|
|
||||||
|
|
||||||
configParser = jasmine.createSpy('configParser');
|
|
||||||
configParser.and.returnValue(rawConfig);
|
|
||||||
|
|
||||||
expressSessionHandler = jasmine.createSpy('expressSessionHandler');
|
|
||||||
passportInitializer = jasmine.createSpy('passportInitializer');
|
|
||||||
passportSessionHandler = jasmine.createSpy('passportSessionHandler');
|
|
||||||
|
|
||||||
(serverUtilities.postgraphile as jasmine.Spy)
|
|
||||||
.and.returnValue(postgraphileMiddleware);
|
|
||||||
(serverUtilities.expressSession as jasmine.Spy)
|
|
||||||
.and.returnValue(expressSessionHandler);
|
|
||||||
(serverUtilities.passport.initialize as jasmine.Spy)
|
|
||||||
.and.returnValue(passportInitializer);
|
|
||||||
(serverUtilities.passport.session as jasmine.Spy)
|
|
||||||
.and.returnValue(passportSessionHandler);
|
|
||||||
|
|
||||||
serverConfig = buildServerConfig(
|
|
||||||
serverUtilities, databaseConfig, undefined);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('provides the Postgraphile options', () => {
|
|
||||||
expect(serverConfig.options).not.toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('it adds the express session handler as the first middleware', () => {
|
|
||||||
expect(serverConfig.options.webSocketMiddlewares[0])
|
|
||||||
.toBe(expressSessionHandler);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('it adds the passport initializer as the second middleware', () => {
|
|
||||||
expect(serverConfig.options.webSocketMiddlewares[1])
|
|
||||||
.toBe(passportInitializer);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('it adds the passport session handler as the third middleware', () => {
|
|
||||||
expect(serverConfig.options.webSocketMiddlewares[2])
|
|
||||||
.toBe(passportSessionHandler);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('provides the database config to Postgraphile', () => {
|
|
||||||
expect(serverUtilities.postgraphile).toHaveBeenCalledWith(
|
|
||||||
`${databaseConfig.host}/${databaseConfig.database}`,
|
|
||||||
databaseConfig.schemas,
|
|
||||||
jasmine.any(Object));
|
|
||||||
});
|
|
||||||
|
|
||||||
it('provides the Postgraphile middleware', () => {
|
|
||||||
expect(serverConfig.middleware).toBe(postgraphileMiddleware);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('sets the default server port', () => {
|
|
||||||
expect(serverConfig.port).toEqual(3000);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('sets an explicit server port', () => {
|
|
||||||
const serverConfigWithPort = buildServerConfig(
|
|
||||||
serverUtilities, databaseConfig, '1234');
|
|
||||||
|
|
||||||
expect(serverConfigWithPort.port).toEqual(1234);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
import { Express } from 'express';
|
|
||||||
import { PassportStatic } from 'passport';
|
|
||||||
import { Server } from 'http';
|
|
||||||
|
|
||||||
import { ServerUtilities, ServerConfig } from '../../src/server/interface';
|
|
||||||
import { bootServer } from '../../src/server/runtime';
|
|
||||||
import { PostgraphileMiddleware } from '../../src/adapters/postgraphile';
|
|
||||||
|
|
||||||
describe('bootServer', () => {
|
|
||||||
let serverUtilities: ServerUtilities;
|
|
||||||
let serverConfig: ServerConfig;
|
|
||||||
let mockExpressApp: Express;
|
|
||||||
let mockHttpServer: Server;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
serverUtilities = {
|
|
||||||
pluginHook: jasmine.createSpy('pluginHook'),
|
|
||||||
express: jasmine.createSpy('express'),
|
|
||||||
expressSession: jasmine.createSpy('expressSession'),
|
|
||||||
httpServerFactory: jasmine.createSpy('httpServerFactory'),
|
|
||||||
passport: jasmine.createSpyObj<PassportStatic>(['initialize', 'session']),
|
|
||||||
postgraphile: jasmine.createSpy('postgraphile')
|
|
||||||
};
|
|
||||||
|
|
||||||
serverConfig = {
|
|
||||||
middleware: jasmine.createSpyObj<PostgraphileMiddleware>(['call']),
|
|
||||||
options: {
|
|
||||||
appendPlugins: [],
|
|
||||||
disableDefaultMutations: false,
|
|
||||||
enableCors: true,
|
|
||||||
exportGqlSchemaPath: '',
|
|
||||||
graphiql: true,
|
|
||||||
ignoreRBAC: false,
|
|
||||||
ownerConnectionString: '',
|
|
||||||
pluginHook: jasmine.createSpy('pluginHook'),
|
|
||||||
watchPg: true,
|
|
||||||
webSocketMiddlewares: [] },
|
|
||||||
port: 5678
|
|
||||||
};
|
|
||||||
|
|
||||||
mockExpressApp = jasmine.createSpyObj<Express>(['use']);
|
|
||||||
(serverUtilities.express as jasmine.Spy)
|
|
||||||
.and.returnValue(mockExpressApp);
|
|
||||||
|
|
||||||
mockHttpServer = jasmine.createSpyObj<Server>(['listen']);
|
|
||||||
(serverUtilities.httpServerFactory as jasmine.Spy)
|
|
||||||
.and.returnValue(mockHttpServer);
|
|
||||||
|
|
||||||
bootServer(serverUtilities, serverConfig);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('builds a new, Node HTTP server', () => {
|
|
||||||
expect(serverUtilities.httpServerFactory)
|
|
||||||
.toHaveBeenCalledWith(mockExpressApp);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('provides Postgraphile middleware to the Express app', () => {
|
|
||||||
const useSpy = mockExpressApp.use as jasmine.Spy;
|
|
||||||
expect(useSpy).toHaveBeenCalledWith(serverConfig.middleware);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('instructs the server to listen on the given port', () => {
|
|
||||||
const listenSpy = mockHttpServer.listen as jasmine.Spy;
|
|
||||||
expect(listenSpy).toHaveBeenCalledWith(serverConfig.port);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
{
|
|
||||||
"spec_dir": "build/spec/",
|
|
||||||
"spec_files": [
|
|
||||||
"**/*[sS]pec.js"
|
|
||||||
],
|
|
||||||
"helpers": [
|
|
||||||
"helpers/*.js"
|
|
||||||
],
|
|
||||||
"stopSpecOnExpectationFailure": false,
|
|
||||||
"random": true
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
import { URL } from 'url';
|
|
||||||
|
|
||||||
export type ReadFileSyncCallback = (
|
|
||||||
path: string | number | Buffer | URL,
|
|
||||||
options?: { encoding?: null | undefined; flag?: string | undefined; }
|
|
||||||
| null
|
|
||||||
| undefined
|
|
||||||
) => string | Buffer;
|
|
||||||
|
|
||||||
export type TomlParseCallback
|
|
||||||
= (fileContents: string) => { [key: string]: { [key: string]: any } };
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
import { IncomingMessage, ServerResponse, Server } from 'http';
|
|
||||||
|
|
||||||
export type RequestListenerCallback
|
|
||||||
= (request: IncomingMessage, response: ServerResponse) => void;
|
|
||||||
|
|
||||||
export type CreateHttpServerCallback
|
|
||||||
= (requestListener?: RequestListenerCallback) => Server;
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
import { RequestHandler } from 'express';
|
|
||||||
import {PluginHookFn } from 'postgraphile/build/postgraphile/pluginHook';
|
|
||||||
import {Plugin} from 'postgraphile';
|
|
||||||
|
|
||||||
// NOTE: Shape of the middleware is not
|
|
||||||
// currently important to this application, but if a need arises,
|
|
||||||
// any needed shape can be assigned from a custom type here. For
|
|
||||||
// the time being, this is a named stub to provide clarity.
|
|
||||||
export interface PostgraphileMiddleware extends RequestHandler {}
|
|
||||||
|
|
||||||
export interface PostgraphileOptions {
|
|
||||||
appendPlugins: Plugin[];
|
|
||||||
disableDefaultMutations: boolean;
|
|
||||||
enableCors: boolean;
|
|
||||||
exportGqlSchemaPath: string;
|
|
||||||
graphiql: boolean;
|
|
||||||
ignoreRBAC: boolean;
|
|
||||||
ownerConnectionString: string;
|
|
||||||
pluginHook: PluginHookFn;
|
|
||||||
watchPg: boolean;
|
|
||||||
// NOTE Shape of the middlewares is not
|
|
||||||
// currently important to this application, but if a need arises,
|
|
||||||
// any needed shape can be assigned from a custom type here.
|
|
||||||
webSocketMiddlewares: object[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export type PostgraphileInitCallback = (
|
|
||||||
databaseUrl: string,
|
|
||||||
schemas: string[],
|
|
||||||
options: PostgraphileOptions
|
|
||||||
) => PostgraphileMiddleware;
|
|
||||||
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
import { SessionOptions } from 'express-session';
|
|
||||||
import { Express, RequestHandler, Handler } from 'express';
|
|
||||||
|
|
||||||
export type ExpressInitCallback = () => Express;
|
|
||||||
|
|
||||||
export type ExpressSessionInitCallback
|
|
||||||
= (options?: SessionOptions) => RequestHandler ;
|
|
||||||
|
|
||||||
export type PassportInitCallback = (
|
|
||||||
options?: { userProperty: string; } | undefined
|
|
||||||
) => Handler;
|
|
||||||
|
|
||||||
export type PassportSessionCallback = (
|
|
||||||
options?: { pauseStream: boolean; } | undefined
|
|
||||||
) => Handler;
|
|
||||||
|
|
||||||
export interface StaticPassportProvider {
|
|
||||||
initialize: PassportInitCallback;
|
|
||||||
session: PassportSessionCallback;
|
|
||||||
}
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
import { CONFIG_PATH_KEY } from '../server/config';
|
|
||||||
import { DatabaseConfig } from '../server/interface';
|
|
||||||
import { ReadFileSyncCallback, TomlParseCallback } from '../adapters/fs';
|
|
||||||
|
|
||||||
export const MISSING_PATH_MESSAGE = `No path to config toml file provided, `
|
|
||||||
+ `please check the value of ${CONFIG_PATH_KEY} in your environment`;
|
|
||||||
|
|
||||||
export const MISSING_HOST_MESSAGE = 'No database host provided in config toml';
|
|
||||||
export const MISSING_USER_MESSAGE = 'No database user & password '
|
|
||||||
+ 'provided in config toml';
|
|
||||||
export const MISSING_DATABASE_MESSAGE = 'No database name provided '
|
|
||||||
+ 'in config toml';
|
|
||||||
|
|
||||||
export function parseConfig(
|
|
||||||
readCallback: ReadFileSyncCallback,
|
|
||||||
tomlParseCallback: TomlParseCallback,
|
|
||||||
configPath?: string
|
|
||||||
): DatabaseConfig {
|
|
||||||
let host = '';
|
|
||||||
let port = '';
|
|
||||||
let database = '';
|
|
||||||
let user = '';
|
|
||||||
let password = '';
|
|
||||||
let gqSchemas = ['public'];
|
|
||||||
let gqUser = '';
|
|
||||||
let gqPassword = '';
|
|
||||||
let disableDefaultMutations = true;
|
|
||||||
|
|
||||||
if (configPath) {
|
|
||||||
const tomlContents = readCallback(`${configPath}`).toString();
|
|
||||||
const parsedToml = tomlParseCallback(tomlContents);
|
|
||||||
|
|
||||||
host = parsedToml['database']['hostname'];
|
|
||||||
port = parsedToml['database']['port'];
|
|
||||||
database = parsedToml['database']['name'];
|
|
||||||
user = parsedToml['database']['user'];
|
|
||||||
password = parsedToml['database']['password'];
|
|
||||||
gqSchemas = parsedToml['database']['gq_schemas'];
|
|
||||||
gqUser = parsedToml['database']['gq_user'] || gqUser;
|
|
||||||
gqPassword = parsedToml['database']['gq_password'] || gqPassword;
|
|
||||||
disableDefaultMutations = parsedToml['database']['disable_default_mutations'] === undefined
|
|
||||||
? true
|
|
||||||
: parsedToml['database']['disable_default_mutations'];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Overwrite config values with env. vars if such are set
|
|
||||||
host = process.env.DATABASE_HOST || host;
|
|
||||||
port = process.env.DATABASE_PORT || port;
|
|
||||||
database = process.env.DATABASE_NAME || database;
|
|
||||||
user = process.env.DATABASE_USER || user;
|
|
||||||
password = process.env.DATABASE_PASSWORD || password;
|
|
||||||
gqSchemas = process.env.GQ_SCHEMAS
|
|
||||||
? process.env.GQ_SCHEMAS.split(',')
|
|
||||||
: gqSchemas;
|
|
||||||
gqUser = process.env.GQ_USER || gqUser;
|
|
||||||
gqPassword = process.env.GQ_PASSWORD || gqPassword;
|
|
||||||
|
|
||||||
if (!host) {
|
|
||||||
throw new Error(MISSING_HOST_MESSAGE);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!database) {
|
|
||||||
throw new Error(MISSING_DATABASE_MESSAGE);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!user || !password) {
|
|
||||||
throw new Error(MISSING_USER_MESSAGE);
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
host: gqUser && gqPassword
|
|
||||||
? `postgres://${gqUser}:${gqPassword}@${host}:${port}`
|
|
||||||
: `postgres://${user}:${password}@${host}:${port}`,
|
|
||||||
database,
|
|
||||||
schemas: gqSchemas,
|
|
||||||
ownerConnectionString: `postgres://${user}:${password}@${host}:${port}/${database}`,
|
|
||||||
disableDefaultMutations
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
import { createServer } from 'http';
|
|
||||||
import { postgraphile, makePluginHook } from 'postgraphile';
|
|
||||||
import { readFileSync } from 'fs';
|
|
||||||
|
|
||||||
import express = require('express');
|
|
||||||
import passport = require('passport');
|
|
||||||
import session = require('express-session');
|
|
||||||
import toml = require('toml');
|
|
||||||
|
|
||||||
const pluginHook = makePluginHook([]);
|
|
||||||
|
|
||||||
import { ServerUtilities } from './server/interface';
|
|
||||||
import { bootServer } from './server/runtime';
|
|
||||||
import { parseConfig } from './config/parse';
|
|
||||||
|
|
||||||
import {
|
|
||||||
buildServerConfig,
|
|
||||||
CONFIG_PATH_KEY,
|
|
||||||
SERVER_PORT_KEY
|
|
||||||
} from './server/config';
|
|
||||||
|
|
||||||
const configPath = process.env[CONFIG_PATH_KEY];
|
|
||||||
const serverPort = process.env[SERVER_PORT_KEY];
|
|
||||||
|
|
||||||
const serverUtilities: ServerUtilities = {
|
|
||||||
express,
|
|
||||||
expressSession: session,
|
|
||||||
httpServerFactory: createServer,
|
|
||||||
passport,
|
|
||||||
postgraphile,
|
|
||||||
pluginHook
|
|
||||||
};
|
|
||||||
|
|
||||||
const databaseConfig = parseConfig(readFileSync, toml.parse, configPath);
|
|
||||||
const serverConfig = buildServerConfig(
|
|
||||||
serverUtilities, databaseConfig, serverPort);
|
|
||||||
|
|
||||||
bootServer(serverUtilities, serverConfig);
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
import { ServerUtilities, DatabaseConfig, ServerConfig } from './interface';
|
|
||||||
|
|
||||||
import {
|
|
||||||
PostgraphileMiddleware,
|
|
||||||
PostgraphileOptions
|
|
||||||
} from '../adapters/postgraphile';
|
|
||||||
|
|
||||||
export const CONFIG_PATH_KEY = 'POSTGRAPHILE_CONFIG_PATH';
|
|
||||||
export const SERVER_PORT_KEY = 'SERVER_PORT';
|
|
||||||
|
|
||||||
const DEFAULT_SERVER_PORT = '3000';
|
|
||||||
|
|
||||||
export function buildServerConfig(
|
|
||||||
utilities: ServerUtilities,
|
|
||||||
databaseConfig: DatabaseConfig,
|
|
||||||
port?: string
|
|
||||||
): ServerConfig {
|
|
||||||
if (!port || port.length < 1) {
|
|
||||||
port = DEFAULT_SERVER_PORT;
|
|
||||||
}
|
|
||||||
|
|
||||||
const expressSessionHandler = utilities.expressSession();
|
|
||||||
const passportInitializer = utilities.passport.initialize();
|
|
||||||
const passportSessionHandler = utilities.passport.session();
|
|
||||||
const pluginHook = utilities.pluginHook;
|
|
||||||
const PgSimplifyInflectorPlugin = require('@graphile-contrib/pg-simplify-inflector');
|
|
||||||
|
|
||||||
const options: PostgraphileOptions = {
|
|
||||||
appendPlugins: [PgSimplifyInflectorPlugin],
|
|
||||||
disableDefaultMutations: databaseConfig.disableDefaultMutations,
|
|
||||||
enableCors: true,
|
|
||||||
exportGqlSchemaPath: 'schema.graphql',
|
|
||||||
graphiql: true,
|
|
||||||
ignoreRBAC: false,
|
|
||||||
ownerConnectionString: databaseConfig.ownerConnectionString,
|
|
||||||
pluginHook: pluginHook,
|
|
||||||
watchPg: true,
|
|
||||||
webSocketMiddlewares: [
|
|
||||||
expressSessionHandler,
|
|
||||||
passportInitializer,
|
|
||||||
passportSessionHandler
|
|
||||||
]
|
|
||||||
};
|
|
||||||
|
|
||||||
const middleware: PostgraphileMiddleware = utilities.postgraphile(
|
|
||||||
`${databaseConfig.host}/${databaseConfig.database}`,
|
|
||||||
databaseConfig.schemas,
|
|
||||||
options
|
|
||||||
);
|
|
||||||
|
|
||||||
return { middleware, options, port: parseInt(port, 10) };
|
|
||||||
}
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
import { CreateHttpServerCallback } from '../adapters/http';
|
|
||||||
|
|
||||||
import {
|
|
||||||
ExpressInitCallback,
|
|
||||||
ExpressSessionInitCallback,
|
|
||||||
StaticPassportProvider
|
|
||||||
} from '../adapters/session';
|
|
||||||
|
|
||||||
import {
|
|
||||||
PostgraphileInitCallback,
|
|
||||||
PostgraphileMiddleware,
|
|
||||||
PostgraphileOptions
|
|
||||||
} from '../adapters/postgraphile';
|
|
||||||
import { PluginHookFn } from 'postgraphile/build/postgraphile/pluginHook';
|
|
||||||
|
|
||||||
export interface DatabaseConfig {
|
|
||||||
host: string;
|
|
||||||
database: string;
|
|
||||||
schemas: string[];
|
|
||||||
ownerConnectionString: string;
|
|
||||||
disableDefaultMutations: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ServerConfig {
|
|
||||||
middleware: PostgraphileMiddleware;
|
|
||||||
options: PostgraphileOptions;
|
|
||||||
port: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ServerUtilities {
|
|
||||||
express: ExpressInitCallback;
|
|
||||||
expressSession: ExpressSessionInitCallback;
|
|
||||||
httpServerFactory: CreateHttpServerCallback;
|
|
||||||
passport: StaticPassportProvider;
|
|
||||||
postgraphile: PostgraphileInitCallback;
|
|
||||||
pluginHook: PluginHookFn;
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import { ServerUtilities, ServerConfig } from './interface';
|
|
||||||
|
|
||||||
export function bootServer(
|
|
||||||
utilities: ServerUtilities,
|
|
||||||
config: ServerConfig
|
|
||||||
): void {
|
|
||||||
const expressApp = utilities.express();
|
|
||||||
expressApp.use(config.middleware);
|
|
||||||
|
|
||||||
const httpServer = utilities.httpServerFactory(expressApp);
|
|
||||||
|
|
||||||
httpServer.listen(config.port);
|
|
||||||
}
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
/* Basic Options */
|
|
||||||
"target": "es2017", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
|
|
||||||
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
|
|
||||||
"lib": ["esnext"], /* Specify library files to be included in the compilation: */
|
|
||||||
// "allowJs": true, /* Allow javascript files to be compiled. */
|
|
||||||
// "checkJs": true, /* Report errors in .js files. */
|
|
||||||
"jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
|
|
||||||
// "declaration": true, /* Generates corresponding '.d.ts' file. */
|
|
||||||
"sourceMap": true, /* Generates corresponding '.map' file. */
|
|
||||||
// "outFile": "./", /* Concatenate and emit output to single file. */
|
|
||||||
"outDir": "build/dist", /* Redirect output structure to the directory. */
|
|
||||||
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
|
|
||||||
"removeComments": true, /* Do not emit comments to output. */
|
|
||||||
// "noEmit": true, /* Do not emit outputs. */
|
|
||||||
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
|
|
||||||
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
|
|
||||||
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
|
|
||||||
|
|
||||||
/* Strict Type-Checking Options */
|
|
||||||
"strict": true, /* Enable all strict type-checking options. */
|
|
||||||
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
|
|
||||||
// "strictNullChecks": true, /* Enable strict null checks. */
|
|
||||||
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
|
|
||||||
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
|
|
||||||
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
|
|
||||||
|
|
||||||
/* Additional Checks */
|
|
||||||
// "noUnusedLocals": true, /* Report errors on unused locals. */
|
|
||||||
// "noUnusedParameters": true, /* Report errors on unused parameters. */
|
|
||||||
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
|
|
||||||
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
|
|
||||||
|
|
||||||
/* Module Resolution Options */
|
|
||||||
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
|
|
||||||
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
|
|
||||||
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
|
|
||||||
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
|
|
||||||
// "typeRoots": [], /* List of folders to include type definitions from. */
|
|
||||||
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
|
|
||||||
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
|
|
||||||
|
|
||||||
/* Source Map Options */
|
|
||||||
// "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
|
|
||||||
// "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
|
|
||||||
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
|
|
||||||
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
|
|
||||||
|
|
||||||
/* Experimental Options */
|
|
||||||
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
|
|
||||||
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
/* Basic Options */
|
|
||||||
"target": "es2017", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
|
|
||||||
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
|
|
||||||
"lib": ["esnext"], /* Specify library files to be included in the compilation: */
|
|
||||||
// "allowJs": true, /* Allow javascript files to be compiled. */
|
|
||||||
// "checkJs": true, /* Report errors in .js files. */
|
|
||||||
"jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
|
|
||||||
// "declaration": true, /* Generates corresponding '.d.ts' file. */
|
|
||||||
"sourceMap": true, /* Generates corresponding '.map' file. */
|
|
||||||
// "outFile": "./", /* Concatenate and emit output to single file. */
|
|
||||||
"outDir": "build/spec", /* Redirect output structure to the directory. */
|
|
||||||
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
|
|
||||||
"removeComments": true, /* Do not emit comments to output. */
|
|
||||||
// "noEmit": true, /* Do not emit outputs. */
|
|
||||||
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
|
|
||||||
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
|
|
||||||
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
|
|
||||||
|
|
||||||
/* Strict Type-Checking Options */
|
|
||||||
"strict": true, /* Enable all strict type-checking options. */
|
|
||||||
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
|
|
||||||
// "strictNullChecks": true, /* Enable strict null checks. */
|
|
||||||
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
|
|
||||||
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
|
|
||||||
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
|
|
||||||
|
|
||||||
/* Additional Checks */
|
|
||||||
// "noUnusedLocals": true, /* Report errors on unused locals. */
|
|
||||||
// "noUnusedParameters": true, /* Report errors on unused parameters. */
|
|
||||||
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
|
|
||||||
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
|
|
||||||
|
|
||||||
/* Module Resolution Options */
|
|
||||||
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
|
|
||||||
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
|
|
||||||
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
|
|
||||||
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
|
|
||||||
// "typeRoots": [], /* List of folders to include type definitions from. */
|
|
||||||
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
|
|
||||||
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
|
|
||||||
|
|
||||||
/* Source Map Options */
|
|
||||||
// "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
|
|
||||||
// "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
|
|
||||||
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
|
|
||||||
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
|
|
||||||
|
|
||||||
/* Experimental Options */
|
|
||||||
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
|
|
||||||
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
{
|
|
||||||
"extends": [
|
|
||||||
"tslint-eslint-rules"
|
|
||||||
],
|
|
||||||
"rules": {
|
|
||||||
"object-curly-spacing": true,
|
|
||||||
"ter-indent": [true, 2],
|
|
||||||
"array-bracket-spacing": ["error", "never"],
|
|
||||||
"class-name": true,
|
|
||||||
"comment-format": [
|
|
||||||
true,
|
|
||||||
"check-space"
|
|
||||||
],
|
|
||||||
"curly": [true, "ignore-same-line"],
|
|
||||||
"eofline": true,
|
|
||||||
"forin": true,
|
|
||||||
"indent": [
|
|
||||||
true,
|
|
||||||
"spaces"
|
|
||||||
],
|
|
||||||
"label-position": true,
|
|
||||||
"max-line-length": [
|
|
||||||
true,
|
|
||||||
80
|
|
||||||
],
|
|
||||||
"member-access": [true, "no-public"],
|
|
||||||
"member-ordering": [true, { "order": "statics-first" }],
|
|
||||||
"no-arg": true,
|
|
||||||
"no-bitwise": true,
|
|
||||||
"no-console": [
|
|
||||||
true,
|
|
||||||
"debug",
|
|
||||||
"info",
|
|
||||||
"time",
|
|
||||||
"timeEnd",
|
|
||||||
"trace"
|
|
||||||
],
|
|
||||||
"no-consecutive-blank-lines": true,
|
|
||||||
"no-construct": true,
|
|
||||||
"no-debugger": true,
|
|
||||||
"no-duplicate-variable": true,
|
|
||||||
"no-empty": false,
|
|
||||||
"no-eval": true,
|
|
||||||
"no-inferrable-types": true,
|
|
||||||
"no-shadowed-variable": false,
|
|
||||||
"no-string-literal": false,
|
|
||||||
"no-switch-case-fall-through": true,
|
|
||||||
"no-trailing-whitespace": false,
|
|
||||||
"no-unused-expression": false,
|
|
||||||
"no-use-before-declare": true,
|
|
||||||
"no-var-keyword": false,
|
|
||||||
"object-literal-sort-keys": false,
|
|
||||||
"one-line": [
|
|
||||||
true,
|
|
||||||
"check-open-brace",
|
|
||||||
"check-whitespace"
|
|
||||||
],
|
|
||||||
"quotemark": [
|
|
||||||
true,
|
|
||||||
"single"
|
|
||||||
],
|
|
||||||
"radix": true,
|
|
||||||
"semicolon": true,
|
|
||||||
"triple-equals": [
|
|
||||||
true,
|
|
||||||
"allow-null-check"
|
|
||||||
],
|
|
||||||
"typedef-whitespace": [
|
|
||||||
true,
|
|
||||||
{
|
|
||||||
"call-signature": "nospace",
|
|
||||||
"index-signature": "nospace",
|
|
||||||
"parameter": "nospace",
|
|
||||||
"property-declaration": "nospace",
|
|
||||||
"variable-declaration": "nospace"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"variable-name": false,
|
|
||||||
"whitespace": [
|
|
||||||
true,
|
|
||||||
"check-branch",
|
|
||||||
"check-decl",
|
|
||||||
"check-operator",
|
|
||||||
"check-separator",
|
|
||||||
"check-type"
|
|
||||||
],
|
|
||||||
|
|
||||||
"use-host-property-decorator": false,
|
|
||||||
"no-access-missing-member": false,
|
|
||||||
"templates-use-public": false,
|
|
||||||
"brace-style": false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
module.exports = {
|
|
||||||
entry: "./src/index.ts",
|
|
||||||
mode: "production",
|
|
||||||
devtool: "source-map",
|
|
||||||
target: 'node',
|
|
||||||
output: {
|
|
||||||
filename: "vulcanize-postgraphile-server.js",
|
|
||||||
path: __dirname + "/build/dist/",
|
|
||||||
publicPath: "build/dist/"
|
|
||||||
},
|
|
||||||
resolve: {
|
|
||||||
extensions: [".ts", ".tsx", ".mjs", ".js", ".json", ".css", ".png"]
|
|
||||||
},
|
|
||||||
module: {
|
|
||||||
rules: [
|
|
||||||
{ test: /\.ts$/, loader: "awesome-typescript-loader" },
|
|
||||||
{ enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
|
|
||||||
]
|
|
||||||
}
|
|
||||||
};
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,17 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
# Travis doesn't support postgres 10
|
|
||||||
# https://github.com/travis-ci/travis-ci/issues/8537
|
|
||||||
|
|
||||||
set -ex
|
|
||||||
|
|
||||||
echo "Installing Postgres 10"
|
|
||||||
sudo service postgresql stop
|
|
||||||
sudo apt-get remove -q 'postgresql-*'
|
|
||||||
sudo apt-get update -q
|
|
||||||
sudo apt-get install -q postgresql-10 postgresql-client-10
|
|
||||||
sudo cp /etc/postgresql/{9.6,10}/main/pg_hba.conf
|
|
||||||
|
|
||||||
echo "Restarting Postgres 10"
|
|
||||||
sudo service postgresql restart
|
|
||||||
|
|
||||||
sudo psql -c 'CREATE ROLE travis SUPERUSER LOGIN CREATEDB;' -U postgres
|
|
||||||
Executable
+15
@@ -0,0 +1,15 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
set -ex
|
||||||
|
|
||||||
|
echo "Installing Postgres 11"
|
||||||
|
sudo service postgresql stop
|
||||||
|
sudo apt-get remove -q 'postgresql-*'
|
||||||
|
sudo apt-get update -q
|
||||||
|
sudo apt-get install -q postgresql-11 postgresql-client-11
|
||||||
|
sudo cp /etc/postgresql/{9.6,11}/main/pg_hba.conf
|
||||||
|
|
||||||
|
echo "Restarting Postgres 11"
|
||||||
|
sudo service postgresql restart
|
||||||
|
|
||||||
|
sudo psql -c 'CREATE ROLE travis SUPERUSER LOGIN CREATEDB;' -U postgres
|
||||||
Reference in New Issue
Block a user