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

Add a modular graphql server #56

Merged
merged 16 commits into from
Nov 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
23,016 changes: 1,438 additions & 21,578 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,5 +47,8 @@
"*.ts": [
"npm run lint:staged"
]
},
"dependencies": {
"graphql-yoga": "^5.0.0"
}
}
1 change: 1 addition & 0 deletions packages/api/jest.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require("../../jest.config.cjs");
42 changes: 42 additions & 0 deletions packages/api/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"name": "@proto-kit/api",
Copy link
Member

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

"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"
}
43 changes: 43 additions & 0 deletions packages/api/src/graphql/GraphqlModule.ts
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);
};
}
77 changes: 77 additions & 0 deletions packages/api/src/graphql/GraphqlSequencerModule.ts
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();
}
}
119 changes: 119 additions & 0 deletions packages/api/src/graphql/GraphqlServer.ts
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 packages/api/src/graphql/modules/BlockStorageResolver.ts
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;
}
}
Loading
Loading