Skip to content

feat: Automatically create indexes for _Session.sessionToken and class relations #8346

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

Open
wants to merge 23 commits into
base: alpha
Choose a base branch
from

Conversation

dblythy
Copy link
Member

@dblythy dblythy commented Dec 6, 2022

New Pull Request Checklist

Issue Description

Parse Server does not create indexes on the _Session class and join tables.

Closes: #8290
Closes: #7832

Approach

Adds indexes

TODOs before merging

  • Add tests

@parse-github-assistant
Copy link

I will reformat the title to use the proper commit message syntax.

@parse-github-assistant parse-github-assistant bot changed the title feat: create sessionToken and relation indexes feat: Create sessionToken and relation indexes Dec 6, 2022
@parse-github-assistant
Copy link

parse-github-assistant bot commented Dec 6, 2022

Thanks for opening this pull request!

  • 🎉 We are excited about your hands-on contribution!

@mtrezza mtrezza changed the title feat: Create sessionToken and relation indexes feat: Automatically create indexes for sessionToken and relations Dec 6, 2022
@mtrezza mtrezza changed the title feat: Automatically create indexes for sessionToken and relations feat: Automatically create indexes for _Session.sessionToken and relations Dec 6, 2022
@mtrezza mtrezza changed the title feat: Automatically create indexes for _Session.sessionToken and relations feat: Automatically create indexes for _Session.sessionToken and class relations Dec 6, 2022
@codecov
Copy link

codecov bot commented Dec 15, 2022

Codecov Report

Base: 94.04% // Head: 93.86% // Decreases project coverage by -0.17% ⚠️

Coverage data is based on head (36f658d) compared to base (b1bb1fc).
Patch coverage: 78.37% of modified lines in pull request are covered.

Additional details and impacted files
@@            Coverage Diff             @@
##            alpha    #8346      +/-   ##
==========================================
- Coverage   94.04%   93.86%   -0.18%     
==========================================
  Files         181      181              
  Lines       14266    14303      +37     
==========================================
+ Hits        13416    13426      +10     
- Misses        850      877      +27     
Impacted Files Coverage Δ
src/SchemaMigrations/DefinedSchemas.js 87.89% <0.00%> (-0.94%) ⬇️
src/Controllers/DatabaseController.js 93.39% <82.85%> (-0.53%) ⬇️
src/GraphQL/loaders/filesMutations.js 41.93% <0.00%> (-38.71%) ⬇️
src/GraphQL/transformers/mutation.js 87.85% <0.00%> (-9.35%) ⬇️
...dapters/Storage/Postgres/PostgresStorageAdapter.js 95.95% <0.00%> (+0.22%) ⬆️

Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here.

☔ View full report at Codecov.
📢 Do you have feedback about the report comment? Let us know in this issue.

Copy link
Member

@Moumouls Moumouls left a comment

Choose a reason for hiding this comment

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

Nice PR @dblythy ! 🚀

But we do not have in Parse Server a single source of truth about default indexes (not like systemClasses from schema controller).

You need to add the session index to isProtectedIndex function in DefinedSchema and update tests to ensure that if Session class is used in DefinedSchema, the _session_token is not deleted.

Note: we don't need to protect join classes index since it's internal classes and should not be defined in a DefinedSchema

@dblythy dblythy requested a review from a team January 1, 2023 05:39
@mtrezza
Copy link
Member

mtrezza commented Jan 5, 2023

@Moumouls Do you want to review this before we merge?

Comment on lines 694 to 728
(async () => {
if (this._relationTablesAdded.includes(className)) {
return;
}
const exists = await this.collectionExists(className);
const names = [];
if (exists) {
const indexes = (await this.adapter.getIndexes(className)) || [];
names.push(
...indexes.map(({ name, indexname }) => {
if (name) {
return name.split('_')[0];
}
const splitName = indexname.split('_');
return splitName.at(-1);
})
);
}
const keys = ['relatedId', 'owningId'];
await Promise.all(
keys.map(async subKey => {
if (names.includes(subKey)) {
return;
}
try {
await this.adapter.ensureIndex(className, relationSchema, [subKey]);
} catch (error) {
if (error.code !== '23505') {
logger.warn('Unable to create relatedId index: ', error);
}
}
})
);
this._relationTablesAdded.push(className);
})();
Copy link
Member

Choose a reason for hiding this comment

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

I'm not a huge fan of "floating promises" because in case of integration testing it could lead to open connections issues. It's a one-shot operation, we could create a cache to store the indexPromise, then other calls for the same relation could await a unique promise. All parallel calls on the same server will also avoid a spam to the index creation api, since only One promise will be created

Index creation is fast (DB do not wait for indexes created for all records). the promise index creation could be wrapped with a try-catch, so even if the index creation fail, the relation will be created.

relation.add(obj);
await obj2.save();
await obj2.destroy();
await new Promise(resolve => setTimeout(resolve, 1000));
Copy link
Member

@Moumouls Moumouls Jan 5, 2023

Choose a reason for hiding this comment

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

We should avoid hard coded timeout, it's flaky

here a simple function that you can use to add to the utils test suite (it's TS, you can convert to JS)

export const waitFor = async (
	fn: () => Promise<any>,
	count = 0,
	timeout = 100,
): Promise<undefined> => {
	try {
		await fn()
		return undefined
	} catch (e: any) {
		await new Promise((resolve) => setTimeout(resolve, timeout))
		if (count < 100) {
			return waitFor(fn, count + 1, timeout)
		}
		throw e
	}
}

And usage

await waitFor(async () => {
			expect(requestSpy).toHaveBeenCalledTimes(3)
		})

Wait for will resolve asap and re execute the provided fn until the fn success.

@Moumouls
Copy link
Member

Moumouls commented Jan 5, 2023

here some feedbacks @dblythy @mtrezza

Comment on lines +707 to +747
createJoinTable(className: string) {
const startupPromise = async () => {
if (this._relationTablesCache.classes.includes(className)) {
return;
}
const exists = await this.collectionExists(className);
const names = [];
if (exists) {
const indexes = (await this.adapter.getIndexes(className)) || [];
names.push(
...indexes.map(({ name, indexname }) => {
if (name) {
return name.split('_')[0];
}
const splitName = indexname.split('_');
return splitName.at(-1);
})
);
}
const keys = ['relatedId', 'owningId'];
await Promise.all(
keys.map(async subKey => {
if (names.includes(subKey)) {
return;
}
try {
await this.adapter.ensureIndex(className, relationSchema, [subKey]);
} catch (error) {
if (error.code !== '23505') {
logger.warn('Unable to create relatedId index: ', error);
}
}
})
);
this._relationTablesCache.classes.push(className);
};
const promise = this._relationTablesCache.promises[className] || startupPromise();
this._relationTablesCache.promises[className] = promise;
return promise;
}

Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
createJoinTable(className: string) {
const startupPromise = async () => {
if (this._relationTablesCache.classes.includes(className)) {
return;
}
const exists = await this.collectionExists(className);
const names = [];
if (exists) {
const indexes = (await this.adapter.getIndexes(className)) || [];
names.push(
...indexes.map(({ name, indexname }) => {
if (name) {
return name.split('_')[0];
}
const splitName = indexname.split('_');
return splitName.at(-1);
})
);
}
const keys = ['relatedId', 'owningId'];
await Promise.all(
keys.map(async subKey => {
if (names.includes(subKey)) {
return;
}
try {
await this.adapter.ensureIndex(className, relationSchema, [subKey]);
} catch (error) {
if (error.code !== '23505') {
logger.warn('Unable to create relatedId index: ', error);
}
}
})
);
this._relationTablesCache.classes.push(className);
};
const promise = this._relationTablesCache.promises[className] || startupPromise();
this._relationTablesCache.promises[className] = promise;
return promise;
}
ensureJoinTable(className: string) {
const classNamePromise = this._relationTablesCache[className]
if(classNamePromise) return classNamePromise
const startupPromise = async () => {
const exists = await this.collectionExists(className);
const names = [];
if (exists) {
const indexes = (await this.adapter.getIndexes(className)) || [];
names.push(
...indexes.map(({ name, indexname }) => {
if (name) {
return name.split('_')[0];
}
const splitName = indexname.split('_');
return splitName.at(-1);
})
);
}
const keys = ['relatedId', 'owningId'];
await Promise.all(
keys.map(async subKey => {
if (names.includes(subKey)) {
return;
}
try {
await this.adapter.ensureIndex(className, relationSchema, [subKey]);
} catch (error) {
if (error.code !== '23505') {
logger.warn('Unable to create relatedId index: ', error);
}
}
})
);
this._relationTablesCache.classes.push(className);
};
const promise = startupPromise()
this._relationTablesCache[className] = promise
return promise
}

Too many source of truth just use a signe object with indexed promises by class names and early return
Code not tested but the strategu should work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Session Lookup should use indexes Indexing owningId and releatedId in mongo _Join documents
3 participants