Skip to content
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
2 changes: 1 addition & 1 deletion AssessmentDelivery.Web/Web.AzureRelease.config
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings>
<add name="AssessmentDelivery"
connectionString="Server=tcp:&lt;your-server&gt;.database.windows.net,1433;Initial Catalog=AssessmentDelivery;Persist Security Info=False;User ID=ad_app;Password=__AZURE_SQL_PASSWORD__;MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
connectionString="Server=tcp:&lt;your-server&gt;.database.windows.net,1433;Initial Catalog=AssessmentDelivery;Persist Security Info=False;User ID=__AZURE_SQL_PORTAL_USER__;Password=__AZURE_SQL_PASSWORD__;MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
</connectionStrings>
<appSettings>
Expand Down
2 changes: 1 addition & 1 deletion AssessmentDelivery.Web/Web.Release.config
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings>
<add name="AssessmentDelivery"
connectionString="Data Source=__ONPREM_SQL_SERVER__,1433;Initial Catalog=AssessmentDelivery;User ID=ad_app;Password=__ONPREM_SQL_PASSWORD__;MultipleActiveResultSets=True;Connect Timeout=30;Application Name=AssessmentDeliveryPortal"
connectionString="Data Source=__ONPREM_SQL_SERVER__,1433;Initial Catalog=AssessmentDelivery;User ID=ad_portal;Password=__ONPREM_SQL_PASSWORD__;MultipleActiveResultSets=True;Connect Timeout=30;Application Name=AssessmentDeliveryPortal"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
</connectionStrings>
<appSettings>
Expand Down
2 changes: 1 addition & 1 deletion AssessmentDelivery.Web/Web.config
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="AssessmentDelivery" connectionString="Data Source=localhost,1433;Initial Catalog=AssessmentDelivery;User ID=ad_app;Password=Northw1nd!Dev2011;MultipleActiveResultSets=True;Connect Timeout=30;Application Name=AssessmentDeliveryPortal" providerName="System.Data.SqlClient" />
<add name="AssessmentDelivery" connectionString="Data Source=localhost,1433;Initial Catalog=AssessmentDelivery;User ID=ad_portal;Password=P0rtal!Dev2026;MultipleActiveResultSets=True;Connect Timeout=30;Application Name=AssessmentDeliveryPortal" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
Expand Down
18 changes: 3 additions & 15 deletions db/schema/000_create_database.sql
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,6 @@ IF DB_ID('AssessmentDelivery') IS NULL
CREATE DATABASE AssessmentDelivery;
GO

IF NOT EXISTS (SELECT 1 FROM sys.server_principals WHERE name = 'ad_app')
CREATE LOGIN ad_app WITH PASSWORD = 'Northw1nd!Dev2011', CHECK_POLICY = OFF;
GO

USE AssessmentDelivery;
GO

IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = 'ad_app')
BEGIN
CREATE USER ad_app FOR LOGIN ad_app;
ALTER ROLE db_datareader ADD MEMBER ad_app;
ALTER ROLE db_datawriter ADD MEMBER ad_app;
GRANT EXECUTE TO ad_app;
END
GO
-- MBA-3823: the shared ad_app login (docs/as-is HB-28, MR-07) is retired. Each component now has its
-- own login, created after the tables exist by db/security/036_component_logins.sql; legacy write denial
-- for the single-writer coexistence is db/security/040_single_writer.sql.
16 changes: 16 additions & 0 deletions db/schema/016_relay_checkpoint.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
-- 016_relay_checkpoint.sql
-- MBA-3823: idempotency ledger for the scheduling-service outbox relay. One row per applied outbox event,
-- written in the same transaction as the relay's Booking/Waitlist/ExamSession/AuditLog changes, so a
-- replayed event (relay killed mid-batch and restarted) finds its EventId here and is a no-op.
USE AssessmentDelivery;
GO
IF OBJECT_ID('dbo.RelayCheckpoint') IS NOT NULL DROP TABLE dbo.RelayCheckpoint;
GO
CREATE TABLE dbo.RelayCheckpoint (
EventId UNIQUEIDENTIFIER NOT NULL CONSTRAINT PK_RelayCheckpoint PRIMARY KEY,
EventSeq BIGINT NOT NULL,
EventType VARCHAR(40) NOT NULL,
AppliedAt DATETIME2(3) NOT NULL CONSTRAINT DF_RelayCheckpoint_AppliedAt DEFAULT (SYSUTCDATETIME())
);
CREATE INDEX IX_RelayCheckpoint_EventSeq ON dbo.RelayCheckpoint (EventSeq);
GO
70 changes: 70 additions & 0 deletions db/security/036_component_logins.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
-- 036_component_logins.sql
-- MBA-3823: one login per component instead of the shared ad_app (docs/as-is HB-28, MR-07).
-- Legacy logins keep the broad role membership ad_app had (reader/writer/EXECUTE) so read pages and
-- non-booking tables (Result, ResultUpload, AuditLog, Candidate...) behave as before; 040_single_writer.sql
-- then DENYs the booking/seat writes. ad_sched_relay is the only writer of Booking/Waitlist/seat columns.
-- Local-development passwords only (same convention as 035); Azure uses contained users + secrets.
-- Applied after the seed by db/apply.sh / db/apply.ps1. Server logins survive the DB rebuild, so idempotent.
USE master;
GO
IF NOT EXISTS (SELECT 1 FROM sys.server_principals WHERE name = 'ad_portal')
CREATE LOGIN ad_portal WITH PASSWORD = 'P0rtal!Dev2026', CHECK_POLICY = OFF, DEFAULT_DATABASE = AssessmentDelivery;
GO
IF NOT EXISTS (SELECT 1 FROM sys.server_principals WHERE name = 'ad_booking_api')
CREATE LOGIN ad_booking_api WITH PASSWORD = 'B00kingApi!Dev2026', CHECK_POLICY = OFF, DEFAULT_DATABASE = AssessmentDelivery;
GO
IF NOT EXISTS (SELECT 1 FROM sys.server_principals WHERE name = 'ad_results')
CREATE LOGIN ad_results WITH PASSWORD = 'Resu1ts!Dev2026', CHECK_POLICY = OFF, DEFAULT_DATABASE = AssessmentDelivery;
GO
IF NOT EXISTS (SELECT 1 FROM sys.server_principals WHERE name = 'ad_capacity_sync')
CREATE LOGIN ad_capacity_sync WITH PASSWORD = 'CapSync!Dev2026', CHECK_POLICY = OFF, DEFAULT_DATABASE = AssessmentDelivery;
GO
IF NOT EXISTS (SELECT 1 FROM sys.server_principals WHERE name = 'ad_sched_relay')
CREATE LOGIN ad_sched_relay WITH PASSWORD = 'Sch3dRelay!Dev2026', CHECK_POLICY = OFF, DEFAULT_DATABASE = AssessmentDelivery;
GO
USE AssessmentDelivery;
GO
-- portal (AssessmentDelivery.Web, EF6)
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = 'ad_portal')
CREATE USER ad_portal FOR LOGIN ad_portal;
ALTER ROLE db_datareader ADD MEMBER ad_portal;
ALTER ROLE db_datawriter ADD MEMBER ad_portal;
GRANT EXECUTE TO ad_portal;
GO
-- booking-api (Java 8, JdbcTemplate)
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = 'ad_booking_api')
CREATE USER ad_booking_api FOR LOGIN ad_booking_api;
ALTER ROLE db_datareader ADD MEMBER ad_booking_api;
ALTER ROLE db_datawriter ADD MEMBER ad_booking_api;
GRANT EXECUTE TO ad_booking_api;
GO
-- results-service (Java 8)
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = 'ad_results')
CREATE USER ad_results FOR LOGIN ad_results;
ALTER ROLE db_datareader ADD MEMBER ad_results;
ALTER ROLE db_datawriter ADD MEMBER ad_results;
GRANT EXECUTE TO ad_results;
GO
-- capacity-sync (Java 8)
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = 'ad_capacity_sync')
CREATE USER ad_capacity_sync FOR LOGIN ad_capacity_sync;
ALTER ROLE db_datareader ADD MEMBER ad_capacity_sync;
ALTER ROLE db_datawriter ADD MEMBER ad_capacity_sync;
GRANT EXECUTE TO ad_capacity_sync;
GO
-- scheduling-service outbox relay: named-table rights only (no roles, no EXECUTE)
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = 'ad_sched_relay')
CREATE USER ad_sched_relay FOR LOGIN ad_sched_relay;
GRANT SELECT, INSERT, UPDATE, DELETE ON dbo.Booking TO ad_sched_relay;
GRANT SELECT, INSERT, UPDATE, DELETE ON dbo.Waitlist TO ad_sched_relay;
GRANT SELECT, UPDATE ON dbo.ExamSession TO ad_sched_relay;
GRANT SELECT, INSERT ON dbo.AuditLog TO ad_sched_relay;
GRANT SELECT, INSERT ON dbo.RelayCheckpoint TO ad_sched_relay;
GRANT SELECT ON dbo.Candidate TO ad_sched_relay;
-- SET IDENTITY_INSERT dbo.Booking ON: relayed bookings keep the BookingId scheduling-service assigned
-- (>= routing.modern-booking-id-floor), so v1 URLs and Result.BookingId resolve the same row on both sides.
GRANT ALTER ON dbo.Booking TO ad_sched_relay;
GO
-- reconciliation reads RelayCheckpoint through the read-only importer login
GRANT SELECT ON dbo.RelayCheckpoint TO ad_sched_import;
GO
49 changes: 49 additions & 0 deletions db/security/040_single_writer.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
-- 040_single_writer.sql
-- MBA-3823: scheduling-service is the single writer of bookings and seat counts. Every legacy login loses
-- direct write access to the contested data (docs/as-is/data-ownership.md; HB-01, HB-02, HB-03, HB-04,
-- HB-05, HB-29; MR-01, MR-02, MR-07, MR-17). Booking/capacity writes for all centres go through the routing
-- gateway (:8000) to scheduling-service; its outbox relay (ad_sched_relay) projects them back here.
-- Legacy read pages keep rendering from these tables. ad_sched_import stays read-only (035).
-- DENY beats the db_datawriter / GRANT EXECUTE membership from 036, so writes fail with error 229/230.
USE AssessmentDelivery;
GO
DENY INSERT, UPDATE, DELETE ON dbo.Booking TO ad_portal;
DENY INSERT, UPDATE, DELETE ON dbo.Waitlist TO ad_portal;
DENY UPDATE ON dbo.ExamSession (Capacity, SeatsAvailable, AccommodationCapacity) TO ad_portal;
DENY EXECUTE ON dbo.usp_BookSeat TO ad_portal;
DENY EXECUTE ON dbo.usp_CancelBooking TO ad_portal;
DENY EXECUTE ON dbo.usp_ChangeCapacity TO ad_portal;
DENY EXECUTE ON dbo.usp_RescheduleBooking TO ad_portal;
DENY INSERT, UPDATE, DELETE ON dbo.RelayCheckpoint TO ad_portal;
GO
DENY INSERT, UPDATE, DELETE ON dbo.Booking TO ad_booking_api;
DENY INSERT, UPDATE, DELETE ON dbo.Waitlist TO ad_booking_api;
DENY UPDATE ON dbo.ExamSession (Capacity, SeatsAvailable, AccommodationCapacity) TO ad_booking_api;
DENY EXECUTE ON dbo.usp_BookSeat TO ad_booking_api;
DENY EXECUTE ON dbo.usp_CancelBooking TO ad_booking_api;
DENY EXECUTE ON dbo.usp_ChangeCapacity TO ad_booking_api;
DENY EXECUTE ON dbo.usp_RescheduleBooking TO ad_booking_api;
DENY INSERT, UPDATE, DELETE ON dbo.RelayCheckpoint TO ad_booking_api;
GO
DENY INSERT, UPDATE, DELETE ON dbo.Booking TO ad_results;
DENY INSERT, UPDATE, DELETE ON dbo.Waitlist TO ad_results;
DENY UPDATE ON dbo.ExamSession (Capacity, SeatsAvailable, AccommodationCapacity) TO ad_results;
DENY EXECUTE ON dbo.usp_BookSeat TO ad_results;
DENY EXECUTE ON dbo.usp_CancelBooking TO ad_results;
DENY EXECUTE ON dbo.usp_ChangeCapacity TO ad_results;
DENY EXECUTE ON dbo.usp_RescheduleBooking TO ad_results;
DENY INSERT, UPDATE, DELETE ON dbo.RelayCheckpoint TO ad_results;
GO
DENY INSERT, UPDATE, DELETE ON dbo.Booking TO ad_capacity_sync;
DENY INSERT, UPDATE, DELETE ON dbo.Waitlist TO ad_capacity_sync;
DENY UPDATE ON dbo.ExamSession (Capacity, SeatsAvailable, AccommodationCapacity) TO ad_capacity_sync;
DENY EXECUTE ON dbo.usp_BookSeat TO ad_capacity_sync;
DENY EXECUTE ON dbo.usp_CancelBooking TO ad_capacity_sync;
DENY EXECUTE ON dbo.usp_ChangeCapacity TO ad_capacity_sync;
DENY EXECUTE ON dbo.usp_RescheduleBooking TO ad_capacity_sync;
DENY INSERT, UPDATE, DELETE ON dbo.RelayCheckpoint TO ad_capacity_sync;
GO
-- a leftover shared login from an older apply must not keep a side door open
IF EXISTS (SELECT 1 FROM sys.database_principals WHERE name = 'ad_app')
DROP USER ad_app;
GO
8 changes: 8 additions & 0 deletions db/triggers/032_trg_Booking_SeatSync.sql
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@
migration) instead of going through usp_BookSeat.
usp_BookSeat already adjusts the counter for portal bookings.
2013-04 migration cutover

MBA-3823: returns early for writes made by the scheduling-service relay
(SESSION_CONTEXT writer = scheduling-relay). The relay projects exactly the
seat count scheduling-service decided, so the extra non-PORTAL decrement
(docs/as-is HB-01 / HB-04, MR-01) must not fire on top of it. Every other
writer keeps the legacy behaviour.
*/
USE AssessmentDelivery;
GO
Expand All @@ -15,6 +21,8 @@ AS
BEGIN
SET NOCOUNT ON;

IF CONVERT(NVARCHAR(64), SESSION_CONTEXT(N'writer')) = N'scheduling-relay' RETURN;

UPDATE s
SET s.SeatsAvailable = s.SeatsAvailable - x.Cnt
FROM dbo.ExamSession s
Expand Down
8 changes: 8 additions & 0 deletions db/triggers/033_trg_ExamSession_Update.sql
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@
trg_ExamSession_Update - maintains ExamSession.LastModified.
(Not every caller remembers to set it - the Java services in particular.)
2014-11

MBA-3823: for writes made by the scheduling-service relay
(SESSION_CONTEXT writer = scheduling-relay) only the LastModified stamp runs.
The newest-first demotion, waitlist bump and SeatsAvailable recompute
(docs/as-is HB-05 / HB-16, MR-01) are skipped because the relay already
writes the bookings, waitlist rows and seat count scheduling-service decided.
*/
USE AssessmentDelivery;
GO
Expand All @@ -21,6 +27,8 @@ BEGIN
FROM dbo.ExamSession s
JOIN inserted i ON i.SessionId = s.SessionId;

IF CONVERT(NVARCHAR(64), SESSION_CONTEXT(N'writer')) = N'scheduling-relay' RETURN;

IF UPDATE(Capacity)
BEGIN
DECLARE @b TABLE (BookingId INT PRIMARY KEY, SessionId INT, CandidateId INT, BookedAt DATETIME);
Expand Down
63 changes: 63 additions & 0 deletions docs/adr/0003-single-writer-outbox-relay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# ADR 0003: scheduling-service is the single writer; legacy tables are an outbox projection (MBA-3823, M4)

Status: accepted. Builds on [ADR 0002](0002-ported-rule-decisions.md) and the M3 routing gateway.

## Context

`ExamSession.SeatsAvailable` has several writers with different formulas: the portal stored procedures, booking-api's
double decrement (HB-01) and leaks (HB-02), capacity-sync's nightly recompute (HB-03, MR-17) and the two triggers
(HB-04, HB-05, HB-16). That is the root of the seat drift in [MR-01 / MR-02](../as-is/migration-risks.md). All
components share the high-privilege `ad_app` login (HB-28, MR-07), so nothing stops a new writer appearing.

## Decisions

1. **One writer.** Only scheduling-service decides bookings, waitlist, attendance and capacity. The gateway sends
booking/capacity traffic for every centre to it (`routing.modern-centers=*`, `routing.coexistence-mode=relay`).
Centre-less portal pages (`/Booking/MyBookings` without `centerCode`, candidate pages, capacity audit) and every
legacy reader keep reading `AssessmentDelivery`.
2. **Per-component logins** (`db/security/036_component_logins.sql`): `ad_portal`, `ad_booking_api`, `ad_results`,
`ad_capacity_sync`, `ad_sched_import` (read-only, M2) and `ad_sched_relay`; `ad_app` is no longer created and its
database user is dropped (HB-28, MR-07). Azure configs carry placeholders only.
3. **Legacy write denial** (`db/security/040_single_writer.sql`, deliberate change to HB-01/HB-02/HB-29 paths): legacy
logins get `DENY INSERT/UPDATE/DELETE` on `dbo.Booking` and `dbo.Waitlist`, `DENY UPDATE` on
`ExamSession(Capacity, SeatsAvailable, AccommodationCapacity)` and `DENY EXECUTE` on `usp_BookSeat`,
`usp_CancelBooking`, `usp_ChangeCapacity` and `usp_RescheduleBooking`. A direct legacy write now fails with SQL
Server error 229/230; booking-api maps it to `403 LEGACY_WRITE_DENIED` (send writes through `:8000`).
4. **Transactional outbox** (`V2__outbox.sql`, `outbox_event`, `event_seq` identity = monotonic sequence): written in the
same transaction as `book`, `cancel`, `reschedule`, `recordAttendance` and `changeCapacity`. Event types
`BookingCreated`, `BookingWaitlisted`, `BookingCancelled`, `BookingRescheduled`, `AttendanceRecorded`,
`CapacityChanged`, plus `InventoryBaselined` written by a `mode=reset` snapshot import so the first relay pass
projects the derived seat counts. Each event carries the full resulting state of the touched bookings and
sessions (state transfer, not deltas), so applying it twice is harmless.
5. **Idempotent relay** (`com.northwind.scheduling.relay`, login `ad_sched_relay`, `SESSION_CONTEXT(N'writer') =
N'scheduling-relay'`): one legacy transaction per event upserts `Booking`, `Waitlist`, `ExamSession` and one
`AuditLog` row, then inserts the event id into `dbo.RelayCheckpoint`; an event already checkpointed is a no-op.
The outbox row is marked relayed afterwards, so a crash between the two only causes a no-op replay.
6. **Booking ids.** Modern booking ids are already disjoint from legacy ids (imported rows keep the legacy id, new rows
start at `routing.modern-booking-id-floor=50000000`), so the relay writes `dbo.Booking.BookingId = booking_id`
with `SET IDENTITY_INSERT` on first relay and stores it in `booking.legacy_booking_id`. `Result.BookingId`, v1 URLs
and results-service attendance keep working with the same number.
7. **Trigger neutralization for relayed writes only** (deliberate change, HB-01/HB-04 in `032_trg_Booking_SeatSync`,
HB-05/HB-16 in `033_trg_ExamSession_Update`, MR-01/MR-14): both triggers return early when the writer is
`scheduling-relay`; `trg_ExamSession_Update` still stamps `LastModified`. Any other writer still gets the legacy
side effects (characterized by `LegacySingleWriterIT`).
8. **Remaining legacy writers.** results-service calls `POST /api/v2/bookings/{bookingId}/attendance` instead of
`UPDATE dbo.Booking SET Status = 'ATTENDED'`; capacity-sync's `runSync` is disabled by `capacity.sync.enabled=false`
and only writes its `CAPACITY_SYNC` audit row with `SKIPPED` (HB-03, MR-17; deliberate change); booking-api keeps
its v1 contract behind the gateway, which already serves v1 for modern centres.
9. **Reconciliation replaces capacity-sync.** `GET /internal/reconciliation` and `java -jar scheduling-service.jar
reconcile` compare every session (Capacity, SeatsAvailable, BOOKED/ATTENDED/WAITLISTED counts, accommodation seats)
and every booking (session, status, accommodation code) and include `db/checks/seat-drift.sql`; the report is
written to `reports/reconciliation-<timestamp>.md`. Exit code 0 only with 0 mismatches and 0 drift rows. Attendance needs a service credential: header `X-Service-Token`, compared in constant time with `scheduling.attendance.service-token` (env `SCHEDULING_ATTENDANCE_SERVICE_TOKEN`). The comparison fails closed when the property is unset. results-service sends `scheduling.service-token`, and the gateway returns 404 for `/api/v2/bookings/*/attendance`. The other v2 writes stay open like the legacy no-auth model (MR-16), but attendance writes ATTENDED into legacy, so results integrity depends on it.

## Not changed

Other legacy oddities stay as documented (e.g. HB-30 destructive `db/apply.*`, HB-31 sessions never closed, HB-17
audit actor inconsistencies). The relay writes `AuditLog.Actor = scheduling-relay` for its own rows only.

## Consequences

- Legacy availability is now exactly `Capacity - (BOOKED + ATTENDED)` as decided by scheduling-service; seat drift
is 0 after mixed traffic (see `reports/`).
- Legacy readers lag by the relay delay (poll `scheduling.relay.poll-ms=250`; p95 well under 2 s locally).
- FU-3 of ADR 0002 (retire capacity-sync and `SeatsAvailable`) is now possible.
Loading
Loading