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

Add endpoint for creating synchronous class merge #95

Merged
merged 3 commits into from
Oct 30, 2023
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
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,8 @@ pnpm-debug.log*
*.njsproj
*.sln
*.sw?

# Elastic Beanstalk Files
.elasticbeanstalk/*
!.elasticbeanstalk/*.cfg.yml
!.elasticbeanstalk/*.global.yml
1 change: 0 additions & 1 deletion src/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -664,7 +664,6 @@ export async function getQuestionsForStory(storyName: string, newestOnly=true):
});
}


export async function getDashboardGroupClasses(code: string): Promise<Class[] | null> {
const group = await DashboardClassGroup.findOne({ where: { code } });
if (group === null) {
Expand Down
6 changes: 6 additions & 0 deletions src/models/class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export class Class extends Model<InferAttributes<Class>, InferCreationAttributes
declare active: CreationOptional<boolean>;
declare code: string;
declare asynchronous: CreationOptional<boolean>;
declare test: CreationOptional<boolean>;
}

export function initializeClassModel(sequelize: Sequelize) {
Expand Down Expand Up @@ -55,6 +56,11 @@ export function initializeClassModel(sequelize: Sequelize) {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
test: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: 0
}
}, {
sequelize,
Expand Down
1 change: 1 addition & 0 deletions src/sql/create_class_table.sql
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ CREATE TABLE Classes (
active tinyint(1) NOT NULL DEFAULT 0,
code varchar(50) NOT NULL UNIQUE,
asynchronous tinyint(1) NOT NULL DEFAULT 0,
test tinyint(1) NOT NULL DEFAULT 0,
updated datetime DEFAULT NULL,

PRIMARY KEY(id),
Expand Down
68 changes: 66 additions & 2 deletions src/stories/hubbles_law/database.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Op, Sequelize, WhereOptions, col, fn, literal } from "sequelize";
import { Op, QueryTypes, Sequelize, WhereOptions, col, fn, literal } from "sequelize";
import { AsyncMergedHubbleStudentClasses, Galaxy, HubbleMeasurement, SampleHubbleMeasurement, initializeModels, SyncMergedHubbleClasses } from "./models";
import { cosmicdsDB, findClassById, findStudentById } from "../../database";
import { classSize, cosmicdsDB, findClassById, findStudentById } from "../../database";
import { RemoveHubbleMeasurementResult, SubmitHubbleMeasurementResult } from "./request_results";
import { setUpHubbleAssociations } from "./associations";
import { Class, StoryState, Student, StudentsClasses } from "../../models";
Expand Down Expand Up @@ -662,3 +662,67 @@ export async function getGalaxiesForDataGeneration(types=["Sp"]): Promise<Galaxy
});
return noMeasurements.concat(measurements);
}

export async function getMergeDataForClass(classID: number): Promise<SyncMergedHubbleClasses | null> {
return SyncMergedHubbleClasses.findOne({ where: { class_id: classID } });
}

export async function eligibleClassesForMerge(classID: number, sizeThreshold=20): Promise<Class[]> {
const size = await classSize(classID);

// Running into the limits of the ORM a bit here
// Maybe there's a clever way to write this?
// But straight SQL gets the job done
return cosmicdsDB.query(
`SELECT * FROM (SELECT
id,
test,
(SELECT
COUNT(*)
FROM
StudentsClasses
WHERE
StudentsClasses.class_id = id) AS size
FROM
Classes) q
WHERE
(size >= ${sizeThreshold - size} AND test = 0)
`, { type: QueryTypes.SELECT }) as Promise<Class[]>;
}

// Try and merge the class with the given ID with another class such that the total size is above the threshold
// We say "try" because if a client doesn't know that the merge has already occurred, we may get
// multiple such requests from different student clients.
// If a merge has already been created, we don't make another one - we just return the existing one, with a
// message that indicates that this was the case.
export interface MergeAttemptData {
mergeData: SyncMergedHubbleClasses | null;
message: string;
}
export async function tryToMergeClass(classID: number): Promise<MergeAttemptData> {
const cls = await findClassById(classID);
if (cls === null) {
return { mergeData: null, message: "Invalid class ID!" };
}

let mergeData = await getMergeDataForClass(classID);
if (mergeData !== null) {
return { mergeData, message: "Class already merged" };
}

const eligibleClasses = await eligibleClassesForMerge(classID);
if (eligibleClasses.length > 0) {
const index = Math.floor(Math.random() * eligibleClasses.length);
console.log(eligibleClasses);
console.log(index);
const classToMerge = eligibleClasses[index];
mergeData = await SyncMergedHubbleClasses.create({ class_id: classID, merged_class_id: classToMerge.id });
if (mergeData === null) {
return { mergeData, message: "Error creating merge!" };
}
return { mergeData, message: "New merge created" };
}

return { mergeData: null, message: "No eligible classes to merge" };

}
27 changes: 26 additions & 1 deletion src/stories/hubbles_law/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ import {
getSampleGalaxy,
getGalaxyById,
removeSampleHubbleMeasurement,
getAllNthSampleHubbleMeasurements
getAllNthSampleHubbleMeasurements,
tryToMergeClass
} from "./database";

import {
Expand Down Expand Up @@ -325,6 +326,30 @@ router.get("/all-data", async (req, res) => {
});
});

router.put("/sync-merged-class/:classID", async(req, res) => {
const classID = parseInt(req.params.classID);
if (isNaN(classID)) {
res.statusCode = 400;
res.json({
error: "Class ID must be a number"
});
return;
}
const data = await tryToMergeClass(classID);
if (data.mergeData === null) {
res.statusCode = 404;
res.json({
error: data.message
});
return;
}

res.json({
merge_info: data.mergeData,
message: data.message
});
});

router.get("/galaxies", async (req, res) => {
const types = req.query?.types ?? undefined;
let galaxies: Galaxy[];
Expand Down