Skip to main content

Governors Overview

What Are Governors?​

Governors are functional modules that organize the Competition Factory's operations into logical domains of responsibility. Each governor provides a collection of related methods for working with tournament data - from generating draws and scheduling matchUps to querying results and publishing information.

Why Governors Exist​

The governor architecture provides:

Separation of Concerns: Related functionality grouped together (e.g., all scheduling methods in Schedule Governor)

Modular Imports: Import only the governors needed for specific use cases

Clear API Organization: Easy discovery of methods by functional area

Custom Engine Construction: Build engines with only required governors (Custom Engines)

Maintainability: Isolated functional areas simplify testing and updates

Governors vs Engines​

Governors are collections of methods organized by domain (scheduling, publishing, scoring, etc.).

Engines are stateful wrappers around governors that:

  • Manage tournament record state
  • Handle subscriptions and notifications
  • Provide middleware hooks
  • Execute governor methods against managed state
import { tournamentEngine } from 'tods-competition-factory';
import { scheduleGovernor, publishingGovernor } from 'tods-competition-factory';

// Engine approach (stateful, convenient)
tournamentEngine.setState(tournamentRecord);
tournamentEngine.scheduleMatchUps({ scheduleDate, matchUpIds });

// Governor approach (stateless, functional)
scheduleGovernor.scheduleMatchUps({
tournamentRecord,
scheduleDate,
matchUpIds,
});

Most applications use engines for convenience. Governors are used for custom engines or specialized processing.


Governor Categories​

The Competition Factory includes 16 governors organized into functional areas:

Tournament Operations​

Tournament Governor - Tournament-level operations

  • Create, modify, and delete tournaments
  • Tournament metadata and properties
  • Tournament-level extensions and time items
  • Tournament validation

Competition Governor - Multi-tournament operations

  • Work across multiple tournaments
  • Competition-wide participant management
  • Cross-tournament queries and reports
  • Aggregate statistics

Draw Management​

Generation Governor - Draw and structure generation

  • Create elimination, round robin, and compass draws
  • Generate playoff structures
  • Feed-in consolation structures
  • Automated structure configuration

Draws Governor - Draw manipulation and modification

  • Modify existing draw structures
  • Add/remove participants from draws
  • Position swaps and manual adjustments
  • Draw validation and integrity checks

Event Management​

Event Governor - Event lifecycle and draw definitions

  • Create and configure events
  • Add/remove draw definitions
  • Event extensions and display settings
  • Event deletion and archival

Entries Governor - Entry management

  • Add/remove event entries
  • Entry status management (direct acceptance, qualifier, wildcard)
  • Alternate and lucky loser handling
  • Entry validation

Participant Operations​

Participant Governor - Participant lifecycle

  • Add individual participants, pairs, teams
  • Modify participant information
  • Scale items (rankings, ratings, seeding)
  • Participant extensions and representatives

Rankings & Ratings​

Ranking Governor - Ranking points and aggregation

  • Compute tournament ranking points from ranking policies
  • Quality win bonus calculation
  • Multi-tournament ranking list generation
  • Persist ranking points to participant records
  • Per-participant point breakdowns
  • Composed into the Scale Engine

MatchUp Management​

MatchUp Governor - MatchUp operations

  • Advance participants through draws
  • Set matchUp outcomes and scores
  • MatchUp status management
  • Walkover, retirement, default handling

Score Governor - Score validation and manipulation

  • Parse and validate score strings
  • Generate score strings from score objects
  • Check set completion
  • Score analysis and statistics

MatchUp Format Governor - Format handling

  • Parse matchUp format codes
  • Stringify matchUp format objects
  • Validate format configurations
  • Format comparison and analysis

tieFormat Governor - Team matchUp format management

  • Define and modify tieFormat structures (collections, groups, win criteria)
  • Centralised storage and deduplication of tieFormats
  • Gender and category validation for collection definitions
  • tieFormat comparison and hierarchical resolution

Scheduling​

Schedule Governor - Scheduling operations

  • Manual schedule assignment (date, time, venue, court)
  • Automated scheduling (Garman formula, grid scheduling)
  • Bulk scheduling operations
  • Schedule clearing and modifications

Venue Governor - Venue and court management

  • Create and modify venues
  • Add/remove courts
  • Court availability and bookings
  • Venue extensions and metadata

Publishing & Queries​

Publishing Governor - Publish state management

  • Publish/unpublish events and draws
  • Publish order of play
  • Publish seeding and participants
  • Granular visibility control (stages, structures, rounds)

Query Governor - Data retrieval

  • Get tournament matchUps
  • Competition schedule queries
  • Event data for visualization
  • Participant queries with filtering

Report Governor - Reporting and analytics

  • Unified report API: getAvailableReports, generateReport, buildReportContext
  • 13 registered reports across 6 categories (Entries, Draws, MatchUps, Participants, Scheduling, Audit)
  • Consistent { reportId, columns, rows, summary } output shape for all reports
  • Entry status, draw structure, venue utilization, match results, competitiveness, participant results, seeding performance, team statistics

Configuration​

Policy Governor - Policy management

  • Attach policies to tournaments, events, draws
  • Remove policies
  • Policy validation
  • Policy inheritance

Testing & Utilities​

Mocks Governor - Test data generation

  • Generate complete tournament records
  • Create participants with realistic data
  • Generate matchUp outcomes
  • Modify existing tournaments for testing

Common Use Cases by Governor​

Create a Tournament​

Use: Tournament Governor + Generation Governor

// Create tournament
const tournament = tournamentEngine.newTournamentRecord({ ... });

// Add participants
tournamentEngine.addParticipants({ participants });

// Generate draw
tournamentEngine.generateDrawDefinition({
eventId,
drawSize: 32,
seedsCount: 8
});

Schedule MatchUps​

Use: Venue Governor + Schedule Governor

// Setup venues
tournamentEngine.addVenue({ venue });
tournamentEngine.addCourt({ venueId, court });

// Define availability
tournamentEngine.modifyCourt({
courtId,
modifications: { dateAvailability: [...] }
});

// Schedule
tournamentEngine.scheduleMatchUps({
scheduleDate: '2024-06-15',
matchUpIds
});

Record Scores and Advance Participants​

Use: MatchUp Governor + Score Governor

// Set outcome
tournamentEngine.setMatchUpStatus({
matchUpId,
drawId,
outcome: {
winningSide: 1,
score: {
sets: [
{ side1Score: 6, side2Score: 4, winningSide: 1 },
{ side1Score: 6, side2Score: 2, winningSide: 1 },
],
},
},
});

Publish Draws and Schedules​

Use: Publishing Governor

// Publish event
tournamentEngine.publishEvent({ eventId });

// Publish order of play
tournamentEngine.publishOrderOfPlay({
scheduledDates: ['2024-06-15'],
});

// Publish seeding
tournamentEngine.publishEventSeeding({ eventId });

Query Tournament Data​

Use: Query Governor

// Get event data for display
const { eventData } = tournamentEngine.getEventData({
eventId,
usePublishState: true,
});

// Get competition schedule
const { dateMatchUps } = tournamentEngine.competitionScheduleMatchUps({
usePublishState: true,
});

// Get all matchUps
const { matchUps } = tournamentEngine.allTournamentMatchUps();

Apply Policies​

Use: Policy Governor

import { policyConstants } from 'tods-competition-factory';

// Attach scheduling policy
tournamentEngine.attachPolicies({
policyType: policyConstants.POLICY_TYPE_SCHEDULING,
policyDefinition: { ... }
});

// Attach seeding policy
tournamentEngine.attachPolicies({
eventId,
policyType: policyConstants.POLICY_TYPE_SEEDING,
policyDefinition: { ... }
});

Governor Method Patterns​

Common Parameters​

Most governor methods accept:

Identifiers:

  • tournamentId - Tournament identifier
  • eventId - Event identifier
  • drawId - Draw definition identifier
  • matchUpId - MatchUp identifier
  • structureId - Structure identifier
  • participantId - Participant identifier

Flags:

  • inContext - Add contextual information to results
  • usePublishState - Filter by publish state
  • disableNotice - Suppress notifications
  • dryRun - Preview without making changes

Options:

  • policyDefinitions - Apply policy configurations
  • removePriorValues - Clear previous time items
  • returnParticipants - Include participant data in results

Return Value Patterns​

Governor methods typically return:

{
success: boolean, // Operation succeeded
info: string, // Informational messages
error: ErrorObject, // Error details if failed
...results // Method-specific data
}

Error Handling:

const result = tournamentEngine.someMethod({ ... });

if (result.error) {
console.error(result.error.message);
console.error(result.error.stack);
}

Notifications and Subscriptions​

Many governor methods trigger subscription notifications:

import { topicConstants } from 'tods-competition-factory';

tournamentEngine.devContext({
subscriptions: {
[topicConstants.PUBLISH_EVENT]: (payload) => {
// React to event publication
},
[topicConstants.MODIFY_MATCHUP]: (payload) => {
// React to matchUp changes
},
},
});

See: Subscriptions for complete topic list.


Importing Governors​

Import All Governors​

import { governors } from 'tods-competition-factory';

const {
competitionGovernor,
drawsGovernor,
entriesGovernor,
eventGovernor,
generationGovernor,
matchUpFormatGovernor,
matchUpGovernor,
mocksGovernor,
participantGovernor,
policyGovernor,
publishingGovernor,
queryGovernor,
reportGovernor,
scheduleGovernor,
scoreGovernor,
tieFormatGovernor,
tournamentGovernor,
venueGovernor,
} = governors;

Import Individual Governors​

import { scheduleGovernor, publishingGovernor, matchUpGovernor } from 'tods-competition-factory';

Use in Custom Engines​

import { governors, syncEngine } from 'tods-competition-factory';

// An engine imports the governors it needs; there is no separate engine factory.
syncEngine.importMethods(governors.tournamentGovernor);
syncEngine.importMethods(governors.matchUpGovernor);
syncEngine.importMethods(governors.scheduleGovernor);

syncEngine.setState(tournamentRecord);
syncEngine.scheduleMatchUps({/* ... */});

See: Custom Engines for detailed examples.


Governor Reference​

Competition Management​

GovernorPurposeKey Methods
Tournament GovernorTournament creation and managementnewTournamentRecord, setTournamentName, addTournamentExtension
Competition GovernorMulti-tournament operationsgetCompetitionParticipants, getCompetitionMatchUps
Event GovernorEvent lifecycleaddEvent, deleteDrawDefinitions, setEventDisplay
Entries GovernorEntry managementaddEventEntries, removeEventEntries, setEntryStatus

Draw Operations​

GovernorPurposeKey Methods
Generation GovernorDraw generationgenerateDrawDefinition, generateQualifyingDrawDefinition, generatePlayoffStructures
Draws GovernorDraw modificationmodifyDrawDefinition, addDrawDefinitionExtension, swapDrawPositions

Participant Management​

GovernorPurposeKey Methods
Participant GovernorParticipant operationsaddParticipants, modifyParticipant, setParticipantScaleItem

MatchUp Operations​

GovernorPurposeKey Methods
MatchUp GovernorMatchUp managementsetMatchUpStatus, setMatchUpScore, advanceParticipants
Score GovernorScore handlingparseScoreString, generateScoreString, checkSetIsComplete
MatchUp Format GovernorFormat handlingparseMatchUpFormat, stringifyMatchUpFormat
tieFormat GovernorTeam format managementmodifyTieFormat, aggregateTieFormats, addCollectionDefinition

Scheduling & Venues​

GovernorPurposeKey Methods
Schedule GovernorScheduling operationsscheduleMatchUps, scheduleProfileRounds, bulkScheduleTournamentMatchUps
Venue GovernorVenue managementaddVenue, addCourt, modifyCourt

Publishing & Query Reference​

GovernorPurposeKey Methods
Publishing GovernorPublish statepublishEvent, publishOrderOfPlay, publishEventSeeding
Query GovernorData retrievalgetEventData, competitionScheduleMatchUps, allTournamentMatchUps
Report GovernorReportingparticipationReport, drawReport, scheduleReport

Configuration Reference​

GovernorPurposeKey Methods
Policy GovernorPolicy managementattachPolicy, removePolicy, getAppliedPolicies

Testing​

GovernorPurposeKey Methods
Mocks GovernorTest data generationgenerateTournamentRecord, generateOutcomes, modifyTournamentRecord

Best Practices​

Use Engines for Application Code​

Engines provide state management and subscriptions. Use them unless you need fine-grained control:

// ✓ GOOD - Use engine for application code
import { tournamentEngine } from 'tods-competition-factory';

tournamentEngine.setState(tournamentRecord);
tournamentEngine.publishEvent({ eventId });

Use Governors for Custom Processing​

Use governors directly when building custom engines or specialized processors:

// ✓ GOOD - Use governors for custom processing
import { publishingGovernor, queryGovernor } from 'tods-competition-factory';

function customPublisher(tournamentRecord, eventId) {
const { eventData } = queryGovernor.getEventData({
tournamentRecord,
eventId,
});

return publishingGovernor.publishEvent({
tournamentRecord,
eventId,
customParam: 'value',
});
}

Check Return Values​

Always check for errors:

const result = tournamentEngine.setMatchUpStatus({ ... });

if (result.error) {
console.error('Failed:', result.error.message);
return;
}

// Proceed with success case
console.log('Success:', result.matchUp);

Use Subscriptions for Side Effects​

React to changes via subscriptions rather than polling:

tournamentEngine.devContext({
subscriptions: {
[topicConstants.MODIFY_MATCHUP]: (payload) => {
// Update UI, sync to database, etc.
updateDisplay(payload.matchUp);
},
},
});