-
Notifications
You must be signed in to change notification settings - Fork 12
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
Add a modular graphql server #56
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
681825f
feat: Removed isSequencerModule field
rpanic d9449c0
feat: Created the graphql container and updated mempool resolver
rpanic 40744ac
feat: Moved Query classes to sequencer
rpanic 8ad8177
feat: Integrated schema generating gql modules
rpanic e75d045
feat: Added query module to graphql
rpanic 13316d8
feat: Added missing check in blockprover
rpanic afb15ca
feat: Removed dead import
rpanic a0fe53b
feat: Added BlockStorageResolver
rpanic 66e38e3
feat: Fixed issue with graphql module resolving
rpanic 55d9597
feat: migrated to koa + yoga
rpanic dfe4818
feat: moved state service to appchain
rpanic f389034
feat: Fixed imports in api
rpanic a464751
Fixed build
rpanic 50f64ef
Fixed block resolver
rpanic bd9f9a9
Refactoring and fixed issues with double resolving modules
rpanic 577bbc2
fixed Pr comments
rpanic File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -47,5 +47,8 @@ | |
"*.ts": [ | ||
"npm run lint:staged" | ||
] | ||
}, | ||
"dependencies": { | ||
"graphql-yoga": "^5.0.0" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
module.exports = require("../../jest.config.cjs"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
{ | ||
"name": "@proto-kit/api", | ||
"license": "MIT", | ||
"private": false, | ||
"type": "module", | ||
"version": "0.1.1-develop.267+b252853", | ||
"scripts": { | ||
"build": "tsc -p tsconfig.json", | ||
"dev": "tsc -p tsconfig.json --watch", | ||
"lint": "eslint ./src ./test", | ||
"test:file": "node --experimental-vm-modules --experimental-wasm-modules --experimental-wasm-threads ../../node_modules/jest/bin/jest.js", | ||
"test": "npm run test:file -- ./src/** ./test/**", | ||
"test:watch": "npm run test:file -- ./src/** ./test/** --watch" | ||
}, | ||
"main": "dist/index.js", | ||
"publishConfig": { | ||
"access": "public" | ||
}, | ||
"dependencies": { | ||
"@graphql-tools/stitch": "^9.0.3", | ||
"@types/humanize-duration": "^3.27.2", | ||
"class-validator": "^0.14.0", | ||
"graphql": "16.6.0", | ||
"graphql-scalars": "^1.22.4", | ||
"humanize-duration": "^3.30.0", | ||
"lodash": "^4.17.21", | ||
"reflect-metadata": "^0.1.13", | ||
"type-graphql": "2.0.0-beta.1" | ||
}, | ||
"peerDependencies": { | ||
"@proto-kit/common": "*", | ||
"@proto-kit/sequencer": "*", | ||
"o1js": "0.13.1", | ||
"tsyringe": "^4.7.0" | ||
}, | ||
"devDependencies": { | ||
"@jest/globals": "^29.5.0", | ||
"@types/lodash": "^4.14.194", | ||
"@types/ws": "^8.5.4" | ||
}, | ||
"gitHead": "b2528538c73747d000cc3ea99ee26ee415d8248d" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import { ConfigurableModule, TypedClass } from "@proto-kit/common"; | ||
import { GraphQLSchema } from "graphql/type"; | ||
import { injectable, Lifecycle, scoped } from "tsyringe"; | ||
import { Resolver } from "type-graphql"; | ||
|
||
const graphqlModuleMetadataKey = "graphqlModule"; | ||
|
||
export abstract class GraphqlModule<Config> extends ConfigurableModule<Config> { | ||
public constructor() { | ||
super(); | ||
|
||
const isDecoratedProperly = | ||
maht0rz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
Reflect.getMetadata(graphqlModuleMetadataKey, this.constructor) === true; | ||
if (!isDecoratedProperly) { | ||
throw new Error( | ||
maht0rz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
`Module ${this.constructor.name} not decorated property. Make sure to use @graphqlModule() on all GraphqlModules` | ||
); | ||
} | ||
} | ||
} | ||
|
||
export abstract class SchemaGeneratingGraphqlModule< | ||
Config | ||
> extends GraphqlModule<Config> { | ||
public abstract generateSchema(): GraphQLSchema; | ||
} | ||
|
||
export function graphqlModule() { | ||
return ( | ||
/** | ||
* Check if the target class extends GraphqlModule, while | ||
* also providing static config presets | ||
*/ | ||
target: TypedClass<GraphqlModule<unknown>> | ||
) => { | ||
injectable()(target); | ||
scoped(Lifecycle.ContainerScoped)(target); | ||
// eslint-disable-next-line new-cap | ||
Resolver()(target); | ||
|
||
Reflect.defineMetadata(graphqlModuleMetadataKey, true, target); | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
import assert from "node:assert"; | ||
|
||
import { SequencerModule } from "@proto-kit/sequencer"; | ||
import { | ||
ChildContainerProvider, | ||
Configurable, | ||
log, | ||
ModuleContainer, | ||
ModulesConfig, | ||
ModulesRecord, | ||
TypedClass, | ||
} from "@proto-kit/common"; | ||
|
||
import { GraphqlServer } from "./GraphqlServer"; | ||
import { GraphqlModule, SchemaGeneratingGraphqlModule } from "./GraphqlModule"; | ||
|
||
export type GraphqlModulesRecord = ModulesRecord< | ||
TypedClass<GraphqlModule<unknown>> | ||
>; | ||
|
||
export interface GraphqlModulesDefintion< | ||
GraphQLModules extends GraphqlModulesRecord | ||
> { | ||
modules: GraphQLModules; | ||
config?: ModulesConfig<GraphQLModules>; | ||
} | ||
|
||
export class GraphqlSequencerModule<GraphQLModules extends GraphqlModulesRecord> | ||
extends ModuleContainer<GraphQLModules> | ||
implements Configurable<unknown>, SequencerModule<unknown> | ||
{ | ||
public static from<GraphQLModules extends GraphqlModulesRecord>( | ||
definition: GraphqlModulesDefintion<GraphQLModules> | ||
): TypedClass<GraphqlSequencerModule<GraphQLModules>> { | ||
return class ScopedGraphQlContainer extends GraphqlSequencerModule<GraphQLModules> { | ||
public constructor() { | ||
super(definition); | ||
} | ||
}; | ||
} | ||
|
||
private graphqlServer?: GraphqlServer; | ||
|
||
public create(childContainerProvider: ChildContainerProvider) { | ||
super.create(childContainerProvider); | ||
|
||
this.graphqlServer = this.container.resolve("GraphqlServer"); | ||
} | ||
|
||
public async start(): Promise<void> { | ||
assert(this.graphqlServer !== undefined); | ||
|
||
this.graphqlServer.setContainer(this.container); | ||
|
||
// eslint-disable-next-line guard-for-in | ||
for (const moduleName in this.definition.modules) { | ||
const moduleClass = this.definition.modules[moduleName]; | ||
this.graphqlServer.registerModule(moduleClass); | ||
|
||
if ( | ||
Object.prototype.isPrototypeOf.call( | ||
SchemaGeneratingGraphqlModule, | ||
moduleClass | ||
) | ||
) { | ||
log.debug(`Registering manual schema for ${moduleName}`); | ||
// eslint-disable-next-line max-len | ||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions | ||
const module = this.resolve( | ||
moduleName | ||
) as SchemaGeneratingGraphqlModule<unknown>; | ||
this.graphqlServer.registerSchema(module.generateSchema()); | ||
} | ||
} | ||
void this.graphqlServer.startServer(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
import { buildSchemaSync, NonEmptyArray } from "type-graphql"; | ||
import { DependencyContainer, injectable } from "tsyringe"; | ||
import { SequencerModule } from "@proto-kit/sequencer"; | ||
import { log, noop, TypedClass } from "@proto-kit/common"; | ||
import { GraphQLSchema } from "graphql/type"; | ||
import { stitchSchemas } from "@graphql-tools/stitch"; | ||
import { createYoga } from "graphql-yoga"; | ||
import Koa from "koa"; | ||
|
||
import type { GraphqlModule } from "./GraphqlModule"; | ||
|
||
interface GraphqlServerOptions { | ||
host: string; | ||
port: number; | ||
graphiql: boolean; | ||
} | ||
|
||
function assertArrayIsNotEmpty<T>( | ||
array: readonly T[], | ||
errorMessage: string | ||
): asserts array is NonEmptyArray<T> { | ||
if (array.length === 0) { | ||
throw new Error(errorMessage); | ||
} | ||
} | ||
|
||
@injectable() | ||
export class GraphqlServer extends SequencerModule<GraphqlServerOptions> { | ||
private readonly modules: TypedClass<GraphqlModule<unknown>>[] = []; | ||
|
||
private readonly schemas: GraphQLSchema[] = []; | ||
|
||
private dependencyContainer?: DependencyContainer; | ||
|
||
public setContainer(container: DependencyContainer) { | ||
this.dependencyContainer = container; | ||
} | ||
|
||
private assertDependencyContainerSet( | ||
container: DependencyContainer | undefined | ||
): asserts container is DependencyContainer { | ||
if (container === undefined) { | ||
throw new Error("DependencyContainer for GraphqlServer not set"); | ||
} | ||
} | ||
|
||
public registerModule(module: TypedClass<GraphqlModule<unknown>>) { | ||
this.modules.push(module); | ||
} | ||
|
||
public registerSchema(schema: GraphQLSchema) { | ||
this.schemas.push(schema); | ||
} | ||
|
||
public async start() { | ||
noop(); | ||
} | ||
|
||
public async startServer() { | ||
const { dependencyContainer, modules } = this; | ||
this.assertDependencyContainerSet(dependencyContainer); | ||
|
||
assertArrayIsNotEmpty( | ||
modules, | ||
"At least one module has to be provided to GraphqlServer" | ||
); | ||
|
||
// Building schema | ||
const resolverSchema = buildSchemaSync({ | ||
resolvers: modules, | ||
|
||
// resolvers: [MempoolResolver as Function], | ||
// eslint-disable-next-line max-len | ||
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument,@typescript-eslint/no-unsafe-return | ||
container: { get: (cls) => dependencyContainer.resolve(cls) }, | ||
|
||
validate: { | ||
enableDebugMessages: true, | ||
}, | ||
}); | ||
|
||
const schema = [resolverSchema, ...this.schemas].reduce( | ||
(schema1, schema2) => | ||
stitchSchemas({ | ||
subschemas: [{ schema: schema1 }, { schema: schema2 }], | ||
}) | ||
); | ||
|
||
const app = new Koa(); | ||
|
||
const yoga = createYoga<Koa.ParameterizedContext>({ | ||
schema, | ||
graphiql: this.config.graphiql, | ||
}); | ||
|
||
// Bind GraphQL Yoga to `/graphql` endpoint | ||
app.use(async (ctx) => { | ||
// Second parameter adds Koa's context into GraphQL Context | ||
const response = await yoga.handleNodeRequest(ctx.req, ctx); | ||
|
||
// Set status code | ||
ctx.status = response.status; | ||
|
||
// Set headers | ||
response.headers.forEach((value, key) => { | ||
ctx.append(key, value); | ||
}); | ||
|
||
// Converts ReadableStream to a NodeJS Stream | ||
ctx.body = response.body; | ||
}); | ||
|
||
const { port, host } = this.config; | ||
|
||
app.listen({ port, host }, () => { | ||
log.info(`GraphQL Server listening on ${host}:${port}`); | ||
}); | ||
} | ||
} |
100 changes: 100 additions & 0 deletions
100
packages/api/src/graphql/modules/BlockStorageResolver.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
/* eslint-disable new-cap */ | ||
import { inject, injectable } from "tsyringe"; | ||
import { | ||
Arg, | ||
Field, | ||
ObjectType, | ||
Query, | ||
Resolver, | ||
} from "type-graphql"; | ||
import { IsBoolean } from "class-validator"; | ||
import { | ||
BlockStorage, | ||
HistoricalBlockStorage, | ||
ComputedBlock, | ||
ComputedBlockTransaction, | ||
} from "@proto-kit/sequencer"; | ||
|
||
import { graphqlModule, GraphqlModule } from "../GraphqlModule"; | ||
|
||
import { TransactionObject } from "./MempoolResolver"; | ||
|
||
@ObjectType() | ||
export class ComputedBlockTransactionModel { | ||
public static fromServiceLayerModel(cbt: ComputedBlockTransaction) { | ||
const { tx, status, statusMessage } = cbt; | ||
return new ComputedBlockTransactionModel( | ||
TransactionObject.fromServiceLayerModel(tx), | ||
status, | ||
statusMessage | ||
); | ||
} | ||
|
||
@Field(() => TransactionObject) | ||
public tx: TransactionObject; | ||
|
||
@Field() | ||
@IsBoolean() | ||
public status: boolean; | ||
|
||
@Field(() => String, { nullable: true }) | ||
public statusMessage: string | undefined; | ||
|
||
public constructor( | ||
tx: TransactionObject, | ||
status: boolean, | ||
statusMessage: string | undefined | ||
) { | ||
this.tx = tx; | ||
this.status = status; | ||
this.statusMessage = statusMessage; | ||
} | ||
} | ||
|
||
@ObjectType() | ||
export class ComputedBlockModel { | ||
public static fromServiceLayerModel({ txs, proof }: ComputedBlock) { | ||
return new ComputedBlockModel( | ||
txs.map((tx) => ComputedBlockTransactionModel.fromServiceLayerModel(tx)), | ||
JSON.stringify(proof.toJSON()) | ||
); | ||
} | ||
|
||
@Field(() => [ComputedBlockTransactionModel]) | ||
public txs: ComputedBlockTransactionModel[]; | ||
|
||
@Field() | ||
public proof: string; | ||
|
||
public constructor(txs: ComputedBlockTransactionModel[], proof: string) { | ||
this.txs = txs; | ||
this.proof = proof; | ||
} | ||
} | ||
|
||
@graphqlModule() | ||
export class BlockStorageResolver extends GraphqlModule<object> { | ||
// TODO seperate these two block interfaces | ||
public constructor( | ||
@inject("BlockStorage") | ||
private readonly blockStorage: BlockStorage & HistoricalBlockStorage | ||
) { | ||
super(); | ||
} | ||
|
||
@Query(() => ComputedBlockModel, { nullable: true }) | ||
public async block( | ||
@Arg("height", () => Number, { nullable: true }) | ||
height: number | undefined | ||
) { | ||
const blockHeight = | ||
height ?? (await this.blockStorage.getCurrentBlockHeight()); | ||
|
||
const block = await this.blockStorage.getBlockAt(blockHeight); | ||
|
||
if (block !== undefined) { | ||
return ComputedBlockModel.fromServiceLayerModel(block); | ||
} | ||
return undefined; | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this package should be api-graphql, otherwise we won't be able to modularize different api impls