lib/Classes/Public/TMBroker.ps1

class TMBroker {

    #region Non-Static Properties

    [TMBrokerSetting]$Settings = [TMBrokerSetting]::new()
    [TMTask]$Task = [TMTask]::new()
    [TMBrokerSubject]$Init
    [TMSession]$TMSession = [TMSession]::new()
    [TMBrokerEventData]$EventData = [TMBrokerEventData]::new()
    [TMBrokerStatus]$Status = [TMBrokerStatus]::new()
    [Object]$Cache
    [Collections.Generic.List[TMBrokerSubject]]$Subjects = [Collections.Generic.List[TMBrokerSubject]]::new()

    #endregion Non-Static Properties

    #region Constructors

    TMBroker() {}

    TMBroker([String]$type, [String]$taskProperty, [String[]]$matchingCriteria) {
        $this.Settings = [TMBrokerSetting]::new($type, $taskProperty, $matchingCriteria)
    }

    TMBroker([String]$type, [ScriptBlock]$matchExpression) {
        $this.Settings = [TMBrokerSetting]::new($type, $matchExpression)
    }

    TMBroker([String]$type, [TMBrokerTaskFilter]$taskFilter) {
        $this.Settings = [TMBrokerSetting]::new($type, $taskFilter)
    }

    TMBroker(
        [String]$type,
        [String]$taskProperty,
        [String[]]$matchingCriteria,
        [Int32]$timeout,
        [Int32]$pauseSeconds
    ) {
        $this.Settings = [TMBrokerSetting]::new($type, $taskProperty, $matchingCriteria, $timeout, $pauseSeconds)
        $this.Status = [TMBrokerStatus]::new($timeout)
    }

    TMBroker(
        [String]$type,
        [ScriptBlock]$matchExpression,
        [Int32]$timeout,
        [Int32]$pauseSeconds
    ) {
        $this.Settings = [TMBrokerSetting]::new($type, $matchExpression, $timeout, $pauseSeconds)
        $this.Status = [TMBrokerStatus]::new($timeout)
    }

    TMBroker(
        [String]$type,
        [TMBrokerTaskFilter]$taskFilter,
        [Int32]$timeout,
        [Int32]$pauseSeconds
    ) {
        $this.Settings = [TMBrokerSetting]::new($type, $taskFilter, $timeout, $pauseSeconds)
        $this.Status = [TMBrokerStatus]::new($timeout)
    }

    TMBroker(
        [String]$type,
        [String]$taskProperty,
        [String[]]$matchingCriteria,
        [Int32]$timeout,
        [Int32]$pauseSeconds,
        [Boolean]$parallel,
        [Int32]$throttle
    ) {
        $this.Settings = [TMBrokerSetting]::new($type, $taskProperty, $matchingCriteria, $timeout, $pauseSeconds, $parallel, $throttle)
        $this.Status = [TMBrokerStatus]::new($timeout, $throttle)
    }

    TMBroker(
        [String]$type,
        [ScriptBlock]$matchExpression,
        [Int32]$timeout,
        [Int32]$pauseSeconds,
        [Boolean]$parallel,
        [Int32]$throttle
    ) {
        $this.Settings = [TMBrokerSetting]::new($type, $matchExpression, $timeout, $pauseSeconds, $parallel, $throttle)
        $this.Status = [TMBrokerStatus]::new($timeout, $throttle)
    }

    TMBroker(
        [String]$type,
        [TMBrokerTaskFilter]$taskFilter,
        [Int32]$timeout,
        [Int32]$pauseSeconds,
        [Boolean]$parallel,
        [Int32]$throttle
    ) {
        $this.Settings = [TMBrokerSetting]::new($type, $taskFilter, $timeout, $pauseSeconds, $parallel, $throttle)
        $this.Status = [TMBrokerStatus]::new($timeout, $throttle)
    }

    #endregion Constructors

    #region Non-Static Methods

    <#
        Method: GetEventData
        Description: Loads the EventData property using this object's TMSession
        Parameters: None
    #>

    [void]GetEventData() {
        if (-not $this.TMSession) {
            throw 'A TM Session is required to invoke this method'
        }

        if ($this.Settings.SubjectScope.FilterType -eq 'TaskFilter') {
            $this.EventData.GetEventData(
                $this.TMSession.UserContext.project.id,
                $this.TMSession.UserContext.event.name,
                $this.TMSession.Name,
                $this.Settings.SubjectScope.TaskFilter
            )
        } else {
            $this.EventData.GetEventData(
                $this.TMSession.UserContext.project.id,
                $this.TMSession.UserContext.event.name,
                $this.TMSession.Name
            )
        }
    }

    <#
        Method: GetTaskData
        Description: Loads all of the broker-related tasks
        Parameters:
            TaskId - The Id of broker task
    #>

    [void]GetTaskData($TaskId) {
        if (-not $this.EventData) {
            throw 'Event data must be loaded before invoking this method'
        }

        # Store this Broker Task's data
        $this.Task = ($this.EventData.Tasks | Where-Object { $_.Id -eq $TaskId })

        if (-not $this.Task) {
            $this.Task = Get-TMTask -Id $TaskId -TMSession $this.TMSession.Name
        }

        # Determine if there is an init cache Task
        $this.GetInitTask()

        # Get all of the subject tasks
        $this.GetSubjectTasks()
    }

    <#
        Method: GetInitTask
        Description: Gets the init task, if present, from the Event's task data
        Parameters: None
    #>

    [void]GetInitTask() {
        if ($this.Settings.SubjectScope.Type -eq 'Inline') {
            if (-not $this.Task) {
                throw 'Broker Task data must be loaded before invoking this method'
            }
            $InitTask = (
                $this.EventData.Tasks |
                    Where-Object { $_.Id -in $this.Task.Successors.TaskId } |
                        Where-Object -FilterScript $this.Settings.SubjectScope.MatchExpression
            )
            if ($InitTask) {
                $this.Init = [TMBrokerSubject]::new($InitTask)
            }
        }
    }

    <#
        Method: GetSubjectTasks
        Description: Gets all of the subject tasks that will be managed by the broker from the Event's task data
        Parameters: None
    #>

    [void]GetSubjectTasks() {
        switch ($this.Settings.SubjectScope.Type) {
            'Inline' {
                if (-not $this.Task -and -not $this.Init) {
                    throw 'Broker Task and Init Task data must be loaded before invoking this method'
                }

                # Initialize the subjects list
                $this.Subjects = [Collections.Generic.List[Collections.Generic.List[TMBrokerSubject]]]::new()

                foreach ($TaskId in ($this.Init.Task.Successors.TaskId ?? $this.Task.Successors.TaskId)) {

                    # Initialize a list to hold all of the subject tasks for a specific asset
                    $Workflow = [Collections.Generic.List[TMBrokerSubject]]::new()

                    # Find the first/direct successor subject task
                    $SubjectTask = $this.EventData.Tasks | Where-Object { $_.Id -eq $TaskId }

                    $i = 0
                    while ($SubjectTask) {
                        $i++

                        # Add the subject task data to the workflow
                        $Workflow.Add([TMBrokerSubject]::new($SubjectTask, $i))

                        # Look for the next subject task in the workflow
                        $SubjectTask = $this.EventData.Tasks | Where-Object { $_.Id -eq $SubjectTask.Successors.TaskId }
                    }

                    # Record how many tasks are in each asset's workflow
                    $this.Status.WorkflowTaskCount = $i

                    # Add this workflow to the list of subjects
                    $this.Subjects.Add($Workflow)
                }
            }

            'Service' {
                # Initialize the subjects list
                $this.Subjects = [Collections.Generic.List[TMBrokerSubject]]::new()

                # Filter all Tasks down to the specified scope
                $ServiceSubjectTasks = $this.EventData.Tasks | Where-Object {
                    ($_.id -ne $Broker.task.id ) -and
                    ($_.Action.Id -ne 0) -and
                    ($_.Action.name -notlike '*broker*') -and
                    -not ($_.Action.MethodParams | Where-Object { $_.ParamName -match 'get_' })
                }

                # Apply the match expression to filter tasks further
                if ($this.Settings.SubjectScope.FilterType -eq 'MatchExpression') {
                    $ServiceSubjectTasks = $ServiceSubjectTasks | Where-Object -FilterScript $this.Settings.SubjectScope.MatchExpression
                }

                foreach ($Task in $ServiceSubjectTasks) {
                    $this.Subjects.Add([TMBrokerSubject]::new($Task))
                }
            }

            default { }
        }
    }

    <#
        Method: PopulateCache
        Description: Invokes the Init Task's Action to fill the cache
        Parameters: None
    #>

    [void]PopulateCache() {
        if (-not $this.Init) {
            throw 'Init Task data must be loaded before invoking this method'
        }

        $this.Init.Invoke($this.TMSession.Name)
    }

    <#
        Method: RefreshTaskData
        Description: Updates each Task's status and Action settings using fresh data from TM
        Parameters: None
    #>

    [void]RefreshTaskData() {
        $TaskIds = [Array]@(
            $this.Subjects.Task.Id
            $this.Task.Id
            $this.Init.Task.Id
        ) | Where-Object { $_ -gt 0 }

        $Statement = "find Task by 'id' inList([$($TaskIds -join ', ')]) fetch 'id', 'status', 'lastUpdated', 'apiAction.methodParams'"
        $TaskData = Invoke-TMQLStatement -TMSession $this.TMSession.Name -Statement $Statement

        $this.Task.Status = ($TaskData | Where-Object Id -eq $this.Task.Id).Status
        if ($this.Init.Task.Id) {
            $this.Init.Task.Status = ($TaskData | Where-Object Id -eq $this.Init.Id).Status
        }

        switch ($this.Settings.SubjectScope.Type) {
            'Inline' {
                foreach ($Workflow in $this.Subjects) {
                    foreach ($Subject in $Workflow) {
                        $Subject.Task.Status = ($TaskData | Where-Object Id -eq $Subject.Task.Id).Status
                    }
                }
            }

            'Service' {
                foreach ($Subject in $this.Subjects) {
                    $TaskFromTM = $TaskData | Where-Object Id -eq $Subject.Task.Id
                    $Subject.Task.Status = $TaskFromTM.Status
                    $Subject.Task.LastUpdated = $TaskFromTM.LastUpdated
                    $Subject.UpdateActionSettings($TaskFromTM.'apiAction.methodParams')

                    # Review Task states to update throttling settings
                    if ($this.Settings.Parallel) {

                        ## Handle updating Subject Task data based on the status of the task
                        switch ($Subject.Task.Status) {
                            'Started' {
                                ## Mark the Action as Started so the Broker ignores it for next time
                                $Subject.Action.ExecutionStatus = 'Started'

                                if ($Subject.Action.ShouldTimeout) {
                                    try {
                                        Write-Host "[$(Get-Date -Format "HH:mm:ss.ffff")] Resetting Task #: $($Subject.Task.TaskNumber). Task has run longer than: $($Subject.Action.Settings.Timeout.Minutes) minutes" -ForegroundColor DarkYellow
                                        $Subject.Timeout($this.TMSession.Name)
                                    } catch {
                                        Write-Host "[$(Get-Date -Format "HH:mm:ss.ffff")] Could not timeout Task # $($Subject.Task.TaskNumber): $($_.Exception.Message)" -ForegroundColor Magenta
                                    }
                                }
                            }
                            'Completed' {
                                ## Check to ensure the broker does not believe it's running completed Tasks
                                if ($this.Status.ActiveSubjects -contains $Subject.Task.Id) {
                                    $this.Status.ActiveSubjects.Remove($Subject.Task.Id)
                                }
                                $Subject.Action.ExecutionStatus = 'Successful'
                            }

                            'Hold' {
                                ## If the Task's status was changed either manually or due to failure,
                                ## reset the execution status so that it can be re-run
                                if ($this.Status.ActiveSubjects -contains $Subject.Task.Id) {
                                    $this.Status.ActiveSubjects.Remove($Subject.Task.Id)
                                }
                                $Subject.Action.ExecutionStatus = 'Failed'

                                # Check if a retry was defined in the Action params
                                if ($Subject.Action.ShouldRetry) {
                                    # Attempt to reset the Task Action and Reset the Task to Ready
                                    try {
                                        Write-Host "[$(Get-Date -Format "HH:mm:ss.ffff")] Resetting Task #: $($Subject.Task.TaskNumber). Retries left: $($Subject.Action.Settings.Retry.RemainingRetries)" -ForegroundColor DarkYellow
                                        $Subject.QueueRetry($this.TMSession.Name)
                                        $this.Status.LastWebRequest = Get-Date
                                    } catch {
                                        Write-Host "[$(Get-Date -Format "HH:mm:ss.ffff")] Could not retry Task # $($Subject.Task.TaskNumber): $($_.Exception.Message)" -ForegroundColor Magenta
                                    }
                                }
                            }

                            { $_ -in 'Pending', 'Ready' } {
                                ## If the Task's status was changed either manually or due to failure,
                                ## reset the execution status so that it can be re-run
                                if ($this.Status.ActiveSubjects -contains $Subject.Task.Id) {
                                    $this.Status.ActiveSubjects.Remove($Subject.Task.Id)
                                }
                                $Subject.Action.ExecutionStatus = 'Pending'
                            }
                        }
                    }
                }
            }
        }
    }

    <#
        Method: RefreshBrokerProgress
        Description: Updates the TMBrokerProgress properties on this Status object to be used for tracking and progress bars
        Parameters: None
    #>

    [void]RefreshBrokerProgress() {
        $this.Status.CompletedTasks.Value = ($this.Subjects | Where-Object { $_.Task.Status -eq 'Completed' -and $_.Action.ExecutionStatus -eq 'Successful' }).Count
        $this.Status.ElapsedMinutes.Value = [Math]::Ceiling($this.Settings.Timing.Timer.Elapsed.TotalMinutes)
        if ($this.Settings.Parallel) {
            $this.Status.Throttle.Value = $this.Status.ActiveSubjects.Count
        }
    }

    <#
        Method: KeepAlive
        Description: Sends a lightweight request to TM to keep the web services session alive
        Parameters: None
    #>

    [void]KeepAlive() {
        if (((Get-Date) - $this.Status.LastWebRequest).TotalMinutes -gt 10) {
            try {
                $RestSplat = @{
                    Uri = "https://$($this.TMSession.TMServer)/tdstm/ws/progress/demo"
                    Method = 'GET'
                    WebSession = $this.TMSession.TMWebSession
                    SkipCertificateCheck = $this.TMSession.AllowInsecureSSL
                }
                $Response = Invoke-WebRequest @RestSplat

                if ($Response.StatusCode -notin 200, 204) {
                    throw "The status code $($Response.StatusCode) does not indicate success"
                }
            } catch {
                Write-Host "[$(Get-Date -Format "HH:mm:ss.ffff")] Keep alive request failed: $($_.Exception.Message)" -ForegroundColor DarkYellow
            }

            $this.Status.LastWebRequest = Get-Date
        }
    }

    <#
        Method: Run
        Description: Executes the scoped subject Tasks
        Parameters: None
    #>

    [void]Run() {

        $this.Status.CompletedTasks.MaxValue = $this.Subjects.Count
        $this.Settings.Timing.Timer.Start()
        $this.RefreshTaskData()

        while (
            ($this.Settings.Timing.Timer.Elapsed.TotalMinutes -lt $this.Settings.Timing.TimeoutMinutes) -and
            ($this.Subjects | Where-Object { $_.Action.ExecutionStatus -eq 'Pending' })
        ) {

            ## Force a refresh after a few tasks have been executed
            if ($this.Status.TasksExecutedSinceRefresh -ge 3) {
                $this.RefreshTaskData()
                $this.Status.TasksExecutedSinceRefresh = 0
            }

            ## Saftey Check the broker task status in TM, exit if the task status is not Started
            if ($this.Task.Status -ne 'Started') {
                throw 'The status of the Broker Task has changed outside of TMConsole'
            }

            # Refresh the progress properties to be output to the TMC UI
            $this.RefreshBrokerProgress()

            # If needed, make a small request to TM to keep the session alive
            $this.KeepAlive()

            $ProgressSplat = @{
                Id              = 1
                ParentId        = 0
                Activity        = 'Subject Tasks'
                Status          = "$($this.Status.CompletedTasks.Value) of $($this.Status.CompletedTasks.MaxValue) tasks completed"
                PercentComplete = $this.Status.CompletedTasks.PercentComplete
            }
            Write-Progress @ProgressSplat

            $ProgressSplat = @{
                Id              = 2
                ParentId        = 0
                Activity        = 'Timeout'
                Status          = "$([Math]::Ceiling($this.Settings.Timing.TimeoutMinutes - $this.Settings.Timing.Timer.Elapsed.TotalMinutes)) minutes left"
                PercentComplete = $this.Status.ElapsedMinutes.PercentComplete
            }
            Write-Progress @ProgressSplat

            if ($this.Settings.Parallel) {
                $ProgressSplat = @{
                    Id              = 3
                    ParentId        = 0
                    Activity        = 'Throttle'
                    Status          = "$($this.Status.ActiveSubjects.Count) of $($this.Settings.Throttle)"
                    PercentComplete = $this.Status.Throttle.PercentComplete
                }
                Write-Progress @ProgressSplat
            }

            # Execute Subject Tasks
            switch ($this.Settings.SubjectScope.Type) {

                ## Inline Brokers run a workflow step worth of tasks at once
                'Inline' {
                    foreach ($Workflow in $this.Subjects) {
                        $Subject = $Workflow | Where-Object { $_.Task.Status -ne 'Completed' -and $_.Action.ExecutionStatus -eq 'Pending' } |
                            Sort-Object Order | Select-Object -First 1

                        if ($Subject) {
                            $Subject.Invoke($this.TMSession.Name, $this.Cache)
                            $this.Status.TasksExecutedSinceRefresh++
                        }
                    }
                }

                ## Service Brokers run one task at a time, when they become ready
                'Service' {

                    ## Get the most preferred actionable subject
                    $PreferredActionableSubject = $this.Subjects |
                        Where-Object { $_.Task.Status -eq 'Ready' -and $_.Action.ExecutionStatus -eq 'Pending' } |
                            Sort-Object { $_.Task."$($this.Settings.ExecutionOrder)" } -Descending:$($this.Settings.ExecutionSortOrder -eq 'Descending') |
                                Select-Object -First 1


                    ## Invoke the Most Preferred, Actionable Subject
                    if ($PreferredActionableSubject) {

                        ## Update the local cache so this task won't run again until another refresh from TM
                        $PreferredActionableSubject.Task.Status = 'Started'

                        ## Run a Subject in a normal invocation runspace, but track that task so it 'consumes' one runspace
                        if ($this.Settings.Parallel) {

                            ## Honor Throttling settings
                            if ($this.Status.ActiveSubjects.Count -lt $this.Settings.Throttle) {

                                ## Record the Task ID as belonging to this broker for Throttling
                                $this.Status.ActiveSubjects.Add($PreferredActionableSubject.Task.Id)
                                Write-Verbose "Invoking Task $($PreferredActionableSubject.Task.Id)"
                                $PreferredActionableSubject.InvokeParallel($this.TMSession.Name, $this.Cache)
                                $this.Status.TasksExecutedSinceRefresh++
                                $this.Status.LastWebRequest = Get-Date
                            }
                        } else {

                            ## Invoke this ActionRequest directly, in this runspace
                            $PreferredActionableSubject.Invoke($this.TMSession.Name, $this.Cache)
                            $this.Status.TasksExecutedSinceRefresh++
                            $this.Status.LastWebRequest = Get-Date
                        }
                    }
                }
            }

            ## Sleep, unless there are more tasks ready
            if ($this.Subjects.Task.Status -notcontains 'Ready') {
                Start-Sleep -Seconds $this.Settings.Timing.PauseSeconds

                ## Refresh the Task statuses and ping TM if needed
                $this.RefreshTaskData()
                $this.Status.TasksExecutedSinceRefresh = 0
            }
        }
    }

    #endregion Non-Static Methods

}


class TMBrokerEventData {

    #region Non-Static Properties

    [TMEvent]$Event = [TMEvent]::new()
    [TMTask[]]$Tasks = [System.Collections.Generic.List[TMTask]]::new()

    #endregion Non-Static Properties

    #region Constructors

    TMBrokerEventData() {}

    TMBrokerEventData([Int32]$projectId, [String]$eventName, [String]$tmSession) {
        $this.GetEventData($projectId, $eventName, $tmSession)
    }

    [void]GetEventData([Int32]$projectId, [String]$eventName, [String]$tmSession) {

        # Get the Event object
        $this.Event = Get-TMEvent -TMSession $tmSession -ProjectId $projectId -Name $eventName

        # Get all of the broker-related Tasks in the Event
        $this.Tasks = Get-TMTask -TMSession $tmSession -ProjectId $projectId -EventName $eventName
    }

    [void]GetEventData([Int32]$projectId, [String]$eventName, [String]$tmSession, [TMBrokerTaskFilter]$Filter) {

        # Get the Event object
        $this.Event = Get-TMEvent -TMSession $tmSession -ProjectId $projectId -Name $eventName

        # Get all of the broker-related Tasks in the Event
        $TaskSplat = $Filter.ToHashTable()
        $this.Tasks = Get-TMTask -TMSession $tmSession -ProjectId $projectId -EventName $eventName @TaskSplat
    }

    #endregion Constructors

}


class TMBrokerSubjectScope {

    #region Non-Static Properties

    [ValidateSet('Service', 'Inline')]
    [String]$Type = 'Service'

    [ValidateSet('ActionName', 'AssetClass', 'AssetName', 'AssetType', 'Category', 'Status', 'TaskNumber', 'TaskSpecId', 'Team', 'Title')]
    [String]$TaskProperty = 'Title'

    [String[]]$MatchingCriteria

    [ScriptBlock]$MatchExpression

    [ValidateSet('TaskFilter', 'MatchExpression')]
    [String]$FilterType = 'TaskFilter'

    [TMBrokerTaskFilter]$TaskFilter = [TMBrokerTaskFilter]::new()

    #endregion Non-Static Properties

    #region Static Properties

    static $ValidTypes = @('Service', 'Inline')
    static $ValidTaskProperties = @('ActionName', 'AssetClass', 'AssetName', 'AssetType', 'Category', 'Status', 'TaskNumber', 'TaskSpecId', 'Team', 'Title')

    #endregion Static Properties

    #region Constructors

    TMBrokerSubjectScope() {
        $this.TaskFilter.Title.Add('\[Subject\]')
    }

    TMBrokerSubjectScope([String]$type, [String]$taskProperty, [String[]]$matchingCriteria) {
        $this.Type = $type
        $this.TaskProperty = $taskProperty
        $this.MatchingCriteria = $matchingCriteria
        $matchingCriteria | ForEach-Object {
            $this.TaskFilter."$taskProperty".Add($_)
        }
    }

    TMBrokerSubjectScope([String]$type, [ScriptBlock]$matchExpression) {
        $this.Type = $type
        $this.MatchExpression = $matchExpression
        $this.FilterType = 'MatchExpression'
    }

    TMBrokerSubjectScope([String]$type, [TMBrokerTaskFilter]$taskFilter) {
        $this.Type = $type
        $this.TaskFilter = $taskFilter
    }

    #endregion Constructors

    #region Non-Static Methods

    hidden [void]GetMatchExpression() {
        $this.MatchExpression = [ScriptBlock]::Create("`$_.$($this.TaskProperty) -match '$([TMBrokerSubjectScope]::GetMatchString($this.MatchingCriteria))'")
    }

    #endregion Non-Static Methods

    #region Static Methods

    static [String]GetMatchString([String[]]$criteria) {
        return ('(' + ($criteria -join ')|(') + ')')
    }

    #endregion Static Methods

}


class TMBrokerSetting {

    #region Non-Static Properties

    [TMBrokerSubjectScope]$SubjectScope = [TMBrokerSubjectScope]::new()
    [TMBrokerTiming]$Timing  = [TMBrokerTiming]::new()
    [ValidateSet('TaskNumber', 'Score', 'TaskSpecId')]
    [String]$ExecutionOrder = 'Score'
    [ValidateSet('Ascending', 'Descending')]
    [String]$ExecutionSortOrder = 'Descending'
    [Boolean]$Parallel = $false
    [Int32]$Throttle = 8

    #endregion Non-Static Properties

    #region Constructors

    TMBrokerSetting() {}

    TMBrokerSetting(
        [String]$type,
        [String]$taskProperty,
        [String[]]$matchingCriteria,
        [Int32]$timeout,
        [Int32]$pauseSeconds
    ) {
        $this.SubjectScope = [TMBrokerSubjectScope]::new($type, $taskProperty, $matchingCriteria)
        $this.Timing = [TMBrokerTiming]::new($timeout, $pauseSeconds)
    }

    TMBrokerSetting(
        [String]$type,
        [ScriptBlock]$matchExpression,
        [Int32]$timeout,
        [Int32]$pauseSeconds
    ) {
        $this.SubjectScope = [TMBrokerSubjectScope]::new($type, $matchExpression)
        $this.Timing = [TMBrokerTiming]::new($timeout, $pauseSeconds)
    }

    TMBrokerSetting(
        [String]$type,
        [TMBrokerTaskFilter]$taskFilter,
        [Int32]$timeout,
        [Int32]$pauseSeconds
    ) {
        $this.SubjectScope = [TMBrokerSubjectScope]::new($type, $taskFilter)
        $this.Timing = [TMBrokerTiming]::new($timeout, $pauseSeconds)
    }

    TMBrokerSetting(
        [String]$type,
        [String]$taskProperty,
        [String[]]$matchingCriteria,
        [Int32]$timeout,
        [Int32]$pauseSeconds,
        [Boolean]$parallel,
        [Int32]$throttle
    ) {
        $this.SubjectScope = [TMBrokerSubjectScope]::new($type, $taskProperty, $matchingCriteria)
        $this.Timing = [TMBrokerTiming]::new($timeout, $pauseSeconds)
        $this.Parallel = $parallel
        $this.Throttle = $throttle
    }

    TMBrokerSetting(
        [String]$type,
        [ScriptBlock]$matchExpression,
        [Int32]$timeout,
        [Int32]$pauseSeconds,
        [Boolean]$parallel,
        [Int32]$throttle
    ) {
        $this.SubjectScope = [TMBrokerSubjectScope]::new($type, $matchExpression)
        $this.Timing = [TMBrokerTiming]::new($timeout, $pauseSeconds)
        $this.Parallel = $parallel
        $this.Throttle = $throttle
    }

    TMBrokerSetting(
        [String]$type,
        [TMBrokerTaskFilter]$taskFilter,
        [Int32]$timeout,
        [Int32]$pauseSeconds,
        [Boolean]$parallel,
        [Int32]$throttle
    ) {
        $this.SubjectScope = [TMBrokerSubjectScope]::new($type, $taskFilter)
        $this.Timing = [TMBrokerTiming]::new($timeout, $pauseSeconds)
        $this.Parallel = $parallel
        $this.Throttle = $throttle
    }

    TMBrokerSetting([String]$type, [String]$taskProperty, [String[]]$matchingCriteria) {
        $this.SubjectScope = [TMBrokerSubjectScope]::new($type, $taskProperty, $matchingCriteria)
    }

    TMBrokerSetting([String]$type, [ScriptBlock]$matchExpression) {
        $this.SubjectScope = [TMBrokerSubjectScope]::new($type, $matchExpression)
    }

    TMBrokerSetting([String]$type, [TMBrokerTaskFilter]$taskFilter) {
        $this.SubjectScope = [TMBrokerSubjectScope]::new($type, $taskFilter)
    }

    #endregion Constructors

}


class TMBrokerTiming {

    #region Non-Static Properties

    [Int64]$TimeoutMinutes = 120
    [Int64]$PauseSeconds = 15
    [Diagnostics.Stopwatch]$Timer = [Diagnostics.Stopwatch]::new()

    #endregion Non-Static Properties

    #region Constructors

    TMBrokerTiming () {}

    TMBrokerTiming ([Int64]$timeoutMinutes, [Int64]$pauseSeconds) {
        $this.TimeoutMinutes = $timeoutMinutes
        $this.PauseSeconds = $pauseSeconds
    }

    #endregion Constructors

}


class TMBrokerStatus {

    #region Non-Static Properties

    [Collections.Generic.List[Int64]]$ActiveSubjects = [Collections.Generic.List[Int64]]::new()
    [Int64]$WorkflowTaskCount = 0
    [Int64]$TasksExecutedSinceRefresh = 0
    [DateTime]$LastWebRequest = (Get-Date).AddMinutes(10)
    [TMBrokerProgress]$CompletedTasks = [TMBrokerProgress]::new()
    [TMBrokerProgress]$ElapsedMinutes = [TMBrokerProgress]::new()
    [TMBrokerProgress]$Throttle = [TMBrokerProgress]::new()

    #endregion Non-Static Properties

    #region Constructors

    TMBrokerStatus () {}

    TMBrokerStatus ([Int32]$timeoutMinutes) {
        $this.ElapsedMinutes = [TMBrokerProgress]::new($timeoutMinutes)
    }

    TMBrokerStatus ([Int32]$timeoutMinutes, [Int32]$throttle) {
        $this.ElapsedMinutes = [TMBrokerProgress]::new($timeoutMinutes)
        $this.Throttle = [TMBrokerProgress]::new($throttle)
    }

    #endregion Constructors

}


class TMBrokerProgress {

    #region Non-Static Properties

    [Int32]$PercentComplete = 0

    #endregion Non-Static Properties

    #region Private Fields

    hidden [Int32]$_currentValue = 0
    hidden [Int32]$_maxValue = 1

    #endregion Private Fields

    #region Constructors

    TMBrokerProgress() {
        $this.addPublicMembers()
        $this.CalculatePercentComplete()
    }

    TMBrokerProgress([Int32]$maxValue) {
        $this.addPublicMembers()
        $this.MaxValue = $maxValue
    }

    TMBrokerProgress([Int32]$currentValue, [Int32]$maxValue) {
        $this.addPublicMembers()
        $this.Value = $currentValue
        $this.MaxValue = $maxValue
    }

    #endregion Constructors

    #region Non-Static Methods

    [void]CalculatePercentComplete() {
        $this.PercentComplete = [Int32][Math]::Ceiling(($this._currentValue / $this._maxValue) * 100)
    }

    #endregion Non-Static Methods

    #region Private Methods

    hidden [void]addPublicMembers() {
        $this.PSObject.Properties.Add(
            [PSScriptProperty]::new(
                'MaxValue',
                { # get
                    return $this._maxValue
                },
                { # set
                    param ($value)

                    $this._maxValue = $value
                    $this.CalculatePercentComplete()
                }
            )
        )

        $this.PSObject.Properties.Add(
            [PSScriptProperty]::new(
                'Value',
                { # get
                    return $this._currentValue
                },
                { # set
                    param ($value)

                    $this._currentValue = $value
                    $this.CalculatePercentComplete()
                }
            )
        )
    }

    #endregion Private Methods

}


class TMBrokerTaskFilter {

    #region Non-Static Properties

    [Collections.Generic.List[Int32]]$TaskNumber = [Collections.Generic.List[Int32]]::new()
    [Collections.Generic.List[Int32]]$TaskSpecId = [Collections.Generic.List[Int32]]::new()
    [Collections.Generic.List[String]]$Status = [Collections.Generic.List[String]]::new()
    [Collections.Generic.List[String]]$AssetName = [Collections.Generic.List[String]]::new()
    [Collections.Generic.List[String]]$AssetType = [Collections.Generic.List[String]]::new()
    [Collections.Generic.List[String]]$AssetClass = [Collections.Generic.List[String]]::new()
    [Collections.Generic.List[String]]$ActionName = [Collections.Generic.List[String]]::new()
    [Collections.Generic.List[String]]$Category = [Collections.Generic.List[String]]::new()
    [Collections.Generic.List[String]]$Title = [Collections.Generic.List[String]]::new()
    [Collections.Generic.List[String]]$Team = [Collections.Generic.List[String]]::new()

    #endregion Non-Static Properties

    #region Constructors

    TMBrokerTaskFilter() {}

    #endregion Constructors

    #region Non-Static Methods

    [Hashtable]ToHashTable() {
        $returnHashtable = @{}

        if ($this.TaskNumber) { $returnHashtable.TaskNumber = $this.TaskNumber }
        if ($this.TaskSpecId) { $returnHashtable.TaskSpecId = $this.TaskSpecId }
        if ($this.Status) { $returnHashtable.Status = $this.Status }
        if ($this.AssetName) { $returnHashtable.AssetName = $this.AssetName }
        if ($this.AssetType) { $returnHashtable.AssetType = $this.AssetType }
        if ($this.AssetClass) { $returnHashtable.AssetClass = $this.AssetClass }
        if ($this.ActionName) { $returnHashtable.ActionName = $this.ActionName }
        if ($this.Category) { $returnHashtable.Category = $this.Category }
        if ($this.Title) { $returnHashtable.Title = $this.Title }
        if ($this.Team) { $returnHashtable.Team = $this.Team }

        return $returnHashtable
    }

    [String]ToString() {
        return "{$($this.ToHashTable().Keys -join ', ')}"
    }

    #endregion Non-Static Methods

}