Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Scheduler and worker #24

Merged
merged 85 commits into from
Mar 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
85 commits
Select commit Hold shift + click to select a range
09b152c
Log all request times
ana0 Oct 20, 2020
3c4827d
Rearrange as queue
ana0 Oct 21, 2020
e424944
Move sync full graph into job, run it nightly
ana0 Oct 22, 2020
413332a
Clean up a bit
ana0 Oct 23, 2020
a372a09
Fix job opts for long running, better logging
ana0 Oct 23, 2020
4de917f
Remove edges.json
adzialocha Oct 26, 2020
d1894ea
Fix merge mistake
adzialocha Oct 26, 2020
5864e39
Make linter happy
adzialocha Oct 26, 2020
b38e573
Clean up a little, simplify logic
adzialocha Oct 26, 2020
71572e3
Update README.md
adzialocha Oct 26, 2020
45fb34b
Store balance as wei string in database
adzialocha Oct 26, 2020
09b24d6
Correct use of fastJsonStringify, fix edges path
adzialocha Oct 23, 2020
c8b82c4
Add additional tasks to export edges to json file and upload it to S3
adzialocha Oct 26, 2020
fa90a26
Fix file name
adzialocha Oct 26, 2020
fd3480b
Use different bucket name for trust network uploads
adzialocha Oct 26, 2020
cff8c59
Fix typos
adzialocha Oct 26, 2020
4faf8ec
Correct task name
adzialocha Oct 26, 2020
8080392
Update .env.example
adzialocha Oct 26, 2020
8ed8438
Fix token address
adzialocha Oct 26, 2020
b9ff815
Select fields from edges query
adzialocha Oct 26, 2020
c50ad8e
Filter out ubi payouts
adzialocha Oct 26, 2020
d6e0c18
Fix Hub check
adzialocha Oct 26, 2020
ec1be2c
Update .env.example
adzialocha Oct 26, 2020
1cb7e4e
Fix a few tests
adzialocha Oct 26, 2020
b9f2f07
Fix overlapping if bug, fix trust args
ana0 Oct 27, 2020
842cb31
Add env var
ana0 Oct 27, 2020
770aa3e
Extended trust graph and ubi working
ana0 Oct 27, 2020
c018598
Fix issue with missing edge ids
adzialocha Oct 27, 2020
57f9a03
Clean up checksum conversion a little, fix outgoing edge
adzialocha Oct 27, 2020
d45cbb6
Update core 2.10.3 and transfer 1.0.1
adzialocha Oct 28, 2020
b9d07f7
Refactor syncFullGraph job to get limit from contracts
adzialocha Oct 28, 2020
4b97fb5
Fix typo
adzialocha Oct 28, 2020
f848899
Refactor structure, move all into separate files
adzialocha Oct 29, 2020
bce9fc3
Trigger file export only when edges got actually changed
adzialocha Oct 29, 2020
cd5fabe
Make linter happy
adzialocha Oct 29, 2020
1ba9ef5
Add EdgeUpdateManager which handles duplicate requests
adzialocha Oct 29, 2020
ce684de
Update the PR with (old) local changes
ana0 Feb 9, 2021
279c345
Update the PR with (old) local changes
ana0 Feb 9, 2021
fae7d37
Update circles-core and circles-transfer
adzialocha Oct 23, 2020
c2804b3
Correct use of fastJsonStringify, fix edges path
adzialocha Oct 23, 2020
dc2b216
New circles-transfer api
adzialocha Oct 29, 2020
4d5f5b7
Fix tests
adzialocha Oct 29, 2020
9f9e076
Migrations to add index to edges and change capacities to strings
adzialocha Oct 30, 2020
3bf9373
Rearrange as queue
ana0 Oct 21, 2020
8b9d75f
Move sync full graph into job, run it nightly
ana0 Oct 22, 2020
72ccf07
Clean up a bit
ana0 Oct 23, 2020
7f07a96
Fix job opts for long running, better logging
ana0 Oct 23, 2020
76e431b
Remove edges.json
adzialocha Oct 26, 2020
a841e53
Fix merge mistake
adzialocha Oct 26, 2020
57d1f38
Make linter happy
adzialocha Oct 26, 2020
5708ff7
Clean up a little, simplify logic
adzialocha Oct 26, 2020
5d7bea0
Store balance as wei string in database
adzialocha Oct 26, 2020
34d244f
Add pathfinder executable
adzialocha Oct 23, 2020
d513314
Add additional tasks to export edges to json file and upload it to S3
adzialocha Oct 26, 2020
8145df8
Fix file name
adzialocha Oct 26, 2020
83bfb4d
Fix typos
adzialocha Oct 26, 2020
98a440e
Select fields from edges query
adzialocha Oct 26, 2020
5eb7160
Update .env.example
adzialocha Oct 26, 2020
8bc10a8
Fix a few tests
adzialocha Oct 26, 2020
4380959
Extended trust graph and ubi working
ana0 Oct 27, 2020
d081c3d
Clean up checksum conversion a little, fix outgoing edge
adzialocha Oct 27, 2020
7e0d47f
Refactor syncFullGraph job to get limit from contracts
adzialocha Oct 28, 2020
f672d7d
Refactor structure, move all into separate files
adzialocha Oct 29, 2020
6433386
Trigger file export only when edges got actually changed
adzialocha Oct 29, 2020
454ffad
Add EdgeUpdateManager which handles duplicate requests
adzialocha Oct 29, 2020
1994125
Correct paths
adzialocha Oct 29, 2020
80282fc
Remove unneeded dependency
adzialocha Oct 30, 2020
baedd8b
Add index name again
adzialocha Oct 30, 2020
43be9d1
Fix merge conflicts in package.json and package-lock
ana0 Feb 9, 2021
e6bfe1d
Fix tests and correct balance for extra edges
adzialocha Oct 30, 2020
edf4cfe
Remove migration as its only causing trouble
adzialocha Nov 12, 2020
f2740ac
Correct tokenholders-related updates on trust event
ana0 Feb 9, 2021
9409086
Successfully pass all test-cases in spec
ana0 Feb 12, 2021
1a0b211
Clean up and improve comments
ana0 Feb 12, 2021
1850f27
Add latest version of spec
ana0 Feb 12, 2021
178395a
Remove unnecessary clause
ana0 Feb 12, 2021
282948a
Improve explanations in spec
ana0 Feb 12, 2021
13db6db
Correct rebase mistake
ana0 Feb 12, 2021
2933e50
Correct another rebase mistake
ana0 Feb 12, 2021
3e8d112
Corrent rebase mistake in constants.js
ana0 Feb 12, 2021
7a9c501
Fix rebase mistake in syncAddress task
ana0 Feb 12, 2021
224610e
Remove console.log
adzialocha Mar 5, 2021
5c420d5
Fix broken and remove outdated tests
adzialocha Mar 5, 2021
06e888b
Remove file from rebase
adzialocha Mar 5, 2021
53456d0
Remove WORKER_TESTCASES.md
adzialocha Mar 5, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,28 @@ PORT=3000
HUB_ADDRESS=0xCfEB869F69431e42cdB54A4F4f105C19C080A601
PROXY_FACTORY_ADDRESS=0xD833215cBcc3f914bD1C9ece3EE7BF8B14f841bb
SAFE_ADDRESS=0xC89Ce4735882C9F0f0FE26686c53074E09B0D550
TX_SENDER_ADDRESS=0xA6452911d5274e2717BC1Fa793b21aB600EC9133

# Circles Services
API_SERVICE_ENDPOINT=http://api.circles.local
GRAPH_NODE_ENDPOINT=http://graph.circles.local
RELAY_SERVICE_ENDPOINT=http://relay.circles.local

# Ethereum RPC Node
ETHEREUM_NODE_WS=ws://localhost:8545

# Graph Node
GRAPH_NODE_ENDPOINT=http://graph.circles.local
SUBGRAPH_NAME=CirclesUBI/circles-subgraph

# Database
DATABASE_URL=postgres://username:password@localhost:5432/dbname
DATABASE_DIALECT=postgres
DATABASE_URL=postgres://postgres:postgres@localhost:5432/api

# Redis
REDIS_URL=redis://localhost:6379

# AWS S3
AWS_REGION=eu-central-1
AWS_S3_BUCKET=circles-ubi
AWS_S3_BUCKET=circles-ubi-development
AWS_S3_BUCKET_TRUST_NETWORK=circles-ubi-network-development
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ An offchain API service to safely store and resolve [`Circles`] user data from p

- NodeJS environment (tested with v12 and v14)
- PostgreSQL database
* Redis

## Usage

Expand Down Expand Up @@ -95,13 +96,14 @@ npm run test:watch
npm run lint

# Start local server and watch changes
npm run serve
npm run watch:all

# Build for production
npm run build

# Run production server
npm start
npm worker:start
```

## License
Expand Down
5,713 changes: 3,659 additions & 2,054 deletions package-lock.json

Large diffs are not rendered by default.

10 changes: 7 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@
"db:seed": "sequelize db:seed:all",
"lint": "eslint --ignore-path .gitignore .",
"serve": "cross-env NODE_ENV=development babel-node ./src/index.js --source-maps inline",
"serve:all": "concurrently --prefix '{pid}-{name}' --names 'API,WORKERS' --kill-others 'npm run serve' 'npm run worker:serve'",
"start": "cross-env NODE_ENV=production node ./build/index.js",
"test": "jest --forceExit --detectOpenHandles",
"test": "cross-env NODE_ENV=test jest --forceExit --detectOpenHandles",
"test:watch": "npm run test -- --watch",
"watch": "nodemon --watch ./src --exec npm run serve",
"worker:serve": "cross-env NODE_ENV=development babel-node ./src/worker.js --source-maps inline",
"watch:all": "concurrently --prefix '{pid}-{name}' --names 'API,WORKERS' --kill-others 'npm run watch' 'npm run worker:watch'",
"worker:serve": "NODE_ENV=development babel-node -r dotenv/config ./src/worker.js --source-maps inline",
"worker:start": "cross-env NODE_ENV=production node ./build/worker.js",
"worker:watch": "nodemon --watch ./src --exec npm run worker:serve"
},
Expand All @@ -37,6 +39,7 @@
"@babel/preset-env": "^7.12.1",
"babel-eslint": "^10.1.0",
"babel-plugin-add-module-exports": "^1.0.4",
"concurrently": "^5.3.0",
"cross-env": "^7.0.2",
"eslint": "^7.12.1",
"eslint-config-prettier": "^6.15.0",
Expand All @@ -52,10 +55,11 @@
},
"dependencies": {
"@babel/runtime": "^7.12.1",
"@circles/core": "^2.10.2",
"@circles/core": "^2.10.3",
"@circles/transfer": "^1.1.0",
"aws-sdk": "^2.781.0",
"body-parser": "^1.19.0",
"bull": "^3.18.0",
"celebrate": "^12.2.0",
"compression": "^1.7.4",
"cors": "^2.8.5",
Expand Down
5 changes: 1 addition & 4 deletions src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ export const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';

export const PATHFINDER_BASE_PATH = path.join(__dirname, '..', 'pathfinder');
export const EDGES_FILE_PATH = path.join(PATHFINDER_BASE_PATH, 'edges.json');
export const EDGES_TMP_FILE_PATH = path.join(
PATHFINDER_BASE_PATH,
'edges.json-tmp',
);

export const PATHFINDER_FILE_PATH = path.join(
PATHFINDER_BASE_PATH,
'pathfinder',
Expand Down
20 changes: 15 additions & 5 deletions src/controllers/transfers.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import httpStatus from 'http-status';

import APIError from '../helpers/errors';
import Transfer from '../models/transfers';
import core from '../services/core';
import transferSteps from '../services/findTransferSteps';
import { checkFileExists } from '../services/edgesFile';
import { checkSignature } from '../helpers/signature';
import { requestGraph } from '../services/graph';
import { respondWithSuccess } from '../helpers/responses';
import { transferSteps, getTransferMetrics } from '../services/transfer';

function prepareTransferResult(response) {
return {
Expand Down Expand Up @@ -79,7 +80,7 @@ export default {
}
}`;

const data = await core.utils.requestGraph({ query });
const data = await requestGraph(query);

if (!data || !data.user) {
throw new APIError(httpStatus.FORBIDDEN, 'Not allowed');
Expand Down Expand Up @@ -114,6 +115,15 @@ export default {
},

findTransferSteps: async (req, res, next) => {
if (!checkFileExists()) {
next(
new APIError(
httpStatus.SERVICE_UNAVAILABLE,
'Trust network file does not exist',
),
);
}

try {
const result = await transferSteps({
...req.body,
Expand All @@ -126,7 +136,7 @@ export default {
},

getMetrics: async (req, res) => {
const result = await getTransferMetrics();
respondWithSuccess(res, result);
// @DEPRECATED
respondWithSuccess(res);
},
};
21 changes: 17 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,24 @@ app.use(helmet());

// Log HTTP requests and route them to winston
app.use(
morgan('dev', {
stream: {
write: (message) => logger.verbose(message.replace('\n', '')),
morgan(
(tokens, req, res) => {
return [
tokens.method(req, res),
tokens.url(req, res),
tokens.status(req, res),
tokens.res(req, res, 'content-length'),
'-',
tokens['response-time'](req, res),
'ms',
].join(' ');
},
}),
{
stream: {
write: (message) => logger.info(message.replace('\n', '')),
},
},
),
);

// Mount all API routes
Expand Down
3 changes: 3 additions & 0 deletions src/models/edges.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,17 @@ const Edge = db.define(
from: {
type: Sequelize.STRING(42),
allowNull: false,
unique: 'edges_unique',
},
to: {
type: Sequelize.STRING(42),
allowNull: false,
unique: 'edges_unique',
},
token: {
type: Sequelize.STRING(42),
allowNull: false,
unique: 'edges_unique',
},
capacity: {
type: Sequelize.STRING,
Expand Down
41 changes: 41 additions & 0 deletions src/services/edgesDatabase.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import Edge from '../models/edges';

export async function upsertEdge(edge) {
if (edge.capacity.toString() === '0') {
return destroyEdge(edge);
} else {
return Edge.upsert(edge, {
where: {
token: edge.token,
from: edge.from,
to: edge.to,
},
});
}
}

export async function destroyEdge(edge) {
return Edge.destroy({
where: {
token: edge.token,
from: edge.from,
to: edge.to,
},
});
}

export async function queryEdges(where) {
return await Edge.findAll({
where,
order: [['from', 'ASC']],
raw: true,
});
}

export async function getStoredEdges({ hasOnlyFileFields = false } = {}) {
return await Edge.findAll({
attributes: hasOnlyFileFields ? ['from', 'to', 'token', 'capacity'] : null,
order: [['from', 'ASC']],
raw: true,
});
}
53 changes: 53 additions & 0 deletions src/services/edgesFile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import fastJsonStringify from 'fast-json-stringify';
import fs from 'fs';
import path from 'path';

import web3 from './web3';
import { EDGES_FILE_PATH, PATHFINDER_BASE_PATH } from '../constants';

const stringify = fastJsonStringify({
title: 'Circles Edges Schema',
type: 'array',
properties: {
from: {
type: 'string',
},
to: {
type: 'string',
},
token: {
type: 'string',
},
capacity: {
type: 'string',
},
},
});

export function checkFileExists() {
return fs.existsSync(EDGES_FILE_PATH);
}

// Store edges into .json file for pathfinder executable
export async function writeToFile(
edges,
tmpFileKey = web3.utils.randomHex(16).slice(2),
) {
return new Promise((resolve, reject) => {
// Write to temporary file first
const tmpFilePath = path.join(
PATHFINDER_BASE_PATH,
`edges.json-tmp-${tmpFileKey}`,
);

fs.writeFile(tmpFilePath, stringify(edges), (error) => {
if (error) {
reject(new Error(`Could not write to ${tmpFilePath} file: ${error}`));
} else {
// Finally rename it to destination file
fs.renameSync(tmpFilePath, EDGES_FILE_PATH);
resolve();
}
});
});
}
Loading