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

Fix creating indexes #26

Merged
merged 3 commits into from
Feb 12, 2024
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
13 changes: 11 additions & 2 deletions src/components/nav/search/NavSearchBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,10 @@ export const NavSearchBar = ({ hideShortcut }: { hideShortcut?: true }) => {
"rgba(255, 255, 255, 0.8)",
"rgba(0, 0, 0, 0.8)"
);
const selectedSearchResultBackgroundColor = useColorModeValue(
"gray.100",
"gray.600"
);

useSearchShortcut(onToggle);

Expand Down Expand Up @@ -260,9 +264,14 @@ export const NavSearchBar = ({ hideShortcut }: { hideShortcut?: true }) => {
{searchResults.map((result, index) => (
<Tr
key={index}
_hover={{ bgColor: "gray.100", cursor: "pointer" }}
_hover={{
bgColor: selectedSearchResultBackgroundColor,
cursor: "pointer",
}}
backgroundColor={
selectedIndex === index ? "gray.100" : undefined
selectedIndex === index
? selectedSearchResultBackgroundColor
: undefined
}
onClick={() => openResult(result)}
>
Expand Down
4 changes: 2 additions & 2 deletions src/components/settings/TeamSettings/TeamMemberRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ import {
useDisclosure,
useToast,
} from "@chakra-ui/react";
import { UserTeamMembership, UserTeamMembershipRole } from "@prisma/client";
import { type UserTeamMembership, UserTeamMembershipRole } from "@prisma/client";
import { useState } from "react";
import { DeleteIconButton } from "~/components/common/DeleteIconButton";
import { useTeam } from "~/lib/SelectedTeamProvider";
import { useErrorHandlingMutation } from "~/lib/useErrorHandling";
import { Member } from "~/server/lib/user/member";
import { type Member } from "~/server/lib/user/member";
import { api } from "~/utils/api";

type TeamMemberRowProps = {
Expand Down
4 changes: 2 additions & 2 deletions src/components/settings/TeamSettings/TeamMemberTable.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Flex, Progress, Table, Tbody, Th, Thead, Tr } from "@chakra-ui/react";
import {
Team,
UserTeamMembership,
type Team,
type UserTeamMembership,
UserTeamMembershipRole,
} from "@prisma/client";
import { api } from "~/utils/api";
Expand Down
2 changes: 1 addition & 1 deletion src/server/api/routers/team.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Team } from "@prisma/client";
import { type Team } from "@prisma/client";
import { z } from "zod";
import { createTRPCRouter, protectedProcedure } from "~/server/api/trpc";
import { teamAddMemberRequest } from "~/server/lib/user/teamAddMemberRequest";
Expand Down
7 changes: 2 additions & 5 deletions src/server/lib/applicationContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ export class ApplicationContext {
);
public readonly assetTypeSearchService = new AssetTypeSearchService(
this.logger.child({ name: "AssetTypeSearchService" }),
this.meiliSearch,
this.teamService
this.meiliSearch
);
public readonly assetTypeService = new AssetTypeService(
this.logger.child({ name: "AssetTypeService" }),
Expand All @@ -44,13 +43,11 @@ export class ApplicationContext {
public readonly assetSearchService = new AssetSearchService(
this.logger.child({ name: "AssetSearchService" }),
this.meiliSearch,
this.teamService,
this.assetTypeService
);
public readonly tagSearchService = new TagSearchService(
this.logger.child({ name: "TagSearchService" }),
this.meiliSearch,
this.teamService
this.meiliSearch
);
public readonly assetService = new AssetService(
this.logger.child({ name: "AssetService" }),
Expand Down
13 changes: 11 additions & 2 deletions src/server/lib/asset-types/assetTypeService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { type Logger } from "winston";
import { type AssetTypeSearchService } from "../search/assetTypeSearchService";
import { type TeamService } from "../user/teamService";
import slugify from "slugify";
import { type TeamId } from "../user/team";

export class AssetTypeService {
constructor(
Expand Down Expand Up @@ -458,6 +459,14 @@ export class AssetTypeService {
);
};

public getSearchableCustomFields = async (): Promise<CustomField[]> =>
this.prisma.customField.findMany();
public getSearchableCustomFields = async (
teamIds: TeamId[]
): Promise<CustomField[]> =>
this.prisma.customField.findMany({
where: {
teamId: {
in: teamIds,
},
},
});
}
64 changes: 55 additions & 9 deletions src/server/lib/search/abstractSearchService.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { type Team } from "@prisma/client";
import type MeiliSearch from "meilisearch";
import { type Logger } from "winston";
import { type TeamId } from "../user/team";
import { type Index } from "meilisearch";
import { waitForTasks } from "../user/meiliSearchUtils";

type TeamOwnedIdentifiable = {
id: string;
Expand All @@ -11,17 +13,55 @@ export abstract class AbstractSearchService<
TDoc extends object,
TEntity extends TeamOwnedIdentifiable
> {
private initialized = false;
constructor(
protected readonly logger: Logger,
protected readonly meilisearch: MeiliSearch,
private readonly indexBaseName: string
) {}

abstract initialize: () => Promise<void>;
public initialize = async (teamIds: TeamId[]) => {
if (this.initialized) {
this.logger.debug("Search service already initialized");
return;
}
this.logger.debug("Initializing search service");
await this.createMissingIndexes(teamIds);
await this.onInitialize(teamIds);
this.initialized = true;
this.logger.debug("Search service initialized");
};

private createMissingIndexes = async (teamIds: TeamId[]) => {
const { results: indexes } = await this.meilisearch.getIndexes({
limit: Number.MAX_SAFE_INTEGER,
});

const indexesMissing = teamIds.filter((teamId) => {
const exists = indexes.some(
(index: Index<TDoc>) => index.uid === this.getIndexName(teamId)
);

public getIndexName = (teamId: string) => `${this.indexBaseName}_${teamId}`;
return !exists;
});

public deleteIndex = async (teamId: string) => {
await waitForTasks(
this.meilisearch,
indexesMissing.map(async (teamId) => {
this.logger.info("Creating missing index", { teamId });
return this.meilisearch.createIndex(this.getIndexName(teamId), {
primaryKey: "id",
});
})
);
this.logger.debug("Creating missing indexes done");
};

protected abstract onInitialize: (teamIds: TeamId[]) => Promise<void>;

public getIndexName = (teamId: TeamId) => `${this.indexBaseName}_${teamId}`;

public deleteIndex = async (teamId: TeamId) => {
this.logger.info("Deleting search index", { teamId });
const index = this.meilisearch.index<TDoc>(this.getIndexName(teamId));
await index.delete();
Expand All @@ -30,28 +70,31 @@ export abstract class AbstractSearchService<

protected abstract mapToSearchDocument: (entity: TEntity) => TDoc;

public rebuildIndex = async (team: Team, entities: TEntity[]) => {
this.logger.debug("Rebuilding index", { teamId: team.id });
public rebuildIndex = async (teamId: TeamId, entities: TEntity[]) => {
this.logger.debug("Rebuilding index", { teamId });
try {
const index = await this.meilisearch.getIndex<TDoc>(
this.getIndexName(team.id)
this.getIndexName(teamId)
);
await index.deleteAllDocuments();
const documents = entities.map(this.mapToSearchDocument);
await index.addDocuments(documents, { primaryKey: "id" });
this.logger.info("Rebuilding index done", {
teamId: team.id,
teamId,
documentCount: documents.length,
});
} catch (error) {
this.logger.error(
"Rebuilding index failed. This may be fine if no index exists.",
{ teamId: team.id, error }
{ teamId, error }
);
}
};

public delete = async (entity: TeamOwnedIdentifiable) => {
if (entity.teamId) {
await this.initialize([entity.teamId]);
}
this.logger.debug("Deleting document from search", { id: entity.id });
if (!entity.teamId) {
return;
Expand All @@ -67,6 +110,9 @@ export abstract class AbstractSearchService<
};

public add = async (entity: TEntity) => {
if (entity.teamId) {
await this.initialize([entity.teamId]);
}
this.logger.debug("Indexing entity", { id: entity.id });
if (!entity.teamId) {
return;
Expand Down
75 changes: 15 additions & 60 deletions src/server/lib/search/assetSearchService.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import { type Index } from "meilisearch";
import type MeiliSearch from "meilisearch";
import { type Logger } from "winston";
import { z } from "zod";
import { type AssetTypeService } from "../asset-types/assetTypeService";
import { type Team } from "@prisma/client";
import { type AssetWithFields } from "../assets/asset";
import { waitForTasks } from "../user/meiliSearchUtils";
import { type TeamService } from "../user/teamService";
import { AbstractSearchService } from "./abstractSearchService";
import { type TeamId } from "../user/team";

export const assetDocumentSchema = z.record(
z.union([z.string(), z.number(), z.boolean(), z.null()])
Expand All @@ -30,69 +27,27 @@ export class AssetSearchService extends AbstractSearchService<
constructor(
readonly logger: Logger,
readonly meilisearch: MeiliSearch,
private readonly teamService: TeamService,
private readonly assetTypeService: AssetTypeService
) {
super(logger, meilisearch, "assets");
}

public initialize = async () => {
this.logger.debug("Initializing asset search indexes");

const teams = await this.teamService.getAllTeams();
await this.createMissingIndexes(teams);
await this.syncFilterableAttributes(teams);

this.logger.debug("Initializing asset search indexes done");
protected onInitialize = async (teamIds: TeamId[]) => {
await this.syncFilterableAttributes(teamIds);
};

private createMissingIndexes = async (teams: Team[]) => {
const { results: indexes } = await this.meilisearch.getIndexes({
limit: Number.MAX_SAFE_INTEGER,
});

const indexesMissing = teams.filter((team) => {
const exists = indexes.some((index: Index<AssetSearchDocument>) => {
const compare = index.uid === this.getIndexName(team.id);
this.logger.debug("Index compare", {
indexId: index.uid,
compare,
name: this.getIndexName(team.id),
});
return compare;
});
this.logger.debug("Index existance", {
teamId: team.id,
exists,
name: this.getIndexName(team.id),
});

return !exists;
});

await waitForTasks(
this.meilisearch,
indexesMissing.map(async (team) => {
this.logger.info("Creating missing index", { teamId: team.id });
return this.meilisearch.createIndex(this.getIndexName(team.id), {
primaryKey: "id",
});
})
public syncFilterableAttributes = async (teamIds: TeamId[]) => {
const customFields = await this.assetTypeService.getSearchableCustomFields(
teamIds
);
this.logger.debug("Creating missing indexes done");
};

public syncFilterableAttributes = async (teams: Team[]) => {
const customFields =
await this.assetTypeService.getSearchableCustomFields();

await Promise.all(
teams.map(async (team) => {
teamIds.map(async (teamId) => {
const index = this.meilisearch.index<AssetSearchDocument>(
this.getIndexName(team.id)
this.getIndexName(teamId)
);
const customFieldsForTeam = customFields.filter(
(field) => field.teamId === team.id
(field) => field.teamId === teamId
);
const customFieldsAndBaseAttributes = [
...baseAttributes,
Expand All @@ -118,33 +73,33 @@ export class AssetSearchService extends AbstractSearchService<
this.logger.info(
"Filterable attributes have changed. Applying new config now. This may take a while!",
{
teamId: team.id,
teamId,
}
);
this.logger.debug("New filterable attributes", {
teamId: team.id,
teamId,
attributes: notYetFilterableAttributes.map((attr) => attr.slug),
});
await index.updateFilterableAttributes(customFieldsAndBaseAttributes);
this.logger.info("Applying filterable attributes done", {
teamId: team.id,
teamId,
});
}

if (notYetSortableAttributes.length > 0) {
this.logger.info(
"Sortable attributes have changed. Applying new config now. This may take a while!",
{
teamId: team.id,
teamId,
}
);
this.logger.debug("New sortable attributes", {
teamId: team.id,
teamId,
attributes: notYetSortableAttributes.map((attr) => attr.slug),
});
await index.updateSortableAttributes(customFieldsAndBaseAttributes);
this.logger.info("Applying sortable attributes done", {
teamId: team.id,
teamId,
});
}
})
Expand Down
Loading