Repository navigation
feat: Typesense search driver (EE) - #1664
Conversation
WalkthroughAdds Redis config and module, search-related queues and jobs, event-driven page lifecycle emissions and a PageListener to enqueue search work, optional Typesense search driver with dynamic enterprise resolution, environment validations and getters, an ISO 639‑1 validator, and small DTO/signature adjustments. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant C as Client
participant SC as SearchController
participant ES as EnvironmentService
participant MR as ModuleRef
participant SS as SearchService
participant EE as Enterprise PageSearchService
C->>SC: GET /search (SearchDTO)
SC->>ES: getSearchDriver()
alt driver == "typesense"
SC->>MR: resolve(PageSearchService from EE)
alt enterprise module present
SC->>EE: searchPage(SearchDTO, {userId, workspaceId})
EE-->>SC: SearchResponseDto[]
else missing enterprise module
SC-->>C: 400 BadRequest (Typesense module not bundled)
end
else driver == "database"
SC->>SS: searchPage(SearchDTO, {userId, workspaceId})
SS-->>SC: SearchResponseDto[]
end
SC-->>C: SearchResponseDto[]
sequenceDiagram
autonumber
participant SVC as PageService / Repo / ImportTask
participant EE2 as EventEmitter2
participant PL as PageListener
participant Q as BullMQ (SEARCH_QUEUE)
SVC->>EE2: emit(EventName.PAGE_..., { pageIds })
EE2-->>PL: event callback (pageIds)
PL->>Q: add(QueueJob.<type>, { pageIds })
Q-->>PL: job queued
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
apps/server/src/core/search/search.service.ts (2)
30-35: Fix: function returns undefined on empty querysearchPage promises SearchResponseDto[], but Line 33 returns undefined. Return an empty array.
Apply:
- const { query } = searchParams; + const { query } = searchParams; - if (query.length < 1) { - return; - } + if (query.length < 1) { + return []; + }
65-65: Bug: bitwise OR used for limit.limit(searchParams.limit | 20) will produce incorrect values (e.g., 10 | 20 = 30). Use nullish coalescing or logical OR.
Apply:
- .limit(searchParams.limit | 20) + .limit(searchParams.limit ?? 20)
🧹 Nitpick comments (6)
apps/server/src/database/repos/page/page.repo.ts (1)
126-128: Consider error handling for event emission.Event emission occurs synchronously after database operations. If event listeners throw errors synchronously (e.g., validation failures before queueing), the entire operation appears to fail even though the database change succeeded.
While EventEmitter2 typically handles listener errors gracefully, consider wrapping event emission in try-catch blocks to ensure database operations always complete successfully regardless of listener failures.
Example for
insertPage:this.eventEmitter.emit(EventName.PAGE_CREATED, { pageIds: [result.id], }); + } catch (err) { + // Log but don't throw - DB operation already succeeded + console.error('Failed to emit PAGE_CREATED event:', err); + } return result;Also applies to: 144-146, 198-200, 264-266
apps/server/src/database/listeners/page.listener.ts (1)
14-14: Logger is defined but never used.The logger is instantiated but error/warning scenarios aren't currently logged. Consider using it for the error handling suggested above.
apps/server/src/integrations/redis/redis-config.service.ts (1)
12-25: Add TLS support for rediss:// URLsIf REDIS_URL uses rediss://, ioredis needs tls: {}. Currently unsupported.
Apply:
- createRedisOptions(): RedisModuleOptions { - const redisConfig = parseRedisUrl(this.environmentService.getRedisUrl()); + createRedisOptions(): RedisModuleOptions { + const url = this.environmentService.getRedisUrl(); + const redisConfig = parseRedisUrl(url); + const isTls = url.toLowerCase().startsWith('rediss://'); return { readyLog: true, config: { host: redisConfig.host, port: redisConfig.port, password: redisConfig.password, db: redisConfig.db, family: redisConfig.family, retryStrategy: createRetryStrategy(), + ...(isTls ? { tls: {} } : {}), }, }; }Optional: extend parseRedisUrl to capture username and set it in config when present.
apps/server/src/integrations/environment/environment.service.ts (1)
223-227: Avoid lowercasing URLsLowercasing TYPESENSE_URL can corrupt case-sensitive paths or query values. Keep original casing.
Apply:
- getTypesenseUrl(): string { - return this.configService - .get<string>('TYPESENSE_URL', 'http://localhost:8108') - .toLowerCase(); - } + getTypesenseUrl(): string { + return this.configService.get<string>( + 'TYPESENSE_URL', + 'http://localhost:8108', + ); + }apps/server/src/core/search/search.controller.ts (1)
110-141: Harden dynamic resolution; minor cleanup
- Rename local var to pageSearchService and guard against undefined before calling.
Apply:
- async searchTypesense( + async searchTypesense( searchParams: SearchDTO, opts: { userId?: string; workspaceId: string; }, ) { const { userId, workspaceId } = opts; let TypesenseModule: any; try { // eslint-disable-next-line @typescript-eslint/no-require-imports TypesenseModule = require('./../../ee/typesense/services/page-search.service'); - const PageSearchService = this.moduleRef.get( + const pageSearchService = this.moduleRef.get( TypesenseModule.PageSearchService, { strict: false, }, ); - - return PageSearchService.searchPage(searchParams, { + if (!pageSearchService?.searchPage) { + throw new Error('Typesense PageSearchService not registered'); + } + return pageSearchService.searchPage(searchParams, { userId: userId, workspaceId, }); } catch (err) { this.logger.debug( 'Typesense module requested but enterprise module not bundled in this build', ); } throw new BadRequestException('Enterprise Typesense search module missing'); }apps/server/src/integrations/environment/environment.validation.ts (1)
102-102: Remove redundant @IsString() decorator.The @IsString() decorator is redundant after @IsISO6391() because ISO 639-1 language codes are strings by definition, and the custom validator already performs string validation.
Apply this diff to remove the redundant decorator:
@IsOptional() @ValidateIf((obj) => obj.SEARCH_DRIVER === 'typesense') @IsISO6391() - @IsString() TYPESENSE_LOCALE: string;
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (19)
apps/server/package.json(3 hunks)apps/server/src/app.module.ts(2 hunks)apps/server/src/common/events/event.contants.ts(1 hunks)apps/server/src/common/validator/is-iso6391.ts(1 hunks)apps/server/src/core/page/page.module.ts(1 hunks)apps/server/src/core/page/services/page.service.ts(4 hunks)apps/server/src/core/search/dto/search-response.dto.ts(2 hunks)apps/server/src/core/search/search.controller.ts(4 hunks)apps/server/src/core/search/search.service.ts(1 hunks)apps/server/src/database/database.module.ts(3 hunks)apps/server/src/database/listeners/page.listener.ts(1 hunks)apps/server/src/database/repos/page/page.repo.ts(8 hunks)apps/server/src/ee(1 hunks)apps/server/src/integrations/environment/environment.service.ts(1 hunks)apps/server/src/integrations/environment/environment.validation.ts(2 hunks)apps/server/src/integrations/import/services/file-import-task.service.ts(3 hunks)apps/server/src/integrations/queue/constants/queue.constants.ts(2 hunks)apps/server/src/integrations/queue/queue.module.ts(1 hunks)apps/server/src/integrations/redis/redis-config.service.ts(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (5)
apps/server/src/integrations/environment/environment.validation.ts (1)
apps/server/src/common/validator/is-iso6391.ts (1)
IsISO6391(17-34)
apps/server/src/core/search/dto/search-response.dto.ts (1)
apps/server/src/database/types/entity.types.ts (1)
Space(42-42)
apps/server/src/database/repos/page/page.repo.ts (2)
apps/server/src/database/listeners/page.listener.ts (1)
Injectable(12-49)apps/server/src/database/utils.ts (1)
dbOrTx(24-33)
apps/server/src/integrations/redis/redis-config.service.ts (1)
apps/server/src/common/helpers/utils.ts (2)
parseRedisUrl(34-57)createRetryStrategy(59-63)
apps/server/src/core/search/search.controller.ts (1)
apps/server/src/core/search/dto/search.dto.ts (1)
SearchDTO(9-33)
🔇 Additional comments (17)
apps/server/src/core/page/page.module.ts (1)
12-12: LGTM!The trailing comma addition follows JavaScript/TypeScript best practices and will reduce diff noise when additional modules are added to the imports array in the future.
apps/server/src/core/search/dto/search-response.dto.ts (2)
1-1: LGTM!The import is correct and properly references the
Spacetype from the entity types module.
13-13: Ensure space field consistency on SearchResponseDto
No instantiations or mappings were found that guaranteespaceis always populated. Confirm that every search response setsspace; if not, change the DTO tospace?: Partial<Space>;apps/server/src/database/database.module.ts (1)
28-28: LGTM! PageListener and ShareRepo additions are correct.The PageListener is properly added to providers for dependency injection, and ShareRepo is correctly exported for use in other modules. The event-driven architecture setup aligns with the broader PR objectives.
Also applies to: 80-80, 95-95
apps/server/src/common/events/event.contants.ts (1)
3-7: LGTM! Event naming is consistent.The new page lifecycle events follow the existing naming convention and are properly integrated with the event-driven architecture introduced in this PR.
apps/server/src/integrations/queue/queue.module.ts (1)
60-67: LGTM! Search queue configuration is appropriate.The SEARCH_QUEUE registration uses reasonable defaults for search indexing operations: auto-cleanup to reduce memory usage and 2 retry attempts for transient failures.
apps/server/src/database/repos/page/page.repo.ts (3)
17-18: Event-driven integration looks good.EventEmitter2 is properly injected and used to emit page lifecycle events after database operations complete. The synchronous emission pattern is standard for NestJS event emitters.
Also applies to: 25-25
51-51: LGTM! Text content retrieval is properly gated.The
includeTextContentoption correctly extends the conditional select pattern used for other optional fields.Also applies to: 69-69
387-403: LGTM! HasChildren computation is correct.The
withHasChildrenhelper properly checks for non-deleted child pages using a correlated subquery with a COUNT check.apps/server/src/core/page/services/page.service.ts (1)
41-42: Event emission follows consistent pattern.Page lifecycle events are emitted after database operations complete, matching the pattern in PageRepo. The same error handling considerations mentioned for PageRepo apply here - ensure event emission failures don't cause the entire operation to appear failed.
Also applies to: 54-54, 386-389, 617-619
apps/server/src/integrations/import/services/file-import-task.service.ts (1)
35-36: LGTM! Event emission is properly guarded.The PAGE_CREATED event is emitted after the transaction commits successfully and only when pages were actually created (
validPageIds.size > 0). This prevents empty event emissions.Also applies to: 50-50, 402-406
apps/server/src/integrations/queue/constants/queue.constants.ts (1)
7-7: LGTM! Queue constants are well-defined.The new SEARCH_QUEUE and page lifecycle job constants follow the existing naming conventions and are properly integrated with PageListener and queue registration.
Also applies to: 30-45
apps/server/package.json (1)
40-40: Version alignment looks fine; add a quick compatibility check noteLooks good. Please just confirm:
- @nestjs-labs/nestjs-ioredis ^11.x matches NestJS 11.x (it should).
- @nestjs/bullmq ^11.0.2 supports bullmq ^5.61.0 you’ve bumped to.
No changes requested; verification only.
Also applies to: 59-59, 67-67, 94-94
apps/server/src/common/validator/is-iso6391.ts (1)
1-34: ISO 639-1 validator looks goodSolid addition; aligns with class-validator patterns. No issues.
apps/server/src/integrations/environment/environment.validation.ts (3)
1-13: LGTM!The added imports are correctly used in the new environment variable validations.
74-77: LGTM!The validation for the search driver field is appropriate, allowing selection between database and Typesense search implementations.
99-103: Keep TYPESENSE_LOCALE optional and remove redundant @IsString()
The environment service defaults to “en” when TYPESENSE_LOCALE isn’t set, so requiring it isn’t necessary. @IsISO6391() already ensures it’s a string.Likely an incorrect or invalid review comment.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
apps/server/src/core/search/search.controller.ts (1)
130-130: Use ES6 shorthand for property.The
userId: userIdassignment is redundant with ES6 shorthand property syntax.Apply this diff:
- userId: userId, + userId,
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
apps/server/src/core/search/search.controller.ts(4 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
apps/server/src/core/search/search.controller.ts (1)
apps/server/src/core/search/dto/search.dto.ts (1)
SearchDTO(9-33)
| async searchTypesense( | ||
| searchParams: SearchDTO, | ||
| opts: { | ||
| userId?: string; | ||
| workspaceId: string; | ||
| }, | ||
| ) { | ||
| const { userId, workspaceId } = opts; | ||
| let TypesenseModule: any; | ||
| try { | ||
| // eslint-disable-next-line @typescript-eslint/no-require-imports | ||
| TypesenseModule = require('./../../ee/typesense/services/page-search.service'); | ||
|
|
||
| const PageSearchService = this.moduleRef.get( | ||
| TypesenseModule.PageSearchService, | ||
| { | ||
| strict: false, | ||
| }, | ||
| ); | ||
|
|
||
| return PageSearchService.searchPage(searchParams, { | ||
| userId: userId, | ||
| workspaceId, | ||
| }); | ||
| } catch (err) { | ||
| this.logger.debug( | ||
| 'Typesense module requested but enterprise module not bundled in this build', | ||
| ); | ||
| } | ||
|
|
||
| throw new BadRequestException('Enterprise Typesense search module missing'); | ||
| } |
There was a problem hiding this comment.
Fix error handling to avoid hiding runtime errors.
The try-catch block wraps both module loading and the service call. If PageSearchService.searchPage() throws a runtime error (e.g., validation failure, database error), it's caught and logged as "enterprise module not bundled", then replaced with a generic BadRequestException. This hides the actual error and provides misleading feedback.
Apply this diff to separate module loading from service execution:
async searchTypesense(
searchParams: SearchDTO,
opts: {
userId?: string;
workspaceId: string;
},
) {
const { userId, workspaceId } = opts;
- let TypesenseModule: any;
+ let PageSearchService;
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
- TypesenseModule = require('./../../ee/typesense/services/page-search.service');
-
- const PageSearchService = this.moduleRef.get(
+ const TypesenseModule = require('./../../ee/typesense/services/page-search.service');
+ PageSearchService = this.moduleRef.get(
TypesenseModule.PageSearchService,
{
strict: false,
},
);
-
- return PageSearchService.searchPage(searchParams, {
- userId: userId,
- workspaceId,
- });
} catch (err) {
this.logger.debug(
'Typesense module requested but enterprise module not bundled in this build',
);
+ throw new BadRequestException('Enterprise Typesense search module missing');
}
- throw new BadRequestException('Enterprise Typesense search module missing');
+ return PageSearchService.searchPage(searchParams, {
+ userId,
+ workspaceId,
+ });
}This matches the pattern used in auth.controller.ts where module loading errors are caught but service calls propagate their own exceptions naturally.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| async searchTypesense( | |
| searchParams: SearchDTO, | |
| opts: { | |
| userId?: string; | |
| workspaceId: string; | |
| }, | |
| ) { | |
| const { userId, workspaceId } = opts; | |
| let TypesenseModule: any; | |
| try { | |
| // eslint-disable-next-line @typescript-eslint/no-require-imports | |
| TypesenseModule = require('./../../ee/typesense/services/page-search.service'); | |
| const PageSearchService = this.moduleRef.get( | |
| TypesenseModule.PageSearchService, | |
| { | |
| strict: false, | |
| }, | |
| ); | |
| return PageSearchService.searchPage(searchParams, { | |
| userId: userId, | |
| workspaceId, | |
| }); | |
| } catch (err) { | |
| this.logger.debug( | |
| 'Typesense module requested but enterprise module not bundled in this build', | |
| ); | |
| } | |
| throw new BadRequestException('Enterprise Typesense search module missing'); | |
| } | |
| async searchTypesense( | |
| searchParams: SearchDTO, | |
| opts: { | |
| userId?: string; | |
| workspaceId: string; | |
| }, | |
| ) { | |
| const { userId, workspaceId } = opts; | |
| let PageSearchService; | |
| try { | |
| // eslint-disable-next-line @typescript-eslint/no-require-imports | |
| const TypesenseModule = require('./../../ee/typesense/services/page-search.service'); | |
| PageSearchService = this.moduleRef.get( | |
| TypesenseModule.PageSearchService, | |
| { | |
| strict: false, | |
| }, | |
| ); | |
| } catch (err) { | |
| this.logger.debug( | |
| 'Typesense module requested but enterprise module not bundled in this build', | |
| ); | |
| throw new BadRequestException('Enterprise Typesense search module missing'); | |
| } | |
| return PageSearchService.searchPage(searchParams, { | |
| userId, | |
| workspaceId, | |
| }); | |
| } |
🤖 Prompt for AI Agents
In apps/server/src/core/search/search.controller.ts around lines 109 to 140, the
current try-catch wraps both the dynamic require and the
PageSearchService.searchPage call so runtime errors from searchPage get caught
and misreported as a missing enterprise module; change it so only the module
loading/require is inside the try-catch (or catch and rethrow only
module-not-found errors), obtain PageSearchService outside that catch, then call
PageSearchService.searchPage without that catch so any runtime errors propagate
normally (allow framework to handle or surface real errors instead of masking
them with a BadRequestException).
* feat: typesense driver (EE) - WIP * feat: typesense driver (EE) - WIP * feat: typesense * sync * fix
* feat: typesense driver (EE) - WIP * feat: typesense driver (EE) - WIP * feat: typesense * sync * fix
4231ba9 Merge commit '042836cb6d7cc1f71af3ce44c7957f8abbbf8f25' into feat/aar_edition 042836c sync 4f1f0ba fix 3164b69 feat: api keys management (EE) (docmost#1665) 16c1e86 fix comment space c9b1cad sync bf8cf62 feat: Typesense search driver (EE) (docmost#1664) 5a2e16a Merge commit '31350303760163384113bf49d07127e886f94907' into feat/aar_edition 3bc710d Adds CLAUDE.md documentation 16914f1 Block search for non-indexed shares ca75e29 Set default page mode to Read 3135030 fix editor converter (docmost#1647) 3fae41a fix: editor performance improvements (docmost#1648) b50e256 sync 1f3b0c7 cloud fix 3c4cab0 v0.23.2 4de25a8 invalidate queries on space deletion cf5bbb1 fix import html processing ac17521 sync 9ac180f fix: enhance page import (docmost#1570) 46669fe (cloud) disable page sharing in trial mode fe6ecdf fix: update combobox props in SpaceSelect component (docmost#1564) 04ae1d7 Allow lastColumnResizable in table 1280f96 feat: implement space and workspace icons (docmost#1558) 61d1cf8 fix: reset file inputs after import f413720 - sync - reinstantiate S3 client to fix file upload errors during import - delete import zip file after use 8e16ad9 v0.23.1 7ada3cb fix: page import task (docmost#1551) 47c5417 sync dc06502 sync 091e790 fix attachment search in cloud ae24ea2 v0.23.0 9df6061 lock file 31053e2 update mermaid eb8e850 use debug c99bfb8 make print better 26ea04e sync 6cc58c5 sync 7d2ff34 UI fixes b08d37f fix d43ee77 remove debug log 5d91eb4 feat: queue imported attachments for indexing 3e9f6b1 Remove version from docker-compose.yml [deprecated] (docmost#1011) db55de9 feat: progressive web app (docmost#614) 1919eba New Crowdin updates (docmost#1522) 7951b2e New Crowdin updates (docmost#1509) 73b78f6 more translations cf7534d fix version display adec36d fix: adjust margins - use default browser highlight background f9e1080 sync 00e499b Fixing extra page bug on print (docmost#1478) 5ee6e46 checkbox aligned to text (docmost#1486) 1f797c3 fix: confluence drawio import (docmost#1518) f12866c feat(EE): full-text search in attachments (docmost#1502) dcbb65d feat(EE): LDAP integration (docmost#1515) 5968764 feat: emoji callout icon (docmost#1323) 242fb6b fix: set mermaid theme based on computed color scheme (docmost#1438) 74cd890 feat(EE): implement SSO group sync for SAML and OIDC (docmost#1452) 509622a ignore type error 937386e fix: hide table handles in readonly mode 60a373f fix: readonly editor table responsiveness 73ee6ee feat: subpages (child pages) list node (docmost#1462) 7d1e5bc feat: table row/column drag and drop (docmost#1467) aa58e27 fix: exclude deleted pages (docmost#1494) 08135a2 sync d92a942 sync 5012a68 sync 5a33777 feat: debug mode env variable (docmost#1450) 3b85f4b fix: enforce C collation for page position ordering to ensure consistent behavior in Postgres 17+ (docmost#1446) cb2a039 fix: invalidate trashed page from tree state 95b7be6 fix: hide trash from can view permission (docmost#1445) b0c5572 fix nested taskList in markdown export (docmost#1443) dddfd48 feat: add attachments support for single page exports (docmost#1440) aa6eec7 fix: exclude trashed pages from position generation 97a7701 fix local storage copy function (docmost#1442) b97eb85 sync git-subtree-dir: vendor/app git-subtree-split: 4231ba9
* feat: typesense driver (EE) - WIP * feat: typesense driver (EE) - WIP * feat: typesense * sync * fix
* feat: typesense driver (EE) - WIP * feat: typesense driver (EE) - WIP * feat: typesense * sync * fix
Summary by CodeRabbit
New Features
Enhancements
Configuration
Chores