├── .gitignore ├── CMakeLists.txt ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── SECURITY.md ├── buildsystem ├── templates │ ├── linux.yml │ └── windows.yml └── toolchains │ ├── aarch64-linux-gnu.cmake │ ├── arm-linux-gnueabi.cmake │ └── arm-linux-gnueabihf.cmake ├── cmake └── AccessorFrameworkConfig.cmake.in ├── include └── AccessorFramework │ ├── Accessor.h │ ├── Event.h │ └── Host.h ├── pipeline.yml ├── src ├── Accessor.cpp ├── AccessorImpl.cpp ├── AccessorImpl.h ├── AtomicAccessorImpl.cpp ├── AtomicAccessorImpl.h ├── BaseObject.h ├── CancellationToken.h ├── CompositeAccessorImpl.cpp ├── CompositeAccessorImpl.h ├── Director.cpp ├── Director.h ├── Host.cpp ├── HostHypervisorImpl.cpp ├── HostHypervisorImpl.h ├── HostImpl.cpp ├── HostImpl.h ├── Port.cpp ├── Port.h ├── PrintDebug.h └── UniquePriorityQueue.h └── test ├── CMakeLists.txt └── src ├── TestCases ├── BasicAccessorTests.cpp ├── BasicHostTests.cpp ├── DynamicSumVerifierTests.cpp └── SumVerifierTests.cpp └── TestClasses ├── DynamicIntegerAdder.h ├── DynamicSumVerifier.h ├── DynamicSumVerifierHost.h ├── EmptyHost.h ├── IntegerAdder.h ├── SpontaneousCounter.h ├── SumVerifier.h └── SumVerifierHost.h /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | 332 | # Output directory 333 | out/ 334 | 335 | CMakeSettings.json -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. 2 | # Licensed under the MIT License. 3 | 4 | cmake_minimum_required (VERSION 3.11) 5 | 6 | project(AccessorFramework 7 | VERSION 1.0.0 8 | DESCRIPTION "A framework for using Accessors" 9 | LANGUAGES CXX 10 | HOMEPAGE_URL "https://github.com/microsoft/AccessorFramework" 11 | ) 12 | 13 | set(CMAKE_CXX_STANDARD 14) 14 | set(CMAKE_CXX_STANDARD_REQUIRED ON) 15 | set(CMAKE_CXX_EXTENSIONS OFF) 16 | 17 | option(BUILD_TESTS "Build test executable (on by default)" ON) 18 | 19 | if(NOT DEFINED CMAKE_DEBUG_POSTFIX) 20 | set(CMAKE_DEBUG_POSTFIX "d") 21 | endif() 22 | 23 | add_library(AccessorFramework 24 | ${PROJECT_SOURCE_DIR}/src/Accessor.cpp 25 | ${PROJECT_SOURCE_DIR}/src/AccessorImpl.cpp 26 | ${PROJECT_SOURCE_DIR}/src/AtomicAccessorImpl.cpp 27 | ${PROJECT_SOURCE_DIR}/src/CompositeAccessorImpl.cpp 28 | ${PROJECT_SOURCE_DIR}/src/Director.cpp 29 | ${PROJECT_SOURCE_DIR}/src/Host.cpp 30 | ${PROJECT_SOURCE_DIR}/src/HostHypervisorImpl.cpp 31 | ${PROJECT_SOURCE_DIR}/src/HostImpl.cpp 32 | ${PROJECT_SOURCE_DIR}/src/Port.cpp 33 | ) 34 | 35 | add_library(AccessorFramework::AccessorFramework ALIAS AccessorFramework) 36 | 37 | if(${VERBOSE}) 38 | target_compile_definitions(AccessorFramework PRIVATE VERBOSE=${VERBOSE}) 39 | endif() 40 | 41 | target_include_directories(AccessorFramework 42 | PUBLIC 43 | $ 44 | $ 45 | PRIVATE 46 | ${PROJECT_SOURCE_DIR}/src 47 | ) 48 | 49 | if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" AND NOT (CMAKE_SYSTEM_PROCESSOR MATCHES "^arm")) 50 | target_compile_options(AccessorFramework PRIVATE -pthread) 51 | target_link_libraries(AccessorFramework PRIVATE -lpthread) 52 | endif() 53 | 54 | set_target_properties(AccessorFramework PROPERTIES 55 | ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib 56 | COMPILE_PDB_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin 57 | LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib 58 | PDB_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin 59 | RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin 60 | ) 61 | 62 | get_target_property(AccessorFramework_NAME AccessorFramework NAME) 63 | get_target_property(AccessorFramework_DEBUG_POSTFIX AccessorFramework DEBUG_POSTFIX) 64 | set_target_properties(AccessorFramework PROPERTIES 65 | COMPILE_PDB_NAME ${AccessorFramework_NAME} 66 | COMPILE_PDB_NAME_DEBUG ${AccessorFramework_NAME}${AccessorFramework_DEBUG_POSTFIX} 67 | PDB_NAME ${AccessorFramework_NAME} 68 | PDB_NAME_DEBUG ${AccessorFramework_NAME}${AccessorFramework_DEBUG_POSTFIX} 69 | ) 70 | 71 | # Install 72 | 73 | install(TARGETS AccessorFramework 74 | EXPORT AccessorFrameworkTargets 75 | ARCHIVE DESTINATION lib 76 | LIBRARY DESTINATION lib 77 | RUNTIME DESTINATION bin 78 | ) 79 | 80 | install(DIRECTORY ${PROJECT_SOURCE_DIR}/include/AccessorFramework DESTINATION ${CMAKE_INSTALL_PREFIX}/include) 81 | 82 | if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC") 83 | get_target_property(AccessorFramework_PDB_OUTPUT_DIRECTORY AccessorFramework PDB_OUTPUT_DIRECTORY) 84 | get_target_property(AccessorFramework_PDB_NAME AccessorFramework PDB_NAME) 85 | get_target_property(AccessorFramework_PDB_NAME_DEBUG AccessorFramework PDB_NAME_DEBUG) 86 | install(FILES 87 | "${AccessorFramework_PDB_OUTPUT_DIRECTORY}/${AccessorFramework_PDB_NAME_DEBUG}.pdb" 88 | "${AccessorFramework_PDB_OUTPUT_DIRECTORY}/${AccessorFramework_PDB_NAME}.pdb" 89 | DESTINATION bin 90 | OPTIONAL 91 | ) 92 | endif() 93 | 94 | install(EXPORT AccessorFrameworkTargets 95 | FILE AccessorFrameworkTargets.cmake 96 | NAMESPACE AccessorFramework:: 97 | DESTINATION lib/cmake/AccessorFramework 98 | ) 99 | 100 | # Export 101 | 102 | export(EXPORT AccessorFrameworkTargets 103 | FILE ${PROJECT_BINARY_DIR}/cmake/AccessorFrameworkTargets.cmake 104 | NAMESPACE AccessorFramework:: 105 | ) 106 | 107 | export(PACKAGE AccessorFramework) 108 | 109 | # Package 110 | 111 | include(CMakePackageConfigHelpers) 112 | write_basic_package_version_file( 113 | ${PROJECT_BINARY_DIR}/cmake/AccessorFrameworkConfigVersion.cmake 114 | VERSION ${ACCESSORFRAMEWORK_VERSION} 115 | COMPATIBILITY AnyNewerVersion 116 | ) 117 | 118 | configure_package_config_file( 119 | ${PROJECT_SOURCE_DIR}/cmake/AccessorFrameworkConfig.cmake.in 120 | ${PROJECT_BINARY_DIR}/cmake/AccessorFrameworkConfig.cmake 121 | INSTALL_DESTINATION lib/cmake/AccessorFramework 122 | ) 123 | 124 | install( 125 | FILES 126 | ${PROJECT_BINARY_DIR}/cmake/AccessorFrameworkConfig.cmake 127 | ${PROJECT_BINARY_DIR}/cmake/AccessorFrameworkConfigVersion.cmake 128 | DESTINATION lib/cmake/AccessorFramework 129 | ) 130 | 131 | # Tests 132 | 133 | if (BUILD_TESTS) 134 | add_definitions(-DUSE_GTEST) 135 | enable_testing() 136 | add_subdirectory(test) 137 | endif (BUILD_TESTS) -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Microsoft Open Source Code of Conduct 2 | 3 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 4 | 5 | Resources: 6 | 7 | - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) 8 | - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) 9 | - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://microsoft.visualstudio.com/Universal%20Print/_apis/build/status/microsoft.AccessorFramework?branchName=master)](https://microsoft.visualstudio.com/Universal%20Print/_build/latest?definitionId=47587&branchName=master) 2 | 3 | ## About 4 | 5 | The Accessor Framework is a C++ SDK that empowers cyber-physical system application developers to build their 6 | applications using the Accessor Model, a component-based programming model originally conceived by researchers at the 7 | [Industrial Cyber-Physical Systems Center (iCyPhy)](https://ptolemy.berkeley.edu/projects/icyphy/) at UC Berkeley. 8 | 9 | The Accessor Model enables embedded applications to embrace heterogeneous protocol stacks and be highly asynchronous 10 | while still being highly deterministic. This enables developers to have well-defined test cases, rigorous 11 | specifications, and reliable error checking without sacrificing the performance gains of multi-threading. In addition, 12 | the model eliminates the need for explicit thread management, eliminating the potential for deadlocks and greatly 13 | reducing the potential for race conditions and other non-deterministic behavior. 14 | 15 | The SDK is designed to be cross-platform. It is written entirely in C++ and has no dependencies other than the C++14 16 | Standard Library. 17 | 18 | The research paper that inspired this project can be found at https://ieeexplore.ieee.org/document/8343871. 19 | 20 | ## Getting Started 21 | 22 | #### Building from Source 23 | 24 | ``` 25 | git clone https://github.com/microsoft/AccessorFramework.git 26 | cd AccessorFramework 27 | mkdir build 28 | cd build 29 | cmake .. 30 | cmake --build . 31 | ``` 32 | 33 | #### Using in a CMake Project 34 | 35 | ```cmake 36 | # CMakeLists.txt 37 | project(myProject) 38 | 39 | find_package(AccessorFramework REQUIRED) 40 | 41 | add_executable(myProject main.cpp) 42 | target_link_libraries(myProject PRIVATE AccessorFramework) 43 | ``` 44 | 45 | ## Contributing 46 | 47 | This project welcomes contributions and suggestions. Most contributions require you to agree to a 48 | Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us 49 | the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. 50 | 51 | When you submit a pull request, a CLA bot will automatically determine whether you need to provide 52 | a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions 53 | provided by the bot. You will only need to do this once across all repos using our CLA. 54 | 55 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 56 | For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or 57 | contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 58 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Security 4 | 5 | Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [many more](https://opensource.microsoft.com/). 6 | 7 | If you believe you have found a security vulnerability in any Microsoft-owned repository that meets Microsoft's [definition](https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc751383(v=technet.10)) of a security vulnerability, please report it to us as described below. 8 | 9 | ## Reporting Security Issues 10 | 11 | **Please do not report security vulnerabilities through public GitHub issues.** Instead, please report them to the Microsoft Security Response Center at [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://technet.microsoft.com/en-us/security/dn606155). 12 | 13 | You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc). 14 | 15 | Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: 16 | 17 | * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) 18 | * Full paths of source file(s) related to the manifestation of the issue 19 | * The location of the affected source code (tag/branch/commit or direct URL) 20 | * Any special configuration required to reproduce the issue 21 | * Step-by-step instructions to reproduce the issue 22 | * Proof-of-concept or exploit code (if possible) 23 | * Impact of the issue, including how an attacker might exploit the issue 24 | 25 | This information will help us triage your report more quickly. 26 | 27 | ## Preferred Languages 28 | 29 | We prefer all communications to be in English. 30 | 31 | ## Policy 32 | 33 | Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://www.microsoft.com/en-us/msrc/cvd). 34 | 35 | -------------------------------------------------------------------------------- /buildsystem/templates/linux.yml: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. 2 | # Licensed under the MIT License. 3 | 4 | parameters: 5 | - name: arch 6 | type: string 7 | 8 | jobs: 9 | - job: Linux_${{ parameters.arch }} 10 | displayName: 'Build for Linux ${{ parameters.arch }}' 11 | pool: 12 | vmImage: ubuntu-18.04 13 | workspace: 14 | clean: all 15 | variables: 16 | Build.BuildDirectory: '$(Build.BinariesDirectory)\${{ parameters.arch }}' 17 | CMakeArgs.x86: -G "Unix Makefiles" -DCMAKE_BUILD_TYPE="Release" $(Build.SourcesDirectory) 18 | CMakeArgs.x64: -G "Unix Makefiles" -DCMAKE_BUILD_TYPE="Release" $(Build.SourcesDirectory) 19 | CMakeArgs.arm: -G "Unix Makefiles" -DCMAKE_BUILD_TYPE="Release" -DCMAKE_TOOLCHAIN_FILE="$(Build.SourcesDirectory)/buildsystem/toolchains/arm-linux-gnueabihf.cmake" $(Build.SourcesDirectory) 20 | CMakeArgs.arm64: -G "Unix Makefiles" -DCMAKE_BUILD_TYPE="Release" -DCMAKE_TOOLCHAIN_FILE="$(Build.SourcesDirectory)/buildsystem/toolchains/aarch64-linux-gnu.cmake" $(Build.SourcesDirectory) 21 | UnitTests.ResultsPrefix: 'UnitTestResults-${{ parameters.arch }}' 22 | steps: 23 | - task: Bash@3 24 | displayName: 'Install ARM Cross-Compile Tools' 25 | condition: and(succeeded(), eq('${{ parameters.arch }}', 'arm')) 26 | inputs: 27 | targetType: 'inline' 28 | script: sudo apt-get install -y gcc-arm-linux-gnueabihf g++-arm-linux-gnueabihf 29 | - task: Bash@3 30 | displayName: 'Install ARM64 Cross-Compile Tools' 31 | condition: and(succeeded(), eq('${{ parameters.arch }}', 'arm64')) 32 | inputs: 33 | targetType: 'inline' 34 | script: sudo apt-get install -y gcc-aarch64-linux-gnu g++-aarch64-linux-gnu 35 | - task: CMake@1 36 | displayName: 'Generate CMake Cache' 37 | inputs: 38 | workingDirectory: $(Build.BuildDirectory) 39 | cmakeArgs: $(CMakeArgs.${{ parameters.arch }}) 40 | - task: CMake@1 41 | displayName: 'Build with CMake' 42 | inputs: 43 | workingDirectory: $(Build.BuildDirectory) 44 | cmakeArgs: --build . 45 | - task: Bash@3 46 | displayName: 'Run Unit Tests' 47 | condition: and(succeeded(), or(eq('${{ parameters.arch }}', 'x86'), eq('${{ parameters.arch }}', 'x64'))) 48 | inputs: 49 | workingDirectory: $(Build.BuildDirectory) 50 | targetType: 'inline' 51 | script: | 52 | $(Build.BinariesDirectory)/${{ parameters.arch }}/test/AccessorFrameworkTests --gtest_filter="-DynamicSumVerifierTest.*" --gtest_output=xml:$(UnitTests.ResultsPrefix)-1.xml 53 | $(Build.BinariesDirectory)/${{ parameters.arch }}/test/AccessorFrameworkTests --gtest_filter="DynamicSumVerifierTest.*" --gtest_output=xml:$(UnitTests.ResultsPrefix)-2.xml 54 | failOnStderr: true 55 | - task: PublishTestResults@2 56 | displayName: 'Publish Unit Test Results' 57 | condition: and(succeeded(), or(eq('${{ parameters.arch }}', 'x86'), eq('${{ parameters.arch }}', 'x64'))) 58 | inputs: 59 | testResultsFormat: 'JUnit' 60 | testResultsFiles: '**/$(UnitTests.ResultsPrefix)*.xml' 61 | searchFolder: $(Build.BuildDirectory) 62 | mergeTestResults: true 63 | testRunTitle: '$(Build.BuildNumber).Linux_${{ parameters.arch }}.UnitTests' -------------------------------------------------------------------------------- /buildsystem/templates/windows.yml: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. 2 | # Licensed under the MIT License. 3 | 4 | parameters: 5 | - name: arch 6 | type: string 7 | 8 | jobs: 9 | - job: Windows_${{ parameters.arch }} 10 | displayName: "Build for Windows ${{ parameters.arch }}" 11 | pool: 12 | vmImage: windows-2019 13 | workspace: 14 | clean: all 15 | variables: 16 | UnitTests.ResultsPrefix: 'UnitTestResults-${{ parameters.arch }}' 17 | steps: 18 | - task: CmdLine@2 19 | displayName: 'Build with CMake and Ninja' 20 | inputs: 21 | script: | 22 | echo off 23 | set vcvars= 24 | set compiler= 25 | if "${{ parameters.arch }}"=="x64" ( 26 | set vcvars=vcvars64.bat 27 | set compiler=bin/HostX64/x64/cl.exe 28 | goto :build 29 | ) 30 | if "${{ parameters.arch }}"=="x86" ( 31 | set vcvars=vcvarsamd64_x86.bat 32 | set compiler=bin/HostX86/x86/cl.exe 33 | goto :build 34 | ) 35 | if "${{ parameters.arch }}"=="arm" ( 36 | set vcvars=vcvarsamd64_arm.bat 37 | set compiler=bin/HostX86/ARM/cl.exe 38 | goto :build 39 | ) 40 | if "${{ parameters.arch }}"=="arm64" ( 41 | set vcvars=vcvarsamd64_arm64.bat 42 | set compiler=bin/HostX86/ARM64/cl.exe 43 | goto :build 44 | ) 45 | 46 | echo "arch '${{ parameters.arch }}' not recognized! Valid values are x86, x64, arm, and arm64" 47 | exit /b -1 48 | 49 | :build 50 | call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Auxiliary\Build\%vcvars%" 51 | echo on 52 | "%DevEnvDir%CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -G "Ninja" -DCMAKE_BINARY_DIR="%BUILD_BINARIESDIRECTORY%" -Dgtest_force_shared_crt:BOOL="True" -DCMAKE_CXX_COMPILER:FILEPATH="%VCToolsInstallDir%%compiler%" -DCMAKE_C_COMPILER:FILEPATH="%VCToolsInstallDir%%compiler%" -DCMAKE_BUILD_TYPE="Release" -DCMAKE_MAKE_PROGRAM="%DevEnvDir%CommonExtensions\Microsoft\CMake\Ninja\ninja.exe" "%BUILD_SOURCESDIRECTORY%" 53 | Ninja 54 | workingDirectory: $(Build.BinariesDirectory) 55 | failOnStderr: true 56 | - task: CmdLine@2 57 | displayName: 'Run Unit Tests' 58 | condition: and(succeeded(), or(eq('${{ parameters.arch }}', 'x86'), eq('${{ parameters.arch }}', 'x64'))) 59 | inputs: 60 | script: | 61 | echo on 62 | :: The *SumVerifier tests fail when run in the same test run. Since the tests use different classes and test fixtures, 63 | :: this failure is most likely due to a bug in Google Test. Run tests separately for now as a workaround. 64 | "%BUILD_BINARIESDIRECTORY%\test\AccessorFrameworkTests.exe" --gtest_filter="-DynamicSumVerifierTest.*" --gtest_output=xml:%UNITTESTS_RESULTSPREFIX%-1.xml 65 | "%BUILD_BINARIESDIRECTORY%\test\AccessorFrameworkTests.exe" --gtest_filter="DynamicSumVerifierTest.*" --gtest_output=xml:%UNITTESTS_RESULTSPREFIX%-2.xml 66 | workingDirectory: $(Build.BinariesDirectory) 67 | failOnStderr: true 68 | - task: PublishTestResults@2 69 | displayName: 'Publish Unit Test Results' 70 | condition: and(succeeded(), or(eq('${{ parameters.arch }}', 'x86'), eq('${{ parameters.arch }}', 'x64'))) 71 | inputs: 72 | testResultsFormat: 'JUnit' 73 | testResultsFiles: '**/$(UnitTests.ResultsPrefix)*.xml' 74 | searchFolder: $(Build.BinariesDirectory) 75 | mergeTestResults: true 76 | testRunTitle: '$(Build.BuildNumber).Windows_${{ parameters.arch }}.UnitTests' -------------------------------------------------------------------------------- /buildsystem/toolchains/aarch64-linux-gnu.cmake: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. 2 | # Licensed under the MIT License. 3 | 4 | set(CMAKE_SYSTEM_NAME Linux) 5 | set(CMAKE_SYSTEM_PROCESSOR arm) 6 | 7 | set(CMAKE_C_COMPILER /usr/bin/aarch64-linux-gnu-gcc) 8 | set(CMAKE_CXX_COMPILER /usr/bin/aarch64-linux-gnu-g++) 9 | 10 | set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) 11 | set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) 12 | set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) 13 | set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) -------------------------------------------------------------------------------- /buildsystem/toolchains/arm-linux-gnueabi.cmake: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. 2 | # Licensed under the MIT License. 3 | 4 | set(CMAKE_SYSTEM_NAME Linux) 5 | set(CMAKE_SYSTEM_PROCESSOR arm) 6 | 7 | set(CMAKE_C_COMPILER /usr/bin/arm-linux-gnueabi-gcc) 8 | set(CMAKE_CXX_COMPILER /usr/bin/arm-linux-gnueabi-g++) 9 | 10 | set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) 11 | set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) 12 | set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) 13 | set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) -------------------------------------------------------------------------------- /buildsystem/toolchains/arm-linux-gnueabihf.cmake: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. 2 | # Licensed under the MIT License. 3 | 4 | set(CMAKE_SYSTEM_NAME Linux) 5 | set(CMAKE_SYSTEM_PROCESSOR arm) 6 | 7 | set(CMAKE_C_COMPILER /usr/bin/arm-linux-gnueabihf-gcc) 8 | set(CMAKE_CXX_COMPILER /usr/bin/arm-linux-gnueabihf-g++) 9 | 10 | set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) 11 | set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) 12 | set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) 13 | set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) -------------------------------------------------------------------------------- /cmake/AccessorFrameworkConfig.cmake.in: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. 2 | # Licensed under the MIT License. 3 | 4 | @PACKAGE_INIT@ 5 | 6 | if(NOT TARGET AccessorFramework::AccessorFramework) 7 | include(${CMAKE_CURRENT_LIST_DIR}/AccessorFrameworkTargets.cmake) 8 | endif() -------------------------------------------------------------------------------- /include/AccessorFramework/Accessor.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef ACCESSOR_H 5 | #define ACCESSOR_H 6 | 7 | #include "Event.h" 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | // Description 18 | // An accessor is an actor that wraps a (possibly remote) device or service in an actor interface. An accessor can 19 | // possess input ports and connected output ports (i.e. output ports that are causally dependent on, or are connected to, 20 | // an input port on the same accessor). All accessors are able to connect their own input ports to their own output ports 21 | // (i.e. feedforward) and their own output ports to their own input ports (i.e. feedback). All accessors can also 22 | // schedule callbacks, or functions, that either occur as soon as possible or at a later scheduled time. Lastly, all 23 | // accessors and their ports are given names. Port names are unique to their accessor; no two ports on a given accessor 24 | // can have the same name. 25 | // 26 | // The Accessor class has two subtypes: AtomicAccessor and CompositeAccessor. In addition to input and connected output 27 | // ports, an atomic accessor can also possess spontaneous output ports, or output ports that do not depend on input from 28 | // any input port. For example, an output port that sends out a sensor reading every 5 seconds is a spontaneous output 29 | // port. An atomic accessor can also contain code that handles, or reacts to, input on its input ports. Input handlers 30 | // are functions that react to input on a specific input port. A single input port can be associated with multiple input 31 | // handlers. Atomic accessors also have a Fire() function that is invoked once regardless of which input port receives 32 | // input or how many input ports recieve input. This invocation occurs after all input handlers have been called. 33 | // Composite accessors do NOT possess spontaneous output ports or any input handling logic. Instead, composite accessors 34 | // contain child accessors, which can be atomic, composite, or both. Composites are responsible for connecting its 35 | // children to itself and to each other and for enforcing name uniquness. A child accessor cannot have the same name as 36 | // its parent, and no two accessors with the same parent can have the same name. Without any input handling logic, 37 | // composites are purely containers for their children. This allows the Accessor Framework to be more modular by hiding 38 | // layered subnetworks in the model behind composites. 39 | // 40 | class Accessor 41 | { 42 | public: 43 | class Impl; 44 | 45 | virtual ~Accessor(); 46 | std::string GetName() const; 47 | Impl* GetImpl() const; 48 | static bool NameIsValid(const std::string& name); 49 | 50 | protected: 51 | Accessor(std::unique_ptr impl); 52 | 53 | // Called once during host setup (base implementation does nothing) 54 | virtual void Initialize(); 55 | 56 | // Schedules a new callback using the deterministic temporal semantics. 57 | // A callback identifier is returned that can be used to clear the callback. 58 | int ScheduleCallback(std::function callback, int delayInMilliseconds, bool repeat); 59 | 60 | // Clears the callback with the given ID 61 | void ClearScheduledCallback(int callbackId); 62 | 63 | // Clears all callbacks for this Accessor 64 | void ClearAllScheduledCallbacks(); 65 | 66 | // Port names cannot be empty, and an accessor can have only one port with a given name 67 | bool NewPortNameIsValid(const std::string& newPortName) const; 68 | 69 | void AddInputPort(const std::string& portName); 70 | void AddInputPorts(const std::vector& portNames); 71 | void AddOutputPort(const std::string& portName); 72 | void AddOutputPorts(const std::vector& portNames); 73 | 74 | void ConnectMyInputToMyOutput(const std::string& myInputPortName, const std::string& myOutputPortName); 75 | void ConnectMyOutputToMyInput(const std::string& myOutputPortName, const std::string& myInputPortName); 76 | 77 | // Get the latest input on an input port 78 | IEvent* GetLatestInput(const std::string& inputPortName) const; 79 | 80 | // Send an event via an output port 81 | void SendOutput(const std::string& outputPortName, std::shared_ptr output); 82 | 83 | private: 84 | std::unique_ptr m_impl; 85 | }; 86 | 87 | class CompositeAccessor : public Accessor 88 | { 89 | public: 90 | class Impl; 91 | 92 | CompositeAccessor( 93 | const std::string& name, 94 | const std::vector& inputPortNames = {}, 95 | const std::vector& outputPortNames = {}); 96 | 97 | protected: 98 | CompositeAccessor(std::unique_ptr impl); 99 | 100 | // Child names cannot be empty or the same as the parent's name, and a parent can have only one child with a given name 101 | bool NewChildNameIsValid(const std::string& newChildName) const; 102 | void AddChild(std::unique_ptr child); 103 | void RemoveChild(const std::string& childName); 104 | void RemoveAllChildren(); 105 | void ConnectMyInputToChildInput(const std::string& myInputPortName, const std::string& childName, const std::string& childInputPortName); 106 | void ConnectChildOutputToMyOutput(const std::string& childName, const std::string& childOutputPortName, const std::string& myOutputPortName); 107 | void ConnectChildren( 108 | const std::string& sourceChildName, 109 | const std::string& sourceChildOutputPortName, 110 | const std::string& destinationChildName, 111 | const std::string& destinationChildInputPortName); 112 | void ChildrenChanged(); // Call after children/connections are added or removed at runtime 113 | }; 114 | 115 | class AtomicAccessor : public Accessor 116 | { 117 | public: 118 | class Impl; 119 | 120 | using InputHandler = std::function; 121 | 122 | AtomicAccessor( 123 | const std::string& name, 124 | const std::vector& inputPortNames = {}, 125 | const std::vector& outputPortNames = {}, 126 | const std::vector& spontaneousOutputPortNames = {}, 127 | const std::map>& inputHandlers = {}); 128 | 129 | protected: 130 | // Declares an input port that changes this accessor's state 131 | void AccessorStateDependsOn(const std::string& inputPortName); 132 | 133 | // Removes a direct causal dependency between an input port and an output port on this accessor 134 | void RemoveDependency(const std::string& inputPortName, const std::string& outputPortName); 135 | void RemoveDependencies(const std::string& inputPortName, const std::vector& outputPortNames); 136 | 137 | // Add an output port that does not depend on input from any input port (i.e. generates outputs spontaneously) 138 | void AddSpontaneousOutputPort(const std::string& portName); 139 | void AddSpontaneousOutputPorts(const std::vector& portNames); 140 | 141 | // Register a function that is called when an input port receives an input 142 | void AddInputHandler(const std::string& inputPortName, InputHandler handler); 143 | void AddInputHandlers(const std::string& inputPortName, const std::vector& handlers); 144 | 145 | // Called once per reaction (base implementation does nothing) 146 | virtual void Fire(); 147 | }; 148 | 149 | #endif //ACCESSOR_H 150 | -------------------------------------------------------------------------------- /include/AccessorFramework/Event.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef EVENT_H 5 | #define EVENT_H 6 | 7 | // Description 8 | // An Event is a data structure that is passed between ports. It may or may not contain a payload. 9 | // 10 | class IEvent {}; 11 | 12 | template 13 | class Event : public IEvent 14 | { 15 | public: 16 | Event(const T& payload) : payload(payload) {} 17 | const T payload; 18 | }; 19 | 20 | #endif // EVENT_H 21 | -------------------------------------------------------------------------------- /include/AccessorFramework/Host.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef HOST_H 5 | #define HOST_H 6 | 7 | #include "Accessor.h" 8 | #include 9 | #include 10 | 11 | // Description 12 | // The host contains and drives the accessor model. It can be thought of as a composite accessor without any input or 13 | // output ports with the ability to set up, run, pause, and tear down the model. It also maintains the model's state and 14 | // passes along any exceptions thrown by the model. It defines an EventListener interface so that other entities can 15 | // subscribe to be notified when the model changes state or throws an exception. 16 | // 17 | // Note: Hosts are not allowed to have ports; calls to inherited Add__Port() methods will throw an exception. 18 | // 19 | class Host : public CompositeAccessor 20 | { 21 | public: 22 | class Impl; 23 | 24 | enum class State 25 | { 26 | NeedsSetup, 27 | SettingUp, 28 | ReadyToRun, 29 | Running, 30 | Paused, 31 | Exiting, 32 | Finished, 33 | Corrupted 34 | }; 35 | 36 | class EventListener 37 | { 38 | public: 39 | virtual void NotifyOfException(const std::exception& e) = 0; 40 | virtual void NotifyOfStateChange(Host::State oldState, Host::State newState) = 0; 41 | }; 42 | 43 | ~Host(); 44 | State GetState() const; 45 | bool EventListenerIsRegistered(int listenerId) const; 46 | int AddEventListener(std::weak_ptr listener); 47 | void RemoveEventListener(int listenerId); 48 | void Setup(); 49 | void Iterate(int numberOfIterations = 1); 50 | void Pause(); 51 | void Run(); 52 | void RunOnCurrentThread(); 53 | void Exit(); 54 | 55 | protected: 56 | Host(const std::string& name); 57 | 58 | // Called during Setup() (base implementation does nothing) 59 | virtual void AdditionalSetup(); 60 | 61 | private: 62 | // Hosts are not allowed to have ports, so we make them private 63 | // These methods will throw if made public and used by a derived class 64 | using CompositeAccessor::AddInputPort; 65 | using CompositeAccessor::AddInputPorts; 66 | using CompositeAccessor::AddOutputPort; 67 | using CompositeAccessor::AddOutputPorts; 68 | }; 69 | 70 | class HostHypervisor 71 | { 72 | public: 73 | HostHypervisor(); 74 | ~HostHypervisor(); 75 | 76 | int AddHost(std::unique_ptr host); 77 | void RemoveHost(int hostId); 78 | std::string GetHostName(int hostId) const; 79 | Host::State GetHostState(int hostId) const; 80 | void SetupHost(int hostId) const; 81 | void PauseHost(int hostId) const; 82 | void RunHost(int hostId) const; 83 | 84 | void RemoveAllHosts(); 85 | std::map GetHostNames() const; 86 | std::map GetHostStates() const; 87 | void SetupHosts() const; 88 | void PauseHosts() const; 89 | void RunHosts() const; 90 | void RunHostsOnCurrentThread() const; 91 | 92 | private: 93 | class Impl; 94 | std::unique_ptr m_impl; 95 | }; 96 | 97 | #endif // HOST_H 98 | -------------------------------------------------------------------------------- /pipeline.yml: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. 2 | # Licensed under the MIT License. 3 | 4 | trigger: 5 | - master 6 | 7 | pr: 8 | - master 9 | 10 | jobs: 11 | - template: buildsystem/templates/windows.yml 12 | parameters: 13 | arch: 'x86' 14 | - template: buildsystem/templates/windows.yml 15 | parameters: 16 | arch: 'x64' 17 | - template: buildsystem/templates/windows.yml 18 | parameters: 19 | arch: 'arm' 20 | - template: buildsystem/templates/windows.yml 21 | parameters: 22 | arch: 'arm64' 23 | - template: buildsystem/templates/linux.yml 24 | parameters: 25 | arch: 'x86' 26 | - template: buildsystem/templates/linux.yml 27 | parameters: 28 | arch: 'x64' 29 | - template: buildsystem/templates/linux.yml 30 | parameters: 31 | arch: 'arm' 32 | - template: buildsystem/templates/linux.yml 33 | parameters: 34 | arch: 'arm64' -------------------------------------------------------------------------------- /src/Accessor.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #include "AccessorFramework/Accessor.h" 5 | #include "AccessorImpl.h" 6 | #include "AtomicAccessorImpl.h" 7 | #include "CompositeAccessorImpl.h" 8 | #include "PrintDebug.h" 9 | #include 10 | 11 | Accessor::~Accessor() = default; 12 | 13 | std::string Accessor::GetName() const 14 | { 15 | return this->m_impl->GetName(); 16 | } 17 | 18 | Accessor::Impl* Accessor::GetImpl() const 19 | { 20 | return this->m_impl.get(); 21 | } 22 | 23 | bool Accessor::NameIsValid(const std::string& name) 24 | { 25 | return Accessor::Impl::NameIsValid(name); 26 | } 27 | 28 | Accessor::Accessor(std::unique_ptr impl) : 29 | m_impl(std::move(impl)) 30 | { 31 | } 32 | 33 | void Accessor::Initialize() 34 | { 35 | // base implementation does nothing 36 | } 37 | 38 | int Accessor::ScheduleCallback(std::function callback, int delayInMilliseconds, bool repeat) 39 | { 40 | return this->m_impl->ScheduleCallback(callback, delayInMilliseconds, repeat); 41 | } 42 | 43 | void Accessor::ClearScheduledCallback(int callbackId) 44 | { 45 | this->m_impl->ClearScheduledCallback(callbackId); 46 | } 47 | 48 | void Accessor::ClearAllScheduledCallbacks() 49 | { 50 | this->m_impl->ClearAllScheduledCallbacks(); 51 | } 52 | 53 | bool Accessor::NewPortNameIsValid(const std::string& newPortName) const 54 | { 55 | return this->m_impl->NewPortNameIsValid(newPortName); 56 | } 57 | 58 | void Accessor::AddInputPort(const std::string& portName) 59 | { 60 | this->m_impl->AddInputPort(portName); 61 | } 62 | 63 | void Accessor::AddInputPorts(const std::vector& portNames) 64 | { 65 | this->m_impl->AddInputPorts(portNames); 66 | } 67 | void Accessor::AddOutputPort(const std::string& portName) 68 | { 69 | this->m_impl->AddOutputPort(portName); 70 | } 71 | 72 | void Accessor::AddOutputPorts(const std::vector& portNames) 73 | { 74 | this->m_impl->AddOutputPorts(portNames); 75 | } 76 | 77 | void Accessor::ConnectMyInputToMyOutput(const std::string& myInputPortName, const std::string& myOutputPortName) 78 | { 79 | this->m_impl->ConnectMyInputToMyOutput(myInputPortName, myOutputPortName); 80 | } 81 | 82 | void Accessor::ConnectMyOutputToMyInput(const std::string& myOutputPortName, const std::string& myInputPortName) 83 | { 84 | this->m_impl->ConnectMyOutputToMyInput(myOutputPortName, myInputPortName); 85 | } 86 | 87 | IEvent* Accessor::GetLatestInput(const std::string& inputPortName) const 88 | { 89 | return this->m_impl->GetLatestInput(inputPortName); 90 | } 91 | 92 | void Accessor::SendOutput(const std::string& outputPortName, std::shared_ptr output) 93 | { 94 | this->m_impl->SendOutput(outputPortName, output); 95 | } 96 | 97 | CompositeAccessor::CompositeAccessor( 98 | const std::string& name, 99 | const std::vector& inputPortNames, 100 | const std::vector& outputPortNames) 101 | : Accessor(std::make_unique(name, this, &CompositeAccessor::Initialize, inputPortNames, outputPortNames)) 102 | { 103 | } 104 | 105 | CompositeAccessor::CompositeAccessor(std::unique_ptr impl) : 106 | Accessor(std::move(impl)) 107 | { 108 | } 109 | 110 | bool CompositeAccessor::NewChildNameIsValid(const std::string& newChildName) const 111 | { 112 | return static_cast(this->GetImpl())->NewChildNameIsValid(newChildName); 113 | } 114 | 115 | void CompositeAccessor::AddChild(std::unique_ptr child) 116 | { 117 | static_cast(this->GetImpl())->AddChild(std::move(child)); 118 | } 119 | 120 | void CompositeAccessor::RemoveChild(const std::string& childName) 121 | { 122 | static_cast(this->GetImpl())->RemoveChild(childName); 123 | } 124 | 125 | void CompositeAccessor::RemoveAllChildren() 126 | { 127 | static_cast(this->GetImpl())->RemoveAllChildren(); 128 | } 129 | 130 | void CompositeAccessor::ConnectMyInputToChildInput(const std::string& myInputPortName, const std::string& childName, const std::string& childInputPortName) 131 | { 132 | static_cast(this->GetImpl())->ConnectMyInputToChildInput(myInputPortName, childName, childInputPortName); 133 | } 134 | 135 | void CompositeAccessor::ConnectChildOutputToMyOutput(const std::string& childName, const std::string& childOutputPortName, const std::string& myOutputPortName) 136 | { 137 | static_cast(this->GetImpl())->ConnectChildOutputToMyOutput(childName, childOutputPortName, myOutputPortName); 138 | } 139 | 140 | void CompositeAccessor::ConnectChildren( 141 | const std::string& sourceChildName, 142 | const std::string& sourceChildOutputPortName, 143 | const std::string& destinationChildName, 144 | const std::string& destinationChildInputPortName) 145 | { 146 | return static_cast(this->GetImpl())->ConnectChildren(sourceChildName, sourceChildOutputPortName, destinationChildName, destinationChildInputPortName); 147 | } 148 | 149 | void CompositeAccessor::ChildrenChanged() 150 | { 151 | static_cast(this->GetImpl())->ChildrenChanged(); 152 | } 153 | 154 | AtomicAccessor::AtomicAccessor( 155 | const std::string& name, 156 | const std::vector& inputPortNames, 157 | const std::vector& outputPortNames, 158 | const std::vector& spontaneousOutputPortNames, 159 | const std::map>& inputHandlers) 160 | : Accessor(std::make_unique(name, this, &AtomicAccessor::Initialize, inputPortNames, outputPortNames, spontaneousOutputPortNames, inputHandlers, &AtomicAccessor::Fire)) 161 | { 162 | } 163 | 164 | void AtomicAccessor::AccessorStateDependsOn(const std::string& inputPortName) 165 | { 166 | static_cast(this->GetImpl())->AccessorStateDependsOn(inputPortName); 167 | } 168 | 169 | void AtomicAccessor::RemoveDependency(const std::string& inputPortName, const std::string& outputPortName) 170 | { 171 | static_cast(this->GetImpl())->RemoveDependency(inputPortName, outputPortName); 172 | } 173 | 174 | void AtomicAccessor::RemoveDependencies(const std::string& inputPortName, const std::vector& outputPortNames) 175 | { 176 | static_cast(this->GetImpl())->RemoveDependencies(inputPortName, outputPortNames); 177 | } 178 | 179 | void AtomicAccessor::AddSpontaneousOutputPort(const std::string& portName) 180 | { 181 | static_cast(this->GetImpl())->AddSpontaneousOutputPort(portName); 182 | } 183 | 184 | void AtomicAccessor::AddSpontaneousOutputPorts(const std::vector& portNames) 185 | { 186 | static_cast(this->GetImpl())->AddSpontaneousOutputPorts(portNames); 187 | } 188 | 189 | void AtomicAccessor::AddInputHandler(const std::string& inputPortName, InputHandler handler) 190 | { 191 | static_cast(this->GetImpl())->AddInputHandler(inputPortName, handler); 192 | } 193 | 194 | void AtomicAccessor::AddInputHandlers(const std::string& inputPortName, const std::vector& handlers) 195 | { 196 | static_cast(this->GetImpl())->AddInputHandlers(inputPortName, handlers); 197 | } 198 | 199 | void AtomicAccessor::Fire() 200 | { 201 | // base implementation does nothing 202 | } -------------------------------------------------------------------------------- /src/AccessorImpl.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #include "AccessorImpl.h" 5 | #include "CompositeAccessorImpl.h" 6 | #include "Director.h" 7 | #include "PrintDebug.h" 8 | 9 | const int Accessor::Impl::DefaultAccessorPriority = INT_MAX; 10 | 11 | Accessor::Impl::~Impl() 12 | { 13 | this->ClearAllScheduledCallbacks(); 14 | } 15 | 16 | bool Accessor::Impl::IsInitialized() const 17 | { 18 | return this->m_initialized; 19 | } 20 | 21 | void Accessor::Impl::Initialize() 22 | { 23 | if (this->m_initializeFunction != nullptr) 24 | { 25 | this->m_initializeFunction(*(this->m_container)); 26 | } 27 | 28 | this->m_initialized = true; 29 | } 30 | 31 | void Accessor::Impl::SetParent(CompositeAccessor::Impl* parent) 32 | { 33 | BaseObject::SetParent(parent); 34 | } 35 | 36 | int Accessor::Impl::GetPriority() const 37 | { 38 | return this->m_priority; 39 | } 40 | 41 | void Accessor::Impl::SetPriority(int priority) 42 | { 43 | PRINT_VERBOSE("%s now has priority %d", this->GetFullName().c_str(), priority); 44 | this->m_priority = priority; 45 | } 46 | 47 | void Accessor::Impl::ResetPriority() 48 | { 49 | this->m_priority = DefaultAccessorPriority; 50 | } 51 | 52 | Director* Accessor::Impl::GetDirector() const 53 | { 54 | auto myParent = static_cast(this->GetParent()); 55 | if (myParent == nullptr) 56 | { 57 | return nullptr; 58 | } 59 | else 60 | { 61 | return myParent->GetDirector(); 62 | } 63 | } 64 | 65 | bool Accessor::Impl::HasInputPorts() const 66 | { 67 | return !(this->m_inputPorts.empty()); 68 | } 69 | 70 | bool Accessor::Impl::HasOutputPorts() const 71 | { 72 | return !(this->m_outputPorts.empty()); 73 | } 74 | 75 | InputPort* Accessor::Impl::GetInputPort(const std::string& portName) const 76 | { 77 | return this->m_inputPorts.at(portName).get(); 78 | } 79 | 80 | OutputPort* Accessor::Impl::GetOutputPort(const std::string& portName) const 81 | { 82 | return this->m_outputPorts.at(portName).get(); 83 | } 84 | 85 | std::vector Accessor::Impl::GetInputPorts() const 86 | { 87 | return std::vector(this->m_orderedInputPorts.begin(), this->m_orderedInputPorts.end()); 88 | } 89 | 90 | std::vector Accessor::Impl::GetOutputPorts() const 91 | { 92 | return std::vector(this->m_orderedOutputPorts.begin(), this->m_orderedOutputPorts.end()); 93 | } 94 | 95 | void Accessor::Impl::AlertNewInput() 96 | { 97 | auto myParent = static_cast(this->GetParent()); 98 | if (myParent != nullptr) 99 | { 100 | myParent->ScheduleReaction(this, this->m_priority); 101 | } 102 | } 103 | 104 | bool Accessor::Impl::operator<(const Accessor::Impl& other) const 105 | { 106 | return (this->m_priority < other.GetPriority()); 107 | } 108 | 109 | bool Accessor::Impl::operator>(const Accessor::Impl& other) const 110 | { 111 | return (this->m_priority > other.GetPriority()); 112 | } 113 | 114 | int Accessor::Impl::ScheduleCallback( 115 | std::function callback, 116 | int delayInMilliseconds, 117 | bool repeat) 118 | { 119 | int callbackId = this->GetDirector()->ScheduleCallback( 120 | callback, 121 | delayInMilliseconds, 122 | repeat, 123 | this->m_priority); 124 | this->m_callbackIds.insert(callbackId); 125 | return callbackId; 126 | } 127 | 128 | void Accessor::Impl::ClearScheduledCallback(int callbackId) 129 | { 130 | this->GetDirector()->ClearScheduledCallback(callbackId); 131 | this->m_callbackIds.erase(callbackId); 132 | } 133 | 134 | void Accessor::Impl::ClearAllScheduledCallbacks() 135 | { 136 | while (!this->m_callbackIds.empty()) 137 | { 138 | int callbackId = *(this->m_callbackIds.begin()); 139 | this->ClearScheduledCallback(callbackId); 140 | } 141 | } 142 | 143 | bool Accessor::Impl::NewPortNameIsValid(const std::string& newPortName) const 144 | { 145 | return ( 146 | NameIsValid(newPortName) && 147 | !this->HasInputPortWithName(newPortName) && 148 | !this->HasOutputPortWithName(newPortName)); 149 | } 150 | 151 | void Accessor::Impl::AddInputPort(const std::string& portName) 152 | { 153 | PRINT_VERBOSE("%s is creating a new input port \'%s\'", this->GetName().c_str(), portName.c_str()); 154 | this->ValidatePortName(portName); 155 | this->m_inputPorts.emplace(portName, std::make_unique(portName, this)); 156 | this->m_orderedInputPorts.push_back(this->m_inputPorts.at(portName).get()); 157 | } 158 | 159 | void Accessor::Impl::AddInputPorts(const std::vector& portNames) 160 | { 161 | for (const std::string& portName : portNames) 162 | { 163 | this->AddInputPort(portName); 164 | } 165 | } 166 | 167 | void Accessor::Impl::AddOutputPort(const std::string& portName) 168 | { 169 | this->AddOutputPort(portName, false /*isSpontaneous*/); 170 | } 171 | 172 | void Accessor::Impl::AddOutputPorts(const std::vector& portNames) 173 | { 174 | for (const std::string& portName : portNames) 175 | { 176 | this->AddOutputPort(portName); 177 | } 178 | } 179 | 180 | void Accessor::Impl::ConnectMyInputToMyOutput(const std::string& myInputPortName, const std::string& myOutputPortName) 181 | { 182 | Port::Connect(this->m_inputPorts.at(myInputPortName).get(), this->m_outputPorts.at(myOutputPortName).get()); 183 | } 184 | 185 | void Accessor::Impl::ConnectMyOutputToMyInput(const std::string& myOutputPortName, const std::string& myInputPortName) 186 | { 187 | Port::Connect(this->m_outputPorts.at(myOutputPortName).get(), this->m_inputPorts.at(myInputPortName).get()); 188 | } 189 | 190 | IEvent* Accessor::Impl::GetLatestInput(const std::string& inputPortName) const 191 | { 192 | return this->GetInputPort(inputPortName)->GetLatestInput(); 193 | } 194 | 195 | void Accessor::Impl::SendOutput(const std::string& outputPortName, std::shared_ptr output) 196 | { 197 | if (!(this->IsInitialized())) 198 | { 199 | throw std::logic_error("Outputs cannot be sent until the accessor is initialized"); 200 | } 201 | 202 | this->ScheduleCallback( 203 | [this, outputPortName, output]() 204 | { 205 | this->GetOutputPort(outputPortName)->SendData(output); 206 | }, 207 | 0 /*delayInMilliseconds*/, 208 | false /*repeat*/); 209 | } 210 | 211 | Accessor::Impl::Impl( 212 | const std::string& name, 213 | Accessor* container, 214 | std::function initializeFunction, 215 | const std::vector& inputPortNames, 216 | const std::vector& connectedOutputPortNames) : 217 | BaseObject(name), 218 | m_initialized(false), 219 | m_container(container), 220 | m_priority(DefaultAccessorPriority), 221 | m_initializeFunction(initializeFunction) 222 | { 223 | this->AddInputPorts(inputPortNames); 224 | this->AddOutputPorts(connectedOutputPortNames); 225 | } 226 | 227 | size_t Accessor::Impl::GetNumberOfInputPorts() const 228 | { 229 | return this->m_orderedInputPorts.size(); 230 | } 231 | 232 | size_t Accessor::Impl::GetNumberOfOutputPorts() const 233 | { 234 | return this->m_orderedOutputPorts.size(); 235 | } 236 | 237 | std::vector Accessor::Impl::GetOrderedInputPorts() const 238 | { 239 | return this->m_orderedInputPorts; 240 | } 241 | 242 | std::vector Accessor::Impl::GetOrderedOutputPorts() const 243 | { 244 | return this->m_orderedOutputPorts; 245 | } 246 | 247 | bool Accessor::Impl::HasInputPortWithName(const std::string& portName) const 248 | { 249 | return (this->m_inputPorts.find(portName) != this->m_inputPorts.end()); 250 | } 251 | 252 | bool Accessor::Impl::HasOutputPortWithName(const std::string& portName) const 253 | { 254 | return (this->m_outputPorts.find(portName) != this->m_outputPorts.end()); 255 | } 256 | 257 | void Accessor::Impl::AddOutputPort(const std::string& portName, bool isSpontaneous) 258 | { 259 | PRINT_VERBOSE("Accessor '%s' is creating a new%s output port \'%s\'", this->GetName().c_str(), isSpontaneous ? " spontaneous" : "", portName.c_str()); 260 | this->ValidatePortName(portName); 261 | this->m_outputPorts.emplace(portName, std::make_unique(portName, this, isSpontaneous)); 262 | this->m_orderedOutputPorts.push_back(this->m_outputPorts.at(portName).get()); 263 | } 264 | 265 | void Accessor::Impl::ValidatePortName(const std::string& portName) const 266 | { 267 | if (!this->NewPortNameIsValid(portName)) 268 | { 269 | std::ostringstream exceptionMessage; 270 | exceptionMessage << "Port name '" << portName << "' is invalid"; 271 | throw std::invalid_argument(exceptionMessage.str()); 272 | } 273 | } -------------------------------------------------------------------------------- /src/AccessorImpl.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef ACCESSOR_IMPL_H 5 | #define ACCESSOR_IMPL_H 6 | 7 | #include "AccessorFramework/Accessor.h" 8 | #include "Director.h" 9 | #include "Port.h" 10 | 11 | // Description 12 | // The Accessor::Impl class implements the Accessor class defined in Accessor.h. In addition, it exposes additional 13 | // functionality for internal use, such as public methods for getting the accessor's ports or parent objects. 14 | // 15 | class Accessor::Impl : public BaseObject 16 | { 17 | public: 18 | virtual ~Impl(); 19 | bool IsInitialized() const; 20 | virtual void Initialize(); 21 | void SetParent(CompositeAccessor::Impl* parent); 22 | int GetPriority() const; 23 | void SetPriority(int priority); 24 | virtual void ResetPriority(); 25 | virtual Director* GetDirector() const; 26 | bool HasInputPorts() const; 27 | bool HasOutputPorts() const; 28 | InputPort* GetInputPort(const std::string& portName) const; 29 | OutputPort* GetOutputPort(const std::string& portName) const; 30 | std::vector GetInputPorts() const; 31 | std::vector GetOutputPorts() const; 32 | bool operator<(const Accessor::Impl& other) const; 33 | bool operator>(const Accessor::Impl& other) const; 34 | 35 | virtual bool IsComposite() const = 0; 36 | 37 | static const int DefaultAccessorPriority; 38 | 39 | protected: 40 | // Accessor Methods 41 | int ScheduleCallback(std::function callback, int delayInMilliseconds, bool repeat); 42 | void ClearScheduledCallback(int callbackId); 43 | void ClearAllScheduledCallbacks(); 44 | bool NewPortNameIsValid(const std::string& newPortName) const; 45 | virtual void AddInputPort(const std::string& portName); 46 | virtual void AddInputPorts(const std::vector& portNames); 47 | virtual void AddOutputPort(const std::string& portName); 48 | virtual void AddOutputPorts(const std::vector& portNames); 49 | void ConnectMyInputToMyOutput(const std::string& myInputPortName, const std::string& myOutputPortName); 50 | void ConnectMyOutputToMyInput(const std::string& myOutputPortName, const std::string& myInputPortName); 51 | IEvent* GetLatestInput(const std::string& inputPortName) const; 52 | void SendOutput(const std::string& outputPortName, std::shared_ptr output); 53 | 54 | // Internal Methods 55 | Impl( 56 | const std::string& name, 57 | Accessor* container, 58 | std::function initializeFunction, 59 | const std::vector& inputPortNames = {}, 60 | const std::vector& connectedOutputPortNames = {}); 61 | size_t GetNumberOfInputPorts() const; 62 | size_t GetNumberOfOutputPorts() const; 63 | std::vector GetOrderedInputPorts() const; 64 | std::vector GetOrderedOutputPorts() const; 65 | bool HasInputPortWithName(const std::string& portName) const; 66 | bool HasOutputPortWithName(const std::string& portName) const; 67 | void AddOutputPort(const std::string& portName, bool isSpontaneous); 68 | 69 | int m_priority; 70 | Accessor* const m_container; 71 | 72 | private: 73 | friend class Accessor; 74 | friend void InputPort::ReceiveData(std::shared_ptr input); 75 | 76 | void AlertNewInput(); // should only be called in InputPort::ReceiveData() by input ports belonging to this accessor 77 | void ValidatePortName(const std::string& portName) const; 78 | 79 | bool m_initialized; 80 | std::function m_initializeFunction; 81 | std::set m_callbackIds; 82 | std::map> m_inputPorts; 83 | std::vector m_orderedInputPorts; 84 | std::map> m_outputPorts; 85 | std::vector m_orderedOutputPorts; 86 | }; 87 | 88 | #endif // ACCESSOR_IMPL_H 89 | -------------------------------------------------------------------------------- /src/AtomicAccessorImpl.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #include "AtomicAccessorImpl.h" 5 | #include "CompositeAccessorImpl.h" 6 | #include "PrintDebug.h" 7 | 8 | template 9 | static void SetSubtract(std::set& minuend, const std::set& subtrahend) 10 | { 11 | for (const auto& element : subtrahend) 12 | { 13 | minuend.erase(element); 14 | } 15 | } 16 | 17 | AtomicAccessor::Impl::Impl( 18 | const std::string& name, 19 | AtomicAccessor* container, 20 | std::function initializeFunction, 21 | const std::vector& inputPortNames, 22 | const std::vector& connectedOutputPortNames, 23 | const std::vector& spontaneousOutputPortNames, 24 | std::map> inputHandlers, 25 | std::function fireFunction) : 26 | Accessor::Impl(name, container, initializeFunction, inputPortNames, connectedOutputPortNames), 27 | m_inputHandlers(inputHandlers), 28 | m_fireFunction(fireFunction), 29 | m_stateDependsOnInputPort(false) 30 | { 31 | this->AddSpontaneousOutputPorts(spontaneousOutputPortNames); 32 | } 33 | 34 | bool AtomicAccessor::Impl::IsComposite() const 35 | { 36 | return false; 37 | } 38 | 39 | std::vector AtomicAccessor::Impl::GetEquivalentPorts(const InputPort* inputPort) const 40 | { 41 | if (this->m_forwardPrunedDependencies.empty() || this->GetNumberOfInputPorts() == 1 || this->GetNumberOfOutputPorts() == 0) 42 | { 43 | return this->GetInputPorts(); 44 | } 45 | 46 | std::set equivalentPorts{}; 47 | std::set dependentPorts{}; 48 | this->FindEquivalentPorts(inputPort, equivalentPorts, dependentPorts); 49 | return std::vector(equivalentPorts.begin(), equivalentPorts.end()); 50 | } 51 | 52 | std::vector AtomicAccessor::Impl::GetInputPortDependencies(const OutputPort* outputPort) const 53 | { 54 | const std::vector& allInputPorts = this->GetInputPorts(); 55 | if (this->m_backwardPrunedDependencies.find(outputPort) == this->m_backwardPrunedDependencies.end()) 56 | { 57 | return allInputPorts; 58 | } 59 | 60 | std::set inputPortDependencies(allInputPorts.begin(), allInputPorts.end()); 61 | SetSubtract(inputPortDependencies, this->m_backwardPrunedDependencies.at(outputPort)); 62 | return std::vector(inputPortDependencies.begin(), inputPortDependencies.end()); 63 | } 64 | 65 | std::vector AtomicAccessor::Impl::GetDependentOutputPorts(const InputPort* inputPort) const 66 | { 67 | const std::vector& allOutputPorts = this->GetOutputPorts(); 68 | if (this->m_forwardPrunedDependencies.find(inputPort) == this->m_forwardPrunedDependencies.end()) 69 | { 70 | return allOutputPorts; 71 | } 72 | 73 | std::set dependentOutputPorts(allOutputPorts.begin(), allOutputPorts.end()); 74 | SetSubtract(dependentOutputPorts, this->m_forwardPrunedDependencies.at(inputPort)); 75 | return std::vector(dependentOutputPorts.begin(), dependentOutputPorts.end()); 76 | } 77 | 78 | void AtomicAccessor::Impl::ProcessInputs() 79 | { 80 | PRINT_DEBUG("%s is reacting to inputs on all ports", this->GetName().c_str()); 81 | auto inputPorts = this->GetOrderedInputPorts(); 82 | for (InputPort* inputPort : inputPorts) 83 | { 84 | if (inputPort->IsWaitingForInputHandler()) 85 | { 86 | this->InvokeInputHandlers(inputPort->GetName()); 87 | inputPort->DequeueLatestInput(); 88 | if (inputPort->IsWaitingForInputHandler()) 89 | { 90 | // Schedule another reaction to process the next queued input 91 | auto myParent = static_cast(this->GetParent()); 92 | if (myParent != nullptr) 93 | { 94 | myParent->ScheduleReaction(this, this->GetPriority()); 95 | } 96 | 97 | inputPort->SendData(inputPort->ShareLatestInput()); 98 | } 99 | } 100 | } 101 | 102 | if (this->m_fireFunction != nullptr) 103 | { 104 | this->m_fireFunction(*(static_cast(this->m_container))); 105 | } 106 | 107 | PRINT_DEBUG("%s has finished reacting to all inputs", this->GetName().c_str()); 108 | } 109 | 110 | void AtomicAccessor::Impl::AccessorStateDependsOn(const std::string& inputPortName) 111 | { 112 | if (!this->HasInputPortWithName(inputPortName)) 113 | { 114 | throw std::invalid_argument("Input port not found"); 115 | } 116 | 117 | this->m_stateDependsOnInputPort = true; 118 | } 119 | 120 | void AtomicAccessor::Impl::RemoveDependency(const std::string& inputPortName, const std::string& outputPortName) 121 | { 122 | const InputPort* inputPort = this->GetInputPort(inputPortName); 123 | const OutputPort* outputPort = this->GetOutputPort(outputPortName); 124 | this->m_forwardPrunedDependencies[inputPort].insert(outputPort); 125 | this->m_backwardPrunedDependencies[outputPort].insert(inputPort); 126 | } 127 | 128 | void AtomicAccessor::Impl::RemoveDependencies(const std::string& inputPortName, const std::vector& outputPortNames) 129 | { 130 | for (const auto& outputPortName : outputPortNames) 131 | { 132 | this->RemoveDependency(inputPortName, outputPortName); 133 | } 134 | } 135 | 136 | void AtomicAccessor::Impl::AddSpontaneousOutputPort(const std::string& portName) 137 | { 138 | this->AddOutputPort(portName, true); 139 | auto inputPorts = this->GetInputPorts(); 140 | for (auto inputPort : inputPorts) 141 | { 142 | this->RemoveDependency(inputPort->GetName(), portName); 143 | } 144 | } 145 | 146 | void AtomicAccessor::Impl::AddSpontaneousOutputPorts(const std::vector& portNames) 147 | { 148 | for (const std::string& portName : portNames) 149 | { 150 | this->AddSpontaneousOutputPort(portName); 151 | } 152 | } 153 | 154 | void AtomicAccessor::Impl::AddInputHandler(const std::string& inputPortName, AtomicAccessor::InputHandler handler) 155 | { 156 | if (!this->HasInputPortWithName(inputPortName)) 157 | { 158 | throw std::invalid_argument("Input port not found"); 159 | } 160 | 161 | this->m_inputHandlers[inputPortName].push_back(handler); 162 | } 163 | 164 | void AtomicAccessor::Impl::AddInputHandlers(const std::string& inputPortName, const std::vector& handlers) 165 | { 166 | if (!this->HasInputPortWithName(inputPortName)) 167 | { 168 | throw std::invalid_argument("Input port not found"); 169 | } 170 | 171 | this->m_inputHandlers[inputPortName].insert(this->m_inputHandlers[inputPortName].end(), handlers.begin(), handlers.end()); 172 | } 173 | 174 | void AtomicAccessor::Impl::FindEquivalentPorts(const InputPort* inputPort, std::set& equivalentPorts, std::set& dependentPorts) const 175 | { 176 | if (equivalentPorts.find(inputPort) == equivalentPorts.end()) 177 | { 178 | equivalentPorts.insert(inputPort); 179 | const std::vector& dependentOutputPorts = this->GetDependentOutputPorts(inputPort); 180 | for (auto dependentOutputPort : dependentOutputPorts) 181 | { 182 | if (dependentPorts.find(dependentOutputPort) == dependentPorts.end()) 183 | { 184 | dependentPorts.insert(dependentOutputPort); 185 | const std::vector& inputPortDependencies = this->GetInputPortDependencies(dependentOutputPort); 186 | for (auto inputPortDependency : inputPortDependencies) 187 | { 188 | this->FindEquivalentPorts(inputPortDependency, equivalentPorts, dependentPorts); 189 | } 190 | } 191 | } 192 | } 193 | } 194 | 195 | void AtomicAccessor::Impl::InvokeInputHandlers(const std::string& inputPortName) 196 | { 197 | PRINT_DEBUG("%s is handling input on input port \"%s\"", this->GetName().c_str(), inputPortName.c_str()); 198 | 199 | IEvent* latestInput = this->GetLatestInput(inputPortName); 200 | const std::vector& inputHandlers = this->m_inputHandlers.at(inputPortName); 201 | for (auto it = inputHandlers.begin(); it != inputHandlers.end(); ++it) 202 | { 203 | try 204 | { 205 | (*it)(latestInput); 206 | } 207 | catch (const std::exception& /*e*/) 208 | { 209 | this->m_inputHandlers.at(inputPortName).erase(it); 210 | throw; 211 | } 212 | } 213 | } -------------------------------------------------------------------------------- /src/AtomicAccessorImpl.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef ATOMIC_ACCESSOR_IMPL_H 5 | #define ATOMIC_ACCESSOR_IMPL_H 6 | 7 | #include "AccessorImpl.h" 8 | 9 | // Description 10 | // The AtomicAccessorImpl implements the public AtomicAccessor interface defined in Accessor.h. In addition, it exposes 11 | // additional functionality for internal use, such as getting an setting the accessor's priority. All atomic accessors 12 | // are given a priority that is used by the Director to help prioritize scheduled callbacks. The priority is derived 13 | // using the causality imperitives implied by the model's port connections; in other words, we use a topological sort of 14 | // the directed graph created by the model's connectivity information. See HostImpl and Director for more details. 15 | // 16 | class AtomicAccessor::Impl : public Accessor::Impl 17 | { 18 | public: 19 | Impl( 20 | const std::string& name, 21 | AtomicAccessor* container, 22 | std::function initializeFunction, 23 | const std::vector& inputPortNames = {}, 24 | const std::vector& connectedOutputPortNames = {}, 25 | const std::vector& spontaneousOutputPortNames = {}, 26 | std::map> inputHandlers = {}, 27 | std::function fireFunction = nullptr); 28 | 29 | // Internal Methods 30 | bool IsComposite() const override; 31 | std::vector GetEquivalentPorts(const InputPort* inputPort) const; 32 | std::vector GetInputPortDependencies(const OutputPort* outputPort) const; 33 | std::vector GetDependentOutputPorts(const InputPort* inputPort) const; 34 | void ProcessInputs(); 35 | 36 | protected: 37 | // AtomicAccessor Methods 38 | void AccessorStateDependsOn(const std::string& inputPortName); 39 | void RemoveDependency(const std::string& inputPortName, const std::string& outputPortName); 40 | void RemoveDependencies(const std::string& inputPortName, const std::vector& outputPortNames); 41 | void AddSpontaneousOutputPort(const std::string& portName); 42 | void AddSpontaneousOutputPorts(const std::vector& portNames); 43 | void AddInputHandler(const std::string& inputPortName, AtomicAccessor::InputHandler handler); 44 | void AddInputHandlers(const std::string& inputPortName, const std::vector& handlers); 45 | 46 | private: 47 | friend class AtomicAccessor; 48 | 49 | void FindEquivalentPorts(const InputPort* inputPort, std::set& equivalentPorts, std::set& dependentPorts) const; 50 | void InvokeInputHandlers(const std::string& inputPortName); 51 | 52 | std::map> m_forwardPrunedDependencies; 53 | std::map> m_backwardPrunedDependencies; 54 | std::map> m_inputHandlers; 55 | std::function m_fireFunction; 56 | bool m_stateDependsOnInputPort; 57 | }; 58 | 59 | #endif // ATOMIC_ACCESSOR_IMPL_H 60 | -------------------------------------------------------------------------------- /src/BaseObject.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef BASE_OBJECT_H 5 | #define BASE_OBJECT_H 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | class BaseObject 12 | { 13 | public: 14 | virtual ~BaseObject() = default; 15 | std::string GetName() const 16 | { 17 | return this->m_name; 18 | } 19 | 20 | std::string GetFullName() const 21 | { 22 | std::string parentFullName = (this->m_parent == nullptr ? "" : this->m_parent->GetFullName()); 23 | return parentFullName.append(".").append(this->m_name); 24 | } 25 | 26 | static bool NameIsValid(const std::string& name) 27 | { 28 | // A name cannot be empty, cannot contain periods, and cannot contain whitespace 29 | return (!name.empty() && name.find_first_of(". \t\r\n") == name.npos); 30 | } 31 | 32 | protected: 33 | explicit BaseObject(const std::string& name, BaseObject* parent = nullptr) : 34 | m_name(name), 35 | m_parent(parent) 36 | { 37 | } 38 | 39 | void ValidateName() 40 | { 41 | if (!NameIsValid(this->m_name)) 42 | { 43 | throw std::invalid_argument("A name cannot be empty, cannot contain periods, and cannot contain whitespace"); 44 | } 45 | } 46 | 47 | BaseObject* GetParent() const 48 | { 49 | return this->m_parent; 50 | } 51 | 52 | void SetParent(BaseObject* parent) 53 | { 54 | if (this->m_parent == nullptr) 55 | { 56 | this->m_parent = parent; 57 | } 58 | else 59 | { 60 | std::ostringstream exceptionMessage; 61 | exceptionMessage << "Object '" << this->GetFullName() << "' already has a parent"; 62 | throw std::invalid_argument(exceptionMessage.str()); 63 | } 64 | } 65 | 66 | private: 67 | const std::string m_name; 68 | BaseObject* m_parent; 69 | }; 70 | 71 | #endif // BASE_OBJECT_H 72 | -------------------------------------------------------------------------------- /src/CancellationToken.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef CANCELLATION_TOKEN_H 5 | #define CANCELLATION_TOKEN_H 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | // Description 12 | // The CancellationToken is a wrapper for an atomic_bool with some convenience methods. This clarifies the intent when 13 | // the Director cancels scheduled execution tasks. 14 | // 15 | class CancellationToken 16 | { 17 | public: 18 | CancellationToken() : 19 | m_isCanceled(false) 20 | { 21 | this->m_timedLock.lock(); 22 | } 23 | 24 | ~CancellationToken() 25 | { 26 | if (!(this->m_isCanceled.load())) 27 | { 28 | this->m_timedLock.unlock(); 29 | } 30 | } 31 | 32 | void Cancel() 33 | { 34 | if (!(this->IsCanceled())) 35 | { 36 | this->m_isCanceled.store(true); 37 | this->m_timedLock.unlock(); 38 | } 39 | } 40 | 41 | bool IsCanceled() const 42 | { 43 | return this->m_isCanceled.load(); 44 | } 45 | 46 | template 47 | void SleepFor(const std::chrono::duration& duration) 48 | { 49 | using namespace std::literals::chrono_literals; 50 | 51 | // sleep in 1-hour chunks to avoid overflow error from very large duration 52 | auto timeLeft = duration; 53 | auto sleepInterval = 1h; 54 | while (timeLeft > std::chrono::duration::zero()) 55 | { 56 | auto timeToSleep = std::min, std::chrono::hours>>(timeLeft, sleepInterval); 57 | if (this->m_timedLock.try_lock_for(timeToSleep)) 58 | { 59 | this->m_timedLock.unlock(); 60 | break; 61 | } 62 | else 63 | { 64 | timeLeft -= timeToSleep; 65 | } 66 | } 67 | } 68 | 69 | private: 70 | std::atomic_bool m_isCanceled; 71 | std::timed_mutex m_timedLock; 72 | }; 73 | 74 | #endif // CANCELLATION_TOKEN_H 75 | -------------------------------------------------------------------------------- /src/CompositeAccessorImpl.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #include "CompositeAccessorImpl.h" 5 | #include "AtomicAccessorImpl.h" 6 | #include "PrintDebug.h" 7 | 8 | CompositeAccessor::Impl::Impl( 9 | const std::string& name, 10 | CompositeAccessor* container, 11 | std::function initializeFunction, 12 | const std::vector& inputPortNames, 13 | const std::vector& connectedOutputPortNames) : 14 | Accessor::Impl(name, container, initializeFunction, inputPortNames, connectedOutputPortNames), 15 | m_reactionRequested(false) 16 | { 17 | } 18 | 19 | CompositeAccessor::Impl::~Impl() 20 | { 21 | this->RemoveAllChildren(); 22 | } 23 | 24 | bool CompositeAccessor::Impl::HasChildWithName(const std::string& childName) const 25 | { 26 | return (this->m_children.find(childName) != this->m_children.end()); 27 | } 28 | 29 | Accessor::Impl* CompositeAccessor::Impl::GetChild(const std::string& childName) const 30 | { 31 | return this->m_children.at(childName)->GetImpl(); 32 | } 33 | 34 | std::vector CompositeAccessor::Impl::GetChildren() const 35 | { 36 | return this->m_orderedChildren; 37 | } 38 | 39 | void CompositeAccessor::Impl::ScheduleReaction(Accessor::Impl* child, int priority) 40 | { 41 | if (priority == INT_MAX) 42 | { 43 | priority = this->GetPriority(); 44 | } 45 | 46 | auto myParent = static_cast(this->GetParent()); 47 | if (myParent != nullptr) 48 | { 49 | this->m_childEventQueue.push(child); 50 | myParent->ScheduleReaction(this, priority); 51 | } 52 | else if (!this->m_reactionRequested) 53 | { 54 | this->m_reactionRequested = true; 55 | this->m_childEventQueue.push(child); 56 | this->GetDirector()->ScheduleCallback( 57 | [this]() { this->ProcessChildEventQueue(); }, 58 | 0 /*delayInMilliseconds*/, 59 | false /*repeat*/, 60 | priority); 61 | } 62 | else 63 | { 64 | this->m_childEventQueue.push(child); 65 | } 66 | } 67 | 68 | void CompositeAccessor::Impl::ProcessChildEventQueue() 69 | { 70 | while (!this->m_childEventQueue.empty()) 71 | { 72 | Accessor::Impl* child = this->m_childEventQueue.top(); 73 | this->m_childEventQueue.pop(); 74 | if (child->IsComposite()) 75 | { 76 | static_cast(child)->ProcessChildEventQueue(); 77 | } 78 | else 79 | { 80 | static_cast(child)->ProcessInputs(); 81 | } 82 | } 83 | 84 | this->m_reactionRequested = false; 85 | PRINT_DEBUG("%s has finished reacting to all inputs", this->GetName().c_str()); 86 | } 87 | 88 | void CompositeAccessor::Impl::ResetPriority() 89 | { 90 | Accessor::Impl::ResetPriority(); 91 | this->ResetChildrenPriorities(); 92 | } 93 | 94 | bool CompositeAccessor::Impl::IsComposite() const 95 | { 96 | return true; 97 | } 98 | 99 | void CompositeAccessor::Impl::Initialize() 100 | { 101 | Accessor::Impl::Initialize(); 102 | for (auto child : this->m_orderedChildren) 103 | { 104 | child->Initialize(); 105 | } 106 | } 107 | 108 | bool CompositeAccessor::Impl::NewChildNameIsValid(const std::string& newChildName) const 109 | { 110 | // A new child's name cannot be the same as the parent's name or the same as an existing child's name 111 | return (NameIsValid(newChildName) && newChildName != this->GetName() && !this->HasChildWithName(newChildName)); 112 | } 113 | 114 | void CompositeAccessor::Impl::AddChild(std::unique_ptr child) 115 | { 116 | std::string childName = child->GetName(); 117 | if (!this->NewChildNameIsValid(childName)) 118 | { 119 | throw std::invalid_argument("Child name is invalid"); 120 | } 121 | 122 | child->GetImpl()->SetParent(this); 123 | this->m_children.emplace(childName, std::move(child)); 124 | this->m_orderedChildren.push_back(this->m_children.at(childName)->GetImpl()); 125 | } 126 | 127 | void CompositeAccessor::Impl::RemoveChild(const std::string& childName) 128 | { 129 | for (auto it = this->m_orderedChildren.begin(); it != this->m_orderedChildren.end(); ++it) 130 | { 131 | if ((*it)->GetName() == childName) 132 | { 133 | this->m_orderedChildren.erase(it); 134 | break; 135 | } 136 | } 137 | 138 | this->m_children.erase(childName); 139 | } 140 | 141 | void CompositeAccessor::Impl::RemoveAllChildren() 142 | { 143 | while (!this->m_orderedChildren.empty()) 144 | { 145 | Accessor::Impl* child = *(this->m_orderedChildren.begin()); 146 | this->RemoveChild(child->GetName()); 147 | } 148 | } 149 | 150 | void CompositeAccessor::Impl::ConnectMyInputToChildInput(const std::string& myInputPortName, const std::string& childName, const std::string& childInputPortName) 151 | { 152 | Port::Connect(this->GetInputPort(myInputPortName), this->GetChild(childName)->GetInputPort(childInputPortName)); 153 | } 154 | 155 | void CompositeAccessor::Impl::ConnectChildOutputToMyOutput(const std::string& childName, const std::string& childOutputPortName, const std::string& myOutputPortName) 156 | { 157 | Port::Connect(this->GetChild(childName)->GetOutputPort(childOutputPortName), this->GetOutputPort(myOutputPortName)); 158 | } 159 | 160 | void CompositeAccessor::Impl::ConnectChildren( 161 | const std::string& sourceChildName, 162 | const std::string& sourceChildOutputPortName, 163 | const std::string& destinationChildName, 164 | const std::string& destinationChildInputPortName) 165 | { 166 | Port::Connect( 167 | this->GetChild(sourceChildName)->GetOutputPort(sourceChildOutputPortName), 168 | this->GetChild(destinationChildName)->GetInputPort(destinationChildInputPortName)); 169 | } 170 | 171 | void CompositeAccessor::Impl::ChildrenChanged() 172 | { 173 | auto myParent = static_cast(this->GetParent()); 174 | if (myParent != nullptr) 175 | { 176 | myParent->ChildrenChanged(); 177 | } 178 | 179 | for (auto child : this->m_orderedChildren) 180 | { 181 | if (!(child->IsInitialized())) 182 | { 183 | child->Initialize(); 184 | } 185 | } 186 | } 187 | 188 | void CompositeAccessor::Impl::ResetChildrenPriorities() const 189 | { 190 | for (auto child : this->m_orderedChildren) 191 | { 192 | child->ResetPriority(); 193 | } 194 | } -------------------------------------------------------------------------------- /src/CompositeAccessorImpl.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef COMPOSITE_ACCESSOR_IMPL_H 5 | #define COMPOSITE_ACCESSOR_IMPL_H 6 | 7 | #include "AccessorImpl.h" 8 | #include "UniquePriorityQueue.h" 9 | 10 | // Description 11 | // The CompositeAccessor::Impl class implements the CompositeAccessor class defined in Accessor.h. In addition, it 12 | // exposes additional functionality for internal use, such as public methods for getting the contained child accessors 13 | // and scheduling reactions for its children. Children's reactions are handled by storing a pointer to the child 14 | // requesting a reaction on a private queue and scheduling an immediate callback for invoking reactions for all children 15 | // on the queue. This mechanism ensures that a child can only schedule one reaction at a time and ensures that children 16 | // react in priority order. 17 | // 18 | class CompositeAccessor::Impl : public Accessor::Impl 19 | { 20 | public: 21 | explicit Impl( 22 | const std::string& name, 23 | CompositeAccessor* container, 24 | std::function initializeFunction, 25 | const std::vector& inputPortNames = {}, 26 | const std::vector& connectedOutputPortNames = {}); 27 | ~Impl(); 28 | bool HasChildWithName(const std::string& childName) const; 29 | Accessor::Impl* GetChild(const std::string& childName) const; 30 | std::vector GetChildren() const; 31 | void ScheduleReaction(Accessor::Impl* child, int priority); 32 | void ProcessChildEventQueue(); 33 | 34 | void ResetPriority() override; 35 | bool IsComposite() const override; 36 | void Initialize() override; 37 | 38 | protected: 39 | // CompositeAccessor Methods 40 | bool NewChildNameIsValid(const std::string& newChildName) const; 41 | void AddChild(std::unique_ptr child); 42 | void RemoveChild(const std::string& childName); 43 | void RemoveAllChildren(); 44 | void ConnectMyInputToChildInput(const std::string& myInputPortName, const std::string& childName, const std::string& childInputPortName); 45 | void ConnectChildOutputToMyOutput(const std::string& childName, const std::string& childOutputPortName, const std::string& myOutputPortName); 46 | void ConnectChildren( 47 | const std::string& sourceChildName, 48 | const std::string& sourceChildOutputPortName, 49 | const std::string& destinationChildName, 50 | const std::string& destinationChildInputPortName); 51 | virtual void ChildrenChanged(); 52 | 53 | // Internal Methods 54 | void ResetChildrenPriorities() const; 55 | 56 | private: 57 | friend class CompositeAccessor; 58 | 59 | // Returns true if accessor A has lower priority (i.e. higher priority value) than accessor B, and false otherwise. 60 | // When used in a priority queue, elements will be sorted from highest priority (i.e. lowest priority value) to 61 | // lowest priority (i.e. highest priority value). 62 | struct GreaterAccessorImplPtrs 63 | { 64 | bool operator()(Accessor::Impl* const a, Accessor::Impl* const b) const 65 | { 66 | if (a != nullptr && b != nullptr) 67 | { 68 | return (*a > *b); 69 | } 70 | else if (a != nullptr && b == nullptr) 71 | { 72 | return false; 73 | } 74 | else if (a == nullptr && b != nullptr) 75 | { 76 | return true; 77 | } 78 | else 79 | { 80 | // both are nullptr 81 | return false; 82 | } 83 | } 84 | }; 85 | 86 | bool m_reactionRequested; 87 | std::map> m_children; 88 | std::vector m_orderedChildren; 89 | unique_priority_queue, GreaterAccessorImplPtrs> m_childEventQueue; 90 | }; 91 | 92 | #endif // COMPOSITE_ACCESSOR_IMPL_H 93 | -------------------------------------------------------------------------------- /src/Director.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #include "Director.h" 5 | #include "PrintDebug.h" 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | static const long long DefaultNextExecutionTime = LLONG_MAX; 13 | 14 | Director::Director() : 15 | m_nextCallbackId(0), 16 | m_currentLogicalTime(PosixUtcInMilliseconds()), 17 | m_startTime(this->m_currentLogicalTime), 18 | m_nextScheduledExecutionTime(DefaultNextExecutionTime), 19 | m_executionResult(nullptr), 20 | m_executionCancellationToken(nullptr) 21 | { 22 | } 23 | 24 | Director::~Director() 25 | { 26 | this->Reset(); 27 | } 28 | 29 | int Director::ScheduleCallback( 30 | std::function callback, 31 | int delayInMilliseconds, 32 | bool isPeriodic, 33 | int priority) 34 | { 35 | ScheduledCallback newCallback{ callback, delayInMilliseconds, isPeriodic, priority }; 36 | newCallback.nextExecutionTimeInMilliseconds = this->m_currentLogicalTime + delayInMilliseconds; 37 | int newCallbackId = this->m_nextCallbackId++; 38 | this->m_scheduledCallbacks[newCallbackId] = newCallback; 39 | this->QueueScheduledCallback(newCallbackId); 40 | if (this->m_nextScheduledExecutionTime > newCallback.nextExecutionTimeInMilliseconds) 41 | { 42 | this->StopExecution(); 43 | this->m_nextScheduledExecutionTime = newCallback.nextExecutionTimeInMilliseconds; 44 | this->ScheduleNextExecution(); 45 | } 46 | 47 | return newCallbackId; 48 | } 49 | 50 | void Director::ClearScheduledCallback(int callbackId) 51 | { 52 | for (auto it = this->m_callbackQueue.begin(); it != this->m_callbackQueue.end(); ++it) 53 | { 54 | if (*it == callbackId) 55 | { 56 | this->m_callbackQueue.erase(it); 57 | break; 58 | } 59 | } 60 | 61 | this->RemoveScheduledCallbackFromMap(callbackId); 62 | if (this->NeedsReset()) 63 | { 64 | this->Reset(); 65 | } 66 | } 67 | 68 | void Director::HandlePriorityUpdate(int oldPriority, int newPriority) 69 | { 70 | for (auto& i : this->m_scheduledCallbacks) 71 | { 72 | if (i.second.priority == oldPriority) 73 | { 74 | i.second.priority = newPriority; 75 | for (auto it = this->m_callbackQueue.begin(); it != this->m_callbackQueue.end(); ++it) 76 | { 77 | if (*it == i.first) 78 | { 79 | this->m_callbackQueue.erase(it); 80 | this->QueueScheduledCallback(i.first); 81 | break; 82 | } 83 | } 84 | } 85 | } 86 | } 87 | 88 | void Director::Execute(int numberOfIterations) 89 | { 90 | if (this->m_executionCancellationToken.get() == nullptr || this->m_executionCancellationToken->IsCanceled()) 91 | { 92 | this->ScheduleNextExecution(); 93 | } 94 | 95 | auto executionResult = this->m_executionResult; 96 | int currentIteration = 0; 97 | while (this->m_executionCancellationToken != nullptr && 98 | !this->m_executionCancellationToken->IsCanceled() && 99 | executionResult->valid() && 100 | (numberOfIterations == 0 || currentIteration < numberOfIterations)) 101 | { 102 | PRINT_DEBUG("-----NEXT ROUND-----"); 103 | bool wasCanceled = executionResult->get(); 104 | if (wasCanceled && this->m_executionResult.get() == nullptr) 105 | { 106 | break; 107 | } 108 | else 109 | { 110 | executionResult = this->m_executionResult; 111 | if (numberOfIterations != 0) 112 | { 113 | ++currentIteration; 114 | } 115 | } 116 | } 117 | 118 | this->StopExecution(); 119 | } 120 | 121 | void Director::StopExecution() 122 | { 123 | if (this->m_executionCancellationToken.get() != nullptr) 124 | { 125 | this->m_executionCancellationToken->Cancel(); 126 | this->m_executionCancellationToken = nullptr; 127 | } 128 | } 129 | 130 | long long Director::GetNextQueuedExecutionTime() const 131 | { 132 | if (this->m_callbackQueue.empty()) 133 | { 134 | return DefaultNextExecutionTime; 135 | } 136 | else 137 | { 138 | return this->m_scheduledCallbacks.at(this->m_callbackQueue.front()).nextExecutionTimeInMilliseconds; 139 | } 140 | } 141 | 142 | void Director::ScheduleNextExecution() 143 | { 144 | long long executionDelayInMilliseconds = std::max(this->m_nextScheduledExecutionTime - PosixUtcInMilliseconds(), 0LL); 145 | this->m_executionCancellationToken = std::make_shared(); 146 | auto executionPromise = std::make_unique>(); 147 | this->m_executionResult = std::make_shared>(executionPromise->get_future()); 148 | 149 | bool retry = false; 150 | do 151 | { 152 | retry = false; 153 | try 154 | { 155 | std::thread executionThread( 156 | &Director::ExecuteInternal, 157 | this, 158 | executionDelayInMilliseconds, 159 | std::move(executionPromise), 160 | this->m_executionCancellationToken); 161 | 162 | executionThread.detach(); 163 | } 164 | catch (const std::system_error& e) 165 | { 166 | if (e.code() == std::errc::resource_unavailable_try_again) 167 | { 168 | retry = true; 169 | } 170 | else 171 | { 172 | throw; 173 | } 174 | } 175 | } while (retry); 176 | } 177 | 178 | void Director::ExecuteInternal(long long executionDelayInMilliseconds, std::unique_ptr> executionPromise, std::shared_ptr cancellationToken) 179 | { 180 | if (executionDelayInMilliseconds != 0LL) 181 | { 182 | auto executionDelay = std::chrono::milliseconds(executionDelayInMilliseconds); 183 | cancellationToken->SleepFor(executionDelay); 184 | } 185 | 186 | while (!cancellationToken->IsCanceled() && !this->NeedsReset() && this->m_nextScheduledExecutionTime <= PosixUtcInMilliseconds()) 187 | { 188 | try 189 | { 190 | this->ExecuteCallbacks(); 191 | } 192 | catch (...) 193 | { 194 | executionPromise->set_exception(std::current_exception()); 195 | return; 196 | } 197 | 198 | if (!(cancellationToken->IsCanceled())) 199 | { 200 | this->m_nextScheduledExecutionTime = this->GetNextQueuedExecutionTime(); 201 | } 202 | } 203 | 204 | bool executionWasCanceled = cancellationToken->IsCanceled(); 205 | if (!executionWasCanceled) 206 | { 207 | if (this->NeedsReset()) 208 | { 209 | this->Reset(); 210 | } 211 | 212 | this->ScheduleNextExecution(); 213 | } 214 | 215 | executionPromise->set_value(executionWasCanceled); 216 | } 217 | 218 | bool Director::ScheduledCallbackExistsInMap(int scheduledCallbackId) const 219 | { 220 | return (this->m_scheduledCallbacks.find(scheduledCallbackId) != this->m_scheduledCallbacks.end()); 221 | } 222 | 223 | void Director::RemoveScheduledCallbackFromMap(int scheduledCallbackId) 224 | { 225 | this->m_scheduledCallbacks.erase(scheduledCallbackId); 226 | } 227 | 228 | // Callbacks are sorted by execution time, then by accessor priority, then by callback ID (i.e. instantiation order) 229 | void Director::QueueScheduledCallback(int newCallbackId) 230 | { 231 | if (this->m_callbackQueue.empty()) 232 | { 233 | this->m_callbackQueue.push_back(newCallbackId); 234 | return; 235 | } 236 | 237 | size_t callbackQueueLength = this->m_callbackQueue.size(); 238 | size_t insertionIndex = 0; 239 | while (insertionIndex < callbackQueueLength) 240 | { 241 | const int queuedCallbackId(this->m_callbackQueue.at(insertionIndex)); 242 | 243 | // Sort Level 1: Execution Time 244 | if (this->m_scheduledCallbacks.at(newCallbackId).nextExecutionTimeInMilliseconds < 245 | this->m_scheduledCallbacks.at(queuedCallbackId).nextExecutionTimeInMilliseconds) 246 | { 247 | // New callback's execution time is sooner than queued callback's execution time 248 | break; 249 | } 250 | else if (this->m_scheduledCallbacks.at(newCallbackId).nextExecutionTimeInMilliseconds > 251 | this->m_scheduledCallbacks.at(queuedCallbackId).nextExecutionTimeInMilliseconds) 252 | { 253 | // New callback's execution time is later than queued callback's execution time 254 | ++insertionIndex; 255 | } 256 | else 257 | { 258 | // Execution times are equal 259 | // Sort Level 2: Accessor Priority 260 | if (this->m_scheduledCallbacks.at(newCallbackId).priority < this->m_scheduledCallbacks.at(queuedCallbackId).priority) 261 | { 262 | // New callback's priority is higher than queued callback's priority 263 | break; 264 | } 265 | else if (this->m_scheduledCallbacks.at(newCallbackId).priority > this->m_scheduledCallbacks.at(queuedCallbackId).priority) 266 | { 267 | // New callback's priority is lower than queued callback's priority 268 | ++insertionIndex; 269 | } 270 | else 271 | { 272 | // Priorities are equal 273 | // Sort Level 3: Callback ID 274 | if (newCallbackId < queuedCallbackId) 275 | { 276 | // new callback's ID is lower than queued callback's ID 277 | break; 278 | } 279 | else if (newCallbackId > queuedCallbackId) 280 | { 281 | // new callback's ID is higher than queued callback's ID 282 | ++insertionIndex; 283 | } 284 | else 285 | { 286 | // Trying to queue two callbacks with the same ID should never happen. 287 | // If it does, it is indicative of a bug in the Director. 288 | assert(queuedCallbackId != newCallbackId); 289 | } 290 | } 291 | } 292 | } 293 | 294 | assert(insertionIndex <= callbackQueueLength); 295 | auto insertionIt = (insertionIndex == callbackQueueLength ? this->m_callbackQueue.end() : this->m_callbackQueue.begin() + insertionIndex); 296 | this->m_callbackQueue.insert(insertionIt, newCallbackId); 297 | } 298 | 299 | void Director::ExecuteCallbacks() 300 | { 301 | this->m_currentLogicalTime = this->m_nextScheduledExecutionTime; 302 | PRINT_DEBUG("Current logical time is t + %lld ms", this->m_currentLogicalTime - this->m_startTime); 303 | while (!this->m_callbackQueue.empty() && this->GetNextQueuedExecutionTime() <= this->m_nextScheduledExecutionTime) 304 | { 305 | int callbackId = this->m_callbackQueue.front(); 306 | this->m_callbackQueue.erase(this->m_callbackQueue.begin()); 307 | try 308 | { 309 | this->m_scheduledCallbacks.at(callbackId).callbackFunction(); 310 | } 311 | catch (const std::exception& e) 312 | { 313 | this->RemoveScheduledCallbackFromMap(callbackId); 314 | throw; 315 | } 316 | 317 | if (this->ScheduledCallbackExistsInMap(callbackId)) 318 | { 319 | // Callback did not cancel itself - either reschedule (if periodic) or remove 320 | if (this->m_scheduledCallbacks.at(callbackId).isPeriodic) 321 | { 322 | // Schedule next occurrence of this periodic callback 323 | this->m_scheduledCallbacks.at(callbackId).nextExecutionTimeInMilliseconds += 324 | this->m_scheduledCallbacks.at(callbackId).delayInMilliseconds; 325 | this->QueueScheduledCallback(callbackId); 326 | } 327 | else 328 | { 329 | this->RemoveScheduledCallbackFromMap(callbackId); 330 | } 331 | } 332 | } 333 | } 334 | 335 | bool Director::NeedsReset() const 336 | { 337 | return (this->m_callbackQueue.empty() || this->m_scheduledCallbacks.empty()); 338 | } 339 | 340 | void Director::Reset() 341 | { 342 | this->StopExecution(); 343 | this->m_callbackQueue.clear(); 344 | this->m_scheduledCallbacks.clear(); 345 | this->m_nextCallbackId = 0; 346 | this->m_currentLogicalTime = PosixUtcInMilliseconds(); 347 | this->m_startTime = this->m_currentLogicalTime; 348 | PRINT_DEBUG("Resetting current logical time to 0"); 349 | this->m_nextScheduledExecutionTime = DefaultNextExecutionTime; 350 | } 351 | 352 | // Returns number of milliseconds elapsed since 01/01/1970 00:00:00 UTC 353 | long long Director::PosixUtcInMilliseconds() 354 | { 355 | struct timespec now; 356 | int err = timespec_get(&now, TIME_UTC); 357 | if (err == 0) 358 | { 359 | return -1; 360 | } 361 | 362 | return (((long long)now.tv_sec) * 1000LL) + (((long long)now.tv_nsec) / 1000000LL); 363 | } -------------------------------------------------------------------------------- /src/Director.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef DIRECTOR_H 5 | #define DIRECTOR_H 6 | 7 | #include "CancellationToken.h" 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | // Description 17 | // The Director manages and executes the accessor model's global callback queue. There is only one director per model. 18 | // The Director prioritizes callbacks first by next execution time, then by the calling accessor's priority, and lastly 19 | // by a monotonically increasing callback ID. This callback ID enables the calling accessor to cancel the scheduled 20 | // callback, and it also ensures that two callbacks scheduled in a given order by a single accessor will execute in the 21 | // order in which they were scheduled. The execution time is calculated using a logical clock loosely tied to physical 22 | // time. However, while physical time is continuous, logical clocks are discrete; that is, the time on the logical clock 23 | // "jumps" instantaneously from one time to the next when the callbacks on the queue are executed. This allows the queued 24 | // callbacks to be executed synchronously while making it appear to the accessors as if they execute atomically and 25 | // concurrently, enabling asynchronous yet coordinated reactions without explicit thread management or locks. 26 | // 27 | class Director 28 | { 29 | public: 30 | Director(); 31 | ~Director(); 32 | int ScheduleCallback( 33 | std::function callback, 34 | int delayInMilliseconds, 35 | bool isPeriodic = false, 36 | int priority = INT_MAX); 37 | 38 | void ClearScheduledCallback(int callbackId); 39 | void HandlePriorityUpdate(int oldPriority, int newPriority); 40 | void Execute(int numberOfIterations = 0); 41 | void StopExecution(); 42 | 43 | private: 44 | class ScheduledCallback 45 | { 46 | public: 47 | std::function callbackFunction = nullptr; 48 | int delayInMilliseconds = 0; 49 | bool isPeriodic = false; 50 | int priority = INT_MAX; 51 | long long nextExecutionTimeInMilliseconds = 0; 52 | }; 53 | 54 | long long GetNextQueuedExecutionTime() const; 55 | void ScheduleNextExecution(); 56 | void ExecuteInternal( 57 | long long executionDelayInMilliseconds, 58 | std::unique_ptr> executionPromise, 59 | std::shared_ptr cancellationToken); 60 | 61 | bool ScheduledCallbackExistsInMap(int scheduledCallbackId) const; 62 | void RemoveScheduledCallbackFromMap(int scheduledCallbackId); 63 | void QueueScheduledCallback(int newCallbackId); 64 | void ExecuteCallbacks(); 65 | bool NeedsReset() const; 66 | void Reset(); 67 | 68 | int m_nextCallbackId; 69 | std::map m_scheduledCallbacks; 70 | std::vector m_callbackQueue; 71 | long long m_currentLogicalTime; 72 | long long m_startTime; 73 | long long m_nextScheduledExecutionTime; 74 | std::shared_ptr> m_executionResult; 75 | std::shared_ptr m_executionCancellationToken; 76 | 77 | static long long PosixUtcInMilliseconds(); 78 | }; 79 | 80 | #endif // DIRECTOR_H 81 | -------------------------------------------------------------------------------- /src/Host.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #include "AccessorFramework/Host.h" 5 | #include "HostImpl.h" 6 | #include "HostHypervisorImpl.h" 7 | #include 8 | 9 | Host::~Host() = default; 10 | 11 | Host::State Host::GetState() const 12 | { 13 | return static_cast(this->GetImpl())->GetState(); 14 | } 15 | 16 | bool Host::EventListenerIsRegistered(int listenerId) const 17 | { 18 | return static_cast(this->GetImpl())->EventListenerIsRegistered(listenerId); 19 | } 20 | 21 | int Host::AddEventListener(std::weak_ptr listener) 22 | { 23 | return static_cast(this->GetImpl())->AddEventListener(std::move(listener)); 24 | } 25 | 26 | void Host::RemoveEventListener(int listenerId) 27 | { 28 | static_cast(this->GetImpl())->RemoveEventListener(listenerId); 29 | } 30 | 31 | void Host::Setup() 32 | { 33 | static_cast(this->GetImpl())->Setup(); 34 | } 35 | 36 | void Host::Iterate(int numberOfIterations) 37 | { 38 | static_cast(this->GetImpl())->Iterate(numberOfIterations); 39 | } 40 | 41 | void Host::Pause() 42 | { 43 | static_cast(this->GetImpl())->Pause(); 44 | } 45 | 46 | void Host::Run() 47 | { 48 | static_cast(this->GetImpl())->Run(); 49 | } 50 | 51 | void Host::RunOnCurrentThread() 52 | { 53 | static_cast(this->GetImpl())->RunOnCurrentThread(); 54 | } 55 | 56 | void Host::Exit() 57 | { 58 | static_cast(this->GetImpl())->Exit(); 59 | } 60 | 61 | void Host::AdditionalSetup() 62 | { 63 | // base implementation does nothing 64 | } 65 | 66 | Host::Host(const std::string& name) : 67 | CompositeAccessor(std::make_unique(name, this, &Host::Initialize)) 68 | { 69 | } 70 | 71 | HostHypervisor::HostHypervisor() : 72 | m_impl(std::make_unique()) 73 | { 74 | } 75 | 76 | HostHypervisor::~HostHypervisor() 77 | { 78 | this->RemoveAllHosts(); 79 | } 80 | 81 | int HostHypervisor::AddHost(std::unique_ptr host) 82 | { 83 | return this->m_impl->AddHost(std::move(host)); 84 | } 85 | 86 | void HostHypervisor::RemoveHost(int hostId) 87 | { 88 | this->m_impl->RemoveHost(hostId); 89 | } 90 | 91 | std::string HostHypervisor::GetHostName(int hostId) const 92 | { 93 | return this->m_impl->GetHostName(hostId); 94 | } 95 | 96 | Host::State HostHypervisor::GetHostState(int hostId) const 97 | { 98 | return this->m_impl->GetHostState(hostId); 99 | } 100 | 101 | void HostHypervisor::SetupHost(int hostId) const 102 | { 103 | this->m_impl->SetupHost(hostId); 104 | } 105 | 106 | void HostHypervisor::PauseHost(int hostId) const 107 | { 108 | this->m_impl->PauseHost(hostId); 109 | } 110 | 111 | void HostHypervisor::RunHost(int hostId) const 112 | { 113 | this->m_impl->RunHost(hostId); 114 | } 115 | 116 | void HostHypervisor::RemoveAllHosts() 117 | { 118 | this->m_impl->RemoveAllHosts(); 119 | } 120 | 121 | std::map HostHypervisor::GetHostNames() const 122 | { 123 | return this->m_impl->GetHostNames(); 124 | } 125 | 126 | std::map HostHypervisor::GetHostStates() const 127 | { 128 | return this->m_impl->GetHostStates(); 129 | } 130 | 131 | void HostHypervisor::SetupHosts() const 132 | { 133 | this->m_impl->SetupHosts(); 134 | } 135 | 136 | void HostHypervisor::PauseHosts() const 137 | { 138 | this->m_impl->PauseHosts(); 139 | } 140 | 141 | void HostHypervisor::RunHosts() const 142 | { 143 | this->m_impl->RunHosts(); 144 | } 145 | 146 | void HostHypervisor::RunHostsOnCurrentThread() const 147 | { 148 | this->m_impl->RunHostsOnCurrentThread(); 149 | } -------------------------------------------------------------------------------- /src/HostHypervisorImpl.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #include "HostHypervisorImpl.h" 5 | #include 6 | #include 7 | 8 | HostHypervisor::Impl::Impl() 9 | { 10 | std::atomic_init(&m_nextHostId, 0); 11 | } 12 | 13 | HostHypervisor::Impl::~Impl() = default; 14 | 15 | int HostHypervisor::Impl::AddHost(std::unique_ptr host) 16 | { 17 | int hostId = this->m_nextHostId++; 18 | this->m_hosts.emplace(hostId, std::move(host)); 19 | return hostId; 20 | } 21 | 22 | void HostHypervisor::Impl::RemoveHost(int hostId) 23 | { 24 | this->m_hosts.erase(hostId); 25 | } 26 | 27 | std::string HostHypervisor::Impl::GetHostName(int hostId) const 28 | { 29 | return this->m_hosts.at(hostId)->GetName(); 30 | } 31 | 32 | Host::State HostHypervisor::Impl::GetHostState(int hostId) const 33 | { 34 | return this->m_hosts.at(hostId)->GetState(); 35 | } 36 | 37 | void HostHypervisor::Impl::SetupHost(int hostId) const 38 | { 39 | this->m_hosts.at(hostId)->Setup(); 40 | } 41 | 42 | void HostHypervisor::Impl::PauseHost(int hostId) const 43 | { 44 | this->m_hosts.at(hostId)->Pause(); 45 | } 46 | 47 | void HostHypervisor::Impl::RunHost(int hostId) const 48 | { 49 | this->m_hosts.at(hostId)->Run(); 50 | } 51 | 52 | void HostHypervisor::Impl::RemoveAllHosts() 53 | { 54 | this->m_hosts.clear(); 55 | } 56 | 57 | std::map HostHypervisor::Impl::GetHostNames() const 58 | { 59 | return this->RunMethodOnAllHostsWithResult(&HostHypervisor::Impl::GetHostName); 60 | } 61 | 62 | std::map HostHypervisor::Impl::GetHostStates() const 63 | { 64 | return this->RunMethodOnAllHostsWithResult(&HostHypervisor::Impl::GetHostState); 65 | } 66 | 67 | void HostHypervisor::Impl::SetupHosts() const 68 | { 69 | this->RunMethodOnAllHosts(&HostHypervisor::Impl::SetupHost); 70 | } 71 | 72 | void HostHypervisor::Impl::PauseHosts() const 73 | { 74 | this->RunMethodOnAllHosts(&HostHypervisor::Impl::PauseHost); 75 | } 76 | 77 | void HostHypervisor::Impl::RunHosts() const 78 | { 79 | this->RunMethodOnAllHosts(&HostHypervisor::Impl::RunHost); 80 | } 81 | 82 | void HostHypervisor::Impl::RunHostsOnCurrentThread() const 83 | { 84 | for (auto it = ++this->m_hosts.begin(); it != this->m_hosts.end(); ++it) 85 | { 86 | it->second->Run(); 87 | } 88 | 89 | this->m_hosts.begin()->second->RunOnCurrentThread(); 90 | } 91 | 92 | void HostHypervisor::Impl::RunMethodOnAllHosts(std::function hypervisorMethod) const 93 | { 94 | std::vector> tasks; 95 | for (auto it = this->m_hosts.begin(); it != this->m_hosts.end(); ++it) 96 | { 97 | tasks.emplace_back(std::async( 98 | std::launch::async, 99 | [this, &hypervisorMethod](int hostId) 100 | { 101 | hypervisorMethod(*this, hostId); 102 | }, 103 | it->first)); 104 | } 105 | 106 | while (!tasks.empty()) 107 | { 108 | tasks.back().wait(); 109 | tasks.pop_back(); 110 | } 111 | } -------------------------------------------------------------------------------- /src/HostHypervisorImpl.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef HOST_HYPERVISOR_IMPL_H 5 | #define HOST_HYPERVISOR_IMPL_H 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include "AccessorFramework/Host.h" 12 | 13 | class HostHypervisor::Impl 14 | { 15 | public: 16 | Impl(); 17 | ~Impl(); 18 | 19 | protected: 20 | int AddHost(std::unique_ptr host); 21 | void RemoveHost(int hostId); 22 | std::string GetHostName(int hostId) const; 23 | Host::State GetHostState(int hostId) const; 24 | void SetupHost(int hostId) const; 25 | void PauseHost(int hostId) const; 26 | void RunHost(int hostId) const; 27 | 28 | void RemoveAllHosts(); 29 | std::map GetHostNames() const; 30 | std::map GetHostStates() const; 31 | void SetupHosts() const; 32 | void PauseHosts() const; 33 | void RunHosts() const; 34 | void RunHostsOnCurrentThread() const; 35 | 36 | private: 37 | friend class HostHypervisor; 38 | 39 | void RunMethodOnAllHosts(std::function hypervisorMethod) const; 40 | 41 | template 42 | std::map RunMethodOnAllHostsWithResult(std::function hypervisorMethod) const 43 | { 44 | std::map results; 45 | std::mutex resultsMutex; 46 | std::vector> tasks; 47 | for (auto it = this->m_hosts.begin(); it != this->m_hosts.end(); ++it) 48 | { 49 | tasks.emplace_back(std::async( 50 | std::launch::async, 51 | [this, &hypervisorMethod, &results, &resultsMutex](int hostId) 52 | { 53 | T result = hypervisorMethod(*this, hostId); 54 | std::lock_guard lock(resultsMutex); 55 | results.emplace(hostId, result); 56 | }, 57 | it->first)); 58 | } 59 | 60 | while (!tasks.empty()) 61 | { 62 | tasks.back().wait(); 63 | tasks.pop_back(); 64 | } 65 | 66 | return results; 67 | } 68 | 69 | std::atomic_int m_nextHostId; 70 | std::map> m_hosts; 71 | }; 72 | 73 | #endif // HOST_HYPERVISOR_IMPL_H 74 | -------------------------------------------------------------------------------- /src/HostImpl.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #include "AtomicAccessorImpl.h" 5 | #include "CompositeAccessorImpl.h" 6 | #include "HostImpl.h" 7 | #include "PrintDebug.h" 8 | #include 9 | #include 10 | 11 | static const int UpdateModelPriority = 0; 12 | static const int HostPriority = UpdateModelPriority + 1; 13 | 14 | Host::Impl::Impl(const std::string& name, Host* container, std::function initializeFunction) : 15 | CompositeAccessor::Impl(name, container, initializeFunction), 16 | m_state(Host::State::NeedsSetup), 17 | m_director(std::make_unique()), 18 | m_nextListenerId(0) 19 | { 20 | this->m_priority = HostPriority; 21 | } 22 | 23 | Host::Impl::~Impl() 24 | { 25 | this->RemoveAllChildren(); 26 | this->ClearAllScheduledCallbacks(); 27 | this->m_director.reset(nullptr); 28 | } 29 | 30 | Host::State Host::Impl::GetState() const 31 | { 32 | return this->m_state.load(); 33 | } 34 | 35 | bool Host::Impl::EventListenerIsRegistered(int listenerId) const 36 | { 37 | bool registered = (this->m_listeners.find(listenerId) != this->m_listeners.end()); 38 | return registered; 39 | } 40 | 41 | int Host::Impl::AddEventListener(std::weak_ptr listener) 42 | { 43 | int listenerId = this->m_nextListenerId++; 44 | this->m_listeners.emplace(listenerId, std::move(listener)); 45 | return listenerId; 46 | } 47 | 48 | void Host::Impl::RemoveEventListener(int listenerId) 49 | { 50 | this->m_listeners.erase(listenerId); 51 | } 52 | 53 | void Host::Impl::Setup() 54 | { 55 | if (this->m_state.load() != Host::State::NeedsSetup) 56 | { 57 | throw std::logic_error("Host does not need setup"); 58 | } 59 | 60 | this->SetState(Host::State::SettingUp); 61 | static_cast(this->m_container)->AdditionalSetup(); 62 | this->ComputeAccessorPriorities(); 63 | this->Initialize(); 64 | this->SetState(Host::State::ReadyToRun); 65 | } 66 | 67 | void Host::Impl::Iterate(int numberOfIterations) 68 | { 69 | this->ValidateHostCanRun(); 70 | this->SetState(Host::State::Running); 71 | 72 | try 73 | { 74 | this->m_director->Execute(numberOfIterations); 75 | } 76 | catch (const std::exception& e) 77 | { 78 | this->m_state.store(Host::State::Corrupted); 79 | this->NotifyListenersOfException(e); 80 | } 81 | 82 | this->SetState(Host::State::Paused); 83 | } 84 | 85 | void Host::Impl::Pause() 86 | { 87 | if (this->m_state.load() != Host::State::Running) 88 | { 89 | throw std::logic_error("Host is not running"); 90 | } 91 | 92 | this->m_director->StopExecution(); 93 | this->SetState(Host::State::Paused); 94 | } 95 | 96 | void Host::Impl::Run() 97 | { 98 | this->ValidateHostCanRun(); 99 | bool retry = false; 100 | do 101 | { 102 | retry = false; 103 | try 104 | { 105 | std::thread(&Host::Impl::RunOnCurrentThread, this).detach(); 106 | } 107 | catch (const std::system_error& e) 108 | { 109 | if (e.code() == std::errc::resource_unavailable_try_again) 110 | { 111 | retry = true; 112 | } 113 | else 114 | { 115 | throw; 116 | } 117 | } 118 | } while (retry); 119 | } 120 | 121 | void Host::Impl::RunOnCurrentThread() 122 | { 123 | this->ValidateHostCanRun(); 124 | this->SetState(Host::State::Running); 125 | 126 | try 127 | { 128 | this->m_director->Execute(); 129 | } 130 | catch (const std::exception& e) 131 | { 132 | this->m_state.store(Host::State::Corrupted); 133 | this->NotifyListenersOfException(e); 134 | } 135 | 136 | this->SetState(Host::State::Paused); 137 | } 138 | 139 | void Host::Impl::Exit() 140 | { 141 | this->SetState(Host::State::Exiting); 142 | this->m_director->StopExecution(); 143 | this->SetState(Host::State::Finished); 144 | } 145 | 146 | void Host::Impl::AddInputPort(const std::string& portName) 147 | { 148 | throw std::logic_error("Hosts are not allowed to have ports"); 149 | } 150 | 151 | void Host::Impl::AddInputPorts(const std::vector& portNames) 152 | { 153 | throw std::logic_error("Hosts are not allowed to have ports"); 154 | } 155 | 156 | void Host::Impl::AddOutputPort(const std::string& portName) 157 | { 158 | throw std::logic_error("Hosts are not allowed to have ports"); 159 | } 160 | 161 | void Host::Impl::AddOutputPorts(const std::vector& portNames) 162 | { 163 | throw std::logic_error("Hosts are not allowed to have ports"); 164 | } 165 | 166 | void Host::Impl::ChildrenChanged() 167 | { 168 | this->m_priority = UpdateModelPriority; 169 | this->ScheduleCallback( 170 | [this]() 171 | { 172 | PRINT_DEBUG("%s is updating the model", this->GetName().c_str()); 173 | this->ComputeAccessorPriorities(true /*updateCallbacks*/); 174 | for (auto child : this->GetChildren()) 175 | { 176 | if (!(child->IsInitialized())) 177 | { 178 | child->Initialize(); 179 | } 180 | } 181 | }, 182 | 0 /*delayInMilliseconds*/, 183 | false /*repeat*/ 184 | ); 185 | 186 | this->m_priority = HostPriority; 187 | } 188 | 189 | void Host::Impl::ResetPriority() 190 | { 191 | this->m_priority = HostPriority; 192 | this->ResetChildrenPriorities(); 193 | } 194 | 195 | Director* Host::Impl::GetDirector() const 196 | { 197 | return this->m_director.get(); 198 | } 199 | 200 | void Host::Impl::ValidateHostCanRun() const 201 | { 202 | if (this->m_state.load() == Host::State::Running) 203 | { 204 | throw std::logic_error("Host is already running"); 205 | } 206 | else if (this->m_state.load() != Host::State::ReadyToRun && this->m_state.load() != Host::State::Paused) 207 | { 208 | throw std::logic_error("Host is not in a runnable state"); 209 | } 210 | } 211 | 212 | void Host::Impl::SetState(Host::State newState) 213 | { 214 | Host::State oldState = this->m_state.exchange(newState); 215 | if (oldState != newState) 216 | { 217 | this->NotifyListenersOfStateChange(oldState, newState); 218 | } 219 | } 220 | 221 | void Host::Impl::ComputeAccessorPriorities(bool updateCallbacks) 222 | { 223 | std::map> accessorDepths{}; 224 | std::map portDepths{}; 225 | this->ComputeCompositeAccessorDepth(this, portDepths, accessorDepths); 226 | int priority = HostPriority; 227 | for (auto entry : accessorDepths) 228 | { 229 | priority = std::max(priority, entry.first); 230 | for (auto accessor : entry.second) 231 | { 232 | if (updateCallbacks) 233 | { 234 | int oldPriority = accessor->GetPriority(); 235 | this->m_director->HandlePriorityUpdate(oldPriority, priority); 236 | } 237 | 238 | accessor->SetPriority(priority); 239 | ++priority; 240 | } 241 | } 242 | } 243 | 244 | int Host::Impl::ComputeCompositeAccessorDepth(CompositeAccessor::Impl* compositeAccessor, std::map& portDepths, std::map>& accessorDepths) 245 | { 246 | int minChildDepth = INT_MAX; 247 | for (auto child : compositeAccessor->GetChildren()) 248 | { 249 | int childDepth = 0; 250 | if (child->IsComposite()) 251 | { 252 | childDepth = this->ComputeCompositeAccessorDepth(static_cast(child), portDepths, accessorDepths); 253 | } 254 | else 255 | { 256 | childDepth = this->ComputeAtomicAccessorDepth(static_cast(child), portDepths, accessorDepths); 257 | } 258 | 259 | minChildDepth = std::min(minChildDepth, childDepth); 260 | } 261 | 262 | int accessorDepth = minChildDepth; 263 | (accessorDepths[accessorDepth]).insert((accessorDepths[accessorDepth]).begin(), compositeAccessor); 264 | return accessorDepth; 265 | } 266 | 267 | int Host::Impl::ComputeAtomicAccessorDepth(AtomicAccessor::Impl* atomicAccessor, std::map& portDepths, std::map>& accessorDepths) 268 | { 269 | int maximumInputDepth = 0; 270 | for (auto inputPort : atomicAccessor->GetInputPorts()) 271 | { 272 | if (portDepths.find(inputPort) == portDepths.end()) 273 | { 274 | std::set visitedInputPorts{}; 275 | std::set visitedOutputPorts{}; 276 | this->ComputeAtomicAccessorInputPortDepth(inputPort, portDepths, visitedInputPorts, visitedOutputPorts); 277 | } 278 | 279 | if (portDepths.at(inputPort) > maximumInputDepth) 280 | { 281 | maximumInputDepth = portDepths.at(inputPort); 282 | } 283 | } 284 | 285 | int minimumOutputDepth = INT_MAX; 286 | for (auto outputPort : atomicAccessor->GetOutputPorts()) 287 | { 288 | if (portDepths.find(outputPort) == portDepths.end()) 289 | { 290 | std::set visitedInputPorts{}; 291 | std::set visitedOutputPorts{}; 292 | this->ComputeAtomicAccessorOutputPortDepth(outputPort, portDepths, visitedInputPorts, visitedOutputPorts); 293 | } 294 | 295 | if (portDepths.at(outputPort) < minimumOutputDepth) 296 | { 297 | minimumOutputDepth = portDepths.at(outputPort); 298 | } 299 | } 300 | 301 | int accessorDepth = (atomicAccessor->HasOutputPorts() ? minimumOutputDepth : maximumInputDepth); 302 | accessorDepths[accessorDepth].push_back(atomicAccessor); 303 | return accessorDepth; 304 | } 305 | 306 | void Host::Impl::ComputeAtomicAccessorInputPortDepth(const InputPort* inputPort, std::map& portDepths, std::set& visitedInputPorts, std::set& visitedOutputPorts) 307 | { 308 | int depth = 0; 309 | auto equivalentPorts = static_cast(inputPort->GetOwner())->GetEquivalentPorts(inputPort); 310 | for (auto equivalentPort : equivalentPorts) 311 | { 312 | visitedInputPorts.insert(equivalentPort); 313 | if (equivalentPort->IsConnectedToSource()) 314 | { 315 | const OutputPort* sourceOutputPort = GetSourceOutputPort(equivalentPort); 316 | if (sourceOutputPort == nullptr) 317 | { 318 | // not connected to source 319 | continue; 320 | } 321 | 322 | if (portDepths.find(sourceOutputPort) == portDepths.end()) 323 | { 324 | if (visitedOutputPorts.find(sourceOutputPort) != visitedOutputPorts.end()) 325 | { 326 | std::ostringstream exceptionMessage; 327 | exceptionMessage << "Detected causality loop involving port " << sourceOutputPort->GetFullName(); 328 | throw std::logic_error(exceptionMessage.str()); 329 | } 330 | else 331 | { 332 | this->ComputeAtomicAccessorOutputPortDepth(sourceOutputPort, portDepths, visitedInputPorts, visitedOutputPorts); 333 | } 334 | } 335 | 336 | int newDepth = portDepths.at(sourceOutputPort) + 1; 337 | if (depth < newDepth) 338 | { 339 | depth = newDepth; 340 | } 341 | } 342 | } 343 | 344 | for (auto equivalentPort : equivalentPorts) 345 | { 346 | PRINT_VERBOSE("Input port '%s' is now priority %d", equivalentPort->GetFullName().c_str(), depth); 347 | portDepths[equivalentPort] = depth; 348 | } 349 | } 350 | 351 | void Host::Impl::ComputeAtomicAccessorOutputPortDepth(const OutputPort* outputPort, std::map& portDepths, std::set& visitedInputPorts, std::set& visitedOutputPorts) 352 | { 353 | visitedOutputPorts.insert(outputPort); 354 | int depth = 0; 355 | std::vector inputPortDependencies = static_cast(outputPort->GetOwner())->GetInputPortDependencies(outputPort); 356 | for (auto inputPort : inputPortDependencies) 357 | { 358 | if (portDepths.find(inputPort) == portDepths.end()) 359 | { 360 | if (visitedInputPorts.find(inputPort) != visitedInputPorts.end()) 361 | { 362 | std::ostringstream exceptionMessage; 363 | exceptionMessage << "Detected causality loop involving port " << inputPort->GetFullName(); 364 | throw std::logic_error(exceptionMessage.str().c_str()); 365 | } 366 | else 367 | { 368 | this->ComputeAtomicAccessorInputPortDepth(inputPort, portDepths, visitedInputPorts, visitedOutputPorts); 369 | } 370 | } 371 | 372 | if (depth < portDepths.at(inputPort)) 373 | { 374 | depth = portDepths.at(inputPort); 375 | } 376 | } 377 | 378 | PRINT_VERBOSE("Output port '%s' is now priority %d", outputPort->GetFullName().c_str(), depth); 379 | portDepths[outputPort] = depth; 380 | } 381 | 382 | void Host::Impl::NotifyListenersOfException(const std::exception& e) 383 | { 384 | auto it = this->m_listeners.begin(); 385 | while (it != this->m_listeners.end()) 386 | { 387 | if (auto strongListener = it->second.lock()) 388 | { 389 | try 390 | { 391 | strongListener->NotifyOfException(e); 392 | ++it; 393 | } 394 | catch (const std::exception&) 395 | { 396 | this->m_listeners.erase(it); 397 | continue; 398 | } 399 | } 400 | else 401 | { 402 | this->m_listeners.erase(it); 403 | } 404 | } 405 | } 406 | 407 | void Host::Impl::NotifyListenersOfStateChange(Host::State oldState, Host::State newState) 408 | { 409 | auto it = this->m_listeners.begin(); 410 | while (it != this->m_listeners.end()) 411 | { 412 | if (auto strongListener = it->second.lock()) 413 | { 414 | try 415 | { 416 | strongListener->NotifyOfStateChange(oldState, newState); 417 | ++it; 418 | } 419 | catch (std::exception) 420 | { 421 | this->m_listeners.erase(it); 422 | continue; 423 | } 424 | } 425 | else 426 | { 427 | this->m_listeners.erase(it); 428 | } 429 | } 430 | } 431 | 432 | const OutputPort* Host::Impl::GetSourceOutputPort(const InputPort* inputPort) 433 | { 434 | const Port* sourcePort = inputPort->GetSource(); 435 | while (sourcePort->GetOwner()->IsComposite()) 436 | { 437 | if (!sourcePort->IsConnectedToSource()) 438 | { 439 | return nullptr; 440 | } 441 | 442 | sourcePort = sourcePort->GetSource(); 443 | } 444 | 445 | return static_cast(sourcePort); 446 | } -------------------------------------------------------------------------------- /src/HostImpl.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef HOST_IMPL_H 5 | #define HOST_IMPL_H 6 | 7 | #include "AccessorFramework/Host.h" 8 | #include "CompositeAccessorImpl.h" 9 | #include "Director.h" 10 | #include 11 | #include 12 | #include 13 | 14 | // Description 15 | // The HostImpl implements the public Host interface defined in Host.h. In addition, it exposes additional functionality 16 | // for internal use, such as a public method to access the contained model. The HostImpl is also responsible for 17 | // assigning priorities to the atomic accessors in the model. To do this, it follows the connections between accessor 18 | // ports, calculating the depth of each port to quantify causal dependencies. At the same time, it also checks the model 19 | // for causal loops; if there is a cyclic connection such that liveness cannot be established, the HostImpl will throw. 20 | // The depth of an input port is defined as the maximum depth of all input ports in the same equivalence class. The 21 | // source depth of an input port is the depth of its source port plus one, or 0 if there is no source. The depth of an 22 | // output port is defined as the maximum depths of all input ports it depends on, or 0 if it does not depend on any input 23 | // ports (i.e. is a spontaneous output port). 24 | // 25 | // For more information, see "Causality Interfaces for Actor Networks" (Zhou and Lee) 26 | // http://www.eecs.berkeley.edu/Pubs/TechRpts/2006/EECS-2006-148.html 27 | // 28 | class Host::Impl : public CompositeAccessor::Impl 29 | { 30 | public: 31 | Impl(const std::string& name, Host* container, std::function initializeFunction); 32 | ~Impl(); 33 | void ResetPriority() override; 34 | Director* GetDirector() const override; 35 | 36 | protected: 37 | // Host Methods 38 | Host::State GetState() const; 39 | bool EventListenerIsRegistered(int listenerId) const; 40 | int AddEventListener(std::weak_ptr listener); 41 | void RemoveEventListener(int listenerId); 42 | void Setup(); 43 | void Iterate(int numberOfIterations = 1); 44 | void Pause(); 45 | void Run(); 46 | void RunOnCurrentThread(); 47 | void Exit(); 48 | 49 | // Hosts are not allowed to have ports; these methods will throw 50 | void AddInputPort(const std::string& portName) final; 51 | void AddInputPorts(const std::vector& portNames) final; 52 | void AddOutputPort(const std::string& portName) final; 53 | void AddOutputPorts(const std::vector& portNames) final; 54 | 55 | void ChildrenChanged() final; 56 | 57 | private: 58 | friend class Host; 59 | 60 | // Internal Methods 61 | void ValidateHostCanRun() const; 62 | void SetState(Host::State newState); 63 | void ComputeAccessorPriorities(bool updateCallbacks = false); 64 | int ComputeCompositeAccessorDepth( 65 | CompositeAccessor::Impl* compositeAccessor, 66 | std::map& portDepths, 67 | std::map>& accessorDepths); 68 | int ComputeAtomicAccessorDepth( 69 | AtomicAccessor::Impl* atomicAccessor, 70 | std::map& portDepths, 71 | std::map>& accessorDepths); 72 | void ComputeAtomicAccessorInputPortDepth( 73 | const InputPort* inputPort, 74 | std::map& portDepths, 75 | std::set& visitedInputPorts, 76 | std::set& visitedOutputPorts); 77 | void ComputeAtomicAccessorOutputPortDepth( 78 | const OutputPort* outputPort, 79 | std::map& portDepths, 80 | std::set& visitedInputPorts, 81 | std::set& visitedOutputPorts); 82 | 83 | void NotifyListenersOfException(const std::exception& e); 84 | void NotifyListenersOfStateChange(Host::State oldState, Host::State newState); 85 | 86 | std::atomic m_state; 87 | std::unique_ptr m_director; 88 | std::map> m_listeners; 89 | int m_nextListenerId; 90 | 91 | static const OutputPort* GetSourceOutputPort(const InputPort* inputPort); 92 | }; 93 | 94 | #endif // HOST_IMPL_H 95 | -------------------------------------------------------------------------------- /src/Port.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #include "Port.h" 5 | #include "AccessorImpl.h" 6 | #include "PrintDebug.h" 7 | 8 | Port::Port(const std::string& name, Accessor::Impl* owner) : 9 | BaseObject(name, owner), 10 | m_source(nullptr) 11 | { 12 | } 13 | 14 | Port::~Port() 15 | { 16 | Port::DisconnectAll(this); 17 | } 18 | 19 | Accessor::Impl* Port::GetOwner() const 20 | { 21 | return static_cast(this->GetParent()); 22 | } 23 | 24 | bool Port::IsSpontaneous() const 25 | { 26 | return false; 27 | } 28 | 29 | bool Port::IsConnectedToSource() const 30 | { 31 | return (this->m_source != nullptr); 32 | } 33 | 34 | const Port* Port::GetSource() const 35 | { 36 | return this->m_source; 37 | } 38 | 39 | std::vector Port::GetDestinations() const 40 | { 41 | return std::vector(this->m_destinations.begin(), this->m_destinations.end()); 42 | } 43 | 44 | void Port::SendData(std::shared_ptr data) 45 | { 46 | #ifdef PRINT_VERBOSE 47 | if (!(this->m_destinations.empty())) 48 | { 49 | PRINT_VERBOSE("Port %s is sending event data at address %p", this->GetFullName().c_str(), data.get()); 50 | } 51 | #endif 52 | 53 | for (auto destination : this->m_destinations) 54 | { 55 | destination->ReceiveData(data); 56 | } 57 | } 58 | 59 | void Port::Connect(Port* source, Port* destination) 60 | { 61 | ValidateConnection(source, destination); 62 | PRINT_VERBOSE("Source port '%s' is connecting to destination port '%s'", source->GetFullName().c_str(), destination->GetFullName().c_str()); 63 | destination->m_source = source; 64 | source->m_destinations.push_back(destination); 65 | } 66 | 67 | void Port::Disconnect(Port* source, Port* destination) 68 | { 69 | if (destination->m_source == source) 70 | { 71 | for (auto it = source->m_destinations.begin(); it != source->m_destinations.end(); ++it) 72 | { 73 | if (*it == destination) 74 | { 75 | source->m_destinations.erase(it); 76 | break; 77 | } 78 | } 79 | 80 | destination->m_source = nullptr; 81 | } 82 | } 83 | 84 | void Port::DisconnectAll(Port* port) 85 | { 86 | if (port->IsConnectedToSource()) 87 | { 88 | Port::Disconnect(port->m_source, port); 89 | } 90 | 91 | while(!port->m_destinations.empty()) 92 | { 93 | Port* destination = *(port->m_destinations.begin()); 94 | Port::Disconnect(port, destination); 95 | } 96 | } 97 | 98 | void Port::ValidateConnection(Port* source, Port* destination) 99 | { 100 | if (destination->IsConnectedToSource() && destination->GetSource() != source) 101 | { 102 | std::ostringstream exceptionMessage; 103 | exceptionMessage << "Destination port '" << destination->GetFullName() << "' is already connected to source port '" << destination->GetSource()->GetFullName() << "'"; 104 | throw std::invalid_argument(exceptionMessage.str()); 105 | } 106 | else if (destination->IsSpontaneous()) 107 | { 108 | std::ostringstream exceptionMessage; 109 | exceptionMessage << "Destination port" << destination->GetFullName() << "is spontaneous, so it cannot be connected to source port " << source->GetFullName(); 110 | throw std::invalid_argument(exceptionMessage.str()); 111 | } 112 | } 113 | 114 | InputPort::InputPort(const std::string& name, Accessor::Impl* owner) : 115 | Port(name, owner), 116 | m_waitingForInputHandler(false) 117 | { 118 | } 119 | 120 | IEvent* InputPort::GetLatestInput() const 121 | { 122 | IEvent* latestInput = (this->m_inputQueue.empty() ? nullptr : this->m_inputQueue.front().get()); 123 | return latestInput; 124 | } 125 | 126 | std::shared_ptr InputPort::ShareLatestInput() const 127 | { 128 | std::shared_ptr latestInput = (this->m_inputQueue.empty() ? nullptr : this->m_inputQueue.front()); 129 | return latestInput; 130 | } 131 | 132 | int InputPort::GetInputQueueLength() const 133 | { 134 | int inputQueueLength = static_cast(this->m_inputQueue.size()); 135 | return inputQueueLength; 136 | } 137 | 138 | bool InputPort::IsWaitingForInputHandler() const 139 | { 140 | return this->m_waitingForInputHandler; 141 | } 142 | 143 | // Should only be called by the port's owner in AtomicAccessor::Impl::ProcessInputs() 144 | void InputPort::DequeueLatestInput() 145 | { 146 | if (!this->m_inputQueue.empty()) 147 | { 148 | this->m_inputQueue.pop(); 149 | if (this->m_inputQueue.empty()) 150 | { 151 | this->m_waitingForInputHandler = false; 152 | } 153 | else 154 | { 155 | this->m_waitingForInputHandler = (this->m_inputQueue.front() != nullptr); 156 | } 157 | } 158 | } 159 | 160 | void InputPort::ReceiveData(std::shared_ptr input) 161 | { 162 | auto myParent = static_cast(this->GetParent()); 163 | if (!(myParent->IsInitialized())) 164 | { 165 | PRINT_VERBOSE("Input port %s is dropping event data at address %p because its parent has not been initialized", this->GetFullName().c_str(), input.get()); 166 | return; 167 | } 168 | 169 | PRINT_VERBOSE("Input port %s is receiving event data at address %p", this->GetFullName().c_str(), input.get()); 170 | if (myParent->IsComposite()) 171 | { 172 | this->SendData(input); 173 | } 174 | else 175 | { 176 | bool wasWaitingForInputHandler = this->m_waitingForInputHandler; 177 | this->QueueInput(input); 178 | if (!wasWaitingForInputHandler && this->m_waitingForInputHandler) 179 | { 180 | myParent->AlertNewInput(); 181 | this->SendData(input); 182 | } 183 | } 184 | } 185 | 186 | void InputPort::QueueInput(std::shared_ptr input) 187 | { 188 | this->m_inputQueue.push(input); 189 | this->m_waitingForInputHandler = (this->m_inputQueue.front() != nullptr); 190 | } 191 | 192 | OutputPort::OutputPort(const std::string& name, Accessor::Impl* owner, bool spontaneous) : 193 | Port(name, owner), 194 | m_spontaneous(spontaneous) 195 | { 196 | } 197 | 198 | bool OutputPort::IsSpontaneous() const 199 | { 200 | return this->m_spontaneous; 201 | } 202 | 203 | void OutputPort::ReceiveData(std::shared_ptr input) 204 | { 205 | auto myParent = static_cast(this->GetParent()); 206 | if (!(myParent->IsInitialized())) 207 | { 208 | PRINT_VERBOSE("Output port %s is dropping event data at address %p because its parent has not been initialized", this->GetFullName().c_str(), input.get()); 209 | return; 210 | } 211 | 212 | PRINT_VERBOSE("Output port %s is receiving event data at address %p", this->GetFullName().c_str(), input.get()); 213 | this->SendData(input); 214 | } -------------------------------------------------------------------------------- /src/Port.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef PORT_H 5 | #define PORT_H 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "BaseObject.h" 13 | 14 | // Description 15 | // A port sends and receives events. A port that sends an event is called a source, and a port that receives an event is 16 | // called a destination. Despite their names, both input and output ports can send and receive events; the names imply 17 | // where the port can send the event. An input port can receive an event from an output port on the same accessor (i.e. 18 | // feedback loop), an output port on a peer accessor, or an input port on a parent accessor. A connected output port can 19 | // receive events from an input port on the same accessor. A spontaneous output port cannot have a source; a spontaneous 20 | // output is produced without any prompting from an input. For example, a timer that fires are regular intervals would be 21 | // considered spontaneous output. Both connected and spontaneous output ports can send events to an input port on the 22 | // same accessor (i.e. feedback loop), an input port on a peer accessor, or an output port on a parent accessor. All 23 | // ports are given a name upon instantiation. The name of a port must be unique among that accessor's ports; no two ports 24 | // on an accessor can have the same name. 25 | // 26 | class Port : public BaseObject 27 | { 28 | public: 29 | Port(const std::string& name, Accessor::Impl* owner); 30 | ~Port(); 31 | Accessor::Impl* GetOwner() const; 32 | virtual bool IsSpontaneous() const; 33 | bool IsConnectedToSource() const; 34 | const Port* GetSource() const; 35 | std::vector GetDestinations() const; 36 | 37 | void SendData(std::shared_ptr data); 38 | virtual void ReceiveData(std::shared_ptr data) = 0; 39 | 40 | static void Connect(Port* source, Port* destination); 41 | static void Disconnect(Port* source, Port* destination); 42 | static void DisconnectAll(Port* port); 43 | 44 | private: 45 | static void ValidateConnection(Port* source, Port* destination); 46 | 47 | Port* m_source; 48 | std::vector m_destinations; 49 | }; 50 | 51 | class InputPort final : public Port 52 | { 53 | public: 54 | InputPort(const std::string& name, Accessor::Impl* owner); 55 | IEvent* GetLatestInput() const; 56 | std::shared_ptr ShareLatestInput() const; 57 | int GetInputQueueLength() const; 58 | bool IsWaitingForInputHandler() const; 59 | void DequeueLatestInput(); // should only be called by port's owner in AtomicAccessor::Impl::ProcessInputs() 60 | void ReceiveData(std::shared_ptr input) override; 61 | 62 | private: 63 | void QueueInput(std::shared_ptr input); 64 | 65 | bool m_waitingForInputHandler; 66 | std::queue> m_inputQueue; 67 | }; 68 | 69 | class OutputPort final : public Port 70 | { 71 | public: 72 | OutputPort(const std::string& name, Accessor::Impl* owner, bool spontaneous); 73 | bool IsSpontaneous() const override; 74 | void ReceiveData(std::shared_ptr input) override; 75 | 76 | private: 77 | const bool m_spontaneous; 78 | }; 79 | 80 | #endif // PORT_H 81 | -------------------------------------------------------------------------------- /src/PrintDebug.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef PRINT_DEBUG_H 5 | #define PRINT_DEBUG_H 6 | 7 | #ifdef NDEBUG 8 | #define PRINT_DEBUG(format, ...) 9 | #define PRINT_VERBOSE(format, ...) 10 | #else 11 | #include 12 | #include 13 | #include 14 | static std::mutex g_stderr_mutex; 15 | #define PRINT_DEBUG(format, ...) { std::lock_guard guard(g_stderr_mutex); fprintf(stderr, format, ##__VA_ARGS__); fprintf(stderr, "\n"); } 16 | #ifdef VERBOSE 17 | #define PRINT_VERBOSE PRINT_DEBUG 18 | #else 19 | #ifdef PRINT_VERBOSE 20 | #undef PRINT_VERBOSE 21 | #endif 22 | #define PRINT_VERBOSE(format, ...) 23 | #endif // VERBOSE 24 | #endif // NDEBUG 25 | 26 | #endif // PRINT_DEBUG_H 27 | -------------------------------------------------------------------------------- /src/UniquePriorityQueue.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef UNIQUE_PRIORITY_QUEUE_H 5 | #define UNIQUE_PRIORITY_QUEUE_H 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | // Description 12 | // A priority_queue that contains at most one instance of a given element 13 | // 14 | template, class Compare = std::less> 15 | class unique_priority_queue 16 | { 17 | public: 18 | T top() const 19 | { 20 | return this->m_queue.top(); 21 | } 22 | 23 | void push(T newElement) 24 | { 25 | if (this->m_elementsInQueue.find(newElement) == this->m_elementsInQueue.end()) 26 | { 27 | this->m_queue.push(newElement); 28 | this->m_elementsInQueue.insert(newElement); 29 | } 30 | } 31 | 32 | void pop() 33 | { 34 | this->m_elementsInQueue.erase(this->m_elementsInQueue.find(this->top())); 35 | this->m_queue.pop(); 36 | } 37 | 38 | bool empty() const 39 | { 40 | return this->m_queue.empty(); 41 | } 42 | 43 | private: 44 | std::priority_queue m_queue; 45 | std::set m_elementsInQueue; 46 | }; 47 | 48 | #endif // UNIQUE_PRIORITY_QUEUE_H 49 | -------------------------------------------------------------------------------- /test/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. 2 | # Licensed under the MIT License. 3 | 4 | cmake_minimum_required (VERSION 3.11) 5 | 6 | # Replace install() to do-nothing macro to avoid installing googletest 7 | macro(install) 8 | endmacro() 9 | 10 | include(FetchContent) 11 | FetchContent_Declare( 12 | googletest 13 | GIT_REPOSITORY https://github.com/google/googletest.git 14 | GIT_TAG release-1.10.0 15 | ) 16 | 17 | FetchContent_MakeAvailable(googletest) 18 | FetchContent_GetProperties(googletest) 19 | if(NOT googletest_POPULATED) 20 | FetchContent_Populate(googletest) 21 | add_subdirectory(${googletest_SOURCE_DIR} ${googletest_BINARY_DIR}) 22 | endif() 23 | 24 | add_executable(AccessorFrameworkTests 25 | src/TestCases/BasicAccessorTests.cpp 26 | src/TestCases/BasicHostTests.cpp 27 | src/TestCases/SumVerifierTests.cpp 28 | src/TestCases/DynamicSumVerifierTests.cpp 29 | ) 30 | 31 | target_link_libraries(AccessorFrameworkTests 32 | PRIVATE 33 | gtest 34 | gmock_main 35 | AccessorFramework::AccessorFramework 36 | ) 37 | 38 | add_test(NAME AccessorFrameworkTests COMMAND AccessorFrameworkTests) 39 | 40 | # Restore original install() behavior 41 | macro(install) 42 | _install(${ARGN}) 43 | endmacro() -------------------------------------------------------------------------------- /test/src/TestCases/BasicAccessorTests.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | namespace BasicAccessorTests 5 | { 6 | // A name cannot be empty, cannot contain periods, and cannot contain whitespace 7 | TEST(Accessor_NameIsValidTests, ValidName) 8 | { 9 | // Arrange 10 | const std::string targetName = "TargetName"; 11 | 12 | // Act 13 | bool nameIsValid = Accessor::NameIsValid(targetName); 14 | 15 | // Assert 16 | ASSERT_TRUE(nameIsValid); 17 | } 18 | 19 | TEST(Accessor_NameIsValidTests, EmptyName) 20 | { 21 | // Arrange 22 | const std::string targetName = ""; 23 | 24 | // Act 25 | bool nameIsValid = Accessor::NameIsValid(targetName); 26 | 27 | // Assert 28 | ASSERT_FALSE(nameIsValid); 29 | } 30 | 31 | TEST(Accessor_NameIsValidTests, NameWithPeriods) 32 | { 33 | // Arrange 34 | const std::string targetName = "Target.Name"; 35 | 36 | // Act 37 | bool nameIsValid = Accessor::NameIsValid(targetName); 38 | 39 | // Assert 40 | ASSERT_FALSE(nameIsValid); 41 | } 42 | 43 | TEST(Accessor_NameIsValidTests, NameWithWhitespace) 44 | { 45 | // Arrange 46 | const std::string targetName = "Target Name"; 47 | 48 | // Act 49 | bool nameIsValid = Accessor::NameIsValid(targetName); 50 | 51 | // Assert 52 | ASSERT_FALSE(nameIsValid); 53 | } 54 | 55 | TEST(Accessor_GetNameTests, ValidName) 56 | { 57 | // Arrange 58 | const std::string expectedTargetName = "TargetName"; 59 | AtomicAccessor target(expectedTargetName); 60 | 61 | // Act 62 | std::string actualTargetName = target.GetName(); 63 | 64 | // Assert 65 | ASSERT_EQ(expectedTargetName, actualTargetName); 66 | } 67 | 68 | TEST(Accessor_GetImplTests, NotNull) 69 | { 70 | // Arrange 71 | const std::string targetName = "TargetName"; 72 | AtomicAccessor target(targetName); 73 | 74 | // Act 75 | Accessor::Impl* targetImpl = target.GetImpl(); 76 | 77 | // Assert 78 | ASSERT_NE(nullptr, targetImpl); 79 | } 80 | } -------------------------------------------------------------------------------- /test/src/TestCases/BasicHostTests.cpp: -------------------------------------------------------------------------------- 1 | // Copyright(c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #include 5 | #include 6 | #include "../TestClasses/EmptyHost.h" 7 | 8 | namespace BasicHostTests 9 | { 10 | class HostTest : public ::testing::Test 11 | { 12 | protected: 13 | // Runs before each test case 14 | void SetUp() override 15 | { 16 | this->target = std::make_unique(this->TargetName); 17 | } 18 | 19 | // Runs after each test case 20 | void TearDown() override 21 | { 22 | this->target.reset(nullptr); 23 | } 24 | 25 | std::unique_ptr target = nullptr; 26 | std::string TargetName = "TargetHost"; 27 | }; 28 | 29 | TEST_F(HostTest, GetName) 30 | { 31 | // Act 32 | std::string actualTargetName = target->GetName(); 33 | 34 | // Assert 35 | ASSERT_STREQ(TargetName.c_str(), actualTargetName.c_str()); 36 | } 37 | 38 | TEST_F(HostTest, CannotRunWithoutSetup) 39 | { 40 | // Act 41 | Host::State initialState = target->GetState(); 42 | 43 | // Assert 44 | ASSERT_EQ(Host::State::NeedsSetup, initialState); 45 | ASSERT_THROW(target->Run(), std::logic_error); 46 | ASSERT_THROW(target->RunOnCurrentThread(), std::logic_error); 47 | ASSERT_THROW(target->Iterate(1), std::logic_error); 48 | ASSERT_THROW(target->Pause(), std::logic_error); 49 | } 50 | 51 | TEST_F(HostTest, SetupEmpty) 52 | { 53 | // Act 54 | target->Setup(); 55 | Host::State stateAfterSetup = target->GetState(); 56 | bool additionalSetupWasCalled = target->AdditionalSetupWasCalled(); 57 | 58 | // Assert 59 | ASSERT_EQ(Host::State::ReadyToRun, stateAfterSetup); 60 | ASSERT_TRUE(additionalSetupWasCalled); 61 | } 62 | 63 | TEST_F(HostTest, CanExitWithoutSetup) 64 | { 65 | // Act 66 | Host::State initialState = target->GetState(); 67 | target->Exit(); 68 | Host::State finalState = target->GetState(); 69 | 70 | // Assert 71 | ASSERT_EQ(Host::State::NeedsSetup, initialState); 72 | ASSERT_EQ(Host::State::Finished, finalState); 73 | } 74 | 75 | TEST_F(HostTest, CanExitWithoutRunning) 76 | { 77 | // Act 78 | target->Setup(); 79 | Host::State stateAfterSetup = target->GetState(); 80 | target->Exit(); 81 | Host::State finalState = target->GetState(); 82 | 83 | // Assert 84 | ASSERT_EQ(Host::State::ReadyToRun, stateAfterSetup); 85 | ASSERT_EQ(Host::State::Finished, finalState); 86 | } 87 | } -------------------------------------------------------------------------------- /test/src/TestCases/DynamicSumVerifierTests.cpp: -------------------------------------------------------------------------------- 1 | // Copyright(c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include "../TestClasses/DynamicSumVerifierHost.h" 10 | 11 | namespace DynamicSumVerifierTests 12 | { 13 | class DynamicSumVerifierTest : public ::testing::Test 14 | { 15 | protected: 16 | // Runs before each test case 17 | void SetUp() override 18 | { 19 | this->latestSum = std::make_shared(0); 20 | this->error = std::make_shared(false); 21 | this->target = std::make_unique(this->TargetName, this->latestSum, this->error); 22 | } 23 | 24 | // Runs after each test case 25 | void TearDown() override 26 | { 27 | this->target.reset(nullptr); 28 | this->error.reset(); 29 | this->latestSum.reset(); 30 | } 31 | 32 | std::string TargetName = "TargetHost"; 33 | std::unique_ptr target = nullptr; 34 | std::shared_ptr latestSum = nullptr; 35 | std::shared_ptr error = nullptr; 36 | }; 37 | 38 | TEST_F(DynamicSumVerifierTest, DynamicSumVerifier_Iterate) 39 | { 40 | /* 41 | Events: 42 | Add: host adds another spontaneous counter to the model (should trigger an update at the beginning of the next round) 43 | Update: host updates the model (recalculates priorities & initializes new actors) 44 | Fire: spontaneous counters output their latest counts 45 | Expected Sequence: 46 | Round 0 (initialization): Add 47 | Rount 1: Update --> Add 48 | Round 2: Update --> Add --> Fire (0) 49 | Round 3: Update --> Add --> Fire (0 + 1) 50 | Round 4: Update --> Add --> Fire (0 + 1 + 2) 51 | Round 5: Update --> Add --> Fire (0 + 1 + 2 + 3) 52 | ... 53 | Round N: Update --> Add --> Fire (0 + 1 + 2 + 3 + ... + N) = 0.5(N-1)(N-2) 54 | */ 55 | 56 | // Arrange 57 | int numberOfIterations = 5; 58 | int expectedSum = ((numberOfIterations - 1) * (numberOfIterations - 2)) / 2; 59 | 60 | // Act 61 | target->Setup(); 62 | target->Iterate(5); 63 | target->Exit(); 64 | 65 | // Assert 66 | ASSERT_FALSE(*error); 67 | ASSERT_EQ(expectedSum, *latestSum); 68 | } 69 | 70 | TEST_F(DynamicSumVerifierTest, DynamicSumVerifier_Run) 71 | { 72 | using namespace std::chrono_literals; 73 | 74 | // Arrange 75 | auto sleepInterval = 5.5s; 76 | int expectedNumberOfIterations = std::floor(sleepInterval.count()); 77 | int expectedSum = ((expectedNumberOfIterations - 1) * (expectedNumberOfIterations - 2)) / 2; 78 | 79 | // Act 80 | target->Setup(); 81 | target->Run(); 82 | std::this_thread::sleep_for(sleepInterval); 83 | target->Exit(); 84 | 85 | // Assert 86 | ASSERT_FALSE(*error); 87 | ASSERT_EQ(expectedSum, *latestSum); 88 | } 89 | } -------------------------------------------------------------------------------- /test/src/TestCases/SumVerifierTests.cpp: -------------------------------------------------------------------------------- 1 | // Copyright(c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include "../TestClasses/SumVerifierHost.h" 10 | 11 | namespace SumVerifierTests 12 | { 13 | class SumVerifierTest : public ::testing::Test 14 | { 15 | protected: 16 | // Runs before each test case 17 | void SetUp() override 18 | { 19 | this->latestSum = std::make_shared(0); 20 | this->error = std::make_shared(false); 21 | this->target = std::make_unique(this->TargetName, this->latestSum, this->error); 22 | } 23 | 24 | // Runs after each test case 25 | void TearDown() override 26 | { 27 | this->target.reset(nullptr); 28 | this->latestSum.reset(); 29 | this->error.reset(); 30 | } 31 | 32 | std::string TargetName = "TargetHost"; 33 | std::unique_ptr target = nullptr; 34 | std::shared_ptr latestSum = nullptr; 35 | std::shared_ptr error = nullptr; 36 | }; 37 | 38 | TEST_F(SumVerifierTest, SumVerifier_Iterate) 39 | { 40 | // Arrange 41 | int numberOfIterations = 5; 42 | int expectedSum = (numberOfIterations - 1) * 2; 43 | 44 | // Act 45 | target->Setup(); 46 | target->Iterate(5); 47 | target->Exit(); 48 | 49 | // Assert 50 | ASSERT_FALSE(*error); 51 | ASSERT_EQ(expectedSum, *latestSum); 52 | } 53 | 54 | TEST_F(SumVerifierTest, SumVerifier_Run) 55 | { 56 | using namespace std::chrono_literals; 57 | 58 | // Arrange 59 | auto sleepInterval = 5.5s; 60 | int expectedSum = (std::floor(sleepInterval.count()) - 1) * 2; 61 | 62 | // Act 63 | target->Setup(); 64 | target->Run(); 65 | std::this_thread::sleep_for(sleepInterval); 66 | target->Exit(); 67 | 68 | // Assert 69 | ASSERT_FALSE(*error); 70 | ASSERT_EQ(expectedSum, *latestSum); 71 | } 72 | } -------------------------------------------------------------------------------- /test/src/TestClasses/DynamicIntegerAdder.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef DYNAMICINTEGERADDER_H 5 | #define DYNAMICINTEGERADDER_H 6 | 7 | #include 8 | 9 | // Description 10 | // An actor that takes n integers received on its input ports and outputs the sum on its output port 11 | // 12 | class DynamicIntegerAdder : public AtomicAccessor 13 | { 14 | public: 15 | explicit DynamicIntegerAdder(const std::string& name) : 16 | AtomicAccessor(name, {} /*inputPortNames*/, { SumOutput }) 17 | { 18 | this->AddNextPort(); 19 | this->AddNextPort(); 20 | } 21 | 22 | static std::string GetInputPortName(int portIndex) 23 | { 24 | std::ostringstream oss; 25 | oss << InputPrefix << "-" << portIndex; 26 | return oss.str(); 27 | } 28 | 29 | // Connected Output Port Names 30 | static const char* SumOutput; 31 | 32 | private: 33 | void AddNextPort() 34 | { 35 | int portIndex = this->m_nextPortIndex++; 36 | this->m_latestInputs.resize(this->m_nextPortIndex); 37 | std::string portName = this->GetInputPortName(portIndex); 38 | this->AddInputPort(portName); 39 | this->AddHandler(portIndex); 40 | } 41 | 42 | void AddHandler(int portIndex) 43 | { 44 | std::string portName = GetInputPortName(portIndex); 45 | this->AddInputHandler(portName, 46 | [this, portIndex](IEvent* event) 47 | { 48 | this->m_latestInputs[portIndex] = static_cast*>(event)->payload; 49 | }); 50 | } 51 | 52 | int CalculateSum() 53 | { 54 | int sum = 0; 55 | for (int i : this->m_latestInputs) 56 | { 57 | sum += i; 58 | } 59 | 60 | return sum; 61 | } 62 | 63 | void Fire() override 64 | { 65 | int sum = this->CalculateSum(); 66 | this->SendOutput(SumOutput, std::make_shared>(sum)); 67 | this->AddNextPort(); 68 | } 69 | 70 | std::vector m_latestInputs; 71 | static const char* InputPrefix; 72 | int m_nextPortIndex = 0; 73 | }; 74 | 75 | const char* DynamicIntegerAdder::InputPrefix = "Input-"; 76 | const char* DynamicIntegerAdder::SumOutput = "SumOutput"; 77 | 78 | #endif // DYNAMICINTEGERADDER_H -------------------------------------------------------------------------------- /test/src/TestClasses/DynamicSumVerifier.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef DYNAMICSUMVERIFIER_H 5 | #define DYNAMICSUMVERIFIER_H 6 | 7 | #include 8 | 9 | // Description 10 | // An actor that verifies the DynamicIntegerAdder's output when used in DynamicIntegerAdderHost 11 | // 12 | class DynamicSumVerifier : public AtomicAccessor 13 | { 14 | public: 15 | DynamicSumVerifier(const std::string& name, std::shared_ptr latestSum, std::shared_ptr error) : 16 | AtomicAccessor(name, { SumInput }), 17 | m_nextAddition(0), 18 | m_expectedSum(0), 19 | m_latestSum(latestSum), 20 | m_error(error) 21 | { 22 | this->AddInputHandler( 23 | SumInput, 24 | [this](IEvent* inputSumEvent) 25 | { 26 | int actualSum = static_cast*>(inputSumEvent)->payload; 27 | *(this->m_latestSum) = actualSum; 28 | this->VerifySum(actualSum); 29 | this->CalculateNextExpectedSum(); 30 | }); 31 | } 32 | 33 | static constexpr char* SumInput = "Sum"; 34 | 35 | private: 36 | void VerifySum(int actualSum) const 37 | { 38 | *(this->m_error) |= !(actualSum == this->m_expectedSum); 39 | if (*(this->m_error)) 40 | { 41 | std::cerr << "FAILURE: received actual sum of " << actualSum << ", but expected " << this->m_expectedSum << std::endl; 42 | } 43 | else 44 | { 45 | std::cout << "SUCCESS: actual sum of " << actualSum << " matched expected" << std::endl; 46 | } 47 | } 48 | 49 | void CalculateNextExpectedSum() 50 | { 51 | ++(this->m_nextAddition); 52 | this->m_expectedSum = *(this->m_latestSum) + this->m_nextAddition; 53 | } 54 | 55 | int m_nextAddition; 56 | int m_expectedSum; 57 | std::shared_ptr m_latestSum; 58 | std::shared_ptr m_error; 59 | }; 60 | 61 | #endif // DYNAMICSUMVERIFIER_H -------------------------------------------------------------------------------- /test/src/TestClasses/DynamicSumVerifierHost.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef DYNAMICSUMVERIFIERHOST_H 5 | #define DYNAMICSUMVERIFIERHOST_H 6 | 7 | #include 8 | #include 9 | #include "DynamicIntegerAdder.h" 10 | #include "DynamicSumVerifier.h" 11 | #include "SpontaneousCounter.h" 12 | 13 | class DynamicSumVerifierHost : public Host 14 | { 15 | public: 16 | explicit DynamicSumVerifierHost(const std::string& name, std::shared_ptr latestSum, std::shared_ptr error) : Host(name) 17 | { 18 | using namespace std::chrono_literals; 19 | this->AddChild(std::make_unique(a1)); 20 | this->AddChild(std::make_unique(v1, latestSum, error)); 21 | this->ConnectChildren(a1, DynamicIntegerAdder::SumOutput, v1, DynamicSumVerifier::SumInput); 22 | } 23 | 24 | private: 25 | 26 | void Initialize() override 27 | { 28 | this->ScheduleCallback( 29 | [this]() 30 | { 31 | int counterIndex = this->m_counterIndex++; 32 | std::string counterName = this->GetCounterName(counterIndex); 33 | this->AddChild(std::make_unique(counterName, this->m_spontaneousInterval.count())); 34 | std::string adderInputPortName = DynamicIntegerAdder::GetInputPortName(counterIndex); 35 | this->ConnectChildren(counterName, SpontaneousCounter::CounterValueOutput, a1, adderInputPortName); 36 | this->ChildrenChanged(); 37 | }, 38 | this->m_spontaneousInterval.count(), 39 | true /*repeat*/); 40 | } 41 | 42 | std::string GetCounterName(int counterIndex) 43 | { 44 | std::ostringstream oss; 45 | oss << this->spontaneousCounterPrefix << "-" << counterIndex; 46 | return oss.str(); 47 | } 48 | 49 | const std::chrono::milliseconds m_spontaneousInterval = std::chrono::milliseconds(1000); 50 | const std::string spontaneousCounterPrefix = "SpontaneousCounter-"; 51 | const std::string a1 = "DynamicIntegerAdder"; 52 | const std::string v1 = "SumVerifier"; 53 | int m_counterIndex = 0; 54 | }; 55 | 56 | #endif // DYNAMICSUMVERIFIERHOST_H -------------------------------------------------------------------------------- /test/src/TestClasses/EmptyHost.h: -------------------------------------------------------------------------------- 1 | // Copyright(c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef EMPTYHOST_H 5 | #define EMPTYHOST_H 6 | 7 | #include 8 | 9 | class EmptyHost : public Host 10 | { 11 | public: 12 | EmptyHost(const std::string& name) : 13 | Host(name) 14 | { 15 | } 16 | 17 | bool AdditionalSetupWasCalled() 18 | { 19 | return this->m_additionalSetupCalled; 20 | } 21 | 22 | protected: 23 | void AdditionalSetup() override 24 | { 25 | this->m_additionalSetupCalled = true; 26 | } 27 | 28 | private: 29 | bool m_additionalSetupCalled = false; 30 | }; 31 | 32 | #endif // EMPTYHOST_H -------------------------------------------------------------------------------- /test/src/TestClasses/IntegerAdder.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef INTEGERADDER_H 5 | #define INTEGERADDER_H 6 | 7 | #include 8 | 9 | // Description 10 | // An actor that takes two integers received on its two input ports and outputs the sum on its output port 11 | // 12 | class IntegerAdder : public AtomicAccessor 13 | { 14 | public: 15 | explicit IntegerAdder(const std::string& name) : 16 | AtomicAccessor(name, { LeftInput, RightInput }, { SumOutput }) 17 | { 18 | this->AddInputHandler(LeftInput, 19 | [this](IEvent* event) 20 | { 21 | this->m_latestLeftInput = static_cast*>(event)->payload; 22 | }); 23 | 24 | this->AddInputHandler(RightInput, 25 | [this](IEvent* event) 26 | { 27 | this->m_latestRightInput = static_cast*>(event)->payload; 28 | }); 29 | } 30 | 31 | // Input Port Names 32 | static const char* LeftInput; 33 | static const char* RightInput; 34 | 35 | // Connected Output Port Names 36 | static const char* SumOutput; 37 | 38 | private: 39 | void Fire() override 40 | { 41 | this->SendOutput(SumOutput, std::make_shared>(this->m_latestLeftInput + this->m_latestRightInput)); 42 | } 43 | 44 | int m_latestLeftInput = 0; 45 | int m_latestRightInput = 0; 46 | }; 47 | 48 | const char* IntegerAdder::LeftInput = "LeftInput"; 49 | const char* IntegerAdder::RightInput = "RightInput"; 50 | const char* IntegerAdder::SumOutput = "SumOutput"; 51 | 52 | #endif // INTEGERADDER_H -------------------------------------------------------------------------------- /test/src/TestClasses/SpontaneousCounter.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef SPONTANEOUSCOUNTER_H 5 | #define SPONTANEOUSCOUNTER_H 6 | 7 | #include 8 | 9 | // Description 10 | // An actor that increments a counter and outputs the value of the counter at regular intervals 11 | // 12 | class SpontaneousCounter : public AtomicAccessor 13 | { 14 | public: 15 | SpontaneousCounter(const std::string& name, int intervalInMilliseconds) : 16 | AtomicAccessor(name, {}, {}, { CounterValueOutput }), 17 | m_initialized(false), 18 | m_intervalInMilliseconds(intervalInMilliseconds), 19 | m_callbackId(0), 20 | m_count(0) 21 | { 22 | } 23 | 24 | static constexpr char* CounterValueOutput = "CounterValue"; 25 | 26 | private: 27 | void Initialize() override 28 | { 29 | this->m_callbackId = this->ScheduleCallback( 30 | [this]() 31 | { 32 | this->SendOutput(CounterValueOutput, std::make_shared>(this->m_count)); 33 | ++this->m_count; 34 | }, 35 | m_intervalInMilliseconds, 36 | true /*repeat*/); 37 | 38 | this->m_initialized = true; 39 | } 40 | 41 | bool m_initialized; 42 | int m_intervalInMilliseconds; 43 | int m_callbackId; 44 | int m_count; 45 | }; 46 | 47 | #endif // SPONTANEOUSCOUNTER_H -------------------------------------------------------------------------------- /test/src/TestClasses/SumVerifier.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef SUMVERIFIER_H 5 | #define SUMVERIFIER_H 6 | 7 | #include 8 | 9 | // Description 10 | // An actor that verifies the IntegerAdder's output 11 | // 12 | class SumVerifier : public AtomicAccessor 13 | { 14 | public: 15 | SumVerifier(const std::string& name, std::shared_ptr latestSum, std::shared_ptr error) : 16 | AtomicAccessor(name, { SumInput }), 17 | m_expectedSum(0), 18 | m_latestSum(latestSum), 19 | m_error(error) 20 | { 21 | this->AddInputHandler( 22 | SumInput, 23 | [this](IEvent* inputSumEvent) 24 | { 25 | int actualSum = static_cast*>(inputSumEvent)->payload; 26 | *(this->m_latestSum) = actualSum; 27 | this->VerifySum(actualSum); 28 | this->CalculateNextExpectedSum(); 29 | }); 30 | } 31 | 32 | static constexpr char* SumInput = "Sum"; 33 | 34 | private: 35 | void VerifySum(int actualSum) const 36 | { 37 | *(this->m_error) |= !(actualSum == this->m_expectedSum); 38 | if (*(this->m_error)) 39 | { 40 | std::cerr << "FAILURE: received actual sum of " << actualSum << ", but expected " << this->m_expectedSum << std::endl; 41 | } 42 | else 43 | { 44 | std::cout << "SUCCESS: actual sum of " << actualSum << " matched expected" << std::endl; 45 | } 46 | } 47 | 48 | void CalculateNextExpectedSum() 49 | { 50 | this->m_expectedSum += 2; 51 | } 52 | 53 | int m_expectedSum; 54 | std::shared_ptr m_latestSum; 55 | std::shared_ptr m_error; 56 | }; 57 | 58 | #endif // SUMVERIFIER_H -------------------------------------------------------------------------------- /test/src/TestClasses/SumVerifierHost.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | #ifndef SUMVERIFIERHOST_H 5 | #define SUMVERIFIERHOST_H 6 | 7 | #include 8 | #include 9 | #include "IntegerAdder.h" 10 | #include "SpontaneousCounter.h" 11 | #include "SumVerifier.h" 12 | 13 | class SumVerifierHost : public Host 14 | { 15 | public: 16 | explicit SumVerifierHost(const std::string& name, std::shared_ptr latestSum, std::shared_ptr error) : Host(name) 17 | { 18 | using namespace std::chrono_literals; 19 | auto spontaneousInterval = 1000ms; 20 | this->AddChild(std::make_unique(s1, spontaneousInterval.count())); 21 | this->AddChild(std::make_unique(s2, spontaneousInterval.count())); 22 | this->AddChild(std::make_unique(a1)); 23 | this->AddChild(std::make_unique(v1, latestSum, error)); 24 | } 25 | 26 | void AdditionalSetup() override 27 | { 28 | // This could also be done in the constructor, but we do it here to illustrate the additional setup feature 29 | // Connect s1's output to a1's left input 30 | this->ConnectChildren(s1, SpontaneousCounter::CounterValueOutput, a1, IntegerAdder::LeftInput); 31 | 32 | // Connect s2's output to a1's right input 33 | this->ConnectChildren(s2, SpontaneousCounter::CounterValueOutput, a1, IntegerAdder::RightInput); 34 | 35 | // Connect a1's output to v1's input 36 | this->ConnectChildren(a1, IntegerAdder::SumOutput, v1, SumVerifier::SumInput); 37 | } 38 | 39 | private: 40 | const std::string s1 = "SpontaneousCounterOne"; 41 | const std::string s2 = "SpontaneousCounterTwo"; 42 | const std::string a1 = "IntegerAdder"; 43 | const std::string v1 = "SumVerifier"; 44 | }; 45 | 46 | #endif // SUMVERIFIERHOST_H --------------------------------------------------------------------------------