-
Notifications
You must be signed in to change notification settings - Fork 3.1k
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
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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, | ||
magrinj marked this conversation as resolved.
Show resolved
Hide resolved
|
||
): 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 { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. 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? There was a problem hiding this comment. Choose a reason for hiding this commentThe 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, | ||
|
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; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same for request scope here There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 🤔 There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
} | ||
|
||
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); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 There was a problem hiding this comment. Choose a reason for hiding this commentThe 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'); | ||
magrinj marked this conversation as resolved.
Show resolved
Hide resolved
|
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 !'); | ||
magrinj marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const hooks = this.discoveryService | ||
.getProviders() | ||
.filter((wrapper) => | ||
this.metadataAccessor.isWorkspaceQueryHook( | ||
!wrapper.metatype || wrapper.inject | ||
? wrapper.instance?.constructor | ||
: wrapper.metatype, | ||
), | ||
); | ||
|
||
console.log('HOOKS: ', hooks.length); | ||
magrinj marked this conversation as resolved.
Show resolved
Hide resolved
magrinj marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
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) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 🤔 There was a problem hiding this comment. Choose a reason for hiding this commentThe 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; | ||
} | ||
} | ||
} |
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.
In which case this is not defined?
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.
It's actually checked in the official libraries, just did it too just in case
https://github.com/nestjs/bull/blob/4ed326178b889bd0f851cad736e03a1a0a1667c5/packages/bullmq/lib/bull.explorer.ts#L166