Skip to content

feat: Dynamic hook registration for WorkspaceQueryHooks #6008

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

Merged
merged 5 commits into from
Jun 25, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,10 @@ export class GraphQLConfigService
// Create a new contextId for each request
const contextId = ContextIdFactory.create();

// Register the request in the contextId
this.moduleRef.registerRequestByContextId(context.req, contextId);
if (this.moduleRef.registerRequestByContextId) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In which case this is not defined?

Copy link
Contributor Author

@magrinj magrinj Jun 25, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

// Register the request in the contextId
this.moduleRef.registerRequestByContextId(context.req, contextId);
}

// Resolve the WorkspaceSchemaFactory for the contextId
const workspaceFactory = await this.moduleRef.resolve(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Scope, SetMetadata } from '@nestjs/common';
import { SCOPE_OPTIONS_METADATA } from '@nestjs/common/constants';

import { WorkspaceQueryHookType } from 'src/engine/api/graphql/workspace-query-runner/workspace-pre-query-hook/interfaces/workspace-query-hook.type';
import { WorkspaceResolverBuilderMethodNames } from 'src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface';

import { HOOK_METADATA } from 'src/engine/api/graphql/workspace-query-runner/workspace-pre-query-hook/workspace-query-hook.constants';

export type WorkspaceQueryHookKey =
`${string}.${WorkspaceResolverBuilderMethodNames}`;

export interface WorkspaceQueryHookOptions {
key: WorkspaceQueryHookKey;
type?: WorkspaceQueryHookType;
scope?: Scope;
}

export function WorkspaceQueryHook(key: WorkspaceQueryHookKey): ClassDecorator;
export function WorkspaceQueryHook(
options: WorkspaceQueryHookOptions,
): ClassDecorator;
export function WorkspaceQueryHook(
keyOrOptions?: WorkspaceQueryHookKey | WorkspaceQueryHookOptions,
): ClassDecorator {
const options: WorkspaceQueryHookOptions =
keyOrOptions && typeof keyOrOptions === 'object'
? keyOrOptions
: { key: keyOrOptions! };

// Default to PreHook
if (!options.type) {
options.type = WorkspaceQueryHookType.PreHook;
}

// eslint-disable-next-line @typescript-eslint/ban-types
return (target: Function) => {
SetMetadata(SCOPE_OPTIONS_METADATA, options)(target);
SetMetadata(HOOK_METADATA, options)(target);
};
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ResolverArgs } from 'src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface';

export interface WorkspacePreQueryHook {
export interface WorkspaceQueryHookInstance {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: WorkspacePreQueryHook and WorkspacePostQueryHook were separated due to their signatures. They almost look the same but pre-hooks are executed before calling the service layer (today it means before calling the DB with pg_graphql) and they return void because they are mostly there for validation checks.
Post-hooks are more "transformers" where you can modify the object returned by pg_graphql before exposing it back to the client (for example by removing some info, anonymising, applying transformations on strings etc). They probably won't take the payload as parameter (ResolverArgs) but the returned results from pg_graphql (at least if we wanted to implement it today).

Now I'm wondering if this separation makes sense. First of all, pre-hook should not replace permission control (so we shouldn't adapt the API for that use case in the long run) but that's all we have for now which is why we use it this way today with messaging/calendar. Maybe both hooks could implement the same signature but that still needs some thinking.

In the meantime since we are not using post-hook I think this change is fine but we will have to modify your code a bit because again I don't think post-hook will use "ResolverArgs" here as parameters for example. Wdyt?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree, I think as we don't have Post hook for now it's fine, but in the code it's already separated in the storage so we can easily type them separately later when we have to implement Post hook

execute(
userId: string | undefined,
workspaceId: string,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export enum WorkspaceQueryHookType {
PreHook = 'PreHook',
PostHook = 'PostHook',
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// hook-registry.service.ts
import { Injectable } from '@nestjs/common';
import { Module } from '@nestjs/core/injector/module';

import { WorkspaceQueryHookInstance } from 'src/engine/api/graphql/workspace-query-runner/workspace-pre-query-hook/interfaces/workspace-query-hook.interface';

import { WorkspaceQueryHookKey } from 'src/engine/api/graphql/workspace-query-runner/workspace-pre-query-hook/decorators/workspace-query-hook.decorator';

interface WorkspaceQueryHookData<T> {
instance: T;
host: Module;
isRequestScoped: boolean;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same for request scope here

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as sorry ?

}

@Injectable()
export class WorkspaceQueryHookStorage {
private preHookInstances = new Map<
WorkspaceQueryHookKey,
WorkspaceQueryHookData<WorkspaceQueryHookInstance>[]
>();
private postHookInstances = new Map<
WorkspaceQueryHookKey,
WorkspaceQueryHookData<WorkspaceQueryHookInstance>[]
>();

registerWorkspaceQueryPreHookInstance(
key: WorkspaceQueryHookKey,
data: WorkspaceQueryHookData<WorkspaceQueryHookInstance>,
) {
if (!this.preHookInstances.has(key)) {
this.preHookInstances.set(key, []);
}

this.preHookInstances.get(key)?.push(data);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does that mean we can register multiple hooks for the same resolver? I'm wondering if at some point we will want to follow a specific order, similarly to middleware (which is kind of what they are). I'm not sure the suggested API will work in this case with decorators and explorer 🤔

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, as it was possible before, I did the same, so we can have multiple hooks for the same resolver and if later we want to run them into a specific order we can add a property position or index into the decorator

}

getWorkspaceQueryPreHookInstances(
key: WorkspaceQueryHookKey,
): WorkspaceQueryHookData<WorkspaceQueryHookInstance>[] | undefined {
return this.preHookInstances.get(key);
}

registerWorkspaceQueryPostHookInstance(
key: WorkspaceQueryHookKey,
data: WorkspaceQueryHookData<WorkspaceQueryHookInstance>,
) {
if (!this.postHookInstances.has(key)) {
this.postHookInstances.set(key, []);
}

this.postHookInstances.get(key)?.push(data);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here, I feel like order will be even more important for post-query hooks

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same answer as above

}

getWorkspaceQueryPostHookInstances(
key: WorkspaceQueryHookKey,
): WorkspaceQueryHookData<WorkspaceQueryHookInstance>[] | undefined {
return this.postHookInstances.get(key);
}
}

This file was deleted.

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/* eslint-disable @typescript-eslint/ban-types */
import { Injectable, Type } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

import { HOOK_METADATA } from 'src/engine/api/graphql/workspace-query-runner/workspace-pre-query-hook/workspace-query-hook.constants';
import { WorkspaceQueryHookOptions } from 'src/engine/api/graphql/workspace-query-runner/workspace-pre-query-hook/decorators/workspace-query-hook.decorator';

@Injectable()
export class WorkspaceQueryHookMetadataAccessor {
constructor(private readonly reflector: Reflector) {}

isWorkspaceQueryHook(target: Type<any> | Function): boolean {
if (!target) {
return false;
}

return !!this.reflector.get(HOOK_METADATA, target);
}

getWorkspaceQueryHookMetadata(
target: Type<any> | Function,
): WorkspaceQueryHookOptions | undefined {
return this.reflector.get(HOOK_METADATA, target);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const HOOK_METADATA = Symbol('hook:metadata');
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { DiscoveryService, ModuleRef, createContextId } from '@nestjs/core';
import { Module } from '@nestjs/core/injector/module';
import { Injector } from '@nestjs/core/injector/injector';

import { WorkspaceQueryHookType } from 'src/engine/api/graphql/workspace-query-runner/workspace-pre-query-hook/interfaces/workspace-query-hook.type';
import { WorkspaceQueryHookInstance } from 'src/engine/api/graphql/workspace-query-runner/workspace-pre-query-hook/interfaces/workspace-query-hook.interface';

import { WorkspaceQueryHookMetadataAccessor } from 'src/engine/api/graphql/workspace-query-runner/workspace-pre-query-hook/workspace-query-hook-metadata.accessor';
import { WorkspaceQueryHookStorage } from 'src/engine/api/graphql/workspace-query-runner/workspace-pre-query-hook/storage/workspace-query-hook.storage';
import { WorkspaceQueryHookKey } from 'src/engine/api/graphql/workspace-query-runner/workspace-pre-query-hook/decorators/workspace-query-hook.decorator';

@Injectable()
export class WorkspaceQueryHookExplorer implements OnModuleInit {
private readonly logger = new Logger('WorkspaceQueryHookModule');
private readonly injector = new Injector();

constructor(
private readonly moduleRef: ModuleRef,
private readonly discoveryService: DiscoveryService,
private readonly metadataAccessor: WorkspaceQueryHookMetadataAccessor,
private readonly workspaceQueryHookStorage: WorkspaceQueryHookStorage,
) {}

onModuleInit() {
this.explore();
}

async explore() {
console.log('EXPLORE !');
const hooks = this.discoveryService
.getProviders()
.filter((wrapper) =>
this.metadataAccessor.isWorkspaceQueryHook(
!wrapper.metatype || wrapper.inject
? wrapper.instance?.constructor
: wrapper.metatype,
),
);

console.log('HOOKS: ', hooks.length);

for (const hook of hooks) {
const { instance, metatype } = hook;

const { key, type } =
this.metadataAccessor.getWorkspaceQueryHookMetadata(
instance.constructor || metatype,
) ?? {};

if (!key || !type) {
this.logger.error(
`PreHook ${hook.name} is missing key or type metadata`,
);
continue;
}

if (!hook.host) {
this.logger.error(`PreHook ${hook.name} is missing host metadata`);

continue;
}

this.registerWorkspaceQueryHook(
key,
type,
instance,
hook.host,
!hook.isDependencyTreeStatic(),
);
}
}

async handleHook(
payload: Parameters<WorkspaceQueryHookInstance['execute']>,
instance: object,
host: Module,
isRequestScoped: boolean,
) {
const methodName = 'execute';

if (isRequestScoped) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note: I'm not sure we have any use case where we would have a pre-hook not scoped since hooks are applied over the flexible schema resolvers 🤔

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm yes, I need to double test that to verify that it's never going through the else

const contextId = createContextId();

if (this.moduleRef.registerRequestByContextId) {
this.moduleRef.registerRequestByContextId(
{
req: {
workspaceId: payload?.[1],
},
},
contextId,
);
}

const contextInstance = await this.injector.loadPerContext(
instance,
host,
host.providers,
contextId,
);

await contextInstance[methodName].call(contextInstance, ...payload);
} else {
await instance[methodName].call(instance, ...payload);
}
}

private registerWorkspaceQueryHook(
key: WorkspaceQueryHookKey,
type: WorkspaceQueryHookType,
instance: object,
host: Module,
isRequestScoped: boolean,
) {
switch (type) {
case WorkspaceQueryHookType.PreHook:
this.workspaceQueryHookStorage.registerWorkspaceQueryPreHookInstance(
key,
{
instance: instance as WorkspaceQueryHookInstance,
host,
isRequestScoped,
},
);
break;
case WorkspaceQueryHookType.PostHook:
this.workspaceQueryHookStorage.registerWorkspaceQueryPostHookInstance(
key,
{
instance: instance as WorkspaceQueryHookInstance,
host,
isRequestScoped,
},
);
break;
default:
this.logger.error(`Unknown WorkspaceQueryHookType: ${type}`);
break;
}
}
}
Loading
Loading