ITR application architecture

From ITR Wiki

This page explains how the ITR works on the inside: which parts there are, how they talk to each other, how a candidate moves through a test, and how the ITR keeps working when someone presses F5. It is written for developers, architects and anyone who wants to understand the platform before changing it.

If you are looking for the reasons behind the main choices, read ITR Design first. If you want to start working on the code, continue with ITR development.

The big picture

The ITR consists of four parts:

The web client (repository ITS2)
A single page application written in JavaScript, with jQuery and Bootstrap. It contains both the office and test taking. Most of the real work happens here: showing screens, running the scripts of a test, scoring, norming and making reports.
The internal API (repository ITS rest api)
A Python Flask application, used only by the web client. It handles login and rights, stores and reads data, sends mail, translates texts and runs a few server side triggers. See Internal API.
The public API (repository ITS public rest api)
A small Flask application for other systems, for example to create a public test link or to fetch results. It reuses the modules of the internal API. See External API.
PostgreSQL
One master database for everything that is shared (organisations, logins, login tokens, credits and centrally published tests, reports and screen templates), and one database per organisation for its own data: persons, sessions, answers, scores and its own tests and reports.

Both APIs share an instance folder with the settings file application.cfg, translations, uploaded media, a cache and the log files.

Why the browser does most of the work

Tests, screen templates, scoring rules, norms and reports are content: JavaScript and HTML stored in the database. The web client loads that content and interprets it. That is how test authors can build new tests without a new software release, and it is why the same test definition behaves the same in the test editor, during test taking, while scoring and in reports.

The server stays small and predictable. Its API calls are short, so many browsers can work at the same time. Only what cannot or should not happen in the browser runs on the server: checking rights, storing data, mail, translations and the triggers described below.

Master data and customer data

Every call from the web client carries the headers SessionID (the login token), CompanyID and BrowserID. The internal API uses the token to find the user and the organisation, and opens the database of that organisation. Two optional headers, IncludeMaster and IncludeClient, tell the API whether to read from the master database, the customer database, or both. This is how centrally managed tests appear next to the tests of the organisation itself.

A customer database is created automatically the first time it is needed, from database/CREATEDB.SQL. Every database stores its version, and the API brings it up to date with the numbered scripts MIGRATEDB1.SQL, MIGRATEDB2.SQL and so on, the first time it opens that database after a start.

Inside the web client

default.htm holds the whole page layout and loads the libraries. Then the ITR scripts load in a fixed order: InitServerVars.js (server address and script folder), InitVars.js (loads the bootstrap and knows the list of plugins), ITSBootstrap.js (loads the Support and DataModel scripts) and finally ITSInit.js.

ITSInit.js creates ITSInstance, the one global object that holds everything:

  • the controllers: the UIController for screens, paths, editors, portlets and menus, the login and logout controllers, and the testTakingController, which is the state engine described below;
  • the data model: companies, users, tests, candidates, candidate sessions, batteries, screen templates and reports. Objects are written to and read from the server as JSON with ITSJSONStringify and ITSJSONLoad; the list persistentProperties of an object says which properties are saved;
  • the services: the login token, the translator, the MessageBus and the queued server calls genericAjaxLoader, genericAjaxUpdate and genericAjaxDelete.

Server calls are placed in a queue and handled one by one. That keeps the load on the server even and makes the order of saves predictable.

Plugins

Almost every office screen is a plugin in ITSScript/Plugins. Plugins are loaded on demand after an office login, so the login screen and test taking start quickly. There are three kinds of building blocks:

  • portlets: the tiles on the Dashboard, registered with registerPortlet;
  • editors and listers: full screens with their own path, registered with registerEditor;
  • menu items: entries in the side menu, added with registerMenuItem.

How to write a plugin yourself is explained on ITR development.

Paths and the address bar

The ITR shows one screen at a time, chosen by the Path parameter in the address bar, for example default.htm?Path=Switchboard for the dashboard or ?Path=SessionEditor&SessionID=... for a session. ITSRedirectPath changes the address with history.pushState. A small watcher in ITSInit.js notices every change of the address and asks the UIController to show the matching screen. That is why the back button of the browser works, and why you can bookmark or share a screen.

A few paths are built in, such as Login, Switchboard, TestTaking and TestTakingPublic. Every other path belongs to a plugin. When the plugin is not registered yet, for example right after a refresh, the UIController simply tries again a moment later. An organisation or a user can be denied paths with the ForbiddenPaths setting.

The MessageBus

Plugins do not call each other directly. They talk through the MessageBus: one part publishes a message such as Session.Update or CurrentUser.Loaded, and every part that subscribed to it is called. Subscribers are called asynchronously, one tick later. A subscriber can ask to be called straight away if the message was already published before it subscribed, which is handy for plugins that load late.

The test taking state engine

Test taking is driven by the ITSTestTakingController in ITSScript/Support/ITSControllers.js. It moves a candidate through the session step by step.

Finding the session
startSession looks for the active sessions of the candidate: status 10 (ready) or 20 (in progress). When there is more than one, the candidate chooses. loadSession then loads the session, its tests and the test definitions.
Choosing the test
firstTestToTake sorts the tests on their sequence number and picks the first one that is taken online and is not done yet, as long as the current time is within the allowed dates of the session.
Starting the test
startTest starts the clock when the test is new, runs the test pre script and sets both the session and the test to status 20. The test pre and post scripts and the time available are part of the test definition, but cannot be set in the test editor at this moment.
Showing a screen
renderTestPage looks at CurrentPage. Past the last screen, the test ends. Otherwise it runs the screen pre script, which may hide the screen; a hidden screen is skipped. Then it draws the screen and puts back the answers that were already given.
Waiting for the candidate
While a screen is shown, screen dynamics are checked every 350 milliseconds, and the answers are stored every minute.
Handling an event
A button, a timer or a screen action calls processEvent. It reads the answers from the screen, checks the validations (except for PreviousScreen, EndTestTimeOut and Logout), runs the screen post script and then carries out the event: NextScreen, PreviousScreen, GotoScreen, Script, Store, EndTest and so on. A new CurrentPage is saved straight away.
Ending the test
endTest runs the test post script and gives the test status 30. If there is another test, it starts, optionally after a closure screen. If not, endSession waits until all saves are done, reloads the session from the server and gives the session status 30.

Status values

Status Session Test in a session
10 Ready to start Ready to start
20 In progress In progress
30 Done Done
31 Done and handled by the server –

What the server does at the end

When a test is saved with status 30, a trigger in the internal API charges the credits, stores the anonymous research data and writes the audit trail. When the session is saved with status 30, the server changes it to status 31 and mails the consultant that the session is ready for reporting.

Scoring and norming happen in the browser, with the same code everywhere. When a consultant opens a session, the scores of its completed tests are calculated and saved. A session that shows a report to the candidate straight away calculates the scores at the end of the session. And when another system asks the public API to score a test, the public API runs the very same DataModel and Support scripts of the web client in Node.js. One test definition, one way of scoring.

Running inside another page

When the ITR runs inside an iframe, the end of a test with a closure screen calls the function ITREndTestFunction if it exists, and sends the message ITREndTestFunction to the parent page with postMessage. The page around the ITR can use this to continue its own flow.

Surviving a page refresh

People press F5, lose their connection or close their laptop halfway through a test. The ITR is built so that this does no harm. The state lives in four places:

The address bar
The Path parameter, plus the parameters of the screen, says which screen is open.
sessionStorage, for this tab only
The login token is kept here, with a sliding lifetime of six minutes. Public sessions also keep Poll, MailTo and ReviewID here.
Cookies and localStorage, for this browser
SessionID remembers the session that is being taken, for nine minutes, renewed at every screen change. ITRLanguage, NoTTHeader, Coupon and ReturnURL live here as well. The ITR writes these values both as a cookie and in localStorage.
The server
A login token stays valid while it is used and expires after ten minutes without use. The test in the session holds CurrentPage, the answers, the time left and the status, and is saved at every screen change and every minute.

What happens after a refresh

  1. The page loads again and ITSInit.js creates a new ITSInstance.
  2. If the tab still has its login token, the ITR loads the current user. Without a token, the login screen appears.
  3. An office user gets the plugins and data loaded again. The path in the address bar is opened as soon as its plugin has registered itself, so the consultant is back on the same screen.
  4. A test taker goes back into the state engine. startSession finds the session through the SessionID cookie, loadSession and firstTestToTake pick up the right test, and renderTestPage opens the saved CurrentPage with the answers given so far.

The same mechanism makes it possible to stop a test and log in again later: the candidate continues on the saved screen.

Closing the tab

The browser cannot tell a refresh from closing a tab. During test taking the ITR therefore clears only the shared login cookie when the page unloads, and does not log out. After a refresh the token is still in sessionStorage of that tab, so the test simply continues. A closed tab loses its sessionStorage, so the next visit on that computer starts at the login screen.

Deployment

The repository ITR-Docker contains everything to run the ITR with Docker. ITRStack.yml describes four containers on one network: nginx, the internal API, the public API and PostgreSQL. The code, settings and data live in folders on the host, so containers can be replaced without losing anything. With an instance suffix and HAProxy, several ITR instances can run on one server. Step by step instructions are on Install on linux and Install on windows.

The internal API can also update the ITR itself: it fetches new versions of the web client, both APIs and the translations from GitHub. See Server settings and tools.

Where to go next