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

IndexOptionsConflict for chunk collection - pr #372

Merged
merged 6 commits into from
Aug 10, 2022
Merged
Show file tree
Hide file tree
Changes from 4 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
133 changes: 45 additions & 88 deletions src/gridfs/indexes.ts
Original file line number Diff line number Diff line change
@@ -1,103 +1,60 @@
import { Document } from "../../deps.ts";
import { Collection } from "../collection/collection.ts";
import { Chunk, File } from "../types/gridfs.ts";
import { IndexOptions } from "../types.ts";

async function ensureIndex<T>(
index: IndexOptions,
collection: Collection<T>,
): Promise<ReturnType<Collection<T>["createIndexes"]>> {
// We need to check collection emptiness (ns not found error for listIndexes on empty collection)
const doc = await collection.findOne({}, { projection: { _id: 1 } });
if (doc === undefined) {
return collection.createIndexes({ indexes: [index] });
}
const keys = Object.keys(index.key);
const indexes = await collection.listIndexes().toArray();
const existing = indexes.find(({ key }) => {
const currentKeys = Object.keys(key);
return currentKeys.length === keys.length &&
currentKeys.every((k) => keys.includes(k));
});
if (existing === undefined) {
return collection.createIndexes({ indexes: [index] });
} else {
return {
ok: 1,
createdCollectionAutomatically: false,
numIndexesBefore: indexes.length,
numIndexesAfter: indexes.length,
};
}
}

const fileIndexSpec = {
name: "gridFSFiles",
key: { filename: 1, uploadDate: 1 },
background: false,
};
export function createFileIndex(collection: Collection<File>) {
const index = { filename: 1, uploadDate: 1 };

return collection.createIndexes({
indexes: [
{
name: "gridFSFiles",
key: index,
background: false,
},
],
});
return ensureIndex<File>(fileIndexSpec, collection);
}
export function createChunksIndex(collection: Collection<Chunk>) {
// deno-lint-ignore camelcase
const index = { files_id: 1, n: 1 };

return collection.createIndexes({
indexes: [
{
name: "gridFSFiles",
key: index,
unique: true,
background: false,
},
],
});
const chunkIndexSpec = {
name: "gridFSFiles",
key: { files_id: 1, n: 1 },
unique: true,
background: false,
};
export function createChunksIndex(collection: Collection<Chunk>) {
return ensureIndex<Chunk>(chunkIndexSpec, collection);
}

export async function checkIndexes(
filesCollection: Collection<File>,
chunksCollection: Collection<Chunk>,
hasCheckedIndexes: (value: boolean) => void,
) {
const filesCollectionIsEmpty = !(await filesCollection.findOne(
{},
{
projection: { _id: 1 },
},
));

const chunksCollectionIsEmpty = !(await chunksCollection.findOne(
{},
{
projection: { _id: 1 },
},
));

if (filesCollectionIsEmpty || chunksCollectionIsEmpty) {
// At least one collection is empty so we create indexes
await createFileIndex(filesCollection);
await createChunksIndex(chunksCollection);
hasCheckedIndexes(true);
return;
}

// Now check that the right indexes are there
const fileIndexes = await filesCollection.listIndexes().toArray();
let hasFileIndex = false;

if (fileIndexes) {
fileIndexes.forEach((index) => {
const keys = Object.keys(index.key);
if (
keys.length === 2 &&
index.key.filename === 1 &&
index.key.uploadDate === 1
) {
hasFileIndex = true;
}
});
}

if (!hasFileIndex) {
await createFileIndex(filesCollection);
}

const chunkIndexes = await chunksCollection.listIndexes().toArray();
let hasChunksIndex = false;

if (chunkIndexes) {
chunkIndexes.forEach((index: Document) => {
const keys = Object.keys(index.key);
if (
keys.length === 2 &&
index.key.filename === 1 &&
index.key.uploadDate === 1 &&
index.options.unique
) {
hasChunksIndex = true;
}
});
}

if (!hasChunksIndex) {
await createChunksIndex(chunksCollection);
}
await createFileIndex(filesCollection);
await createChunksIndex(chunksCollection);
hasCheckedIndexes(true);
}
27 changes: 23 additions & 4 deletions tests/cases/06_gridfs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,15 @@ testWithClient("GridFS: Echo large Image", async (client) => {
chunkSizeBytes: 255 * 8,
});

await (await fetch("https://deno.land/images/deno_logo.png")).body!.pipeTo(
upstream,
);
await (await fetch("https://deno.land/images/artwork/snow_den.png")).body!
.pipeTo(
upstream,
);

const getId =
(await bucket.find({ filename: "deno_logo.png" }).toArray())[0]._id;

const expected = await fetch("https://deno.land/images/deno_logo.png");
const expected = await fetch("https://deno.land/images/artwork/snow_den.png");
const actual = await new Response(await bucket.openDownloadStream(getId))
.arrayBuffer();

Copy link
Member

@erfanium erfanium Aug 10, 2022

Choose a reason for hiding this comment

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

Please revert these changes, because we already localized these assets so this PR has merge conflicts

Expand Down Expand Up @@ -113,3 +114,21 @@ testWithClient(
assert(!file[0]);
},
);

// https://www.mongodb.com/docs/manual/reference/command/createIndexes/#considerations
testWithClient(
"GridFS: Creating indexes - skip index creation on same index keys",
async (client) => {
const addAsset = async (index: number) => {
const bucket = new GridFSBucket(client.database("test"), {
bucketName: "sameKeys",
});
const upstream = await bucket.openUploadStream(`test-asset-${index}`);
const writer = upstream.getWriter();
await writer.write(new TextEncoder().encode(`[asset${index}]`));
await writer.close();
};
await addAsset(0);
await addAsset(1);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Where is the assert in this code? Shouldn’t the test case somehow check if the indexes where skipped?

},
);